Tuesday, December 10, 2013

Hide sharepoint webparts (Server side code and client side code)

There are two ways to create sharepoint web parts. once is visual webpart another one is normal web part.
Since we all know the difference between those two , there are no point of covering about that here.
But the question is, how can we hide entire web part when the time comes? There are two ways to hide it. one is client side scripting another one is server side coding.

Client side script to hide (Javascript)

Hide the webpart which is create as normal web part in sharepoint

HTML Content of that web part.

      <div id=""div1"">
                    <div id=""div2"" class = ""user-profile-wp-header"">
                       
                    </div>
                    <div id=""div3"">
                        <div id='div4' class=""recom-nav-next"">
                               
                        </div>                                                                 
                    </div>
                    <div id=""div5"">
                   
                    </div>
      </div>

This web part can be hide using javascript. get the outerwrap div id and use it to hide that webpart, or else get the webpart ID using sharepoint designer then use that id instead of outer div Id.

You can use this javascript to hide,
                 $('#div1').hide();

Server side code (C#)

You can hide the entire web part in page load method ( or can be anywhere) if it is a visual web part.

protected void Page_Load(object sender, EventArgs e)
{
                this.ChromeType = PartChromeType.None;
                this.Hidden = true;  
}


Update app config values in run time using C#

Normally we use app.config file to store some config values. as we all know, we can easily read values from app.config using C#. but we rarely update that file in run time. but this is also possible in C#.
here i have explained how to write back(Add new keys or update values of certain key) to app.config file in run time.


/// <summary>
/// Update app config values
/// </summary>
 /// <param name="key">app config key</param>
/// <param name="value">app config value</param>

public static void UpdateAppSettings(string key, string value)
{
          // Give the correct path of an app.config file
          Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (ConfigurationManager.AppSettings[key] == null)
            {
                config.AppSettings.Settings.Add(key, value);
            }
            else
            {
                config.AppSettings.Settings[key].Value = value;
             
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");          
}

Write a main method and call this function to update app.config values. cool :)


Store and Read Cookies using Javascript

When we are working in client side coding (Javascript or normal sharepoint web part projects), we cannot use session variables for storing values. so in that case, we go with cookies. here i have mentioned how to read and store cooikes using javascript.

we can also set the expire time for cookies (in ms).

// expire time = 2 min (120*1000 ms)
storeCookie = function(CookieName,value)
{
    var exdate = new Date();
    var time = exdate.getTime();
    time += 120 * 1000;
    exdate.setTime(time);
    document.cookie = CookieName+ "=" + value + '; expires=' + exdate.toGMTString() ;

};


readCookie = function(CookieName)
{
    var value = document.cookie;
    var start = value.indexOf(" " + CookieName+ "=");
    if (start == -1)
    {
        start = value.indexOf(CookieName+ "=");
    }
    if (start == -1)
    {
        value = null;
    }
    else
    {
        start = value.indexOf("=", start) + 1;
        var end = c_value.indexOf(";", start);
        if (end == -1)
        {
            end = value.length;
        }
        value = unescape(value.substring(start,end));
    }
    return value;
}; 

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


Wednesday, June 12, 2013

Creating a Team Project in TFS 2012

In this post we are see how to create new team project in Team foundation server 2012 from Visual Studio 2012.


  • Open the Visual Studio 2012
  • In the Connection to Team Project dialog box, click Servers.
  • In the Add/Remove Team Foundation Server dialog box, click Add.
  • In the Add Team Foundation Server dialog box, provide the details of your TFS instance, and then click OK.

  •      In the Add/Remove Team Foundation Server dialog box, click Close.
  •      In the Connect to Team Project dialog box, select the TFS instance you want to connect to, select the team project collection you want to add to, and then click Connect.


  •      In the Team Explorer window, click New Team Project.



  • In the New Team Project dialog box, provide a name and a description for the team project, and then click Next.



  • On the Select a Process Template page, select the process template that you want to use to manage the development process, and then click Next.



  • On the Team Site Settings page, leave the default settings unchanged, and then click Next.
  • On the Specify Source Control Settings page, leave the default settings unchanged, and then click Next.
  • On the Confirm Team Project Settings page, click Finish.
  • When the new team project is successfully created, on the Team Project Created page, click Close.
Now Team project is created , now we will add some users to Team Project. this is also can be  done through Visual Studio 2012

Add Users to a Team Project

  •      Open VS 2012 >> go to team explorer >> click Home Button >> Settings

             Substitute the values for "TFS Server", ""Team Project Collection" and " Team Project Name".

  • Sign In As “Admin User” , or else you will not have enough privilege to assign the team members

  •      Click Teams Group (VBlog Team) and add members one by one.
  • Add the same group("VBlog Team") to “Contributors”, or else they can’t add, modify …etc. 
                once we have added  members to tha VBlog Team , add that team to other gorups ("Contributors",   "Reader" and etc)

Thursday, June 6, 2013

Publish Window Azure cloud Services into Window Azure

  • Create window azure cloud services and add web role
a.       Create new Project (File --> New --> Project --> Cloud --> Windows Azure Cloud Services)


  •  Click ok,

Select ASP.Net Web Role and click “>” , then click OK.

  •       Modify the web project
         Add some pages (Home.aspx , Default.aspx)


  •       Modify the cloud project
         For the moment keep it as default 

  •       Publish the web role

  •       If it is the first time you are connecting with window azure, you have to click “Sign in to download credentials” to download the subscription then import it via “import” button.
            Or else, choose your Subscription from dropdown list.


  •        Click next



Cloud Service – Select the correct Cloud Service, or else create new one
Environment – Select production or Staging
Build Configuration – select release or debug
Service configuration – select cloud or local

Go to Setting to configure remote desktop connections
Give username and password

  • Go to Advanced settings tab



Give a name to deployment label – just a name

Storage account – select one , if you don’t have anything , create new one

  • Click Next


You can check the status of publish by “Window Azure Activity Log” window in visual studio (Enable it, if it is not exist)




  • Once the publish get succeed , you will get like this (Check the Window Azure Activity Log window)



Finally , You can go to that URL and check whether everything works fine or not.