Saturday, January 8, 2011

Creating Custom Sections and Encrypting the Section in web.config

Creating Custom Sections and Encryption in web.config
Web application development need different kind of customization,one of the common scenario is creation custom sections in web.config.For the ease of development .net framework supports different set of custom sections.There are mainly three kind custom section.
1. SingleTagSectionHandler
This will help to add a custom single xml tag to web.config. Define your custom section in < configSections >.

< configSections >
< section name="UserInfo"
type="System.Configuration.NameValueSectionHandler"/>

</ configSections >

Add your custom single tag section. For example I would like keep a user credential information.(Below we will talk how to encrypt)

< UserInfo UserName ="Myuser" Password ="****" Domain ="MyDomain"/>

Read the data from code

(System.Collections.IDictionary) System.Configuration.ConfigurationSettings.GetConfig("UserInfo")



2. NameValueSectionHandler This will help you to keep key value pairs of data.It will be usefull to keep the data in custom section so you can define /name you section properly in web.config.

For example going to create new section for supported extensions and supported special servers .

Define a custom section group

< section name ="SupportedExtensions"
type ="System.Configuration.NameValueSectionHandler"/>


< section name ="SupportedServer"
type ="System.Configuration.NameValueSectionHandler"/>


< SupportedExtensions >
< add key ="Image" value =".jpg,png"/>
< add key ="Video" value ="flv,wmv"/>
</ SupportedExtensions >


< SupportedServer >
< add key ="AppServer" value ="server1,server2"/>
< add key ="ImageServer" value ="server4,server5"/>
</ SupportedServer >


Read the data from code

(System.Collections.NameValueCollection) System.Configuration.ConfigurationSettings.GetConfig("SupportedServer")

3. DictionarySectionHandler
This will help you to keep key value pairs of data in nested sections. It will be use full to keep the data in custom section so you can define /name you section properly in web.config. You could read the data as a hash table.
For example create section for the application .
Define a custom section
< section name ="MyApplicatinSection"
type ="System.Configuration.DictionarySectionHandler"/>

< MyApplicatinSection >
< SupportedExtensions >
< add key ="Image" value =".jpg,png"/>
< add key ="Video" value ="flv,wmv"/>
</ SupportedExtensions >

< SupportedServer >
< add key ="AppServer" value ="server1,server2"/>
< add key ="ImageServer" value ="server4,server5"/>
</ SupportedServer >

< MyApplicatinSection &gt;

Read the data from code

(System.Collections.Hashtable) System.Configuration.ConfigurationSettings.GetConfig("MyApplicatinSection")

Encrypting the web.config
Once we define the data in config we need to encrypt the data to keep the information secured. There are easy way to encrypt the sections.
1. Creat web.config entry
< section name ="UserInfoSection"
type ="System.Configuration.SingleTagSectionHandler"/>

< UserInfoSection username ="value1" password ="value2" domain ="value3"/>
2. Encrypt the section
Go to visual studio command prompt and run or go to C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
aspnet_regiis –pef UserInfoSection

3. Read the value from code

MyUserData = (System.Collections.IDictionary)
System.Configuration.ConfigurationSettings.GetConfig(" UserInfoSection ");
Also read http://msdn.microsoft.com/en-us/library/zhhddkxy.aspx

Sunday, January 2, 2011

Active Directory (AD) - C# .NET

How to handle Active Directory in C#
.Net Framework provides namespaces named System.DirectoryServices and System.DirectoryServices.ActiveDirectory to handle all the interaction with AD,"Sounds exciting right!".This two namespces contains rich collection of classes , which provides n number of functionality to manage active directory.

Which classes allow us to perform basic functionality?

DirectoryEntry : Represcent a node in Active Directory Domain Service Hierarchy.There is four overloads available for creating DirectoryEntry class's instance.
1. DirectoryEntry()
2. DirectoryEntry(string path) - Here parameter path means The path at which to
bind the System.DirectoryServices.DirectoryEntry. ex:- new DirectoryEntry
("LDAP://OU=PROJECTS,DC=MyDomain")
3. DirectoryEntry(string path, string username, string password) - here user
should be a AD user. Ex: new DirectoryEntry
("LDAP://OU=PROJECTS,DC=MyDomain",username,password)
4. DirectoryEntry(string path, string username, string password,
System.DirectoryServices.AuthenticationTypes authenticationType) - Here we have
to mention the authentication type .This overload is usefull when we are using
currently logged in /applcation identity as AD authentication user.

