Tuesday, September 9, 2014

Binding Pie Chart Asp .Net with Dictionary?


Step1: Making Dictionary

Dictionary<string,int> dic=new Dictionary<string,int>();

dic.Add("Done",10);
dic.Add("Pending",2);
dic.Add("InProgress",4);

Step2: Binding

    Chart1.DataSource = dic;
    foreach (KeyValuePair<string, int> progress in data)
    {
    Chart1.Series[0].Points.AddXY(progress.Key, progress.Value);
    }
    Chart1.DataBind();


Tuesday, September 2, 2014

How to use AJAX calendar extender and Limit it to not select Future Dates ?



Step1:  Add Ajax Toolkit

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>

Step2: Add Calendar Extender along with Control ID

<asp:CalendarExtender ID="CalendarExtender" runat="server" TargetControlID="txtDateTime"></asp:CalendarExtender>

<asp:TextBox ID="txtDateTime" runat="server" AutoPostBack="True"></asp:TextBox>

Step3: Disable Future Dates

  protected void Page_Load(object sender, EventArgs e)
    {

        CalendarExtender.EndDate = DateTime.Now.AddDays(-1);
    }

A generic Method for conversion List to DataTable ?


public void function()
{
List<Students> o = ctx.Students.ToList();
   DataTable MainData = ToDataTable<Students>(o);

}        


   //convert any list to datatable
    public DataTable ToDataTable<T>(List<T> items)
    {
        DataTable dataTable = new DataTable(typeof(T).Name);
        //Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
        {
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name);
        }
        foreach (T item in items)
        {
            var values = new object[Props.Length];
            for (int i = 0; i < Props.Length; i++)
            {
                //inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
            }
            dataTable.Rows.Add(values);
        }
        //put a breakpoint here and check datatable
        return dataTable;
    }

Monday, September 1, 2014

How to Query to Active Directory using C#?



Step1: Add this code in Web.Config File.

   <add key="LDAPPath" value="LDAP://DC=MicrosoftCorp,DC=Microsoft,DC=com"/>

   <add key="LDAPPathEurope" value="LDAP://DC=MicrosoftEurope,DC=Microsoft,DC=com"/>

<add key="LDAPPathAmerica" value="LDAP://DC=MicrosoftAmerica,DC=Microsoft,DC=com"/>


<identity impersonate="true" userName="microsoft\abcdef" password="********"/>


* Identity must be declared in Web.Config because on localhost there is no need but after publishing application on Server the Active Directory need a user account to access the information of user. 
* In yellow Marks you can put your Company domain Name. 
* If your company has multiple Search directories you have to mention all like MicrosoftCorp, MicrosoftEurope,MicrosoftAmerica.


