Get FormDigest from C# using REST in SharePoint 2013

By Namwar Rizvi - Last updated: Sunday, March 17, 2013

If you want to communicate with SharePoint 2013 through REST, you need to send FormDigest value with every request.
In JavaScript, it is very easy as it will always be available on SharePoint Page where your JavaScript code is executing. It is quite tricky when you need to submit REST requests from C# code as there is no such thing called FormDigest control. Following is a function to get the FormDigest control for your REST request in C#

private static string GetFormDigest(string webUrl)
//Validate input
if (String.IsNullOrEmpty(webUrl) || String.IsNullOrWhiteSpace(webUrl))
return String.Empty;

//Create REST Request
Uri uri = new Uri(webUrl + "/_api/contextinfo");
HttpWebRequest restRequest = (HttpWebRequest)WebRequest.Create(uri);
restRequest.Credentials = CredentialCache.DefaultCredentials;
restRequest.Method = "POST";
restRequest.ContentLength = 0;

//Retrieve Response
HttpWebResponse restResponse = (HttpWebResponse)restRequest.GetResponse();
XDocument atomDoc = XDocument.Load(restResponse.GetResponseStream());
XNamespace d = "";

//Extract Form Digest
return atomDoc.Descendants(d + "FormDigestValue").First().Value;
Filed in C#, Code, SharePoint 2013 • Tags: , ,

Custom Timer Jobs versus PowerShell and Task Scheduler for Scheduled Tasks

By Namwar Rizvi - Last updated: Friday, December 7, 2012

Although I am a great fan of using PowerShell for performing lots of tasks in SharePoint quickly, but there are certain areas where PowerShell may not be the optimum solution.

One of which is Custom Timer Jobs in SharePoint. Although you can schedule a PowerShell script by a task scheduler in windows to run some process on a regular interval but creating a TimerJob will give you long term benefits and manageability.  Next, I will try to compare the two approaches, Your comments are most welcome:


Custom Timer Job PowerShell
Configuration Timer Jobs have Property Bags. This will give you power to store configuration data along with specific timer job.
To modify the data, a custom application page can be deployed to Central Admin UI as a link.
In this way, an Admin can manage the job easily through web interface without the need of going to a Shared Folder.
PowerShell script will need either input parameters or a custom config file (preferably XML) for configuration.
To update the configuration data, admin needs to access the Shared Folder or should upload the updated config file through FTP or some other way, which in my opinion is a cumbersome process
User Experience Having a central admin page allows gives a professional and managed user experience with proper branding. User Experience is standard console without any branding.
Training By using standard SharePoint theming and controls, It will be easier for any SharePoint user to quickly learn the usage and management of Timer Job.  Description below each configuration item will reduce/remove the need of separate help document. A separate help documentation will be needed to make sure user remembers the usage of parameters.
Parameter usage will need to be provided with some standard help parameter e.g. /? Or -help
Deployment/Installation A standard WSP solution can be deployed with everything packaged in it without the need of copying multiple dependency files. No standard built in deployment method for PowerShell scripts so administrator has to come up its own way of deployment management.
Retraction/Uninstallation Standard WSP retraction with guaranteed clean of everything initially deployed with the solution. Administrator needs to make sure that every dependency has been cleared.
Application Context Timer Job has the context of Web Application which means it can have a logic to behave differently on per application basis, if needed. By default, PowerShell script can not assume an application context. It needs to create that context, if needed.
Security/Execution Account Timer Jobs always run under specified SharePoint account which gives them specific level of access as per Administrator needs. PowerShell script can also run under a specific account but you need to specify it in Task Scheduler.
This mean another administration task for an administrator.
Backup/Restore Schedule of Timer Job will be backed up and restore in your normal process of SharePoint backup and restore. Administrator needs to manually manage backup and restore of Schedule Tasks and their PowerShell scripts.
Multiple Instances Custom Timer Jobs provides the power to specify Job LockTypes (i.e. SPJobLockTypes) which guarantees that multiple instances of same job will never execute at the same point in time. No multiple instance guarantee. Administrator needs to make sure that no two instances are running at the same time.
Load Balancing To reduce the load on SharePoint Servers, administrator can specify to run the job on all servers, in one particular server, or only the front end servers. Administrator needs to manually schedule a script on some specific server.
Execution Time Window In a farm environment, where a job is setup to run on all server, SharePoint automatically selects the server and a time window of few minutes to start the job as per schedule. It greatly improves the execution reliability. No execution time window management.
Development Complex, as it needs Visual Studio and C#/VB.Net and development skills Easy, as no special development tool is needed. A notepad will be enough.
Debugging Complex but more powerful as it needs the knowledge of how to attach the debugger to the running process. Easy but less powerful as you have to print the messages for debugging.
Filed in Administration, Architecture, Concepts, Management, SP2010, Timer Jobs • Tags: , , , , , , , ,