DirectorySearcher : This class is used to perform queries against Active Directory.This has 8 overloads for creating object here i am specifying only two.
1. DirectorySearcher() - simple creating instance.
2. System.DirectoryServices.DirectorySearcher.DirectorySearcher
(System.DirectoryServices.DirectoryEntry) - Passing Directory entry object, so
that will be the search root node for directory seracher.

SearchResult : Represcent a node in the active directory.This can be treated as directory entry object.

How to Build LDAP Path ?
I saw many people are blindely get a copy from google and pasting it in their code without knowing about it.Have a look at the sample LDAP path

"LDAP://,ou=Marketing,dc=TestDomain"
LDAP: provider (case sensitive)
ou - Organizational Unit
dc - Domain Component
cn - Common Name
Directory Service Providers
Windows NT version 5.0, Windows 2000, or Windows XP - WinNT://path
Lightweight Directory Access Protocol (LDAP - LDAP://path
Novell NetWare Directory Service - NDS://path
Novell Netware 3.x - NWCOMPAT://path
Internet Information Services (IIS) - IIS://

So in a LDAP path you have to specify the Directory service provider,Specify the domain component and the organizational unit which you are looking for.Try to be more specific if you are not looking for all users in LDAP.

Following sample code reads all the user from Active Directory

Add System.DirectoryServices reference
using System.DirectoryServices;

public void GetUsersList()
{
DirectoryEntry dntry = null;
DirectorySearcher dschr = null;

//Creating Directory entry object with current application context user
dntry = new DirectoryEntry("Ldap path", null, null, AuthenticationTypes.Secure);

// In the above line we are pasing user name and pasword as null so it will take
//current user credentials
//Create a searcher for this directory entry.
dschr = new DirectorySearcher(dntry);

// Next i am going to specify the filter
dschr.Filter = "(&(objectCategory=person)(objectClass=user))";

//Now i am going to specify which are the properties need to be loaded
//By specifying property we dont need to load unnecessary properties in AD.
dschr.PropertiesToLoad.Add("mail");
dschr.PropertiesToLoad.Add("name");
dschr.PropertiesToLoad.Add("userPrincipalName");

//Loading result into search result collection
SearchResultCollection sResult = dschr.FindAll();

//Loop through the collection
foreach (SearchResult sRlt in sResult)
{
//Get the property value
string sMailAddr = sRlt.Properties["mail"][0].ToString();
}
}

File Upload Ajax Control

It's quite common nowadays using ajax in asp.net development.In recent times many people came to me and complain that file upload is not working.

For example you are using ajax tab control in asp.net page so the controls in your page will come inside the update panel.In that case there will be problem because we will normally set triggers for partial update,this will cause the file upload to fail.

In a normal scenario people will set the ajax update panel like below.

asp:updatepanel id="uppanel1" updatemode="Conditional" runat="server"
//here the we will place the control need to be updated
triggers
asp:asyncpostbacktrigger eventname="SelectedIndexChanged" controlid="ddlState"
triggers
asp:updatepanel
asp:asyncpostbacktrigger


Actually we can set two kind of triggers, one is AsyncPostBackTrigger and Postbacktrigger.One will cause partial update and other will raise normal full post back.

here the trick on tab button click i will fire asynchronus postback trigger . in submit button click i will fire postback trigger.The reason i think already you know, File upload requires full post back if we are doing partial updates then it will not work. This issue will come only when we placed all the controls including submit button also within the update panel.


Hope this will help people to stop cracking the heads
asp:asyncpostbacktrigger eventname="SelectedIndexChanged" controlid="ddlState"
asp:asyncpostbacktrigger eventname="Click" controlid="btnData"
asp:asyncpostbacktrigger eventname="Click" controlid="btnHistory"
asp:postbacktrigger controlid="btnSubmit"
asp:postbacktrigger
asp:asyncpostbacktrigger
asp:asyncpostbacktrigger
asp:asyncpostbacktrigger

asp:updatepanel id="uppanel1" updatemode="Conditional" runat="server"
asp:updatepanel