Step2: Create a Class for Active Directory Properties.

 public class ADProperties
    {
        public const String OBJECTCLASS = "objectClass";
        public const String CONTAINERNAME = "cn";
        public const String LASTNAME = "sn";
        public const String COUNTRYNOTATION = "c";
        public const String CITY = "l";
        public const String STATE = "st";
        public const String TITLE = "title";
        public const String POSTALCODE = "postalCode";
        public const String PHYSICALDELIVERYOFFICENAME = "physicalDeliveryOfficeName";
        public const String FIRSTNAME = "givenName";
        public const String MIDDLENAME = "initials";
        public const String DISTINGUISHEDNAME = "distinguishedName";
        public const String INSTANCETYPE = "instanceType";
        public const String WHENCREATED = "whenCreated";
        public const String WHENCHANGED = "whenChanged";
        public const String DISPLAYNAME = "displayName";
        public const String USNCREATED = "uSNCreated";
        public const String MEMBEROF = "memberOf";
        public const String USNCHANGED = "uSNChanged";
        public const String COUNTRY = "co";
        public const String DEPARTMENT = "department";
        public const String COMPANY = "company";
        public const String PROXYADDRESSES = "proxyAddresses";
        public const String STREETADDRESS = "streetAddress";
        public const String DIRECTREPORTS = "directReports";
        public const String NAME = "name";
        public const String OBJECTGUID = "objectGUID";
        public const String USERACCOUNTCONTROL = "userAccountControl";
        public const String BADPWDCOUNT = "badPwdCount";
        public const String CODEPAGE = "codePage";
        public const String COUNTRYCODE = "countryCode";
        public const String BADPASSWORDTIME = "badPasswordTime";
        public const String LASTLOGOFF = "lastLogoff";
        public const String LASTLOGON = "lastLogon";
        public const String PWDLASTSET = "pwdLastSet";
        public const String PRIMARYGROUPID = "primaryGroupID";
        public const String OBJECTSID = "objectSid";
        public const String ADMINCOUNT = "adminCount";
        public const String ACCOUNTEXPIRES = "accountExpires";
        public const String LOGONCOUNT = "logonCount";
        public const String LOGINNAME = "sAMAccountName";
        public const String SAMACCOUNTTYPE = "sAMAccountType";
        public const String SHOWINADDRESSBOOK = "showInAddressBook";
        public const String LEGACYEXCHANGEDN = "legacyExchangeDN";
        public const String USERPRINCIPALNAME = "userPrincipalName";
        public const String EXTENSION = "ipPhone";
        public const String SERVICEPRINCIPALNAME = "servicePrincipalName";
        public const String OBJECTCATEGORY = "objectCategory";
        public const String DSCOREPROPAGATIONDATA = "dSCorePropagationData";
        public const String LASTLOGONTIMESTAMP = "lastLogonTimestamp";
        public const String EMAILADDRESS = "mail";
        public const String MANAGER = "manager";
        public const String MOBILE = "mobile";
        public const String PAGER = "pager";
        public const String FAX = "facsimileTelephoneNumber";
        public const String HOMEPHONE = "homePhone";
        public const String MSEXCHUSERACCOUNTCONTROL = "msExchUserAccountControl";
        public const String MDBUSEDEFAULTS = "mDBUseDefaults";
        public const String MSEXCHMAILBOXSECURITYDESCRIPTOR = "msExchMailboxSecurityDescriptor";
        public const String HOMEMDB = "homeMDB";
        public const String MSEXCHPOLICIESINCLUDED = "msExchPoliciesIncluded";
        public const String HOMEMTA = "homeMTA";
        public const String MSEXCHRECIPIENTTYPEDETAILS = "msExchRecipientTypeDetails";
        public const String MAILNICKNAME = "mailNickname";
        public const String MSEXCHHOMESERVERNAME = "msExchHomeServerName";
        public const String MSEXCHVERSION = "msExchVersion";
        public const String MSEXCHRECIPIENTDISPLAYTYPE = "msExchRecipientDisplayType";
        public const String MSEXCHMAILBOXGUID = "msExchMailboxGuid";
        public const String NTSECURITYDESCRIPTOR = "nTSecurityDescriptor";
        public const String PHONE = "telephoneNumber";
        public const String EMPLOYEEID = "extensionAttribute2";
        public const String MANAGEDBY = "manager";
       

    }

* This contains almost all properties of Active Directory.

