Tuesday, December 9, 2014

Using Secure Store Service In SharePoint

Many times you need to work with external applications or services from SharePoint. These applications or services may require credentials to communicate. There are many ways to store the credential and pass it when needed. SharePoint provides Secure Store Service which can store credentials in an encrypted database. Credentials can be map to identity of SharePoint Users or Groups. Secure Store Service is an authorization service. You can create Target Application under Secure store service to hold and map the credential with user, group or claim which will be stored in encrypted database.

Create Target Application

  • Go to Central Administration Web site à Application Management à Manage Service Applications. Click on Secure Store Service


  • On the ribbon, click on New link in Manage Target Applications section


  • On the Create New Secure Store Target Application page set the following fields:
    1. Target Application ID : Unique Application ID
    2. Display Name : Display name for application
    3. Contact e-mail address : Primary contact for this target application.
    4. Target Application Type : Group or Individual. The Secure Store Service supports individual and group mappings. In group mapping, every member of domain group is mapped to the credentials. Group mapping is easy to maintain and can provide improved performace. In an idividual mapping, each user is mapped to unique set of credentials.

  • Provide fields. You can choose the field name and type.
    Note: Later you need this field name to access the value using code.
  • Provide Target Application Administrators and Members and click OK.
    1. Target Application Administrators : List of users who have access to manage the target application settings
    2. Members : List of user groups to map to a set of credentials for this target application


  • You can set credentials after creating target application. On Secure Store Service Application page, select created target application id and select Set Credentials on ECB menu.


  • Provide the user name and password.


Access credentials using code

  • Add reference - Microsoft.Office.SecureStoreService.Server namespace.
  • using Microsoft.Office.SecureStoreService.Server;
    using Microsoft.SharePoint;
    using System;
    using System.Collections.Generic;
    using System.Runtime.InteropServices;
    using System.Security;
    public static class SecureStore
    {
    public static Dictionary<string, string> GetCredentials(string applicationId)
    {
    if (applicationId == null)
    {
    throw new ArgumentNullException("applicationId");
    }
    var serviceContext = SPServiceContext.Current;
    var secureStoreProvider = new SecureStoreProvider { Context = serviceContext };
    var credentialMap = new Dictionary<string, string>();
    using (var credentials = secureStoreProvider.GetCredentials(applicationId))
    {
    var fields = secureStoreProvider.GetTargetApplicationFields(applicationId);
    for (var i = 0; i < fields.Count; i++)
    {
    var field = fields[i];
    var credential = credentials[i];
    var decryptedCredential = credential.Credential.ToRegularString();
    credentialMap.Add(field.Name, decryptedCredential);
    }
    }
    return credentialMap;
    }
    public static string ToRegularString(this SecureString secureString)
    {
    var intPtr = Marshal.SecureStringToBSTR(secureString);
    try
    {
    return Marshal.PtrToStringBSTR(intPtr);
    }
    finally
    {
    Marshal.FreeBSTR(intPtr);
    }
    }
    }
    view raw SecureStore.cs hosted with ❤ by GitHub
    private NetworkCredential GetAuth()
    {
    var cr = SecureStore.GetCredentials("TARGET_APPLICATION_ID");
    var networkCredentials = new NetworkCredential
    {
    UserName = cr["FIELDNAME_USER"],
    Password = cr["FIELDNAME_PASSWORD"]
    };
    return networkCredentials;
    }

Monday, October 27, 2014

SPListItem Extension Methods To Get And Set Field Values

Followings are the extension methods for SPListItem class.

Single line of text, Multiline lines of text and Choice(Single)


public static string GetStringValue(this SPListItem item, string columnName)
{
return item[columnName] as String;
}
public static void SetStringValue(this SPListItem item, string columnName, string value)
{
item[columnName] = value;
}

Choice (Multiple)


public static SPFieldMultiChoiceValue GetMultipleChoiceValueCollection(this SPListItem item, string columnName)
{
return (item[columnName] == null) ? null : new SPFieldMultiChoiceValue(item[columnName] as string);
}
public static void SetMultipleChoiceValueCollection(this SPListItem item, string columnName, string[] choices)
{
var value = new SPFieldMultiChoiceValue();
foreach (var choice in choices)
{
value.Add(choice);
}
item[columnName] = value;
}
public static void SetChoiceToMultipleChoiceValueCollection(this SPListItem item, string columnName, string choice)
{
SPFieldMultiChoiceValue choices = (item[columnName] == null)
? new SPFieldMultiChoiceValue()
: new SPFieldMultiChoiceValue(item[columnName] as string);
choices.Add(choice);
item[columnName] = choices;
}

