Category Archives: ASP .Net

Active Directory via C#

There is a requirement to perform CRUD operation on an Active Directory and we need to create it on C#. The following code will help an engineer accordingly:

Create

using (DirectoryEntry directoryEntry = new DirectoryEntry("LDAP:\\url\ou", "username", "password"))
                {
                    using (DirectoryEntry newUser = directoryEntry.Children.Add("CN=Name", "User"))
                    {
                        if (!DirectoryEntry.Exists(newUser.Path))
                        {
                            newUser.Properties["property1"].Add(propertyValue);
                            newUser.CommitChanges();
                            ret = true;
                        }
                    }
                }

Update

using (DirectoryEntry directoryEntry = new DirectoryEntry("LDAP:\\url\ou", "username", "password"))
                {
                    using (DirectorySearcher search = new DirectorySearcher(directoryEntry))
                    {
                        search.Filter = String.Format("(IdentifierProperty={0})", identifier);
                        search.PropertiesToLoad.Add("property1");
                        SearchResult result = search.FindOne();
                        if (result != null)
                        {
                            using (DirectoryEntry entryToUpdate = result.GetDirectoryEntry())
                            {
                                entryToUpdate.Properties["property1"].Value = "property1value";
                                entryToUpdate.CommitChanges();
                                ret = true;
                            }
                        }
                    }
                }

Delete

using (DirectoryEntry directoryEntry = new DirectoryEntry("LDAP:\\url\ou", "username", "password"))
                {
                    using (DirectorySearcher search = new DirectorySearcher(directoryEntry))
                    {
                        search.Filter = String.Format("(IdentifierProperty={0})", identifier);
                        search.PropertiesToLoad.Add("property1");
                        SearchResult result = search.FindOne();
                        if (result != null)
                        {
                            using (DirectoryEntry entryToUpdate = result.GetDirectoryEntry())
                            {
                                directoryEntry.Children.Remove(entryToUpdate);
                                directoryEntry.CommitChanges();
                                ret = true;
                            }
                        }
                    }
                }

MSSQL Grant Execute Stored Procedure only

There are cases that we only want to grant read-write only access then also enable users to execute stored procedure with in the SQL Server database.

In order to do this we will need to:

  1. Create a new Role named, db_exec_storedprocedure

    CREATE ROLE db_exec_storedprocedure
  2. Grant that role with execute stored procedure

    GRANT EXECUTE TO db_exec_storedprocedure
  3. Then add the user as a member of that role.

That’s it you can now grant specific permission to execute stored procedure.

God Bless!
Thanks,
Thomie

Visual Studio Extension -Ngrok

Ngrok is now widely being used. From simple web development up to complex development. Is hard to run Ngrok everytime you are coding specially when using IIS Express that if not configured to use a specific IP it will generate random port which is a hard to map.

Thankfully there is a plug-in for our beloved Visual Studio to integrate this.

Ngrok Extensions

With Ngrok Extension we only open our Visual Studio solution and navigate to Tool>Start ngrok Tunnel and it will create a tunnel for the websites under your solution.

Try it now!

God Bless!

Thanks,
Thomie

Ngrok – Free Web Tunneling

In the verge of today’s web development we encounter cases that in order to proceed we need to have a public accessible URL. Thankfully, Ngrok provide a free service to do this.

What it does is tunnel your machine to a Ngrok URL with a specific port. We just need to download the ngrok.exe from their website and run the command like

ngrok http 80


With this command your service on your local machine that is running on port 80 will be mapped and accessible publicly for FREE. For a full documentation view it here.

God Bless!

Thanks,
Thomie

Adding Proxy on Web.Config

Hi,

There are some cases when developing your web application on .net you may experience proxy issues when you are accessing APIs on your application. To fix this you may add this on your web.config/app.config under the configuration section

 

<system.net>
<defaultProxy useDefaultCredentials=”true”>
<proxy usesystemdefault=”true” proxyaddress=”http://proxy:8080″ bypassonlocal=”true” />
<bypasslist />
</defaultProxy>
</system.net>

God Bless!

Thanks,
Thomie

Fix SignalR OnDisconnected not working