Step3: Create a Class for Active Directory Details which will Store all information.

  public class ADUserDetail
    {
        private String _firstName;
        private String _middleName;
        private String _lastName;
        private String _loginName;
        private String _loginNameWithDomain;
        private String _streetAddress;
        private String _city;
        private String _state;
        private String _postalCode;
        private String _country;
        private String _homePhone;
        private String _extension;
        private String _mobile;
        private String _fax;
        private String _emailAddress;
        private String _title;
        private String _company;
        private String _manager;
        private String _managerName;
        private String _department;
        private String _displayName;      
        private String _telephone;
        private String _employeeId;
        private String _name;
        private String _managedBy;
        public DirectoryEntry  de { get; set; }

        public String Name
        {
            get { return _name; }
        }

        public String EmployeeId
        {
            get { return _employeeId; }
        }

        public String Telephone
        {
            get { return _telephone; }
        }

        public String DisplayName
        {
            get { return _displayName; }
        }

        public String Department
        {
            get { return _department; }
        }

        public String FirstName
        {
            get { return _firstName; }
        }

        public String MiddleName
        {
            get { return _middleName; }
        }

        public String LastName
        {
            get { return _lastName; }
        }

        public String LoginName
        {
            get { return _loginName; }
        }

        public String LoginNameWithDomain
        {
            get { return _loginNameWithDomain; }
        }

        public String StreetAddress
        {
            get { return _streetAddress; }
        }

        public String City
        {
            get { return _city; }
        }

        public String State
        {
            get { return _state; }
        }

        public String PostalCode
        {
            get { return _postalCode; }
        }

        public String Country
        {
            get { return _country; }
        }

        public String HomePhone
        {
            get { return _homePhone; }
        }

        public String Extension
        {
            get { return _extension; }
        }

        public String Mobile
        {
            get { return _mobile; }
        }

        public String Fax
        {
            get { return _fax; }
        }

        public String EmailAddress
        {
            get { return _emailAddress; }
        }

        public String Title
        {
            get { return _title; }
        }

        public String Company
        {
            get { return _company; }
        }

        public ADUserDetail Manager
        {
            get
            {
                if (!String.IsNullOrEmpty(_managerName))
                {
                    ActiveDirectoryFunctions ad = new ActiveDirectoryFunctions();
                    return ad.GetUserByFullName(_managerName,de);
                }
                return null;
            }
        }

        public String ManagerName
        {
            get { return _managerName; }
        }
        public String ManagedBy
        {
            get { return _managedBy; }
        }
        public ADUserDetail(DirectoryEntry directoryUser)
        {

            String domainAddress;
            String domainName;
            _managedBy = GetProperty(directoryUser, ADProperties.MANAGEDBY);
            _name = GetProperty(directoryUser, ADProperties.NAME);
            _employeeId = GetProperty(directoryUser, ADProperties.EMPLOYEEID);
            _telephone = GetProperty(directoryUser, ADProperties.PHONE);
            _firstName = GetProperty(directoryUser, ADProperties.FIRSTNAME);
            _middleName = GetProperty(directoryUser, ADProperties.MIDDLENAME);
            _lastName = GetProperty(directoryUser, ADProperties.LASTNAME);
            _loginName = GetProperty(directoryUser, ADProperties.LOGINNAME);
            String userPrincipalName = GetProperty(directoryUser, ADProperties.USERPRINCIPALNAME);
            if (!string.IsNullOrEmpty(userPrincipalName))
            {
                domainAddress = userPrincipalName.Split('@')[1];
            }
            else
            {
                domainAddress = String.Empty;
            }

            if (!string.IsNullOrEmpty(domainAddress))
            {
                domainName = domainAddress.Split('.').First();
            }
            else
            {
                domainName = String.Empty;
            }
            _loginNameWithDomain = String.Format(@"{0}\{1}", domainName, _loginName);
            _streetAddress = GetProperty(directoryUser, ADProperties.STREETADDRESS);
            _city = GetProperty(directoryUser, ADProperties.CITY);
            _state = GetProperty(directoryUser, ADProperties.STATE);
            _postalCode = GetProperty(directoryUser, ADProperties.POSTALCODE);
            _country = GetProperty(directoryUser, ADProperties.COUNTRY);
            _company = GetProperty(directoryUser, ADProperties.COMPANY);
            _department = GetProperty(directoryUser, ADProperties.DEPARTMENT);
            _homePhone = GetProperty(directoryUser, ADProperties.HOMEPHONE);
            _extension = GetProperty(directoryUser, ADProperties.EXTENSION);
            _mobile = GetProperty(directoryUser, ADProperties.MOBILE);
            _fax = GetProperty(directoryUser, ADProperties.FAX);
            _emailAddress = GetProperty(directoryUser, ADProperties.EMAILADDRESS);
            _title = GetProperty(directoryUser, ADProperties.TITLE);
            _manager = GetProperty(directoryUser, ADProperties.MANAGER);
            
            _displayName = GetProperty(directoryUser, myADProperties.DISPLAYNAME);
            if (!String.IsNullOrEmpty(_manager))
            {
               // String[] managerArray = _manager.Split(',');
                _managerName=_manager.Replace(@"\,","");
              int i=  _managerName.IndexOf(',');
              _managerName = _managerName.Remove(i);
              _managerName = _managerName.Replace("CN=", "");
                
            }
        }

        private static String GetProperty(DirectoryEntry userDetail, String propertyName)
        {
            if (userDetail.Properties.Contains(propertyName))
            {
                return userDetail.Properties[propertyName][0].ToString();
            }
            else
            {
                return string.Empty;
            }
        }

        public static ADUserDetail GetUser(DirectoryEntry directoryUser)
        {
            return new ADUserDetail(directoryUser);
        }

    }

Step4: Create a Class for Active Directory Functions.