Number, Currency


public static Double? GetNumberValue(this SPListItem item, string columnName)
{
return item[columnName] as Double?;
}
public static void SetNumberValue(this SPListItem item, string columnName, Double value)
{
item[columnName] = value;
}

DateTime


public static DateTime? GetDateTimeValue(this SPListItem item, string columnName)
{
return item[columnName] as DateTime?;
}
public static void SetDateTimeValue(this SPListItem item, string columnName, DateTime value)
{
item[columnName] = value;
}

Lookup (Single)


public static SPFieldLookupValue GetLookupValue(this SPListItem item, string columnName)
{
return (item[columnName] == null) ? null : new SPFieldLookupValue(item[columnName] as string);
}
public static void SetLookupValue(this SPListItem item, string columnName, int itemId)
{
item[columnName] = itemId;
}

Lookup (Multiple)


public static SPFieldLookupValueCollection GetLookupValueCollection(this SPListItem item, string columnName)
{
return (item[columnName] == null)
? null
: new SPFieldLookupValueCollection(item[columnName] as string);
}
public static void SetLookupValueCollection(this SPListItem item, string columnName, int[] itemIds)
{
SPWeb web = item.Web;
var value = new SPFieldLookupValueCollection();
value.AddRange(itemIds.Select(i => new SPFieldLookupValue(i.ToString())));
item[columnName] = value;
}
public static void SetLookupValueToLookupValueCollection(this SPListItem item, string columnName, int itemId)
{
SPFieldLookupValueCollection value = (item[columnName] != null)
? value = item[columnName] as SPFieldLookupValueCollection
: value = new SPFieldLookupValueCollection();
value.Add(new SPFieldLookupValue(itemId.ToString()));
item[columnName] = value;
}

Yes/No


public static Boolean? GetYesNoValue(this SPListItem item, string columnName)
{
return item[columnName] as Boolean?;
}
public static void SetYesNoValue(this SPListItem item, string columnName, Boolean value)
{
item[columnName] = value;
}

User


public static SPFieldUserValue GetUserValue(this SPListItem item, string columnName)
{
SPFieldUser field = item.Fields[columnName] as SPFieldUser;
if (field != null)
{
SPFieldUserValue fieldValue = field.GetFieldValue(item[columnName].ToString()) as SPFieldUserValue;
return (fieldValue == null) ? null : fieldValue;
}
else
{
return null;
}
}
public static void SetUserValue(this SPListItem item, string columnName, int userId)
{
SPWeb web = item.Web;
item[columnName] = new SPFieldUserValue(web, userId.ToString());
}

User Collection


public static SPFieldUserValueCollection GetUserValueCollection(this SPListItem item, string columnName)
{
return (item[columnName] == null) ? null : item[columnName] as SPFieldUserValueCollection;
}
public static void SetUserValueCollection(this SPListItem item, string columnName, int[] userIds)
{
SPWeb web = item.Web;
var value = new SPFieldUserValueCollection();
value.AddRange(userIds.Select(i => new SPFieldUserValue(web, i.ToString())));
item[columnName] = value;
}
public static void SetUserToValueCollection(this SPListItem item, string columnName, int userId)
{
SPWeb web = item.Web;
SPFieldUserValueCollection value = (item[columnName] != null)
? value = item[columnName] as SPFieldUserValueCollection
: value = new SPFieldUserValueCollection();
value.Add(new SPFieldUserValue(web, userId.ToString()));
item[columnName] = value;
}

Hyperlink or Picture


public static SPFieldUrlValue GetUrlValue(this SPListItem item, string columnName)
{
return (item[columnName] == null) ? null : new SPFieldUrlValue(item[columnName] as string);
}
public static void SetUrlValue(this SPListItem item, string columnName, string url, string description)
{
var value = new SPFieldUrlValue { Url = url, Description = description };
item[columnName] = value;
}

Managed Metadata (Single)


public static TaxonomyFieldValue GetTaxonomyValue(this SPListItem item, string columnName)
{
return item[columnName] as TaxonomyFieldValue;
}
public static void SetTaxonomyValue(this SPListItem item, string columnName, Guid termId)
{
var field = item.Fields[columnName] as TaxonomyField;
var session = new TaxonomySession(item.Web.Site);
Term term = session.GetTerm(termId);
field.SetFieldValue(item, term);
}

Managed Metadata (Multiple)


