Tuesday, April 30, 2013

Create a Web Part Page Programmatically

When creating SharePoint Solutions we need to deploy Web part pages with the solution. I'm sure most of us deploy pages as a module. But we are copying aspx page from some ware else and include it to module. (Visual studio does not allow to create web part aspx pages in SharePoint Solutions) 

So I think it is good to use a method to create web part pages rather than copying from somewhere else and put it to the solution. Using below method you can add web part page to document library with  specified template. of cause you can add custom template ; in that case you can deploy custom template first and use the following method to create a web part page.

First you need to generate the XML for add Web Part Page

private string GetCreateWebPartPage(String list, string pageTitle, int layoutTemplate)
const string newItemTemplate = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<Batch>" +
"<Method ID=\"0,NewWebPage\">" +
"<SetList Scope=\"Request\">{0}</SetList>" +
"<SetVar Name=\"Cmd\">NewWebPage</SetVar>" +
"<SetVar Name=\"ID\">New</SetVar>" +
"<SetVar Name=\"Type\">WebPartPage</SetVar>" +
"<SetVar Name=\"WebPartPageTemplate\">{2}</SetVar>" +
"<SetVar Name=\"Overwrite\">true</SetVar>" +
"<SetVar Name=\"Title\">{1}</SetVar>" +
"</Method>" +
var newItemXml = string.Format(newItemTemplate, list, pageTitle, layoutTemplate);

return newItemXml;

Then Pass it to ProcessBatchData method in SPWeb to create the page.

using (SPWeb oWebsite = SPContext.Current.Site.OpenWeb("Website_URL"))
string xml = GetCreateWebPartPage("SitePages", "SamplePage", 2);

You can put the code in Feature Activation for deployment.

Monday, April 29, 2013

How to Check Bit is Set (Compare to Bits)

I had a recent requirement to check whether bit is set looking another bit. But then i found; it is easy to compare integer values it self rather than converting to bit arrays.

public bool isBitSet(int value , int checkBit) 
return (value & checkBit) == checkBit;

Ex: I want to check number 8 is set in 6164 ,

You can get it by isBitSet(6164,8)

Friday, April 26, 2013

CAML – LookUp Column (Where using lookup column) [Day Today CAML]

This CAML Query simply filter samplecategory which given as LookUp column in the SharePoint

<FieldRef Name='Category' />
<Value Type='Lookup'>samplecategory</Value>

Sunday, April 21, 2013

Access is Denied when submitting Task Job to Azure Media Services

When submitting Job task in Azure media service it is giving error “Access Denied”.

ITask task = job.Tasks.AddNew("My task",processor,"H264 Broadband 720p",TaskOptions.ProtectedConfiguration);
// Specify the input asset to be encoded.
task.OutputAssets.AddNew("Output asset",AssetCreationOptions.None);
// Launch the job.

This is the code segment I have used. This is working in my local machine but I published to Cloud Web Site it is giving access denied error.

I found that the  TaskOptions.ProtectedConfiguration caused this error. When you use this option it is accessing client machine certificate store. Since running context does not have sufficient permission; causing  access denied error.

So change the TaskOptions.None. it will work.

How to Get SharePoint Client Context in SharePoint Apps (Provider Hosted / SharePoint Access ) in CSOM (Client Side Object Model)

First step of the of the app development is to correctly get the access to SharePoint client context. I have struggling with develop a simple model to initialize the SharePoint Client context. Most of the App development include ASP Master pages. So I need to figure out a working model for app development.

First you need to know how SharePoint offer the contextString. contextString Offers when SharePoint is getting redirect from appredirect.aspx url.

Ex:- https://rajee.sharepoint.com/_layouts/15/appredirect.aspx?instance_id={B0D5D768-303F-4AE7-A4D3-F94B687C6AB3

that point we need to capture the contextString and generate either AccessToken or RefreshToken and save it for access the SharePoint  Client Context in later time. other wise it will result in generating the  error The parameter 'token' cannot be a null or empty string (This is nasty error which drove me crazy)

Normally AccessToken is valid for 12 hours and RefreshToken is valid for 6 months.

In my approach I used another key which is called as CacheKey to identify the user uniquely. Therefore I use this value to maintain a cookie based on user the user.

Ref : http://msdn.microsoft.com/en-us/library/office/apps/fp179932


Following shows my approach to do this. If you have master page you need to put the code in the onInit() rather than page load.

protected void Page_Load(object sender, EventArgs e)
var key = Session["CashKey"];

// sharepoint url (app hosted url)
var hostWeb = Page.Request["SPHostUrl"];

// Sharepoint url with app Title (app deployed sp url)
Uri SharePointUri = new Uri(hostWeb + "/SharePointApp1/");

