Tuesday, July 9, 2013

Integrate Lync presence indicator with sharepoint 2013 custom web parts

As we know, we can easily intergrate lync features with sharepoint. in this post i am going to show how to integrate lync presence indicator with custom sharepoint web parts.

before that you have to make sure that Lync is already enabled in your sharepoint environment.if not, first installed it.

now follow these steps :

1. Create web part (In this post i am going to create normal web aprt not a visual web part) in visual studio and name it as "UserIndicator" then copy and paste this script into CreateChildControls() method

// get the current user

string[] CurrentUser = SPContext.Current.Web.CurrentUser.LoginName.ToString().Split(new string[] { "\\", "%5C" }, StringSplitOptions.RemoveEmptyEntries);
string UrlUserWithDomain = HttpContext.Current.Request.QueryString["accountname"];
string[] UrlUser;
string userName = string.Empty;
if (UrlUserWithDomain != null)
{
  UrlUser = UrlUserWithDomain.Split(new string[] { "\\", "%5C" }, StringSplitOptions.RemoveEmptyEntries);
  userName = UrlUser[UrlUser.Length - 1];
}
else
{
  userName = CurrentUser[CurrentUser.Length - 1];
}

// format the page

string pageFormat = string.Empty;
pageFormat += string.Format(@"
<div id = ""indicator"" class=""myProfile-user-presence""  onmouseover=""ShowOOUI()"" onmouseout=""HideOOUI()"">
    <div id = ""indicatorImg""></div>                       
</div>
                    
<script type=""text/javascript"" src='http://code.jquery.com/jquery-latest.js'></script>
<object id=""application/x-sharepoint-uc"" type=""application/x-sharepoint-uc"" width=""0"" height=""0"" style=""visibility: hidden;""></object>
                
<script type=""text/javascript"">
    jQuery.support.cors = true;
    var nameCtrl = null;
    var sipUri = ""{0}"".concat(""@virtusa.com""); 

    $(document).ready(function () {{
       try {{
         if (window.ActiveXObject) {{
           nameCtrl = new ActiveXObject(""Name.NameCtrl"");
         }} else {{
           nameCtrl = CreateNPApiOnWindowsPlugin(""application/x-sharepoint-uc"");
         }}

         if (nameCtrl.PresenceEnabled) {{
            nameCtrl.OnStatusChange = onStatusChange;
            nameCtrl.GetStatus(sipUri, ""1"");
         }}
                                
         }}
         catch (ex) {{ }}
         }}); 

function getLyncPresenceString(status) {{
  switch (status) {{
    case 0:
      return ""{1}"".concat('_layouts/images/IMNON.PNG');
      break;
    case 1:
      return ""{1}"".concat('_layouts/images/IMNOFF.PNG');
      break;
    case 2:                                
      return ""{1}"".concat('_layouts/images/IMNAWAY.PNG');
      break;
    case 3:
      return ""{1}"".concat('_layouts/images/IMNBUSY.PNG');
      break;
    case 4: 
      return ""{1}"".concat('_layouts/images/IMNAWAY.PNG');
      break;
    case 9:
      return ""{1}"".concat('_layouts/images/IMNDND.PNG');
      break;
    default:
      return ""{1}"".concat('_layouts/images/IMNAWAY.PNG');
  }}
}}
  
function onStatusChange(name, status, id) {{
 alert(name + "", "" + status + "", "" + id);
 $('#indicatorImg').replaceWith(
  '<img id=""StatusImg""  alt=""' + getLyncPresenceString(status) + '""src=""' + getLyncPresenceString(status) + '""/>'                                   
                                );
}}

function ShowOOUI() {{
   nameCtrl.ShowOOUI(sipUri, 0, 15, 15);
}}

function HideOOUI() {{
   nameCtrl.HideOOUI();
}}

</script>                 
", userName, GetSPServerUrl());

//Add the controls to page

Controls.Add(new LiteralControl(pageFormat));

// insert other support methods to return required URLs .

private string GetImageUrl()
{
     // read it from config file
     return "../_layouts/15/images/ProfileContactCard/";
}

private string GetSPServerUrl()
{
    // read it from config file
    return "Sharepoint MySiteUrl";
}

Note :
Replace GetImageUrl() , GetSPServerUrl() with actual values

finally deploy to sharepoint site using visual studio and insert that webpart to your page. 
If you want to deploy using wsp file manually , check this post

Wednesday, July 3, 2013

Export User profiles into Excel Sheet Using User Profile Service

In this post i am going to show how to export user profiles of sharepoint 2010/2013 to Excel sheet. normally we export User profiles for analysis purpose or comparison purpose.

If you want to retrieve all the User profiles from Sharepoint 2010 or 2013 server, you can use profileManager (ServerObjectModel) or UserprofileService(.asmx service). Here i am going to use .asmx service.

1. Create a Console project in Visual Studio and named it as ExportUPSToExcel

2. Add user profile service as Web Service Reference and name it as ProdUPS


3. Refer the service in .cs file
    using ExportUPSToExcel.ProdUPS;

4. Copy and paste following code into program.cs (or create new .cs file , in my case it is ExportUPS.cs  ) file

using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;

namespace ExportUPSToExcel
{
    public class ExportUPS
    {
        static void Main(string[] args)
        {
            ExportToExcel();
        }

        static void ExportToExcel()
        {
                Console.WriteLine("Accessing User profile Service.......");

                StringBuilder sb = new StringBuilder();
            
                //Creating headers in the first row

                //Loop through all the user profiles in the sharepoint database
                Console.WriteLine("Starting to Connect.......");

                ProdUPS.UserProfileService ups = new VplusProdUPS.UserProfileService();
                System.Net.NetworkCredential nc = new System.Net.NetworkCredential("adminUserName", "AdminPassword", "DomainName");
                ups.PreAuthenticate = false;
                ups.Credentials = nc;
                Console.WriteLine("Starting ........");
                long count = ups.GetUserProfileCount();
                int inteIndex = 0;
                VplusProdUPS.PropertyData[] properties; 
            
                GetUserProfileByIndexResult  p = ups.GetUserProfileByIndex(-1); // gets the first profile on the list
                int k = 0;
                while (p.UserProfile != null)
                { 
                    // do what you want with the User Profile
                    properties = p.UserProfile;
                    Console.WriteLine("Processing: " + k.ToString());
                    // update the columns name - first row
                    if (k == 0)
                    {
                        for (int i = 0; i < properties.Length; i++)
                        {                         
                                sb.Append(properties[i].Name + ",");
                            
                            
                        }
                        sb.Append("\r\n");
                    }
                    // update the values into appropriate columns
                    for (int m = 0; m < properties.Length; m++)
                    {
                        StringBuilder value = new StringBuilder();                      
                            //continue;
                            if (properties[m].Values.Length == 0)
                            {
                                value.Append("" + ",");
                            }
                            else    // if the field has more than one value
                            {
                                for (int j = 0; j < properties[m].Values.Length; j++)
                                {
                                    if (properties[m].Values[j].Value != null)
                                    {
                                        if (j == 0)
                                        {
                                            value.Append(properties[m].Values[j].Value);
                                        }
                                        else
                                        {
                                            value.Append("&" + properties[m].Values[j].Value);
                                        }
                                    }
                                    else
                                    {
                                        if (j == 0)
                                        {
                                            value.Append("");
                                        }
                                        else
                                        {
                                            value.Append("&" + "");
                                        }
                                    }

                                }
                                value.Append(",");
                            }
                            sb.Append(value);                       
                    }
                    sb.Append("\r\n");
                    // get the next value for index
                    int nextValue;
                    bool res = int.TryParse(p.NextValue, out nextValue);
                    p = ups.GetUserProfileByIndex(nextValue);
                    k++;
                }

                Console.WriteLine("Finished profile retrieval");
                Console.WriteLine("Writing to csv file");
                Console.WriteLine("Total User Profiles :" + count.ToString());

                //Write the long string to a csv file and save it to the desktop

                TextWriter tw = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + "UPS2010Final1.csv");
                tw.WriteLine(sb.ToString());
                tw.Close();

        }
    }
}

Replace "adminUserName", "AdminPassword", "DomainName" with appropriate values. but this account should have enough permission to read and retrieve the user profiles from Sharepoint server.

5. Run the application and check the console for progress status

6. finally open the excel sheet and check the fields.


Notes :
  • If any fields has value with comma(",") replace with other characters before write to excel since it creates new columns in excel.
  • Don't use For loop for iteration. sometimes it will give duplicate entries. More details refer this article