public static TaxonomyFieldValueCollection GetTaxonomyValueCollection(this SPListItem item, string columnName)
{
return item[columnName] as TaxonomyFieldValueCollection;
}
public static void SetTaxonomyValueCollection(this SPListItem item, string columnName, Guid[] termIds)
{
var field = item.Fields[columnName] as TaxonomyField;
var session = new TaxonomySession(item.Web.Site);
TermCollection terms = session.GetTerms(termIds);
field.SetFieldValue(item, terms);
}
public static void SetTaxonomyToTaxonomyValueCollection(this SPListItem item, string columnName, Guid termId)
{
var field = item.Fields[columnName] as TaxonomyField;
var session = new TaxonomySession(item.Web.Site);
TaxonomyFieldValueCollection collection = (item[columnName] != null)
? collection = item[columnName] as TaxonomyFieldValueCollection
: collection = new TaxonomyFieldValueCollection(field);
Term term = session.GetTerm(termId);
TaxonomyFieldValue taxonomyFieldValue = new TaxonomyFieldValue(field)
{
TermGuid = term.Id.ToString(),
Label = term.Name
};
collection.Add(taxonomyFieldValue);
field.SetFieldValue(item, collection);
}


You can download SPListItemExtensions.cs file containing all above extension methods.

Monday, October 20, 2014

Relative Path Using SPUrlExpressionBuilder & URL Tokens

Many time you need to provide relative path when you are working with image, js or css files. Of course you can use hard coded (Absolute) path but it fails after changing domain name or environment. Absolute path is more useful when linking to another website. You can also build relative path using ../ but it fails when you add reference in master page.

Fortunately, SharePoint provides SPUrlExpressionBuilder and URL tokens to generate the relative url. You can use following url tokens:
  • ~Site - Resolve to current web
  • ~SiteCollection - Resolve to current site collection root
URL Tokens can be use only with server side control. Followings are snippets to generate the relative url:

JavaScript


<!-- ~Site/FILE_LOCATION -->
<SharePoint:ScriptLink Language="JavaScript" Name="~Site/SiteAssets/File.js" runat="server" OnDemand="false">
</SharePoint:ScriptLink>
<!-- OR -->
<script type="text/javascript" src='<asp:Literal runat="server" Text="<%$SPUrl:~Site/%>" />SiteAssets/File.js'>
</script>

CSS


<!-- ~Site\FILE_LOCATION -->
<link rel="stylesheet" type="text/css" href='<asp:Literal runat="server" Text="<% $SPUrl:~Site/%>" />SiteAssets/abc111.css' />
<!-- OR -->
<SharePoint:CssRegistration Name="<% $SPUrl:~Site/SiteAssets/File.css %>" runat="server"></SharePoint:CssRegistration>
<!-- OR -->
<Sharepoint:CssLink runat="server" DefaultUrl="<% $SPUrl:~Site/SiteAssets/File.css %>"/>

Favicon


<!-- ~Site\FILE_LOCATION -->
<link rel='shortcut icon' href='<asp:Literal runat="server" Text="<% $SPUrl:~Site/SiteAssets/favicon.ico%>"/>' type="image/vnd.microsoft.icon" />

Image


<!-- ~Site\FILE_LOCATION -->
<img src='<asp:Literal runat="server" Text="<%$SPUrl:~Site/%>" />SiteAssets/File.png' />
<!-- OR -->
<img runat="Server" src='<% $SPUrl:~site/SiteAssets/File.png %>' />
<!-- OR -->
<asp:Image ImageUrl="<% $SPUrl:~site/SiteAssets/File.png %>" runat="server" />

Hyperlink


<!-- ~Site\FILE_LOCATION -->
<a href='<asp:Literal runat="server" Text="<%$SPUrl:~Site/%>" />SiteAssets/PAGE.aspx' >Page URL</a>
<!-- OR -->
<a runat="Server" href="<% $SPUrl:~Site/SiteAssets/PAGE.aspx %>" >Page URL</a>
<!-- OR -->
<asp:HyperLink runat="Server" NavigateUrl="<% $SPUrl:~Site/SiteAssets/PAGE.aspx %>" Text="Page URL">
</asp:HyperLink>

Server side


// ~Site/FILE_LOCATION
string filePath = SPUrlExpressionBuilder.EvaluateUrlExpression("~Site/SiteAssets/File.png").ToString();

SharePoint 2013 search users/group autocomplete with presence 2.0

Recently I have updated my SharePoint 2013 search users/group auto complete with presence plugin on CodePlex. Now it will look for search suggestions along with users.

Features

  • Update SharePoint 2013 search input box to search people with the presence
  • Redirect to Profile page on selection [optional]
  • Show user picture with presence [optional]
  • Show search suggestions

