none
Webservice Modification to add more logic to get the Managers details

    Question

  • It is SharePoint 2007 environment. I cant recreate other webservice/solution as this web-service is currenly be used in Infopath. i need to amend this web-service only.
    This web service uses SharePoint Object Model to get the current user details.
    I am not a developer so any input will be much appreciated.
    I need to add logic under web method GetExecutiveGeneralManagerDetails() the logic should be if you are Regional employee then your EGM Will be the person contains words "Regional General Manager" in their title.
    Any Help will be much appraciated. Thanks in Advance.

    Code :

    using System;
    using System.Web;
    using System.Web.Services;
    using System.Web.Services.Protocols;
    using System.DirectoryServices;
    using Microsoft.SharePoint;
    using System.Xml;
    using System.Configuration;    
    using System.IO;
    using System.Security.AccessControl;
    using System.Security.Principal;
    using System.Diagnostics;    
    [WebService(Namespace = "ORG.MOSS")]

    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

    public class UserActiveDirectory : System.Web.Services.WebService

    {
    private static object _lockObject = new object();

    private const string c_strADUserName = "Domain\\oracleimport";
    private const string c_strADPassword = "**********";

    public UserActiveDirectory()
    {
       
    //Uncomment the following line if using designed components
       
    //InitializeComponent();
    }

    [WebMethod]
    public XmlNode GetManagerDetails()
    {
       
    XmlDocument xmlDocument = new XmlDocument();
       
    XmlElement xmlPropertyData = xmlDocument.CreateElement("PropertyData");
       
    XmlElement xmlDisplayName = xmlDocument.CreateElement("DisplayName");
       
    XmlElement xmlUsername = xmlDocument.CreateElement("Username");

       
    try
       
    {
           
    if (!IsRegionalEmployee())
           
    {
               
    using (SPSite objSite = SPContext.Current.Site)
               
    {
                   
    using (SPWeb objWeb = objSite.OpenWeb())
                   
    {
                       
    SPUser objCurrentUser = objWeb.CurrentUser;
                       
    string strAccountUsername = objCurrentUser.LoginName.Substring(objCurrentUser.LoginName.IndexOf(@"\") + 1);

                        _trace("
    GetManagerDetails", "Processing non-regional employee {0} [{1}]", objCurrentUser.Name, strAccountUsername);

                        using (DirectoryEntry objDirectoryEntry = RetrieveActiveDirectoryUserByAccountName(strAccountUsername))
                        {
                            if (objDirectoryEntry != null)
                            {
                                if (objDirectoryEntry.Properties["
    manager"].Value != null)
                                {
                                    _trace("
    GetManagerDetails", "  Manager property: {0}", objDirectoryEntry.Properties["manager"].Value);
                                    using (DirectoryEntry objManagerEntry = RetrieveActiveDirectoryUserByAccountPath(objDirectoryEntry.Properties["
    manager"].Value.ToString()))
                                    {
                                        if (objManagerEntry != null)
                                        {
                                            _trace("
    GetManagerDetails", "  Found manager: {0}", objManagerEntry.Properties["sAMAccountName"].Value.ToString());
                                            xmlDisplayName.InnerText = objManagerEntry.Properties["
    displayName"].Value.ToString();
                                            xmlUsername.InnerText = objManagerEntry.Properties["
    sAMAccountName"].Value.ToString();
                                            objManagerEntry.Close();
                                        }
                                    }
                                }
                                objDirectoryEntry.Close();
                            }
                        }
                        objWeb.Close();
                    }
                    objSite.Close();
                }
            }
        }
        catch (Exception ex)
        {
            _trace("
    GetManagerDetails", "!!Exception: {0}{1}{2}" + ex.Message + ex.GetType().Name, Environment.NewLine, ex.StackTrace);
            throw;
        }

        xmlDocument.AppendChild(xmlPropertyData);
        xmlPropertyData.AppendChild(xmlDisplayName);
        xmlPropertyData.AppendChild(xmlUsername);

        return xmlDocument;
    }

    [WebMethod]
    public XmlNode GetExecutiveGeneralManagerDetails()
    {
        XmlDocument xmlDocument = new XmlDocument();
        XmlElement xmlPropertyData = xmlDocument.CreateElement("
    PropertyData");
        XmlElement xmlDisplayName = xmlDocument.CreateElement("
    DisplayName");
        XmlElement xmlUsername = xmlDocument.CreateElement("
    Username");

        bool blnContinueLoop = true;

        using (SPSite objSite = SPContext.Current.Site)
        {
            using (SPWeb objWeb = objSite.OpenWeb())
            {
                string userAc = objWeb.CurrentUser.LoginName.Split('\\')[1];

                using (DirectoryEntry deUser = RetrieveActiveDirectoryUserByAccountName(userAc))
                {
                    if (deUser != null)
                    {
                        bool isUserCorpComms = ( _prop(deUser, "
    department") == "Corporate Communications" );

                        DirectoryEntry tmp = deUser; //placeholder for recursing up the org chart
                        string mgrTitle = _getManagerTitle(tmp);

                        //if your manager is "
    Managing Director" then they are the EGM
                        if (mgrTitle == "
    Managing Director")
                        {
                            DirectoryEntry tmpMgr = _getManager(tmp);
                            xmlDisplayName.InnerText = _prop(tmpMgr, "
    displayName");
                            xmlUsername.InnerText = _prop(tmpMgr, "
    sAMAccountName");
                        }
                        else
                        {
                            while (mgrTitle != "
    Managing Director" )
                            {
                                tmp = _getManager(tmp);
                                if (tmp == null) break;
                                mgrTitle = _getManagerTitle(tmp);
                            }

                            xmlDisplayName.InnerText = _prop(tmp, "
    displayName");
                            xmlUsername.InnerText = _prop(tmp, "
    sAMAccountName");
                        }
                        deUser.Close();
                    }
                }
                objWeb.Close();
            }
            objSite.Close();
        }

        xmlDocument.AppendChild(xmlPropertyData);
        xmlPropertyData.AppendChild(xmlDisplayName);
        xmlPropertyData.AppendChild(xmlUsername);

        return xmlDocument;
    }

    [WebMethod]
    public bool IsRegionalEmployee()
    {
        bool blnResult = false;

        using (SPSite objSite = SPContext.Current.Site)
        {
            using (SPWeb objWeb = objSite.OpenWeb())
            {
                SPUser objCurrentUser = objWeb.CurrentUser;
                string strAccountUsername = objCurrentUser.LoginName.Substring(objCurrentUser.LoginName.IndexOf(@"
    \") + 1);

                using (DirectoryEntry objDirectoryEntry = RetrieveActiveDirectoryUserByAccountName(strAccountUsername))
                {
                    if (objDirectoryEntry != null)
                    {
                        if (objDirectoryEntry.Properties["
    physicalDeliveryOfficeName"].Value != null && objDirectoryEntry.Properties["physicalDeliveryOfficeName"].Value.ToString() != "TA Sydney Office" &&
                            objDirectoryEntry.Properties["
    department"].Value != null && (objDirectoryEntry.Properties["department"].Value.ToString().StartsWith("International (Eastern)") || objDirectoryEntry.Properties["department"].Value.ToString().StartsWith("International (Western)")))
                        {
                            _trace("
    IsRegionalEmployee", "Found regional employee {0} [{1}]", objCurrentUser.Name, strAccountUsername);
                            blnResult = true;
                        }

                        objDirectoryEntry.Close();
                    }
                }
                objWeb.Close();
            }
            objSite.Close();
        }
        return blnResult;
    }

    private DirectoryEntry RetrieveActiveDirectoryUserByAccountName(string strAccountUsername)
    {
        DirectoryEntry objDirectoryEntry = null;

        using (DirectoryEntry objDirectoryRoot = new DirectoryEntry("
    LDAP://office.local.pri/DC=office,DC=local,DC=pri", c_strADUserName, c_strADPassword))
       
    {
           
    using (DirectorySearcher objDirectorySearcher = new DirectorySearcher(objDirectoryRoot))
           
    {
                objDirectorySearcher
    .Filter = "(&(objectClass=user)(objectCategory=person)(sAMAccountName=" + strAccountUsername + "))";
                objDirectorySearcher
    .SearchScope = SearchScope.Subtree;
                objDirectorySearcher
    .PageSize = 1000;
               
    SearchResultCollection colSearchResults = objDirectorySearcher.FindAll();

               
    foreach (SearchResult objSearchResult in colSearchResults)
               
    {
                    objDirectoryEntry
    = objSearchResult.GetDirectoryEntry();
                   
    break;
               
    }
           
    }
            objDirectoryRoot
    .Close();
       
    }
       
    return objDirectoryEntry;
    }

    private DirectoryEntry RetrieveActiveDirectoryUserByAccountPath(string strAccountPath)
    {
       
    DirectoryEntry objDirectoryEntry = new DirectoryEntry("LDAP://" + strAccountPath.Replace("/", @"\2f"), c_strADUserName, c_strADPassword);

       
    return objDirectoryEntry;
    }

    #region Helpers
    private bool _isTracing
    {
       
    get
       
    {
           
    bool ret = false;
           
    bool.TryParse(ConfigurationSettings.AppSettings["UserActiveDirectoryWebservice.Tracing.Enabled"] ?? "False", out ret);
           
    return ret;
       
    }
    }
    private string _tracePath
    {
       
    get { return ConfigurationManager.AppSettings["UserActiveDirectoryWebservice.Tracing.Path"] ?? @"C:\InetPub\LogFiles\UserActiveDirectoryWebservice"; }
    }
    private void _ensureTracePath()
    {
       
    lock (_lockObject)
       
    {
           
    WindowsImpersonationContext wctx = null;
           
    try
           
    {
                wctx
    = WindowsIdentity.Impersonate(IntPtr.Zero); //app pool identity

               
    if (Application["TA.MOSS.UserActiveDirectory::_ensureTracePath()"] != null)
                   
    return;

               
    if (!Directory.Exists(_tracePath))
               
    {
                   
    //adding access for everyone here didn't work too well
                   
    //better to inherit the access through the normal file system ACL inheritance mechanisms
                   
    //DirectorySecurity acl = new DirectorySecurity();
                   
    //acl.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.Write, AccessControlType.Allow)); //Everyone
                   
    Directory.CreateDirectory(_tracePath); //, acl);
               
    }
               
    /* - ACL update disabled; see note above
                else
                {
                    DirectorySecurity acl = Directory.GetAccessControl(_tracePath);

                    //get ACLs
                    AuthorizationRuleCollection rules = acl.GetAccessRules(true, true, typeof(SecurityIdentifier));
                    bool aclOK = false;
                    foreach (FileSystemAccessRule rule in rules)
                    {
                        if (((SecurityIdentifier)rule.IdentityReference).IsWellKnown(WellKnownSidType.WorldSid))
                        {
                            if ((rule.FileSystemRights & FileSystemRights.Write) != 0)
                            {
                                aclOK = true;
                                break;
                            }
                        }
                    }

                    if (!aclOK)
                    {
                        acl.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.Write, AccessControlType.Allow)); //Everyone
                        Directory.SetAccessControl(_tracePath, acl);
                    }
                }
                */


               
    //write an application-wide marker so we don't do this every time
               
    Application["TA.MOSS.UserActiveDirectory::_ensureTracePath()"] = true;
           
    }
           
    catch (Exception ex)
           
    {
               
    try
               
    {
                   
    if (!EventLog.SourceExists("UserActiveDirectory Web Service"))
                       
    EventLog.CreateEventSource("UserActiveDirectory Web Service", "Application");

                   
    EventLog.WriteEntry("UserActiveDirectory Web Service", "Failed to ensure Trace Path was accessible to the log writer [" + _tracePath + "]" + Environment.NewLine + "Tracing is disabled." + Environment.NewLine + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace, EventLogEntryType.Error);
               
    }
               
    catch { } //if that failed there's really nothing left to do
           
    }
           
    finally
           
    {
               
    if (wctx != null)
               
    {
                    wctx
    .Undo();
                    wctx
    .Dispose();
               
    }
           
    }
       
    }
    }
    private void _trace(string method, string message, params object[] args)
    {
       
    if (!_isTracing) return;

       
    //this should only happen once
        _ensureTracePath
    ();

       
    //one file per Hour
       
    WindowsImpersonationContext wctx = null;
       
    try
       
    {
            wctx
    = WindowsIdentity.Impersonate(IntPtr.Zero);
           
    lock (_lockObject)
           
    {
               
    string traceFileName = Path.Combine(_tracePath, "UserActiveDirectory Log " + DateTime.Now.ToString("yyyyMMdd-HH") + "00.log");
               
    File.AppendAllText(traceFileName, DateTime.Now.ToString("yyyyMMdd HHmmss") + "\t" + method + "\t" + String.Format(message, args) + Environment.NewLine);
           
    }
       
    }
       
    catch { } //a tracing fail must not fail the execution of the main thread
       
    finally
       
    {
           
    if (wctx != null)
           
    {
                wctx
    .Undo();
                wctx
    .Dispose();
           
    }
       
    }
    }
    private string _prop(DirectoryEntry de, string propertyName)
    {
       
    //does not return null, only empty string to make logic clearer
       
    //there is no difference to us in this case between null & empty string
       
    if (de==null || de.Properties[propertyName] == null || de.Properties[propertyName].Value == null) return String.Empty;
       
    else return de.Properties[propertyName].Value.ToString();
    }
    private DirectoryEntry _getManager(DirectoryEntry user)
    {
       
    string mgrAc = _prop(user, "manager");
       
    if (mgrAc == "") return null;

       
    return RetrieveActiveDirectoryUserByAccountPath(mgrAc);
    }
    private string _getManagerTitle(DirectoryEntry user)
    {
       
    string mgrAc = _prop(user, "manager");
       
    if (mgrAc == "") return "";

       
    string mgrTitle = "";
       
    using (DirectoryEntry deMgr = RetrieveActiveDirectoryUserByAccountPath(mgrAc))
       
    {
            mgrTitle
    = _prop(deMgr, "title");
            deMgr
    .Close();
       
    }

       
    return mgrTitle;
    }
    #endregion

    }


    Aniket

    Thursday, February 23, 2012 1:39 AM

Answers

All replies