This just come up and after searching and testing it like to Fix SignalR OnDisconnected if not working is to implement on the client at least one method so that this method will be called. Think of it like a requirement.

Example for the SignalR residing on the same server

<!– Reference to jQuery –>
<!– Reference to SignalR –>
<script src=”~/hubs/signalr“></script>
<script>
var onlineHubProxy = $.connection.onlineHub;

onlineHubProxy.client.void = function(){
//do nothing
};

$.connection.start();

</script>

Then try again now and the Default methods of hubs will now be working properly.

God Bless!

Thanks,
Thomie

Replace words on MS Word using C#

Hi,

Recently I was instructed to create an application that will be able to replace an array of words and replace them with an array of corresponding words on an MS Word document. With this I’ve searched the following:

Prerequisites

  1. Visual Stduio
  2. Install the nuget package DocX
  3. Administrative access on the context the application is running

Code

Dictionary<string, string> lReplacements = new Dictionary<string, string>();
string newFullPath = @”c:\sample.docx”;

using (DocX document = DocX.Load(newFullPath))
{

//for loop is better than foreach
foreach (var item in lReplacements)
{

document.ReplaceText(item.Key, item.Value);

}
document.Save();

}

Hope it helped you as it helped me with this simple snippet.

God Bless!
Thanks,
Thomie

C# Task<object> return Type

In every signalr or webapi request based application there is a need to indicate the return type of Task<object> along with the async keyword. Let say this sample:

public async Task<MyObject> GetItem(){

MyObject myObject = new MyObject();

myObject = await getSomeWhereThere();

#doSomethingElse

return myObject;

}

In this sample, we all know that this is a asynchronous request from somewhere. Which dictates that myObject will return later after the getSomeWhereThere(); has finished executing. But we need to remind of a very important thing that #doSomethingElse will not be executed in Xamarin if it is not properly used. Let say we did this instead:

public async void GetItem(){

MyObject myObject = new MyObject();

myObject = await getSomeWhereThere();

#doSomethingElse

}

In this code the #doSomethingElse will not be executed because it will only assume that after the getSomeWhereThere(); is executed you don’t mind if #doSomethingElse is still needed. Thus make sure that we use the Task<MyObject> in cases like this so that #doSomethingElse will still be executed.

Convert.ToDateTime Regardless of Culture

Did you upgrade to Windows 10 recently and your MVC website now have an issue under the development phase after it? Then maybe you also experience the same issue that affected your code on IIS. That is becuase Convert.ToDateTime utilizes the machine’s Culture(It changes when you use Windows 10 even you are using the same Country set) to parse a Date time. So to use it regardless of the Culture use the code snippet below.

 

string s = “20.09.2015 10.16.12”;
string expextedFormat = “dd.MM.yyyy HH.mm.ss”;
DateTime d;
bool isValid = DateTime.TryParseExact(s, expextedFormat , CultureInfo.InvariantCulture, DateTimeStyles.None, out d);

 

Hope it helped you as it helped me.

ELMAH – Error Logging Modules and Handlers

What is ELMAH?

  • ELMAH (Error Logging Modules and Handlers) is an application-wide error logging facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment.
  • Once ELMAH has been dropped into a running web application and configured appropriately, you get the following facilities without changing a single line of your code:
    • Logging of nearly all unhandled exceptions.
    • A web page to remotely view the entire log of recoded exceptions.
    • A web page to remotely view the full details of any one logged exception, including colored stack traces.
    • In many cases, you can review the original yellow screen of death that ASP.NET generated for a given exception, even with customErrors mode turned off.
    • An e-mail notification of each error at the time it occurs.
    • An RSS feed of the last 15 errors from the log.

How to Install ELMAH on your MVC Project?

  • Open Nuget Package Manager on the MVC Project
  • Search for ELMAH and Install it.
  • Then configure it.

ELMAH Configuration

  • It will already add some configuration under your web.config but we need to include some configuration so that it will point to a database.
  • <connectionStrings>

  <add name=”elmahConnectionString” connectionString=”Data Source=Server;Initial Catalog=ELMAH_DEV;uid=user;pwd=user;Pooling=true;Min Pool Size=0;Max Pool Size=999;” providerName=”System.Data.SqlClient” />