Prerequisites

  • SharePoint 2013
  • jQuery 1.8.x +
  • jQuery UI JS 1.10.x
  • jQuery UI CSS 1.10.x

Solution Deployment

  • Deploy Arya.SearchUser.wsp using following PowerShell Command:
    add-spsolution -LiteralPath "SOLUTION_LOCATION\Arya.SearchUser.wsp"
                        
  • Activate "SearchUserFeature" for particular WebApplication from Central Admin

Manual Installation

  • Copy jquery.searchpeople.js, imgPreload.js, arya.searchpeople.css, loader.gif and spinner.gif to Site.
  • Add reference to the page/masterpage
    <script src="http://code.jquery.com/jquery-1.8.3.min.js" type="text/javascript"></script>
    <script src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js" type="text/javascript"></script>
    <script src="/SiteAssets/jquery.searchpeople.js" type="text/javascript"></script>
    <script src="/SiteAssets/imgPreload.js" type="text/javascript"></script>
    <link href="http://code.jquery.com/ui/1.10.1/themes/smoothness/jquery-ui.css" type="text/css"/>
    <link href="/SiteAssets/arya.searchpeople.css" type="text/css"/>
  • Add following javascript
    $(document).ready(function () {
    _spBodyOnLoadFunctionNames.push("addSearchBox");
    setTimeout(addSearchBox, 1500);
    });
    function addSearchBox() {
    var settings = {
    mySiteUrl: "http://PROFILE_URL",
    redirectToProfilePage: true,
    maxSuggetions: 10,
    showpicture: false,
    showInitials: true,
    principleType: 1,
    showSearchSuggetions: true
    }
    $.searchPeople(settings);
    }

Settings


mySiteUrl :

My site url. User will redirect to profile page url. default: ""
e.g. http://PROFILEURL/person.aspx?accountname=NETWORID

redirectToProfilePage :

If true then user will be redirected to profile page url on selection. default: false

maxSuggetions :

Maximum suggestions to display. default: 10

showpicture:

Show user picture. default: true

showInitials:

Show Gmail like text avatar in case user profile image in not available. default: false

showSearchSuggetions:

Show search suggestions. default: true

principalType:

Principal type to search. default: 1
options:
  • 0 - User, DL, SecGroup, SPGroup
  • 1 - User
  • 2 - DL
  • 4 - SecGroup
  • 8 - SPGroup

Enable search suggestions:

  • Go to Central Admin
  • Click on "Manage service applications" under "Application Management"
  • Click on Search Service Application
  • Click on "Query Suggestions" under "Queries and Results" in left navigation
  • Check "Show search suggestions" and click "Save Settings"

Search without picture


Search with picture


Contact card


You can download the latest source code from codeplex

Thursday, August 14, 2014

Snippets to create custom SharePoint forms/pages

Many times I create custom SharePoint forms in my solutions. More appropriate way is to create SharePoint form using InputFormSection. InputFormSection takes care of the layout and positioning of your controls. You can add InputFormControl containing asp.net/SharePoint controls under InputFormSection.

Add the following references in .aspx pages:

<%@ Register TagPrefix="SharePoint"
Namespace="Microsoft.SharePoint.WebControls"
Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="wssuc" TagName="InputFormSection" Src="~/_controltemplates/InputFormSection.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="InputFormControl" Src="~/_controltemplates/InputFormControl.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="ButtonSection" Src="~/_controltemplates/ButtonSection.ascx" %>
view raw References.aspx hosted with ❤ by GitHub

Container for InputFormSection:

<table border="0" cellspacing="0" cellpadding="0" width="100%">
<!--Add InputFormSection-->
</table>

Followings are some snippets of few common controls I use in custom SharePoint forms/pages:

Texbox


<wssuc:InputFormSection Title="Input Title" Description="Input Description" runat="server">
<template_inputformcontrols>
<wssuc:InputFormControl LabelText="" LabelAssociatedControlId="inputID" runat="server">
<Template_Control>
<SharePoint:InputFormTextBox title="Name" class="ms-input" ID="inputID" Columns="35" runat="server" MaxLength="256" />
<SharePoint:InputFormRequiredFieldValidator ID="InputValidator" ControlToValidate="inputID" ErrorMessage="Required field" Width="300px" runat="server" />
</Template_Control>
</wssuc:InputFormControl>
</template_inputformcontrols>
</wssuc:InputFormSection>






Multiline Textbox