public class ActiveDirectoryFunctions
   {

public ADUserDetail GetUserByFullName(String userName,DirectoryEntry SearchRoot)
        {
            try
            {
             
            DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot);
            directorySearch.Filter = "(&(objectClass=user)(cn=" + userName + "))";
            SearchResult results = directorySearch.FindOne();

                if (results != null)
                {
                    DirectoryEntry user = new DirectoryEntry(results.Path);
                    return myADUserDetail.GetUser(user);
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }
       public ADUserDetail GetUserByLoginName(String userName, DirectoryEntry SearchRoot)
        {
            try
            {
              
                DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot);

                directorySearch.Filter = "(&(objectClass=user)(SAMAccountName=" + userName + "))";
                SearchResult results = directorySearch.FindOne();

                if (results != null)
                {
                    DirectoryEntry user = new DirectoryEntry(results.Path);
                    return ADUserDetail.GetUser(user);
                }
                return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

       //get userdetail by emailaddress

       public ADUserDetail GetUserbyEmail(String email, DirectoryEntry SearchRoot)
        {
            try
            {
               
                DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot);
                directorySearch.Filter = "(&(objectClass=user)(mail=" + email + "))";
                SearchResult results = directorySearch.FindOne();

                if (results != null)
                {
                    DirectoryEntry user = new DirectoryEntry(results.Path);
                    return ADUserDetail.GetUser(user);
                }
                return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }


        /// <summary>
        /// This function will take a DL or Group name and return list of users
        /// </summary>
        /// <param name="groupName"></param>
        /// <returns></returns>

       public List<ADUserDetail> GetUserFromGroup(String groupName, DirectoryEntry SearchRoot)
        {
            List<ADUserDetail> userlist = new List<myADUserDetail>();
            try
            {
               
                DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot);
                directorySearch.Filter = "(&(objectClass=group)(SAMAccountName=" + groupName + "))";
                SearchResult results = directorySearch.FindOne();
                if (results != null)
                {

                    DirectoryEntry deGroup = new DirectoryEntry(results.Path);
                    System.DirectoryServices.PropertyCollection pColl = deGroup.Properties;
                    int count = pColl["member"].Count;


                    for (int i = 0; i < count; i++)
                    {
                        string respath = results.Path;
                        string[] pathnavigate = respath.Split("CN".ToCharArray());
                        respath = pathnavigate[0];
                        string objpath = pColl["member"][i].ToString();
                        string path = respath + objpath;


                        DirectoryEntry user = new DirectoryEntry(path);
                        myADUserDetail userobj = myADUserDetail.GetUser(user);
                        userlist.Add(userobj);
                        user.Close();
                    }
                }
                return userlist;
            }
            catch (Exception ex)
            {
                return userlist;
            }

        } 
        #region Get user with First Name

       public List<ADUserDetail> GetUsersByFirstName(string fName, DirectoryEntry SearchRoot)
        {

            //UserProfile user;
            List<ADUserDetail> userlist = new List<myADUserDetail>();
            string filter = "";

           
            DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot);
            directorySearch.Asynchronous = true;
            directorySearch.CacheResults = true;
                        filter = string.Format("(givenName={0}*", fName);
            //            filter = "(&(objectClass=user)(objectCategory=person)(givenName="+fName+ "*))";


            directorySearch.Filter = filter;
           
            SearchResultCollection userCollection = directorySearch.FindAll();
            foreach (SearchResult users in userCollection)
            {
                DirectoryEntry userEntry = new DirectoryEntry(users.Path);
                ADUserDetail userInfo =  myADUserDetail.GetUser(userEntry);

                                userlist.Add(userInfo);
               
            }
               
                directorySearch.Filter = "(&(objectClass=group)(SAMAccountName=" +fName  + "*))";
                SearchResultCollection results = directorySearch.FindAll();
                if (results != null)
                {

                    foreach (SearchResult r in results)
                    {
                        DirectoryEntry deGroup = new DirectoryEntry(r.Path);
                      
                        ADUserDetail agroup = myADUserDetail.GetUser(deGroup);
                        userlist.Add(agroup);
                    }

                }
            return userlist;             
        }

        #endregion    
        #region AddUserToGroup
       //public bool AddUserToGroup(string userlogin, string groupName, DirectoryEntry SearchRoot)
       // {
       //     try
       //     {
                              
       //         ADManager admanager = new ADManager(LDAPDomain, LDAPUser, LDAPPassword);
       //         admanager.AddUserToGroup(userlogin, groupName);
       //         return true;
       //     }
       //     catch (Exception ex)
       //     {
       //         return false;
       //     }
       // }
        #endregion

        #region RemoveUserToGroup
        //public  bool RemoveUserToGroup(string userlogin, string groupName)
        //{
        //    try
        //    {
        //        _directoryEntry = null;
        //        ADManager admanager = new ADManager("xxx", LDAPUser, LDAPPassword);
        //        admanager.RemoveUserFromGroup(userlogin, groupName);
        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        return false;
        //    }
        //}
        #endregion

    }


Step5: Call Active Directory Functions.

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ActiveDirectoryHelper obj = new ActiveDirectoryHelper();

        string ldap = ConfigurationManager.AppSettings["LDAPPath"];
        string ldapEu = ConfigurationManager.AppSettings["LDAPPathEurope"];

             
        //getting user and domain
        string u = System.Web.HttpContext.Current.User.Identity.Name;
        int domainIndex = u.IndexOf(@"\");
        string domain = u.Remove(domainIndex);
        DirectoryEntry de;

       
        if (domain.ToLower()=="microsoftcorp")
        {
            de = new DirectoryEntry(ldap);
        }
        else
        {
            de = new DirectoryEntry(ldapEu);
        }
       
        
            string s = u.Substring(domainIndex + 1);
          
            myADUserDetail person = obj.GetUserByLoginName(s,de);
            string co = person.Company;
            string name = person.DisplayName;
            string dep = person.Department;
            string ss = person.ManagerName;
            string ssdsss = person.ManagerName;
            string sssss = person.EmployeeId;

       
            lblUserName.Text = "WellCome: " + name + "<br/>" + co + " | " + dep ;
     
          

        }


    }

Secure you Asp .NET by Web.config & Global.ascx?

Add to Global.ascx protected void Application_BeginRequest(object sender,EventArgs e)     {         //to remove x frame         Resp...