Click here to Skip to main content
15,908,931 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I am using claim authentication in my share-point portal and i have create one webpart to show lastlogin time, last failed login time, name, id etc.. everything is coming from request headers, id, name, office code etc is coming fine but login time as well last failed login is coming incorrect, kindly suggest how exactly i can solve it?
I done my small Google search on below mentioned article:
http://msdn.microsoft.com/en-us/library/hh147177%28v=office.14%29.aspx#SPO_RA_ClaimsSequence

but i did not get anything, one more thing i would want to know can i see those request header on _layouts/authenticate.aspx if possible then how?

My Code for refrence:
C#
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.DirectoryServices;
using Microsoft.SharePoint;
using System.Data;
using System.Text;
using System.Globalization;

namespace UC_Welcome.MyVisualWebPart
{
    public partial class MyVisualWebPartUserControl : UserControl
    {



        #region"Public Variables"
        private DirectoryEntry root;
        private DirectorySearcher searcher;

        EmployeeDTO EmployeeDTO = new EmployeeDTO();


        static StringBuilder sb = new StringBuilder();
        static SPListItemCollection itemsProperty = null;

        DataTable dtProperty;
        public string MasterList = "LDAP";

        public static String SERVICE_REQUEST_LDAP_HOST = "";
        public static String SERVICE_REQUEST_LDAP_PORT = "";
        public static String SERVICE_REQUEST_LDAP_USERNAME = "";
        public static String SERVICE_REQUEST_LDAP_PASSWORD = "";//"P@ssw0rd";
        public static String SERVICE_REQUEST_LDAP_BASEDN = "";

        public static String SERVICE_REQUEST_EMP_CPF_NUMBER = "cpfnumber";
        public static String SERVICE_REQUEST_EMP_OFFICE_TYPE = "";
        public static String SERVICE_REQUEST_EMP_OFFICE_CODE = "";
        public static String SERVICE_REQUEST_EMP_SAMACCOUNTNAME = "";
        public static String SERVICE_REQUEST_EMP_OFFICE_PARENTCODE = "";
        public static String SERVICE_REQUEST_EMP_DEPARTMENT = "";

        public static string SiteName = "";
        public static String SQL_CONN = "";
        public static string strddlFilter = "";


        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            string strURL = Context.Request.Url.ToString();
                       
            string[] strNew = strURL.Split('/');
            if (strNew[3].ToString().ToUpper() == "PORTAL")
            {
                SiteName = strNew[0].ToString() + "//" + strNew[2].ToString() + "/" + strNew[3].ToString(); ;
            }
            else
            {
                SiteName = strNew[0].ToString() + "//" + strNew[2].ToString() + "/portal";
            }