<wssuc:InputFormSection runat="server" Title="MultiLine Textbox Title" Description="MultiLine Textbox Description">
<template_inputformcontrols>
<wssuc:InputFormControl runat="server" LabelText="">
<Template_Control>
<sharepoint:InputFormTextBox title="Title" class="ms-input" ID="TxtCreateSiteDescription" Runat="server" TextMode="MultiLine" Columns="40" Rows="3"/>
</Template_Control>
</wssuc:InputFormControl>
</template_inputformcontrols>
</wssuc:InputFormSection>






Dropdown


<wssuc:InputFormSection Title="Dropdown Title" Description="Dropdown Description" runat="server">
<template_inputformcontrols>
<wssuc:InputFormControl LabelText="" LabelAssociatedControlId="dropdownID" runat="server">
<Template_Control>
<asp:DropDownList ID="dropDownID" runat="server" width="300">
<asp:ListItem Text="Select" Value="0" Selected="True" />
</asp:DropDownList>
<SharePoint:InputFormRequiredFieldValidator ID="DropDownValidator" ControlToValidate="dropDownID" InitialValue="0" ErrorMessage="Required field" Width="300px" runat="server" />
</Template_Control>
</wssuc:InputFormControl>
</template_inputformcontrols>
</wssuc:InputFormSection>



Checkbox


<wssuc:InputFormSection Title="Checkbox Title" Description="Checkbox Description" runat="server">
<Template_InputFormControls>
<wssuc:InputFormControl LabelText="" LabelAssociatedControlId="checkBoxID" runat="server">
<Template_Control>
<asp:CheckBox ID="checkBoxID" runat="server" Text="Some description about checkox" Title="Checkbox Title" Checked="true" />
</Template_Control>
</wssuc:InputFormControl>
</Template_InputFormControls>
</wssuc:InputFormSection>





Radio button


<wssuc:InputFormSection Title="Radio Button Title" Description="Radio Button Description" runat="server">
<Template_InputFormControls>
<wssuc:InputFormControl LabelText="" LabelAssociatedControlId="" runat="server">
<Template_Control>
<asp:RadioButton ID="radioButtonID1" runat="server" Text="Choice 1" GroupName="RadioButtonGroup" Title="Radio Button 1 Title" />
<asp:RadioButton ID="radioButtonID2" runat="server" Text="Choice 2" GroupName="RadioButtonGroup" Title="Radio Button 2 Title" />
</Template_Control>
</wssuc:InputFormControl>
</Template_InputFormControls>
</wssuc:InputFormSection>






Url Field


<wssuc:InputFormSection Title="Url Title" Description="Url Description" runat="server">
<template_inputformcontrols>
<wssuc:InputFormControl runat="server">
<Template_Control>
<table border="0" cellspacing="1" class="ms-authoringcontrols" width="100%">
<tr>
<td class="ms-formdescription" nowrap="nowrap" width="100%">
<SharePoint:EncodedLiteral runat="server" text="Type the Web address: " />
<a href="javascript:" onclick="javascript:TestURL('<%= urlInputID.ClientID %>');return false;">
<SharePoint:EncodedLiteral runat="server" text="(Click here to test)" EncodeMethod='HtmlEncode'/>
</a>:
</td>
</tr>
<tr>
<td class="ms-authoringcontrols" width="100%" >
<SharePoint:InputFormTextBox title="Url Title" CssClass="ms-input" ID="urlInputID" Columns="35" Runat="server" text="http://" maxlength="255" width="300" />
</td>
</tr>
<tr>
<td class="ms-formdescription nowrap="nowrap" >
<SharePoint:EncodedLiteral runat="server" text="Type the description:" EncodeMethod='HtmlEncode'/>
</td>
</tr>
<tr>
<td nowrap="nowrap" class="ms-authoringcontrols" width="100%">
<SharePoint:InputFormTextBox title="Url Description Title" CssClass="ms-input" ID="InputFormTextBox2" Columns="35" Runat="server" maxlength="255" width="300" />
<SharePoint:InputFormRequiredFieldValidator ID="urlRequiredValidator" InitialValue="http://" ControlToValidate="urlInputID" ErrorMessage="Required field" runat="server" Display="Dynamic" CssClass="ms-error"/>
<SharePoint:InputFormRegularExpressionValidator ID="urlRegularExpressionValidator" ControlToValidate="urlInputID" ErrorMessage="URL is invalid." runat="server" ValidationExpression="http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?" Display="Dynamic" CssClass="ms-error"/>
</td>
</tr>
</table>
</Template_Control>
</wssuc:InputFormControl>
</template_inputformcontrols>
</wssuc:InputFormSection>









