Search code examples
c#siplyncucma

Retrieve Lync contact from a phone number in an UCMA application


I have a C# managed Application that runs on a Lync 2013 Server and uses MSPL. I route every call from MSPL to the application and handle it there. Lync to Lync calls work fine and their to Header is in the form sip:user@domain.com. But when a call from outside the network (non-lync like mobile phone etc.) to the workphone of a Lyncuser is started, the Uri is like sip:+12341234@domain.com;user=phone (sip:[workphone]@domain). Passing this string to the Presence Retrieval function does not work.

var sips = new string[] { phone }; // The "To" number
presenceService.BeginPresenceQuery(sips, categories, null, null, null);

This always returns an empty result. How can I first retrieve the user associated with the phone number to get its presence?


Solution

  • I solved it this way:

    public static UserObject FindContactBySip(string sip)
    {
        return UserList.FirstOrDefault(u => u.HasSip(sip));
    }
    
    private static void InitFindUsersInAD()
    {
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
        var user = new UserPrincipal(ctx);
        user.Name = "*";
        var searcher = new PrincipalSearcher(user);
        var result = searcher.FindAll();
    
        var sipList = new List<string>();
        UserList = new List<UserObject>();
    
        foreach (var res in result)
        {
            var underlying = (DirectoryEntry)res.GetUnderlyingObject();
            string email = string.Empty, phone = string.Empty, policies = string.Empty;
    
            foreach (var keyval in underlying.Properties.Values)
            {
                var kv = keyval as System.DirectoryServices.PropertyValueCollection;
                if (kv != null && kv.Value is string)
                {
                    if (kv.PropertyName.Equals("msRTCSIP-PrimaryUserAddress"))
                    {
                        email = (kv.Value ?? string.Empty).ToString();
                    }
                    else if (kv.PropertyName.Equals("msRTCSIP-Line"))
                    {
                        phone = (kv.Value ?? string.Empty).ToString();
                    }
                    else if (kv.PropertyName.Equals("msRTCSIP-UserPolicies"))
                    {
                        policies = (kv.Value ?? string.Empty).ToString();
                    }
                }
            }
    
            if (!string.IsNullOrEmpty(phone) && !string.IsNullOrEmpty(email))
            {
                var userobj = new UserObject(email, phone, policies);
                UserList.Add(userobj);
            }
        }
    }
    

    First I initialize the UserList (List // Custom class) from the AD. Then I call FindContactBySip and check if the provided SIP equals the Email or Phone of the User.