</connectionStrings>

  • <elmah>

    <!–

See http://code.google.com/p/elmah/wiki/SecuringErrorLogPages for

more information on remote access and securing ELMAH.

–>

<security allowRemoteAccess=”true” />

<errorLog type=”Elmah.SqlErrorLog, Elmah” applicationName=”NameOfApplication_DEV” connectionStringName=”elmahConnectionString” />

</elmah>

  • We also need to remove some sections that we don’t need specially the section below that automatically create a page for the logs.
  • <location path=”elmah.axd” inheritInChildApplications=”false”>…</location>

Logging

  • All uncatched exception will automatically be recorded.
  • All exception handling will NOT be recorded automatically. It needs to be manually logged by including the Elmah.ErrorSignal.FromCurrentContext().Raise(ex);

try{
throw new Exception(“Some Exception”);
}catch(Exception ex){

Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}

 

Signalr – OnDisconnect(bool stopCalled)

Most of us who are using .Net as our Programming language use Signalr as our Real-Time Framework. And we implement OnDisconnect in most cases to catch clients that have been disconnected. Since then there were no parameter included as an Overload of the said method. Lately on the latest releases by the Signalr team they have included an Overload so that we can distinguish what triggers the disconnection and help us manage our Apps behavior to it.

With this said I have one experience that I want to share as this may also frustrate some people who are counting connected users and having a problem that when their app have multi workers (Web Garden) they app somehow always trigger OnDisconnect even if the user is still connect. So I want to share this findings on how to properly address it.

  1. Make sure that the App is using a Backplane to manage connection on your hub so that the connections are shared on all threads/servers. I use SQLServer.
  2. Make sure to use the Database on counting your list of connection and tagging who is who. Because in memory List even its static will not be shared on a different server (obviously).
  3. Make sure to trigger disconnection action when the OnDisconnect is called with the stopCalled is equal to true.

Let me highlight what is stopCalled is equal to true means.

  1. It returns true if the method on the connection to close is trigger
  2. It returns true if the browser is called
  3. It returns false if the timeout has been met

Hope this instructions will help you manage your site as it help me on our projects.

God Bless!

Thanks,
Thomie

RockRMS : Free Relationship Management System

RockRMS

I have been searching for an Open Source management of our church that is also created on ASP .Net. I have found RockRMS. RockRMS is created using ASP .Net Web Form that is so dynamic and Scale-able it can accommodate both external website and internal operation of a Church. There is even a dedicated hosting that will maintain your system and is hosted on Windows Azure.

Its source code is also available on GitHub so others can contribute to the pipeline. You may visit their website at https://www.rockrms.com/

Here are some of the screenshots provided on their website:

 

God Bless!

Thanks,
Thomie

Pechkin – NET Wrapper for WkHtmlToPdf

Pechkin

.NET Wrapper for WkHtmlToPdf DLL, library that uses Webkit engine to convert HTML pages to PDF. It is now available on Nuget for easy installation on your Visual Studio Solution/Projects.

How easy is it to use? Just install it via Nuget and add a reference on your code then use either one of the following:

byte[] pdfBuf = new SimplePechkin(new GlobalConfig()).Convert("<html><body><h1>Hello world!</h1></body></html>");

and

// create global configuration object
GlobalConfig gc = new GlobalConfig();

// set it up using fluent notation
gc.SetMargins(new Margins(300, 100, 150, 100))
  .SetDocumentTitle("Test document")
  .SetPaperSize(PaperKind.Letter);
//... etc

// create converter
IPechkin pechkin = new SynchronizedPechkin(gc);

// subscribe to events
pechkin.Begin += OnBegin;
pechkin.Error += OnError;
pechkin.Warning += OnWarning;
pechkin.PhaseChanged += OnPhase;
pechkin.ProgressChanged += OnProgress;
pechkin.Finished += OnFinished;

// create document configuration object
ObjectConfig oc = new ObjectConfig();

// and set it up using fluent notation too
oc.SetCreateExternalLinks(false)
  .SetFallbackEncoding(Encoding.ASCII)
  .SetLoadImages(false)
  .SetPageUri("http://google.com");