File Upload


<wssuc:InputFormSection runat="server" title="File Upload Title" Description="File Upload Description">
<Template_InputFormControls>
<wssuc:InputFormControl runat="server" SmallIndent="true">
<Template_Control>
<table class="ms-authoringcontrols" width="100%">
<tr><td>
<input type="file" id="InputFile" runat="server" class="ms-fileinput ms-fullWidth" size="35" />
</td></tr>
<tr><td>
<SharePoint:InputFormRequiredFieldValidator ControlToValidate="InputFile"
Display="Dynamic" ErrorMessage="Select the document" Runat="server"/>
</td></tr>
<tr><td><asp:CheckBox id="OverwriteSingle" Checked="true" Text="Overwrite existing files" runat="server" CssClass="ms-upload-overwrite-cb" /></td></tr></table>
</Template_Control>
</wssuc:InputFormControl>
</Template_InputFormControls>
</wssuc:InputFormSection>







People Picker


<wssuc:InputFormSection Title="User Title" Description="User Description" runat="server">
<template_inputformcontrols>
<wssuc:InputFormControl LabelText="User name:"
runat="server">
<Template_Control>
<Sharepoint:PeopleEditor AllowEmpty=false SingleLine=true ValidatorEnabled="true" MultiSelect=false id="PickerOwner" runat="server" SelectionSet="User" />
</Template_Control>
</wssuc:InputFormControl>
</template_inputformcontrols>
</wssuc:InputFormSection>





Button


<wssuc:ButtonSection runat="server">
<template_buttons>
<asp:Button
runat="server"
OnClick="Onclick_Method"
class="ms-ButtonHeightWidth"
Text="<%$Resources:wss,multipages_okbutton_text%>"
id="_btnSubmit"
accesskey="<%$Resources:wss,okbutton_accesskey%>"
Enabled="true"/>
</template_buttons>
</wssuc:ButtonSection>


Tuesday, August 12, 2014

Sharepoint Selector Controls for custom administration pages

Sharepoint comes with four selector controls to choose destination elements for the operations.  These controls can be used in custom administration pages.  You can locate this controls under Microsoft.SharePoint.WebControls namespace.  To add selector controls you have include following page directive:

<%@ Register TagPrefix="SharePoint"
Namespace="Microsoft.SharePoint.WebControls"
Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>


WebApplicationSelector

WebApplicationSelector control allow user to get or set the web application.

<SharePoint:WebApplicationSelector id="webAppSelector" runat="server" />



SiteAdministrationSelector

SiteAdministrationSelector control allow user to get or set the site collection.

<SharePoint:SiteAdministrationSelector id="siteSelector" runat="server" />




WebAdministrationSelector

WebAdministartionSelector allow user to gets or sets the Web.  The web selector requires that SiteSelector not be a null reference.  So you have to use SiteAdministartionSelector to use this control.
<SharePoint:SiteAdministrationSelector id="siteSelector" runat="server" />
<SharePoint:WebAdministrationSelector id="webSelector" runat="server" />
protected void Page_Load(object sender, EventArgs e)
{
// Set SiteSelector for Web
webSelector.SiteSelector = siteSelector;
}


ListAdministrationSelector

ListAdministrationSelector allow user to get or set the List or Document Library.  The List selector requires WebAdministartionSelector.  So if you want to use list selector then you have to use WebAdministartionSelector as well as SiteAdministrationSelector.

<SharePoint:SiteAdministrationSelector id="siteSelector" runat="server" />
<SharePoint:WebAdministrationSelector id="webSelector" runat="server" />
<SharePoint:ListAdministrationSelector id="listSelector" runat="server" />
protected void Page_Load(object sender, EventArgs e)
{
webSelector.SiteSelector = siteSelector;
listSelector.SiteSelector = siteSelector;
listSelector.WebSelector = webSelector;
}




To get the selected values from above controls use CurrentItem property:

SPWebApplication webApp = webAppSelector.CurrentItem;
SPSiteAdministration site = siteSelector.CurrentItem;
SPWeb web = webSelector.CurrentItem;
SPList list = listSelector.CurrentItem;
view raw Selectors.cs hosted with ❤ by GitHub

Friday, August 1, 2014

Get operating system name from HttpRequest

I was creating a HttpModule in SharePoint to track the request related data such as browser name and client platform. If you are tracking request related data then you must be familiar with System.Web.HttpBrowserCapabilities class. HttpBrowserCapabilities class enables the server to gather information on the capabilities of the browser that is running on the client. I was using HttpCapabilitiesBase.Platform Property to get the client operating system name. But for Windows platform it was returning "WinNt" instead of actual operating system name. After doing some research I noticed that Request.UserAgent returns operating system information along with operating system version number. 