SharePoint 2013 beta announced

By Namwar Rizvi - Last updated: Tuesday, July 17, 2012

Microsoft has announced the new version of SharePoint  i.e. SharePoint 2013. It is in beta version right now and can be downloaded from SharePoint site

To get the better idea of what is coming in next version of SharePoint, please check the Microsoft presentations at

For developers, there are training videos available at

One of the big news from developer’s perspective is “SharePoint Apps“. Yes, you read correctly, SharePoint now has the App model which means you can create widgets, full blown applications or just a web page to provide a specific functionality.

To get the better idea of new functionalities in SharePoint 2013, check following video


Filed in Information, SharePoint 2013 • Tags: , ,

How to detect if the given webpage is generated by SharePoint?

By Namwar Rizvi - Last updated: Tuesday, June 5, 2012

If you want to find out whether the given web page is generated by SharePoint or not then the most authentic way of verification is to check Response Headers. SharePoint adds an specific response header (along with others) called


The presence of this header is a proof that the given web page is served by SharePoint. The value of MicrosoftSharePointTeamServices header will be similar to 14.0.0.xxxx where major version 14 means it is SharePoint 2010.


The quickest way to check the response header is to use fiddler . For example,

Response Header of a SharePoint Page



As any web server is allowed to add any Response Header therefore, please make extra checks if there is a mission critical dependency on this check.

Filed in Architecture, Concepts, Information, SP2010 • Tags: , , , , ,

Difference between Security Context of Workflow Code in SharePoint 2007 and 2010

By Namwar Rizvi - Last updated: Wednesday, May 16, 2012

In SharePoint 2010, any code which executes because of the changes made by the workflow process will run in context of the user who either started the workflow or responsible for changes which caused the code to be executed.

But …

In SharePoint 2007,  any code which executes because of the changes made by the workflow process will always run in context of SharePoint\System.

Due to the above difference, your SharePoint 2007 code will be able to perform anything on your Site as it will always have Full Permissions whereas in SharePoint 2010, it will depend on the user permission. If you are porting your code from 2007 to 2010 and will need full permission then you should consider using SPSecurity.RunWithElevatedPrivileges method. For details on it, click here

Filed in Architecture, Code, Information, Security, SP2010, Tips, Tools, Troubleshooting, Workflow • Tags: , , , , , , ,

Ideal list of tools you need for SharePoint Development

By Namwar Rizvi - Last updated: Monday, May 7, 2012

After working with several clients, I have compiled a list of tools, addons, plugins and technologies which are needed for development, customization or administration at any point in the journey to learn to use Sharepoint. This list is not a “Mandatory Tools List” but in fact, it is a compilation of tools and technologies which can be used at any point in time depending on your role. I will keep extending this list.

Please feel free to suggest more:


  1. VMWare Workstation
  2. Windows 2008 R2
  3. SQL Server 2008
  4. Team Foundation Server 2010


  1. Visual Studio 2010 Professional / Ultimate / Premium
  2. SharePoint Designer 2010
  3. Visio 2010
  4. Infopath 2010
  5. Fiddler
  6. Nintex Workflow
  7. K2 Workflow
  8. AgilePoint Workflow
  9. Bamboo WebParts
  10. Microsoft Expression Studio
  11. Telerik Controls
  12. Infragistics Controls
  13. SharePoint Manager (Codeplex)
  14. ULS Log Viewer (Codeplex)
  15. CKSDev (Codeplex)
  16. .NET Reflector or
  17. JustDecompile (Free from Telerik)
  18. Notepad++
  19. Firebug

End User Tools

  1. Colligo Contributor Pro

Graphics Designing

  1. Photoshop
  2. GIMP


  1. PowerShell
  2. Axceler’s ControlPoint
  3. AvePoint Products


  1. Global knowledge

Learning Resources:

  1. SharePoint Developer Center (MSDN)
  2. SharePoint StackExchange