// This is first time the app is running
if (key == null)
// get the TokenString
var contextTokenString = TokenHelper.GetContextTokenFromRequest(Page.Request);
// Get the contexttoken by passing the token string
var contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);

//Since some browsers does not support cookie name more than 40 chars
// Im taking first 40 chars
var cookieName = contextToken.CacheKey.Substring(0, 40);

//Add User specific cookie name to the Session
Session.Add("CashKey", cookieName);

// Get the Refresh Token
var refreshToken = contextToken.RefreshToken;
// Add the cookie value (refresh Token)
Response.Cookies.Add(new HttpCookie(cookieName, refreshToken));

// USER already in the applicaiton, means it is not getting redirect from the appRedirect
// So contextstring is null

this is code for button click

protected void Button1_Click(object sender, EventArgs e)

// sharepoint url (app hosted url)
var hostWeb = Page.Request["SPHostUrl"];

// Sharepoint url with app name (app deployed sp url)
Uri SharePointUri = new Uri(hostWeb + "/SharePointApp1/");

// Get the cookie name from the session
var key = Session["CashKey"] as string;
// Get the refresh token from the cookie
var refreshToken = Request.Cookies[key].Value;

//Get the access Token By pasing refreshToken
// 00000003-0000-0ff1-ce00-000000000000 is principla name for SP2013 it is unique
var accessToken = TokenHelper.GetAccessToken(refreshToken,
SharePointUri.Authority, TokenHelper.GetRealmFromTargetUrl(SharePointUri));

// Access the Sharepoint Do your work
using (var clientContext = TokenHelper.GetClientContextWithAccessToken("https://rajee.sharepoint.com/SharepointApp1", accessToken.AccessToken))
clientContext.Load(clientContext.Web, web => web.Title);

Note: In the middle of the app if the context broken due to expiation or some other case you need to initialize the app from the AppRedirect therefore you can

var hostWeb = Page.Request["SPHostUrl"];
var val = TokenHelper.GetAppContextTokenRequestUrl(hostWeb, Server.UrlEncode(Request.Url.ToString()));

Friday, April 12, 2013

Understanding Asure Media Service Core Components

Azure media service contains few components. Lets look as abstract.


You can find your existing components and there status by navigating to LINK RESOURCES in Azure Media Service.


Storage Account

Storage account is capable of storing media files that is uploaded to azure media service. Storage account is a Shared Resource which we can use for store other items through out the cloud. Storage Account is mapped to Cloud Storage.  You need to specify a existing account or you can create a new storage account when you are creating a Azure Media Service.


Single storage unit is called as Asset in the Azure Media Service. In the same time Asset is also refer as container in the Azure Storage context. Asset / Container is a group which can contains files.

When you go to Azure Media service you can view existing assets by navigating to CONTENT link in the azure.


Most people misunderstand Asset and Asset files. Though media service shows a publish URL; it doesn’t mean that you can view or download a asset. Actually it shows link to a Asset File inside the Asset.

Asset creation can be done using several security storage options.

  • AssetCreationOptions.None (No Encryption)
  • AssetCreationOptions.CommonEncryptionProtected (Use for PlayReady protection )
  • AssetCreationOptions.StorageEncrypted (Store encrypted files)



Encoder is used to encode media files to MP4 format. MP4 encoded files are used to deliver the assets in either on demand or downloadable link. Currently Encoder support only following file types to encode.

.asf , .avi, .m2ts, .m2v. .mp4, .mpeg, .mpg, .mts, .ts, .wmv

On Demand Streaming

This component responsible for provide on demand stream based on demand parameters. This component uses ism, ismc, isma, ismv files to provide the service.

Wednesday, April 10, 2013

How To Access Server.MapPath in a Class that is not inside Web Project

In My case I have decoupled WCF Class Libraries and WCF Host in to two separate projects.  Then i need to get the Server.MapPath in a class library.


I have add the Reference to System.web 

Since I'm using 4.5 dll is available on
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Web.dll


Monday, April 8, 2013

A text field contains invalid data. Please check the value and try again.

This error occurred when I'm trying to  insert URL to SharePoint Text field. I found that my text value contains more than 255 characters. Therefore i changed the SharePoint Column Type to Single Text to Multiple Text.

In addition i have disabled the RichText since my value contains a URL.

Wednesday, April 3, 2013

Request format is unrecognized for URL unexpectedly ending in

This error occurred to me when I try to call web service (asmx) from SharePoint provider hosted app. asmx is written to retrieve some list data from SharePoint app host web.

I found that this error occurs because of missing configuration in the web.config.

<add name="HttpGet"/>
<add name="HttpPost"/>