Here is my code to get the Operating System name from Request.UserAgent

/// <summary>
/// Get OS Name from User Agent
/// </summary>
/// <returns>OS Name</returns>
private string GetOsName()
{
// Create collection of user agent string and OS Name
var list = new List<KeyValuePair<string, string>>();
list.Add(new KeyValuePair<string, string>("windows nt 6.3", "Windows 8.1"));
list.Add(new KeyValuePair<string, string>("windows nt 6.2", "Windows 8"));
list.Add(new KeyValuePair<string, string>("windows nt 6.1", "Windows 7"));
list.Add(new KeyValuePair<string, string>("windows nt 6.0", "Windows Vista"));
list.Add(new KeyValuePair<string, string>("windows nt 5.2", "Windows Server 2003/XP x64"));
list.Add(new KeyValuePair<string, string>("windows nt 5.1", "Windows XP"));
list.Add(new KeyValuePair<string, string>("windows xp", "Windows XP"));
list.Add(new KeyValuePair<string, string>("windows nt 5.0", "Windows 2000"));
list.Add(new KeyValuePair<string, string>("windows me", "Windows ME"));
list.Add(new KeyValuePair<string, string>("win98", "Windows 98"));
list.Add(new KeyValuePair<string, string>("win95", "Windows 95"));
list.Add(new KeyValuePair<string, string>("win16", "Windows 3.11"));
list.Add(new KeyValuePair<string, string>("macintosh|mac os x", "Mac OS X"));
list.Add(new KeyValuePair<string, string>("mac_powerpc", "Mac OS 9"));
list.Add(new KeyValuePair<string, string>("linux", "Linux"));
list.Add(new KeyValuePair<string, string>("ubuntu", "Ubuntu"));
list.Add(new KeyValuePair<string, string>("iphone", "iPhone"));
list.Add(new KeyValuePair<string, string>("ipod", "iPod"));
list.Add(new KeyValuePair<string, string>("ipad", "iPad"));
list.Add(new KeyValuePair<string, string>("android", "Android"));
list.Add(new KeyValuePair<string, string>("blackberry", "BlackBerry"));
list.Add(new KeyValuePair<string, string>("webos", "Mobile"));
string userAgent = application.Request.UserAgent;
string os = string.Empty;
for (int i = 0; i < list.Count; i++)
{
if (userAgent.ToLower().IndexOf(list[i].Key.ToLower())>0)
{
// Set OS Name for particuler user agent
os = list[i].Value;
break;
}
}
return os;
}
view raw GetOSName.cs hosted with ❤ by GitHub
If you find more combinations please add it to comments section.

Thursday, July 17, 2014

SharePoint 2013 Lync Presence using jQuery

In my last couple of assignments I was working on Lync presence for user in SharePoint 2013. After that I decided to create a jQuery plugin to render user presence in SharePoint 2013. This plugin  renders lync presence on the basis of account name ("DomainName\\UserName" or "i:0%23.f|membership|username@domain.com"). I have also uploaded the plugin to codeplex

Prerequisites


  • SharePoint 2013
  • JQuery 1.8.x +


Installation




Settings


type:


Output for the lync presence. default : "default"
Options
     default
     withpicturesmall
     withpicture
     pictureonlysmall
     pictureonly
     presenceonly

redirectToProfile:


Redirect to profile page after click. default : true

Output


Default

With Picture [Small]

With Picture

Picture Only [Small]

Picture Only

Presence Only

Contact Card

You can download the latest source code from codeplex
Please report any bugs or feature requests in comments.

Wednesday, July 16, 2014

SharePoint 2013 jQuery PeoplePicker with picture & presence

In my previous post I shared a solution to extend the SharePoint search box to search the user/group with presence/picture. That gave me an idea to create a tokenized input box with user picture and presence. To create tokenized input box I used the original jquery plugin Token Input.

I have uploaded jQuerySPPeoplePicker plugin on codeplex.


Features


jQuery tokenized PeoplePicker for SP 2013 with picture and presence.


Prerequisites




  • SharePoint 2013
  • jQuery 1.8.x +



Installation



Configuration


Following options are available:

searchDelay


The delay, in milliseconds, between the user finishing typing and the search being performed. default: The minimum number of characters the user must enter before a search is performed.default: 1 

minChars


The minimum number of characters the user must enter before a search is performed. default: 1 

principalType


