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 :)


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


Monday, March 18, 2013

AJAX Supporting Sharepoint Web parts with JSONP WCF Services

What is AJAX ?

AJAX = Asynchronous JavaScript and XML.
AJAX is a technique for creating fast and dynamic web pages.
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.
Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

Click here for AJAX Tutorial

In this post , we are going to create a share point page with AJAX Supporting web parts which invokes JSONP services to get data from Server.

1. Create JSONP WCF Services(How to create?)


Format of the Result

Link : 
http://ServerName:PorNumber/Service.svc/jsp/GetEmployeMoreDetailsByUserName?method=JsonPCallBack&logInName=User1

Result :

JsonPCallBack(
{
    "DateOfBirth":"\/Date(969042600000+0530)\/",
    "AboutMe":"This is all About Me",
    "CurrentATC":"CMB ATC",
    "Department":"OIG--CMB-VPL-Shared Services-Center Management",
    "Experience":16.2,
    "Interests":["UX Design","SharePoint","Photography"],
    "Languages":[""],
    "NoofPastProjects":33,
    "PermanentATC":"CMB ATC",
    "ReportingManager":"Domain\\UserName",
    "Tier":0,
    "Since":"\/Date(852057000000+0530)\/"
}
);

 
2. Create Empty/Visual Web part project and create web parts.

3. In aspx page create client side controls (Button , Label , text box ...etc)

<div>

Search Employee : <input id="SearchEmpName" type="text" name="SearchEmpName"  value=""/>
<input id="btnWCFREST" type = "button" value = "Search" /><br/>

<b>Reporting Manager:</b> <label id = "EmpReportlbl" ></label><br/>
<b>Department:</b> <label id = "EmpDepartlbl" ></label><br/>
<b>Tier:</b> <label id = "EmpTierlbl" ></label><br/>
<b>Permanent Office:</b> <label id = "EmpPermAtclbl" ></label><br/>
<b>Current Office:</b> <label id = "EmpCurrAtclbl" ></label><br/>
<b>Interests:</b> <label id = "EmpIntelbl" ></label><br/>
<b>Date Of Birth:</b> <label id = "EmpDOBlbl" ></label><br/>
<b>Languages:</b> <label id = "Emplanglbl" ></label><br/>
<b>Experience:</b> <label id = "EmpExpelbl" ></label><br/>

</div>



4. Add reference to the project in order to use JQuery in Web parts

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js"></script> 

5. Use the JQuery to invoke the WCF Services in AJAX.
Check this for more about JQuery :  JQuery, Write Less, do more

<script type="text/javascript">
    jQuery.support.cors = true;

    $(document).ready(function () {
        $("#btnWCFREST").click(function () {
            $.ajax({
                url: 'http://ServerName:PortNumber/Service.svc/jsp/GetEmployeMoreDetailsByUserName?logInName=' + $("#SearchEmpName").val() + '&method=?',
                type: 'GET',
                dataType: 'jsonp',
                error: function (x, t, r) { alert("Error In Employee More Details"); },
                success: function (data) {
                    document.getElementById('EmpReportlbl').innerText = data.ReportingManager;
                    document.getElementById('EmpDepartlbl').innerText = data.Department;
                    document.getElementById('EmpTierlbl').innerText = data.Tier;
                    document.getElementById('EmpPermAtclbl').innerText = data.PermanentATC;
                    document.getElementById('EmpCurrAtclbl').innerText = data.CurrentATC;
                    document.getElementById('EmpIntelbl').innerText = data.Interests;
                    document.getElementById('EmpDOBlbl').innerText = Date(data.DateOfBirth);  
                    document.getElementById('Emplanglbl').innerText = data.Languages;
                    document.getElementById('EmpExpelbl').innerText = data.Experience;
                }
            });


        });
    });
</script>


6. check whether AJAX is working or not by putting breakpoints in VS project in Page load method and attach appropriate process.

Friday, March 8, 2013

Push Newsfeed to Sharepoint 2013 Site From External Sources

SharePoint 2013 comes with a lot of new features especially for Social Networking. News Feed is one of those features. SharePoint 2010 also has that feature but External systems can't send external feeds to the SharePoint farm. SharePoint 2013 has defined some libraries (API) to push feeds from outside to SharePoint farm.
In addition to that there are some different between 2010 newsfeed and SharePoint 2013 Newsfeed.
 
Prerequisites

1. Configured SharePoint 2013 Farm  
2. MySiteHost URL or Team Site URL
3. Visual Studio 2012 installed in machine

Steps to create the Project to send Newsfeed to SharePoint My site or Team site


1. Create New Class library in Visual Studio 2012 and named it as "NewsFeedPushLib"


2. Create a file and named it as "NewsFeedPushClass.cs"

3. Add below dlls as reference to that project 