Filed in Configuration, Guidance, Information, SP2010, Tips • Tags: , , ,

Solution for viewing HTML files in browser from SharePoint Document Library

By Namwar Rizvi - Last updated: Sunday, March 25, 2012

In SharePoint 2010 document library, if you click on a file with .html extension, you will notice that browser will open Save File dialogue box. This behaviour stops you to view HTML files directly in browser from document library and some times it is very annoying.

To resolve it and view HTML files in browser, here are the steps:

  1. Open SharePoint Central Administration
  2. Click Application Management
  3. Under Web Applications, click Manage web applications
  4. Click on your target web application to select it
  5. On ribbon, click on Web Application tab
  6. Open General Settings menu and click on General Settings
  7. General Settings UI Tab

  8. Scroll to Browser File Handling and change it from Strict to Permissive
  9. Browser File Handling

  10. Click OK to save your changes
  11. Thats it!

Now, go back and try to view HTML file, browser will display it. Enjoy!

Filed in Architecture, Management, SP2010, Tips, Troubleshooting • Tags: , , , , , ,

Correct way of generating Source parameter value in your SharePoint Link

By Namwar Rizvi - Last updated: Tuesday, February 21, 2012

As you may already know that SharePoint uses Source parameter in query string to take you back to the page from where you came.

The value of the Source paramter must be properly encoded. Don’t worry, you do not need to write your own Javascript function to do this. Just use already provided function called


It will return you properly encoded string to pass as Source parameter value. Following is the logic inside this function:

  1. Try to retrieve the value Source parameter from current query string.
  2. if Source parameter found then return it by properly encoding and making sure it is safe to navigate.
  3. If there is no Source parameter in Query string then
    • Check if defaultSource has a non empty value,
    • if yes then return it by properly encoding and making sure it is safe to navigate.
    • Otherwise, return the current page url by properly encoding and making sure it is safe to navigate.
Filed in How To, Information, JavaScript • Tags: , , , , , ,

Useful Javascript Functions and objects in SharePoint – Part 2

By Namwar Rizvi - Last updated: Monday, February 20, 2012
In my last article “Useful Javascript Functions and objects in SharePoint – Part 1”  I listed some useful javascript objects in SharePoint.
Today I will continue exploring useful functions.
DOM Management
  1. byid(id) = Return element for the given id
  2. newE(tag) = Create a new dom element of the given tag e.g. div etc.
  3. wpf() = return form object for the current web part page
  4. GetEventSrcElement(e) = return source element for the given event object
  5. GetEventKeyCode(e) = Return key code of the currently pressed key for the given object
  6. GetInnerText(e) = Return inner html for the given object

HTML Encoding and Decoding

  1. escapeProperlyCoreCore(str, bAsUrl, bForFilterQuery, bForCallback) = Very useful function to perform any type of string escaping. Last three parameters are flags to perform deifferent type of escaping i.e.
    • bAsUrl = true, for url escaping
    • bForFilterQuery = true, for filter query escaping
    • bForCallback = true, for call back escaping
  2. escapeProperly(str) = Escapes the given string to make it valid SharePoint compatible string. It internally calls escapeProperlyCoreCore to perform the actual escaping
  3. escapeUrlForCallback(str) = Escapes the given string to make it valid url for call back
  4. encodeScriptQuote(str) = Replace the apostrophe i.e. ‘ to %27 in the given string
  5. STSHtmlEncode(str) = Encodes the reserved characters to their respective HTML entities in the given string. For example “<div>” will become &lt;div&gt;
  6. StAttrQuote(st) = Encodes the “&”, “ “ ” and carriage return to their respective HTML entities in the given string.
  7. STSScriptEncode(str) = Encodes the given string for use in script. It has the same functionality as SPEncode.ScriptEncode defined here
  8. STSScriptEncodeWithQuote = Encodes the specified string so that characters in embedded HTML tags are displayed as text in the browser, and writes the string in quotation marks
  9. escapeForSync(str) = Encodes the given string for syncing. Need further clarification.
  10. Vutf8ToUnicode(rgBytes) = Converts the given utf8 string to unicode
  11. unescapeProperly(str) = Unescapes the given escaped string


  1. PageUrlValidation(url) = Checks if the given string is a valid url or not.
  2. IndexOfIllegalCharInUrlLeafName(strLeafName) = Return the index of character in the given string which is illegal to be used in url leaf name.
  3. IndexOfIllegalCharInUrlPath(strPath) = Return the index of character in the given string which is illegal to be used in url leaf name.
  4. UrlContainsIllegalStrings(strPath) = Returns true if the given string contains an illegal character which can not be used in a url. Otherwise, return false.
  5. UrlLeafNameValidate(source, args) = Validates the url leaf name. Returns true if valid otherwise, false. Need further clarification.
  6. UrlPathValidate (source, args) = Validates the url path. Returns true if valid otherwise, false. Need further clarification.
  7. IsCheckBoxListSelected(checkboxlist) = Returns true, if the given checkbox is either null or at least one check box is checked in it.
  8. IsAccessibilityFeatureEnabled() = Returns true, if the accessibility feature is enabled by checking the cookie called “WSS_AccessibilityFeature”

