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"

</ 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

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
3. DirectoryEntry(string path, string username, string password) - here user
should be a AD user. Ex: new DirectoryEntry
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: 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.

//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 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 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
asp:asyncpostbacktrigger eventname="SelectedIndexChanged" controlid="ddlState"

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:updatepanel id="uppanel1" updatemode="Conditional" runat="server"

Wednesday, November 3, 2010

How to Get Current User Name

All the developers might have coded atleast once for finding the current context User

Windows Application




Web Application




Tuesday, June 29, 2010

Binary to String Conversion in C#

Converting binary to different format is quiet common scenario for developers.Its just two line of code that will do the magic , but when time matter love search in google so if this blog help someone really happy for that.
Binary to String

System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
string str = enc.GetString(MyByteArray);
if you want to make sure that there is no data loss then use Base64 Encoding

Base64 Encoding :- converts binary data to plain text using 64 case-sensitive, printable ASCII characters: A-Z, a-z, 0-9, plus sign (+) and forward slash (/), and may be terminated with 0-2 "padding" characters represented by the equal sign (=).

when you are working with picture it will be good to use Base64 conversion so you could make sure that there is no data lose

XDocument or XElement with XmlNamespace

Loading or parsing xml with namspaces are common in development scenarios.When we work with Xdocument and XElement there is no direct way to pass the namespace. Let see how we can work with namspace.

Step1 Create a NameTable

NameTable nameTable = new NameTable();

Step2 Create Namespace Manager
XmlNamespaceManager nameSpaceManager = new XmlNamespaceManager(nameTable );
Step3 Add the Namespace or Ignore It
nameSpaceManager.AddNamespace("p", "office.server.policy");
nameSpaceManager.AddNamespace("log4net", "urn:ignore");

Step4 Create a ParserContext
XmlParserContext parserContext = new XmlParserContext(null, nameSpaceManager,
null, XmlSpace.None);
Step5 Create a XmlTextReader
XmlTextReader txtReader = new XmlTextReader("Strin XML", XmlNodeType.Element,

Step6 Load the XML
XElement elem = XElement.Load(txtReader);

For Example we have a Log4net xml and we need to parse it

<log4net:event logger="TestingTransmitter.Program"
<log4net:message>Log entry 103</log4net:message>
<log4net:data name="log4net:HostName" value="machine" />

Following code will load the xml without error like "an undeclared namespace"

NameTable nameTable = new NameTable();
XmlNamespaceManager nameSpaceManager
= new XmlNamespaceManager(nameTable );
nameSpaceManager.AddNamespace("log4net", "urn:ignore");
parserContext = new XmlParserContext(null, nameSpaceManager,
XmlTextReader txtReader = new XmlTextReader("Strin XML",
parserContext );
XElement elem =

Thursday, June 24, 2010

Object reference not set to an instance of an object at System.Linq.Enumerable.WhereListIterator`1.MoveNext()

Linq query are one of the favourite among the developers, sometimes people get following error in the Linq Query and became clueless.Error will look like following

Object reference not set to an instance of an object at System.Linq.Enumerable.WhereListIterator`1.MoveNext()

For Example we have a query like following
cars = from car in Vehicle.Cars
where car.Make.Contains("BMW")
select car;
we then enumerate through the cars like
foreach (var myCar in cars)
the code starts blowing up in the enumeration with a error Object reference not set to an instance of an object at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
At first instance we may wonder why this is not working looks like the code has no issue. If we look at the query closely we can see the where condition "car.Make.Contains("BMW") " can blow up if the Make is null. So we found the issue next we need to change the query like following
cars = from car in Vehicle.Cars
where ((car.Make != null) && (car.Make.Contains("BMW")))
select car;

Now we are good to go.Stop Googling !!!
Shyju Mohan