4. write the following code into that class.


a. Check for accessibility - Need to ensure that that user has enough rights to push feeds into share point site.
 
          System.Net.NetworkCredential cred = new System.Net.NetworkCredential("UserName", "Password");
          ClientContext clientContext = new ClientContext("siteURL");
          clientContext.Credentials = cred;


b. Get the thread owner from the PeopleManager object.

          Microsoft.SharePoint.Client.UserProfiles.PersonProperties owner = new Microsoft.SharePoint.Client.UserProfiles.PeopleManager(clientContext).GetPropertiesFor(
"UserName");
 

c. Get the MicrofeedManager object.

                MicrofeedManager microfeedManager = new MicrofeedManager(clientContext);


d. Register the requests that you want to run.
                // The first call requests only the DisplayName and AccountName
                // properties of the owner object.


                clientContext.Load(owner, o => o.DisplayName, o => o.AccountName);
                clientContext.Load(microfeedManager);


e. Run the requests on the server.
                clientContext.ExecuteQuery();


f. Define defenitionName

 MicrofeedPostOptions postOptions = new MicrofeedPostOptions();
postOptions.DefinitionName = "defenitionName";

Eg : "Microsoft.SharePoint.Microfeed.UserPost" for User Post  

g. Send the Feed

    if (!string.IsNullOrEmpty(feedItem))
     // remove the empty/Null feed                 

   {
         if (feedItem.Length > 512)
         {
               feedItem = feedItem.Substring(0, 508) + "...";
// to limit the feed limit
         }
         postOptions.Content = feedItem; 
// content for the feed 

         if ((!(feedItem == null)) && !(feedItem.Equals("")))
        {
            if (true)
            {
                postOptions.TargetActor = targetActor;
// set the target actor for a feed               
                microfeedManager.Post(postOptions); 
//post the feed on each user's newsfeed
                clientContext.ExecuteQuery();
                success = true;
            }
            else
            {
                success = false;
//couldn't push it to target no valid target
            }

        }
   }

}

5. Create another project (console Application) and create new file. then call Push newsfeed method in this class

 NewsFeedPushClass.PushToSharePoint("Testing Feed1", "Sharepoint_Web_application_URL", "domain\\user", "password", "Team Site URL", "Microsoft.SharePoint.Microfeed.UserPost");

6. Run the program and check whether it is working or not.



Sample feed(Defect Information) pushed from external system(Project management system) to Team Site

 
Download the Solution File - MediaFire Link
 
 

 

 

Tuesday, January 29, 2013

Create Simple Application page in SharePoint 2013


Before create the application page in SharePoint you should know general idea about what is Application page? and How it differs from master page and web part? (See here for more details)

      Steps :
      
   01.  Open Visual Studio 2012 
   02.  Create New Project , select SharePoint 2013 project. then type the Name and click "OK".
      
   03. Select “Deploy as Farm Solution” and Select the site for debugging. it should be your    local host.
      
      
   04. Check whether your site is working or not by clicking "Validate" . if it is successful , click "Finish".
           

 
   05. Add New Item (Right click on the Project , Add >> New Item>> Office/SharePoint >>Application Page(Farm Solutions only))

   06. Type the Application Page Name (ApplicationPage1.aspx) and click “Add”.

   07. Once it creates the project, check the site URL and Startup item (Right click on the project file , and click properties). 

       

  • Startup Item will create automatically if you double click the empty box. If you have more than one application page, you have to select the start-up item.
  • There are two ways to edit the page. One is edit the Page Markup and second one is edit the Page code (You can open the View Code , or View Markup to edit if you right click on the applicationpage1.aspx  file)
  • Edit the Page Markup. Put the controls (Button, List box, Radio button…etc.) between the main content tag. You can drag & drop the controls from the toolbox. You can’t view the page until you deploy into SharePoint farm.
  • Once you edit the page markup, you can edit the page code according to your Business logic.


08. Finally build the project and deploy the solution and check the "Output"window for deployment status whether it succeed or failed.

09. Once the deployment is succeed , you can check the page (check the UI & functionality)
  • If you want to check the page after deployed, you have to go to that URL. Or else if you click RUN Button on Visual studio it will automatically open the URL. After that you can use that URL for open the page.
10. If you want to debug the code, attach the processes (w3wp.exe) with visual studio project after deploy before open the page. (Debug >> Attached to Processes >> select all w3wp.exe and click attach). Then open the page , it will automatically stop at first break point



Be careful
  • Since all the controls are ASP.Net, every time it will send the request to server, so every time it will reload the page. Design your code according to this.
  • If you want, you can use “IsPostBack”  method to identify the first page load . 
        - First time page load/ refresh the page/ reload the page - - - > IsPostBack = = true
        - Page load by clicking the buttons - - - > IsPostBack = false Or else you can use session variables