Cookie Management

  1. DeleteCookie(sName) = Deletes the given cookie by setting its expiry date to 01-Jan-1970
  2. GetCookie(sName) = Returns the given cookie


  1. navigateMailToLink(strUrl, strUrlNew) = Creates a mail to link for the given url
  2. GetUrlFromWebUrlAndWebRelativeUrl(webUrl, webRelativeUrl) = Creates a url by combining webUrl and relative url. It takes care of checking null webUrl and slash character at the end.

Syncing with other applications

  1. GetStssyncAppNameForType(strType,strDefault) = Returns an string similar to “Connect to Outlook” etc. depending on the given type.
  2. GetStssyncIconPath(strDefault, strPrefix) = Returns the path of icon image for the given syncing application type.
  3. ExportHailStorm ( ….. ) = Creates connection to Outlook. Check here for further details.


  1. DeferCall() = Not sure.
  2. AdmBuildParam(stPattern) = Not sure.

To be continued….

Filed in Architecture, Concepts, Guidance, How To, Information, JavaScript • Tags: , , , , , , ,

Useful Javascript Functions and objects in SharePoint – Part 1

By Namwar Rizvi - Last updated: Sunday, February 19, 2012

SharePoint has a huge set of javascript functions and objects which are defined in essential SharePoint javascript files like init.js, core.js, forms.js etc. These files are necessary for SharePoint to function properly. There is no reason to reinvent the wheel by writing your own javascript function for something which is already provided by these core javascript files.
I will run a series of articles to list down necessary objects and functions provided by SharePoint. I hope you will find them useful.

Useful Objects

JSRequest : It is a global object which is used to get information about current page. It has following properties:

  1. QueryString : An array of Querystring key and values,
  2. FileName : Name of the current file e.g. default.aspx
  3. PathName : current path of the page

NOTE: Before using this object properties, always call JSRequest.Ensuresetup()

L_Menu_BaseUrl : Relative path for current site. e.g.  “/TestSite”. It is useful to construct web relative paths for ajax calls of web services etc.

L_Menu_LCID : Current culture Id e.g.  “1033” for US English.  It is useful to retrieve culture specific files, if need.

L_Menu_SiteTheme : Current site theme name e.g. Lacquer. If no theme is applied then it will be empty.

browseris : This object has several properties to detect browser name, major and minor version, operating system version etc. For example, if you want to know whether the current browser is IE or not then check If it is true then IE else others. To get full details of its properties, use FireBug.

LegalUrlChars : Array of all characters which are allowed in Url for SharePoint.

_spBodyOnLoadFunctionNames : Array of javascript function names to be executed just after DOM is fully loaded. If you want to execute any of your function once the page is fully loaded then add your function name in this array. For example _spBodyOnLoadFunctionNames.push(“MyFunction”);

_spUserId : User Id of the currently logged in user. It is an integer e.g. 1. You can use this value perform any logic against a currently logged in user.

ctx or ctx1 or ctx2 … etc. There can be many ctx objects in a single page. These objects are instances of ContextInfo class. They are used to provide user context information necessary to create Edit Control Block menu items. Please use FireBug to see the list of all properties available. Visit here for more info

g_ExtensionDefaultForRead : An array of file extension strings which are always checked out as Read only. For example, jpg, jpeg, bmp etc.

g_ExtensionNotSupportCheckoutToLocal : An array of file extension strings which are not allowed to checkout locally. For example, aspx, ascx, cmd etc.

Check my next post for available Javascript functions.


Filed in Architecture, How To, Information, JavaScript, SP2010, Tips, Troubleshooting • Tags: , , , , , , , , , , , ,