CHunky Universe of Vigourous Astonishing SHarepoint :)

Tag Archives: ASP.NET

Trying out Visual Studio Code on Ubuntu

I am very curious about the new .NET Core, ASP.NET 5, EF 7 and Visual Studio Code for Linux, Mac and Windows. I have tried it out on an Ubuntu 15.04 machine. The installation and configuration required a few steps, so it is not an usual “Next-next-next”-installation. But, hey, it is just a beta, a preview so far, and first of all: It worked. I am sharing a couple of screenshots and the commands I ran in the terminal, mixed with comments and links:





#install latest node and npm
curl -sL | sudo bash -
sudo apt-get install -y nodejs
sudo npm install -g yo
sudo npm install -g generator-aspnet
# download VS Code and make a link
# make a folder
mkdir workspace/tryvs
cd workspace/tryvs
# create "src/global.json" file:
  "sdk": {
    "version": "1.0.0-beta7"
nano src/global.json
# start VS Code 
# create 
# install omnisharp:
curl -sSL | DNX_BRANCH=dev sh && source ~/.dnx/dnvm/
#install dnx
sudo apt-get install -y libunwind8 gettext libssl-dev libcurl3-dev zlib1g libicu-dev
dnvm upgrade -r coreclr
cd EmptyApplication
dnu restore

#install libuv
sudo apt-get install make automake libtool curl
curl -sSL | sudo tar zxfv - -C /usr/local/src
cd /usr/local/src/libuv-1.4.2
sudo sh
sudo ./configure
sudo make
sudo make install
sudo rm -rf /usr/local/src/libuv-1.4.2 && cd ~/
sudo ldconfig

#build, I got an error here
dnu build

#start the web server
dnx web

cross browser console.log

console.log is the best tool for debugging javascript. In Firefox Firebug and Chrome Dev Tools you can even log objects which are represented as tree nodes of properties.

If Firebug or Dev Tools in Chrome and IE9 are not opened, all these messages are ignored. But IE8 doesn’t understand console (if Dev Tools are closed) and raises an error:

To avoid these errors, just declare an empty function just for IE8–:

var console = window.console || { log: function() {} };
Microsoft Ajax Library and console.log

In SharePoint and of course in ASP.NET we can use the built-in console tools: Sys.Debug.trace(“some message”);

XMLHttpRequest the hard way

$.ajax is great, it hides much of the complexity. But sometimes we need to work with “raw” javascript 🙂 So let’s look behind the scenes. The XMLHttpRequest (or just XHR) is used to open a connection to a server without a page reload. Internet Explorer calls it ActiveXObject and it differs in IE versions. Wikipedia article gives a good example how to create one constructor for all browsers:

if (typeof XMLHttpRequest == "undefined")
  XMLHttpRequest = function () {
    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
      catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
      catch (e) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP"); }
      catch (e) {}
    //Microsoft.XMLHTTP points to Msxml2.XMLHTTP and is redundant
    throw new Error("This browser does not support XMLHttpRequest.");

The remainder is more or less the same among the browsers. We open a connection defining the HTTP verb, URI and async mode (true or false):

var xhr = new XMLHttpRequest();"GET", "/_vti_bin/listdata.svc", true);
xhr.onreadystatechange = onStateChange;

Pay attention to onreadystatechange (only lower case letters). If we choose async=false, the UI waits for the response which is not so kind to users, but maybe it is easier to write a program. Well, there is actually no option but to have async=true.

To provide the callback for success and error we can write the responding function onreadystatechange. This function will be called every time the state is changed. There are 5 states:

0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete

The state 4 “complete” and status 200 (OK) means success.

function onStateChange() {
  if (xhr.readyState == 4) {
    if (xhr.status == 200) {
      response = xhr.responseText;

This onreadystatechange is actually cool stuff. It helps to understand how ajax actually works, and how jQuery “is talking” to browser in order to partially load data. The onreadystatechange callback function opens even new opportunities. What if you want to show a spinner when the data has began to load? Very simple. Let’s just add a couple of code lines to our onStateChange function. When the state is 1 (loading) – show, when 4 (complete) – hide. Suppose we have a spinner object already:

function onStateChange() {
  if (xhr.readyState == 1) {
  if (xhr.readyState == 4) {
    if (xhr.status == 200) {
      response = xhr.responseText;

By the way, if you must parse XML from response, check out this blog post by Santosh

Sys.Web.Request (Update 2013-03-05)

In ASP.NET there is a wrapper for this: Sys.Web.Request. I found it in a question on SharePoint stackexchange. Here is a simple example without any error handling, without any parameters, just to show how to invoke the Sys.Web.Request:

function onCompleted(response, eventArgs) {
    var results = response.get_responseData().d.results;
var url = "the actual url";
var request = new Sys.Net.WebRequest();
request.get_headers()["Accept"] = "application/json";


Another way to make an ajax call is to use SP.RequestExecutor which is javascript utility available in SharePoint 15 (maybe not only 15?) under /_layouts/15/sp.requestexecutor.js. I found this thanks to a question on SharePoint StackExchange: Upload a non-text as an attachment using SharePoint 2013 REST API. I mentioned it in my other post: REST API: Add a plain text file as an attachment to a list item:

var request = new SP.RequestExecutor("/");
	url: "MY URL",
	method: "GET"

Datetime in ASP.NET javascript and $.ajax

In one of my previous blogs I wrote about serializing of javascript objects. You can do it with JSON.stringify or Sys.Serialization.JavaScriptSerializer.serialize. Both methods work fine… almost. There is a big difference when it comes to datetime objects. MS treats dates a little bit different (like RegEx and much more).

Let’s try this one:

var writer = { name: "Ajgi", birthdate: new Date(1934, 8-1, 21) };
var json = JSON.stringify(writer);
var msjson = Sys.Serialization.JavaScriptSerializer.serialize(writer);

What happens if we try to parse back msjson with JSON.parse:
Well, the date isn’t a valid date anymore.

How can we improve it. Rick Strahl gives a solution with custom functions for serializing and deserializing of ms date. But the thing is: we don’t need any custom functions for this, not if you run ASP.NET. The only thing we need is to use serialize and deserialize functions from Sys.Serialization.JavascriptSerializer namespace which you get automatically when you add ScriptManager in ASP.NET (and you get it even automagically in SharePoint).

But what about $.ajax and functions I wrote about for retrieving list items and populating them, and updating list items with listdata.svc?

Well, there comes the really nice tip from Rick Strahl: not to force $.ajax to parse the response. So instead of dataType: “json”, use the plain dataType: “text”. As the result we’ll get just a text, which we, of course, will deserialize with the native code for Microsoft:….

Use text when possible. When you define json as response format:

[WebGet(UriTemplate = "/GetSomething?id={id}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
object GetSomething(string id);


There we have to use json as datatype, but how to prevent jQuery.parseJSON. Well a digging into jQuery lib helped, just provide converters[“text json”] property to your jQuery.ajax invokation:

 	type: "GET",
	contentType: "application/jsonp; charset=utf-8",
 	url: "/_vti_bin/ListData.svc/Oppgaver()",
 	data: {},
 	dataType: "json",
	success: function(data) { foo = data; },
	error: function() { console.log("error"); },
	converters: { "text json": Sys.Serialization.JavaScriptSerializer.deserialize }

Alternatives are to rever to the invokation: var s = $.ajax…., then in callback get the s.responseText and deserialize.

Datetime and WCF

The response in json formats date like serialize. Let’s try to send datetime to wcf service. Here is the data contract and its implementation:

[WebGet(UriTemplate = "/Foo?date={date}", 
	ResponseFormat = WebMessageFormat.Json, 
	BodyStyle = WebMessageBodyStyle.Wrapped)]
string Foo(DateTime date);

public string Foo(DateTime date)
	return date.ToString("s");

If we pass date formatted in ISO, we’ll get the right date:

	type: "GET",
	contentType: "application/json; charset=utf-8",
	async: true,
	url: "/_vti_bin/MyWcfService.svc/Foo",
	data: { date: date.toISOString() },
	dataType: "json",
	success: function (data) { console.log(data.FooResult); },
	error: function (data) { console.log("error"); }

Now lets try this with POST. First we change the contract:

[WebInvoke(Method = "POST", 
	UriTemplate = "/Foo", 
	ResponseFormat = WebMessageFormat.Json, 
	RequestFormat = WebMessageFormat.Json, 
	BodyStyle = WebMessageBodyStyle.Wrapped)]
string Foo(DateTime date);

Pay attention to UriTemplate, now there are no GET parameters. It is important, otherwise it will conflict with the parameters passed inside the body.

Then let’s create the argument to pass:

var date = new Date()
var arg = { date: date }

Then we serialize it with JSON.stringify and Microsoft native serializing method:

var j = JSON.stringify(arg) // "{"date":"2012-01-18T23:35:35.878Z"}"
var ms = Sys.Serialization.JavaScriptSerializer.serialize(arg) // "{"date":"\/Date(1326929735878)\/"}"

Now let’s try both:

	type: "POST",
	contentType: "application/json; charset=utf-8",
	async: true,
	url: url,
	data: j,
        processData: false,
	dataType: "json",
	success: function (data) { console.log(data.FooResult); },
	error: function (data) { console.log("error"); }
// output: Foo 400 (Bad Request) 
// output: error

	type: "POST",
	contentType: "application/json; charset=utf-8",
	async: true,
	url: url,
	data: ms,
        processData: false,
	dataType: "json",
	success: function (data) { console.log(data.FooResult); },
	error: function (data) { console.log("error"); }
// output: 2012-01-18T23:35:35

So to pass a datetime argument in a GET request to WCF we have to create an ISO string (by running date.toISOString() or JSON.stringify(date) and removing outer quotes). In a POST request scenario we have to format the date in a WCF way, and the easiest way is to use Sys.Serialization.JavaScriptSerializer.serialise(date).

String.format for javascript

sprintf is actually the best javascript implementation of sprintf (string.format). But wait, shouldn’t it be some more .NET-like stuff in SharePoint environment? Indeed there is! (Well, not only in SP, but ASP.NET)

String.format(“Hello {0}”, “world”) does exactly the same thing as on server side. Wow, it opens for many opportunities, e.g. in jQuery tmpl:

String.format validates arguments, and if all is OK, it invokes another function String._toFormattedString:

function String$_toFormattedString(useLocale, args) {
    var result = '';
    var format = args[0];
    for (var i=0;;) {
        var open = format.indexOf('{', i);
        var close = format.indexOf('}', i);
        if ((open < 0) && (close < 0)) {             
            result += format.slice(i);
        if ((close > 0) && ((close < open) || (open < 0))) {
            if (format.charAt(close + 1) !== '}') {
                throw Error.argument('format', Sys.Res.stringFormatBraceMismatch);
            result += format.slice(i, close + 1);
            i = close + 2;
        result += format.slice(i, open);
        i = open + 1;
        if (format.charAt(i) === '{') {
            result += '{';
        if (close < 0) throw Error.argument('format', Sys.Res.stringFormatBraceMismatch);
        var brace = format.substring(i, close);
        var colonIndex = brace.indexOf(':');
        var argNumber = parseInt((colonIndex < 0)? brace : brace.substring(0, colonIndex), 10) + 1;
        if (isNaN(argNumber)) throw Error.argument('format', Sys.Res.stringFormatInvalid);
        var argFormat = (colonIndex < 0)? '' : brace.substring(colonIndex + 1);
        var arg = args[argNumber];
        if (typeof(arg) === "undefined" || arg === null) {
            arg = '';
        if (arg.toFormattedString) {
            result += arg.toFormattedString(argFormat);
        else if (useLocale && arg.localeFormat) {
            result += arg.localeFormat(argFormat);
        else if (arg.format) {
            result += arg.format(argFormat);
            result += arg.toString();
        i = close + 1;
    return result;

By the way, take a look at summary part of String.format:

/// <summary locid="M:J#String.format" />
/// <param name="format" type="String"></param>
/// <param name="args" parameterArray="true" mayBeNull="true"></param>
/// <returns type="String"></returns>

Great summary, how could we get intellisense on that in Visual Studio? Anyone know?

Another aspect of String.format I have discovered is that unfortunately you cannot format digitals like {0:00} like in C# (e.g. 8 gets 08). Then I recommend you zlib licensed javascript library called StringFormat from Daniel Mester PirttijÀrvi.

ASP.NET Ajax Toolkit

To integrate ASP.NET Ajax Toolkit is not the most straight forward task in SharePoint. If you want to take the risk, “Inspired by Technology” provides the best guide so far.

Push a copy of an object to client

To reduce postbacks and database calls, a copy of the current object(s) can be pushed down to the client in JSON format. Say a webpart renders information about a person, another webpart shows related information which is retrieved dynamically (like web services). Instead of getting the current person from the database in the second webpart again, we can reuse the same person object from the first webpart. To do so we must provide a DataContract for the Person class:

public class Person
	public string Firstname { get; set; }
	public string Lastname { get; set; }
	public string PhoneMobile { get; set; }

Then we can serialize the current object using DataContractJsonSerializer:

private void RegisterPersonOnClient(Person person)
	var serializer =
		new System.Runtime.Serialization.Json
	var ms = new MemoryStream();
	serializer.WriteObject(ms, person);
	var json = Encoding.UTF8.GetString(ms.ToArray());
	var script = "var personOnClient = " + json + ";\n";
		.RegisterStartupScript(GetType(), "uniqueScriptKey", script, true);

To be able to use these classes, add reference to System.Runtime.Serialization and System.ServiceModel.Web dlls. Don’t forget to append a semicolon and newline so that script doesn’t collide with other scripts.

On the client we get a copy of the person object:

Read more of this post

json serializer in Sharepoint

There is a very handy JSON lib for serializing javascript objects. It is hosted on github under douglas crockford.

Download json2.js and serialize with JSON.stringify function:

EDIT: There is actually this function in core javascript. It exists since javascript 1.7 and ecmascript 5. So you don’t have to add anything to get this functionality:

var t = { name: "dev", city: "new york" };

There are actually built-in goodies for serializing javascript objects in ASP.NET: Sys.Serialization.JavaScriptSerializer.serialize

var t = { name: "dev", city: "new york" };

I discovered it when I “studied” the javascript code which follows with every page. Will see if more goodies can be discovered there:

Read more of this post


Om du vill behÄlla dina vÀrden pÄ variabler mellan postbacks, anvÀnd ViewState:

if (ViewState["MaxNumberOfArticles"] != null)
	MaxNumberOfArticles = (int) ViewState["MaxNumberOfArticles"];
MaxNumberOfArticles += 10;
ViewState.Add("MaxNumberOfArticles", MaxNumberOfArticles);



Ett mycket bra inlÀgg frÄn Tom Puleos blogg om SPSecurityTrimmedControl. MÄste absolut testa det.

Discovering SharePoint

And having fun doing it

Bram de Jager talking Office 365, SharePoint and Azure

My view and thoughts on Productivity and more.

My programming life

and everything in between

SharePoint Development Lab by @avishnyakov

It is a good place to share some SharePoint stories and development practices.

SharePoint Dragons

Nikander & Margriet on SharePoint

RealActivity - Real-time and trustworthy

Blog site of founder, RealActivty - Paul J. Swider

Mai Omar Desouki - Avid SharePointer

Egyptian & Vodafoner - Senior SharePoint Consultant

Cameron Dwyer | Office 365, SharePoint, Outlook, OnePlace Solutions

Office 365, SharePoint, OnePlace Solutions & Life's Other Little Wonders


Me and My doings!

Share SharePoint Points!!

By Mohit Vashishtha

Jimmy Janlén "Den Scrummande Konsulten"

Erfarenheter, synpunkter och raljerande om Scrum frÄn Jimmy Janlén


SharePoint for everyone


Ryan Dennis is a SharePoint Solution Architect with a passion for SharePoint and PowerShell

SharePoint 2020

The Vision for a Future of Clarity

Aharoni in Unicode, ya mama

Treacle tarts for great justice

... And All That JS

JavaScript, Web Apps and SharePoint


Mostly what I know about SharePoint - CommunicoCuspis