             String strUseName = "";
            using (SPSite site = new SPSite(SiteName))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    try
                    {

                        SPUser user = web.CurrentUser;
                        strUseName = user.LoginName;

                       
                        String[] strUserNameSplit = strUseName.Split('\\');
                        if (strUserNameSplit.Length > 1)
                        {
                            strUseName = strUserNameSplit[1];
                        }
                        else if (strUseName.Contains("|"))
                        {
                            strUserNameSplit = strUseName.Split('|');
                            strUseName = strUserNameSplit[strUserNameSplit.Length - 1].ToString().Trim();
                        }
                        else
                        {
                            strUseName = user.Name;
                        }
                        SetProperties(SiteName, MasterList);
                    }
                    catch (Exception ex)
                    { }
                }
            }

            if (strUseName != "" && strUseName != null)
            {

                GetEmployeeDetails(strUseName);
                lblName.Text = strUseName;  //EmployeeDTO.strName;
                lblDesignation.Text = EmployeeDTO.strDesignation;
                lblOfficeCode.Text = EmployeeDTO.strOfficeCode;
                lblOfficeName.Text = EmployeeDTO.strOfficeName;

                lblLastLogonTime.Text = Context.Request.Headers["SM_CLIENT_IP"];
                lblBadPasswordTime.Text = Context.Request.Headers.ToString();
                 if (Context.Request.Headers["LAST_LOGON_TIMESTAMP"] != null)
                {
                    if (Convert.ToString(Context.Request.Headers["LAST_LOGON_TIMESTAMP"]) != "")
                    {
                    long lastLoginTime = Convert.ToInt64(Context.Request.Headers["LAST_LOGON_TIMESTAMP"]); //1342431441;//130270729355460866;// //Convert.ToInt64(EmployeeDTO.strLastLogOn);//1342431441;
                        if (lastLoginTime != 0)
                        {


                            DateTime userLastLogindateTime = new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(lastLoginTime);
                            String strLastLogonTime = userLastLogindateTime.ToLocalTime().ToString("dd MMM yyyy hh:mm:ss tt");
                            //strLastLogonTime = strLastLogonTime + "/" + Convert.ToString(Context.Request.Headers["LAST_LOGON_TIMESTAMP"]);
                            lblLastLogonTime.Text = strLastLogonTime;

                        }
                    }
                }

                  
           
                
                if (Context.Request.Headers["LAST_BAD_PASSWORD_TIME"] != null)
                {
                    if (Convert.ToString(Context.Request.Headers["LAST_BAD_PASSWORD_TIME"]) != "")
                    {
                        long lstFaileddateTimelong = Convert.ToInt64(Context.Request.Headers["LAST_BAD_PASSWORD_TIME"]);// Convert.ToInt64(EmployeeDTO.strBadPasswordTime); //129869035186724791;
                        if (lstFaileddateTimelong != 0)
                        {
                            DateTime humanDateTime = DateTime.FromFileTime(lstFaileddateTimelong);

                            string strBadPasswordTime = humanDateTime.ToLocalTime().ToString("dd MMM yyyy hh:mm:ss tt");

                        }
                    }
                   
               }
                    
               

            }
            else
            {
                lblName.Text = "Not Found";
            }


        }


        public void GetEmployeeDetails(String strcpfNumber)
        {
            Dictionary<string,> searchMap = new Dictionary<string,>();
            //searchMap.Add(LdapConstants.SERVICE_REQUEST_EMP_CPF_NUMBER, "00940828");
            searchMap.Add(SERVICE_REQUEST_EMP_CPF_NUMBER, strcpfNumber);
            searchActiveDirecotryUsers(searchMap);

        }

        public static string getSearchFilter(Dictionary<string,> searchMap)
        {
            //-- objectClass and object category will based on searchType - user or office
            //   if(searchType==ApplicationConstants.s)
            string filter = "(&(objectClass=user)(objectcategory=person)(";
            if (searchMap.Count > 1)
            {
                filter = filter + "|";
            }
            foreach (KeyValuePair<string,> keyValuePair in searchMap)
            {

                filter = filter + " (" + keyValuePair.Key + "=" + keyValuePair.Value + ")";
            }
            filter = filter + ")";
            return filter + ")";



        }

        protected string getOfficeCodeName(String OfficeCode)
        {
            string strOfficeCodeName = "";
            try
            {
                if (searcher == null)
                {
                    searcher = connect();
                }
                searcher.Filter = "(&(objectclass=organizationalunit)(officecode=" + OfficeCode + "))";
                searcher.PropertiesToLoad.Add(SERVICE_REQUEST_EMP_OFFICE_CODE);
                searcher.PropertiesToLoad.Add("ou");
                SearchResultCollection results = searcher.FindAll();
                foreach (SearchResult result in results)
                {
                    ResultPropertyCollection rpc = result.Properties;
                    foreach (string property in rpc.PropertyNames)
                    {
                        foreach (object value in rpc[property])
                        {
                            if ("ou" == property)
                            {
                                strOfficeCodeName = value.ToString();
                                //Added By Pankaj on 10 Feb 2012 
                                strOfficeCodeName = strOfficeCodeName.Replace('/', '-');
                            }

                        }
                    }
                }
                return strOfficeCodeName;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                try
                {
                    disconnect();
                }
                catch (Exception ignore)
                {
                }
            }
            //return officeNamesList;

        }

        protected void SetProperties(string SiteName, string ListName)
        {
            try
            {
                string strURL = SiteName;
                string[] strNew = strURL.Split('/');
                String SiteURL = strNew[0].ToString() + "//" + strNew[2].ToString() + "/" + strNew[3].ToString();

                //CH#1
                using (SPSite site = new SPSite(SiteURL))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        string sourceList = ListName;
                        Microsoft.SharePoint.SPList list = web.Lists[sourceList];
                        //SPListItemCollection items = null;
                        SPQuery query = new SPQuery();
                        query.Query = "<where><eq><fieldref name="Title" /><value type="Text">AD</value></eq></where><orderby><fieldref name="Title" ascending="True" /></orderby>"; // All items at root
                        itemsProperty = list.GetItems(query);



                        if (itemsProperty.Count > 0)
                        {
                            dtProperty = itemsProperty.GetDataTable();


                            SERVICE_REQUEST_LDAP_HOST = Convert.ToString(dtProperty.Rows[0]["HOST"]);
                            SERVICE_REQUEST_LDAP_PORT = Convert.ToString(dtProperty.Rows[0]["PORT"]);
                            SERVICE_REQUEST_LDAP_USERNAME = Convert.ToString(dtProperty.Rows[0]["UID"]);
                            SERVICE_REQUEST_LDAP_PASSWORD = Convert.ToString(dtProperty.Rows[0]["PWD"]);
                            SERVICE_REQUEST_LDAP_BASEDN = Convert.ToString(dtProperty.Rows[0]["BASEDN"]);

                            SERVICE_REQUEST_EMP_CPF_NUMBER = Convert.ToString(dtProperty.Rows[0]["CPFNumber"]);
                            SERVICE_REQUEST_EMP_OFFICE_CODE = Convert.ToString(dtProperty.Rows[0]["OfficeCode"]);


                            //dtProperty = itemsProperty.GetDataTable();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        public string searchActiveDirecotryUsers(Dictionary<string,> searchMap)
        {
            string connectionString = SERVICE_REQUEST_LDAP_HOST + ":" + SERVICE_REQUEST_LDAP_PORT + "/" + SERVICE_REQUEST_LDAP_BASEDN;
            DirectoryEntry root = new DirectoryEntry(connectionString, SERVICE_REQUEST_LDAP_USERNAME, SERVICE_REQUEST_LDAP_PASSWORD);
            DirectorySearcher searcher = new DirectorySearcher(root);
            string filter = getSearchFilter(searchMap);
            searcher.Filter = filter;
            searcher.PropertiesToLoad.Add("officecode");
            searcher.PropertiesToLoad.Add("displayname");
            searcher.PropertiesToLoad.Add("designation");

           
            searcher.PropertiesToLoad.Add("lastlogon");
            searcher.PropertiesToLoad.Add("badpasswordtime");
            


            SearchResultCollection results = searcher.FindAll();
            foreach (SearchResult result in results)
            {
                //
                ResultPropertyCollection rpc = result.Properties;
                foreach (string property in rpc.PropertyNames)
                {
                    foreach (object value in rpc[property])
                    {
                        if ("officecode" == property)
                        {
                            EmployeeDTO.strOfficeCode = value.ToString();
                            EmployeeDTO.strOfficeName = getOfficeCodeName(EmployeeDTO.strOfficeCode);
                        }
                        else if ("displayname" == property)
                        {
                            EmployeeDTO.strName = value.ToString();
                        }
                        else if ("designation" == property)
                        {
                            EmployeeDTO.strDesignation = value.ToString();
                        }
                        else if ("lastlogon" == property)
                        {
                            EmployeeDTO.strLastLogOn = value.ToString();
                        }
                        else if ("badpasswordtime" == property)
                        {
                            EmployeeDTO.strBadPasswordTime = value.ToString();
                        }
                    }
                }
            }
            return "";

        }

        private DirectorySearcher connect()
        {
            string connectionString = SERVICE_REQUEST_LDAP_HOST + ":" + SERVICE_REQUEST_LDAP_PORT + "/" + SERVICE_REQUEST_LDAP_BASEDN;
            root = new DirectoryEntry(connectionString, SERVICE_REQUEST_LDAP_USERNAME, SERVICE_REQUEST_LDAP_PASSWORD);
            searcher = new DirectorySearcher(root);
            return searcher;
        }

        private void disconnect()
        {
            if (root != null)
            {
                root.Close();
            }
        }
    }
    #region"Classes"



    public class EmployeeDTO
    {
        string _strcpfNo, _strName, _strDesignation, _strOfficeCode, _strOfficeName, _strDepartment,_strLastLogOn,_strBadPasswordTime;

        public string strcpfNo
        {
            get { return _strcpfNo; }
            set { _strcpfNo = value; }
        }

        public string strName
        {
            get { return _strName; }
            set { _strName = value; }
        }

        public string strDesignation
        {
            get { return _strDesignation; }
            set { _strDesignation = value; }
        }

        public string strOfficeCode
        {
            get { return _strOfficeCode; }
            set { _strOfficeCode = value; }
        }

        public string strOfficeName
        {
            get { return _strOfficeName; }
            set { _strOfficeName = value; }
        }

        public string strDepartment
        {
            get { return _strDepartment; }
            set { _strDepartment = value; }
        }


        public string strLastLogOn
        {
            get { return _strLastLogOn; }
            set { _strLastLogOn = value; }
        }

        public string strBadPasswordTime
        {
            get { return _strBadPasswordTime; }
            set { _strBadPasswordTime = value; }
        }

    }




    #endregion
}
Posted
Updated 31-Oct-13 23:19pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900