Principal type to search. default: 0
options: 
        0 - [User, DL, SecGroup, SPGroup]
        1 - [User]
        2 - [DL]
        4 - [SecGroup]
        8 - [SPGroup]

hintText


The text to show in the dropdown label which appears when you first click in the search field. default: “Type in a user/group name”

mySiteHostUrl


My site host url to pull the user picter. default: ""

noResultsText


The text to show in the dropdown label when no results are found which match the current query. default: “No results” 

searchingText


The text to show in the dropdown label when a search is currently in progress. default: “Searching…”

deleteText


The text to show on each token which deletes the token when clicked. If you wish to hide the delete link, provide an empty string here. Alternatively you can provide a html string here if you would like to show an image for deleting tokens. default: × 

animateDropdown


Set this to false to disable animation of the dropdown default: true 

tokenLimit


The maximum number of results allowed to be selected by the user. Use null to allow unlimited selections. default: 10 

tokenDelimiter


The separator to use when sending the results back to the server. default: “;”

prePopulate


Prepopulate the peoplePicker with existing data. Set to an array of JSON objects, eg: [{"id": "i:0#.w|Domain\User", "value": "User Title", "email": "user@domain.com", "networkaddress": "domain\username", "sip": "sip@domain.com" }] to pre-fill the input. default: null

Callbacks


onAdd


A function to call whenever the user adds another token to their selections. defaut: null 

onDelete


A function to call whenever the user removes a token from their selections. default: null 

onReady


A function to call after initialization is done and the peoplePicker is ready to use. default: null

Methods


add


Add a new token to the peoplePicker with id x and name y.

selector.peoplePicker("add", {id: x, name: y});

remove


Remove the tokens with id x from the peoplePicker.

selector.peoplePicker("remove", {id: x});

Remove the tokens with name y from the peoplePicker.

selector.peoplePicker("remove", {name: y});

clear


Clear all tokens from the peoplePicker.

selector.peoplePicker("clear");

get


Gets the array of selected tokens from the peoplePicker (each item being an object of the kind {"id": "i:0#.w|Domain\User", "value": "User Title", "email": "user@domain.com", "networkaddress": "domain\username", "sip": "sip@domain.com" }).

selector.peoplePicker("get");


Output







jQuery PeoplePicker also uses imgPreload plugin to show spinner before loading the user picture.

You can download the latest source code from codeplex

SharePoint 2013 search users/group auto complete with presence

Recently my client ask me to update the SharePoint 2013 search box to display the user/group with presence. Also on selection of user it should redirected to user profile page. I came up with SPSearchUserAutocomplete plugin to search user.


Features


  • Update SharePoint 2013 search input box to search people with the presence
  • Redirect to Profile page on selection [optional]
  • Show user picture with presence [optional]


Prerequisites


  • SharePoint 2013
  • jQuery 1.8.x +
  • jQuery UI JS 1.10.x
  • jQuery UI CSS 1.10.x


Installation

  • Copy jquery.searchpeople.js, imgPreload.js and spinner.gif to Site.
  • Add reference to the page/masterpage
  • <script src="http://code.jquery.com/jquery-1.8.3.min.js" type="text/javascript"></script>
    <script src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js" type="text/javascript"></script>
    <script src="/SiteAssets/jquery.searchpeople.js" type="text/javascript"></script>
    <script src="/SiteAssets/imgPreload.js" type="text/javascript"></script>
    <link href="http://code.jquery.com/ui/1.10.1/themes/smoothness/jquery-ui.css" type="text/css"/>
  • Add following javascript
  • jQuery(document).ready(function () {
    var settings = {
    mySiteUrl: "http://PROFILE_URL",
    redirectToProfilePage: false,
    maxSuggetions: 20,
    showpicture: true,
    principleType: 1
    }
    jQuery.searchPeople(settings);
    });

Settings


mySiteUrl :

My site url. User will redirect to profile page url. default: ""
e.g.  http://PROFILE_URL/person.aspx?accountname=NETWOR_ID 


redirectToProfilePage :

If true then user will be redirected to profile page url on selection. default: false


maxSuggetions :

Maximum suggestions to display. default: 10.

showpicture:

Show user picture. default: true


principalType:

Principal type to search. default: 0
options:
        0 - [User, DL, SecGroup, SPGroup]
        1 - [User]
        2 - [DL]
        4 - [SecGroup]
        8 - [SPGroup]

Search without picture






Search with picture



Contact card




jQuery search people also uses imgPreload plugin to show spinner before loading the user picture.

You can download the latest source code from codeplex