//... etc

// convert document
byte[] pdfBuf = pechkin.Convert(oc);

 

God Bless!

Thanks,
Thomie

Opencast, Your Free and Open Video Casting!

Hi There,

We are glad to invite you to our first Free service product, OpenCast. OpenCast is an online broadcasting websites that aim to help people broadcast freely and openly. The website is created using ASP.Net MVC, Entity Framework, SignalR, & OpenTok.

 

Feel Free to register now at http://opencast.info

God Bless!

Thanks,
Thomie

Mediafire API for C# + Resharper

 Hi There,

I have been searching on the net of a Mediafire API for C#. I gently saw this API from Google. It has a note that it needs Resharper so I think you need that plugin before you can use it. As for the testing I don’t have any Resharper yet so I can test it myself so I have decided to publish it here so you can use and try it. You may give some feed back of your trying and share it to the world!

Source: http://pastebin.com/Cj1syDss

Mirror Download: Mediafire API C# + Resharper

Thanks,

 

Creating a file to Download dynamically in an https / SSL connection

Hi there, 

Here is a tip when you are programming something that you want your file’s path to be hidden. It’s specially when its under a secure connection or https or SSL connection.

  1. Remember the mime type ea. image/jpg
  2. Remember the file name ea. image.jpg
  3. Remember not to put expiration and no-cache on your header
  4. Remember to open it on another tab or window as much as possible
  5. When you are debugging you can remove the headers so the file won’t be downloaded

Hope this tips can help you specially #3 because your download will fail on lower version of IE.

Thanks,

A potentially dangerous Request.Form value was detected from the client

Have you ever experience the following error in ASP .NET?

A potentially dangerous Request.Form value was detected from the client 

Then you are one like me. Then you should now that one of the values of your elements (<inputs> or <button> or <textarea>) has html elements on it. Example is bellow:

<input type=’text’ name=’content’ value='<script language=”javascript”>alert(“Hello World!”);</script>’/>

Then you should also know that this error is persisting because the values given above might be an XSS attack. If you are sure that you want to accept this type of values on your dabatase you may explicitly remove this validation by adding this tag to your page’s masterpage or 1st line of tag.

validateRequest=”false”

If you are on ASP .NET MVC you can add this to your model, assuming that your model has the content variable.

[AllowHtml]
public string content = String.Empty;

Thanks hope it help you allot. Also if you are not familiar with XSS attacks, I will try to make an article for that so you can create your own script that is hack-able, be able to prevent it, and know what are it’s crons.

God Bless!

IIS Missing ASP .Net 4.0 Pool

Have you’ve been missing some pool in your IIS for your ASP .Net?

The this article entitle IIS Missing ASP .Net 4.0 Pool will help you.

Chances are, you need to install .NET 4 (Which will also take care of a new AppPool for you)

  1. Open your command prompt (Windows + R) and type cmd and press ENTER
    You may need to start this as an administrator if you have UAC enabled.
    To do so, locate the exe (usually you can start typing with Start Menu open), right click and select “Run as Administrator”
  2. Type cd C:\Windows\Microsoft.NET\Framework\v4.0.30319\ and press ENTER.
  3. Type aspnet_regiis.exe -ir and press ENTER again.
    • at this point you will see it begin working on installing .NET’s framework in to IIS for you
  4. Close the DOS prompt, re-open your start menu and right click Computer and select Manage
  5. Expand the left-hand side (Services and Applications) and select Internet Information Services
    • You’ll now have a new applet within the content window exclusively for IIS.
  6. Expand out your computer and locate the Application Pools node, and select it. (You should now see ASP.NET v4.0 listed)
  7. Expand out your Sites node and locate the site you want to modify (select it)
  8. To the right you’ll notice Basic Settings… just below the Edit Site text. Click this, and a new window should appear
  9. Select the .NET 4 AppPool using the Select… button and click ok.
  10. Restart the site, and you should be good-to-go.

(You can repeat steps 7-on for every site you want to apply .NET 4 on as well)

That’s it!

Thanks,
Thomie