Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

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();
}
}

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

WindowsIdentity.GetCurrent().Name


Environment.UserName

System.Windows.Forms.SystemInformation.UserName

Web Application

HttpContext.Current.User
WindowsIdentity.GetCurrent().Name

SharePoint

SPContext.Current.User

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 (=).

Convert.ToBase64String(myByteArray);
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
Adding
nameSpaceManager.AddNamespace("p", "office.server.policy");
Ignoring
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,
parserContext);

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"
timestamp="2009-08-02T17:50:18.928+01:00"
level="ERROR"
thread="9"
domain="TestingTransmitter.vshost.exe"
username="domain\user">
<log4net:message>Log entry 103</log4net:message>
<log4net:properties>
<log4net:data name="log4net:HostName" value="machine" />
</log4net:properties>
</log4net:event>


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");
XmlParserContext
parserContext = new XmlParserContext(null, nameSpaceManager,
null,
XmlSpace.None);
XmlTextReader txtReader = new XmlTextReader("Strin XML",
XmlNodeType.Element,
parserContext );
XElement elem =
XElement.Load(txtReader);