[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Unable to retrieve AD login ASP.net

Posted on 2012-08-20
1
Medium Priority
?
249 Views
Last Modified: 2012-11-22
Hi,

I've got the following code. When running the code in development on my local PC the username shows correctly. When I upload it to the IIS server it shows "Unkown Error", "Configuration Error". This is a piece of code from a previous collegue who has left the company now i'm afraid. I'm running on IIS 7.5.

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Web.Configuration;
using System.Xml;
using System.Text;
using System.Globalization;

namespace PromptedInspConfig
{
    public partial class Site : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Header.DataBind();
            Menu1.DataSource = Server.MapPath("./SiteMenu.xml");
            Menu1.DataBind();
        }

        private User user;
        public User LocalUser { get { return user; } set { user = value; } }
        public Dictionary<string, User> users = new Dictionary<string, User>();

        public List<Menu> menus = new List<Menu>();

        public User FindUser(string username)
        {
            if (string.IsNullOrEmpty(username)) return null;
            if (users.ContainsKey(username)) return users[username];

            try
            {
                string ldap = WebConfigurationManager.AppSettings["LDAP"];
                DirectorySearcher searcher = new DirectorySearcher(new DirectoryEntry(ldap), string.Format("(&(objectClass=user)(sAMAccountName={0}))", username));
                searcher.PropertiesToLoad.Add("sAMAccountName");
                searcher.PropertiesToLoad.Add("givenName");
                searcher.PropertiesToLoad.Add("sn");
                searcher.PropertiesToLoad.Add("userPrincipalName");
                searcher.PropertiesToLoad.Add("mail");
                searcher.PropertiesToLoad.Add("telephoneNumber");
                searcher.PropertiesToLoad.Add("distinguishedName");
                searcher.PropertiesToLoad.Add("memberOf");

                SearchResult result = searcher.FindOne();
                if (result != null)
                {
                    User user = new User();
                    user.Username = username;
                    if (result.Properties.Contains("givenName")) user.Forename = result.Properties["givenName"][0] as string;
                    if (result.Properties.Contains("sn")) user.Surname = result.Properties["sn"][0] as string;
                    if (result.Properties.Contains("userPrincipalName")) user.Principal = result.Properties["userPrincipalName"][0] as string;
                    if (result.Properties.Contains("mail")) user.Email = result.Properties["mail"][0] as string;
                    if (result.Properties.Contains("telephoneNumber")) user.Telephone = result.Properties["telephoneNumber"][0] as string;
                    if (result.Properties.Contains("distinguishedName")) user.DistinguishedName = result.Properties["distinguishedName"][0] as string;
                    if (result.Properties.Contains("memberOf"))
                    {
                        foreach (object o in result.Properties["memberOf"])
                        {
                            user.MemberOf.Add((string)o);
                        }
                    }

                    users.Add(username, user);
                    return user;
                }
                return null;
            }
            catch (Exception ex) { return null; }
        }

        public List<User> ListUsers(string ou)
        {
            if (string.IsNullOrEmpty(ou)) return new List<User>();

            try
            {
                string ldap = WebConfigurationManager.AppSettings["LDAP"];
                DirectorySearcher searcher = new DirectorySearcher(new DirectoryEntry(ldap), string.Format("(&(objectClass=user)(ou:dn:={0}))", ou));
                searcher.PropertiesToLoad.Add("sAMAccountName");
                searcher.PropertiesToLoad.Add("givenName");
                searcher.PropertiesToLoad.Add("sn");
                searcher.PropertiesToLoad.Add("userPrincipalName");
                searcher.PropertiesToLoad.Add("mail");
                searcher.PropertiesToLoad.Add("telephoneNumber");

                SearchResultCollection results = searcher.FindAll();
                List<User> list = new List<User>();
                if (results.Count > 0)
                {
                    foreach (SearchResult result in results)
                    {
                        User user = new User();
                        if (result.Properties.Contains("sAMAccountName")) user.Username = result.Properties["sAMAccountName"][0] as string;
                        if (result.Properties.Contains("givenName")) user.Forename = result.Properties["givenName"][0] as string;
                        if (result.Properties.Contains("sn")) user.Surname = result.Properties["sn"][0] as string;
                        if (result.Properties.Contains("userPrincipalName")) user.Principal = result.Properties["userPrincipalName"][0] as string;
                        if (result.Properties.Contains("mail")) user.Email = result.Properties["mail"][0] as string;
                        if (result.Properties.Contains("telephoneNumber")) user.Telephone = result.Properties["telephoneNumber"][0] as string;

                        list.Add(user);
                    }
                }
                return list;
            }
            catch (Exception ex) { return new List<User>(); }
        }

        public User FindUser()
        {
            if (Context.Items.Contains("x-localuser-obj")) return (User)Context.Items["x-localuser-obj"];

            string username = Request.LogonUserIdentity.Name;
            if (string.IsNullOrEmpty(username)) return null;

            if (username.IndexOf('\\') > -1) username = username.Substring(username.IndexOf('\\') + 1);
            User local = FindUser(username);
            if (local != null) Context.Items.Add("x-localuser-obj", local);
            return local;
        }

        public string GetDateInformation()
        {
            DateTime now = DateTime.Now;

            StringBuilder builder = new StringBuilder();
            builder.Append(CultureInfo.CurrentCulture.Calendar.GetDayOfWeek(now).ToString());

            string suf = "th";
            switch (now.Day)
            {
                case 1: { suf = "st"; break; }
                case 2: { suf = "nd"; break; }
                case 3: { suf = "rd"; break; }
                case 21: { suf = "st"; break; }
                case 22: { suf = "nd"; break; }
                case 23: { suf = "rd"; break; }
                case 31: { suf = "st"; break; }
            }

            builder.AppendFormat(" {0}{1}", now.Day, suf);
            builder.AppendFormat(" {0} {1}", now.ToString("MMMM"), now.Year);

            return builder.ToString();
        }

        public string GetWeekInformation()
        {
            return string.Format("Week {0}", CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday));
        }

        
        protected override void OnInit(EventArgs e)
        {
            LocalUser = FindUser();
            if (LocalUser == null)
            {
                LocalUser = new User();
                LocalUser.Forename = "Unknown";
                LocalUser.Surname = "User";
                LocalUser.Username = "Configuration Error";
            }

            //GetMenu();

            base.OnInit(e);
        }
    }
}

Open in new window


Many Thanks
Lee
0
Comment
Question by:Codingitup
1 Comment
 
LVL 5

Accepted Solution

by:
kevinhigg earned 2000 total points
ID: 38314542
Has this ever ran successfully in the prod site that you're deploying to?  This may be configuration related to the site; do you have Windows auth enabled, and are the clients and server in the same domain?  Here are a couple of links that may be helpful:

http://technet.microsoft.com/en-us/library/cc754628(v=ws.10).aspx

http://msdn.microsoft.com/en-us/library/system.web.httprequest.logonuseridentity.aspx

Best of luck!
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
Screencast - Getting to Know the Pipeline
Suggested Courses

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question