Friday, May 11, 2012

Retrieve user’s photo from Active directory in ASP.NET

This article describes how to get the user’s photo from Active directory and display in to an aspx page. I’m creating a new ASP web application and the users photo will be displayed in Default.aspx page.  To do this you need to include 
System.DirectoryServices,  
System.DirectoryServices.AccountManagement           

assemblies to the project references.


Include following using statements in Default.aspx.cs page:


using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
 
The following method gets the users photo from the AD and return as a Bitmap.

public static Bitmap GetThumbnailPhoto(string userName)
        {
            using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain))
            {
                using (UserPrincipal userPrincipal = new UserPrincipal(principalContext))
                {
                    userPrincipal.SamAccountName = userName;
                    using (PrincipalSearcher principalSearcher = new PrincipalSearcher())
                    {
                        principalSearcher.QueryFilter = userPrincipal;
                        Principal principal = principalSearcher.FindOne();
                        if (principal!=null)
                        {
                            DirectoryEntry directoryEntry = (DirectoryEntry)principal.GetUnderlyingObject();
                            PropertyValueCollection collection = directoryEntry.Properties["thumbnailPhoto"];

                            if (collection.Value!=null && collection.Value is byte[])
                            {
                                byte[] thumbnailInBytes = (byte[])collection.Value;
                                return new Bitmap(new MemoryStream(thumbnailInBytes));
                            }                           
                        }
                        return null;
                    }
                }
            }
        }

thumbnailPhoto is the property returns the user’s thumbnail photo from the AD.


The above method gives the user's photo as bitmap. Next we have to display the image in the Default.aspx page. Add asp image control to the page.


<asp:Image ID="imbThumbnail" runat="server" />


At the Page_Load event add the image to the image control.


protected void Page_Load(object sender, EventArgs e)
        {
            Bitmap thumbnail = GetThumbnailPhoto("t-ictdev05");

            String saveImagePath = Server.MapPath("~/Images/image.jpg");
            thumbnail.Save(saveImagePath, ImageFormat.Jpeg);
            imbThumbnail.ImageUrl = "~/Images/image.jpg";
        }
 
To set the ImageUrl, I am saving the image to Images/image.jpg and displaying the photo.

 

Wednesday, May 2, 2012

XSL Transformation


XSL is stand for Extensible Style sheet Language, and it is the style sheet language for xml documents. The CSS is used to style html documents and XSL is used to style the xml documents.
The XSL transformation process is like this. Let’s say you have an xml file named ‘books.xml’. When you open this file in a browser it will show the information in xml format. Using XSL transformation you have the chance to style the xml. So that it will display in an easy to readable format. The books.xml file can be displayed in a table with heading, columns, etc..
Normal way of doing this is, we need an xsl file (books.xsl) which is for style the xml file. And we are referring the xsl file from the xml file as follows.

 <?xml version="1.0" encoding="ISO-8859-1"?>               
 <?xml-stylesheet type="text/xsl" href="books.xsl"?>  

 Now the books.xml will display in a browser in nice format.
The above method is ok if the xml file is under our control. What happens if the xml is taken from the web, like reading an rss feed from the web? These situations we can’t add the reference to the xml file because the xml is going to change time to time.
The .Net provides the solution. XslCompiledTransform Class is used to transforms XML data using an XSLT style sheet. It is available in System.Xml.Xsl namespace. The following code describes how to do XSL Transformation in .Net.

public static string TransformXML(string sFeedURL, string sXSLTFile)
        {
            string result = string.Empty;
            string host = ConfigurationManager.AppSettings["Host"].ToString();
            int port = Convert.ToInt16(ConfigurationManager.AppSettings["Port"].ToString());
            string username = ConfigurationManager.AppSettings["Username"].ToString();
            string password = ConfigurationManager.AppSettings["Password"].ToString();

            try
            {
                XslCompiledTransform xslFile = new XslCompiledTransform();
                xslFile.Load(sXSLTFile);


                System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(sFeedURL);

                webRequest.Timeout = 5000;

                WebProxy proxy = new WebProxy(host, port);
                webRequest.Proxy = proxy;
                webRequest.Proxy.Credentials = new NetworkCredential(username, password);
                webRequest.Credentials = new NetworkCredential(username, password);

                using (System.Net.HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse())
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(webResponse.GetResponseStream()))
                    {
                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.Load(new System.IO.StringReader(sr.ReadToEnd()));
                        XPathDocument xPathDoc = new XPathDocument(new XmlNodeReader(xmlDoc));

                        StringWriter writer = new StringWriter();
                        xslFile.Transform(xPathDoc, null, writer);
                        result += writer.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return result;
        }

 
sFeedURL is the url of rss feed, that is a xml taken from the web and sXSLTFile is the xsl file path. This will return some html code, which can be used to display information on a web page. For example if there is a div with Id = P1, P1.InnerHtml = result will gives the formatted output in the browser.