SharePoint and Google Maps – How to use them together

Here is an example how to use Google Maps and how to integrate it with SharePoint.

To start with you need to include the following files somewhere in your project

<SharePoint:ScriptLink ID=”JQueryJSFunctionality” runat=”server” Name=”/_layouts/myfolder/scripts/jquery-1.11.2.min.js”></SharePoint:ScriptLink>
<script src=”; type=”text/javascript”>

<script type=”text/javascript”>
var listName = ‘<%=ListName %>’; // This can be used to pass a list name from web part properties to the JavaScript/JQuery logic, this is a propert defined in the code behind of a user control

<!–<SharePoint:ScriptLink Name=”SP.js” runat=”server” OnDemand=”true” Localizable=”false” />–>
<SharePoint:ScriptLink ID=”ScriptLink1″ Name=”sp.debug.js” LoadAfterUI=”true” Localizable=”false” runat=”server” />
<SharePoint:ScriptLink ID=”userWorldMapJSFunctionality” runat=”server” Name=”/_layouts/myfolder/scripts/yourGoogleMapsLogicFileName.js”></SharePoint:ScriptLink>


Next is the JavaScript/JQuery code

Create instances of needed Google Maps functionalities

var gmGeocoder = new google.maps.Geocoder();
var gmBounds = new google.maps.LatLngBounds();

var mapOptions = {
zoom: 5,
mapTypeId: google.maps.MapTypeId.HYBRID

var gmMap = new google.maps.Map($(“#map_canvas”)[0], mapOptions);

// You can use this to listen when the Google Maps has finnished its operations
google.maps.event.addListenerOnce(gmMap, ‘idle’, function () {



// You can use this function class to pass on information to the Google Maps geo location finder

var street = “”;
var zip = “”;
var city = users[iter].city;
var country = users[iter].country;
address = street + “,” + zip + “,” + city + “,” + country;

gmGeocoder.geocode({ ‘address’: address }, function (user, allUsers) {
return (function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results.length == 0) {
//console.log(“Geocoding: There are no results for address ‘” + results[0].formatted_address + “‘! Expected exactly one result. > Do not show any marker on map for this address.”);
else {

// Here is where you get a results back for the specified address and start to construct data for a Google Maps marker
var externalCount = 0;
var internalCount = 0;
gmLatLng = results[0].geometry.location;
var msgForInfoWindow = “<div id=’slider1′ >”;
var colorValue = “red”;
if (user.isexternal == true) {
colorValue = “blue”;
} else {
var orderID = 0;

// The actual content that goes into the marker starts here
msgForInfoWindow += “<div class=’viewport’>”;
msgForInfoWindow += “<ul class=’overview’>”;


msgForInfoWindow += “<li>”;
msgForInfoWindow += “Add your data here”;
msgForInfoWindow += “</li>”;
msgForInfoWindow += “</ul>”;
msgForInfoWindow += “</div>”;
msgForInfoWindow += “<a class=’buttons prev’ href=’#’><</a>”;
msgForInfoWindow += “<a class=’buttons next’ href=’#’>></a>”;

msgForInfoWindow += “</div>”;
var isExternalMarker = false;
if (externalCount > internalCount)
isExternalMarker = true;

// Calling this function will create a maker based on the given parameters
SetMarkerForGoogleMapForSharePointList(gmLatLng, gmMap, gmBounds, + “, ” +, msgForInfoWindow, isExternalMarker);
else {
//console.log(“Geocode for address ‘” + address + “‘ was not successful for the following reason: ” + status);
} (users[iter], users));

//getting coordinates
gmGeocoder.geocode({ ‘address’: address }, function (results, status) {



function NullVerification(stringValue) {
var returnValue = ” “;
if (stringValue != null)
returnValue = stringValue;

return (returnValue);

function NullVerificationBool(stringValue) {
var returnValue = false;
if (stringValue != null)
returnValue = true;

return (returnValue);


function SetMarkerForGoogleMapForSharePointList(gmLatLng, gmMap, gmBounds, title, contentForInfoWindow, isExternalMarker) {

// This is just a logic on how to control the marker styling, you can use your own

var icon = “”;

if (isExternalMarker)
icon = “yellow”;
icon = “red”;
icon = “; + icon + “.png”;

// Create the marker for the Goole Map
var gmMarker = new google.maps.Marker({
position: gmLatLng,
map: gmMap,
title: title,
zIndex: 0,
icon: new google.maps.MarkerImage(icon)

// This will center the map based on given marker positions

// Define properties for the info window that is opened when the marker is pressed

if (contentForInfoWindow != null && contentForInfoWindow != “”) {
var gmInfowindow = new google.maps.InfoWindow({
content: contentForInfoWindow,
maxWidth: 500,
maxHeight: 600

// This will attach a listener to the marker to that we can apply logic when it is opened.

google.maps.event.addListener(gmMarker, ‘click’, function () {, gmMarker);
$(‘#slider1’).tinycarousel({ bullets: true });
var t = 0;

// This is an example how to retrieve data from a SharePoint list using JavaScript 

function retrieveListItems() {

var clientContext = SP.ClientContext.get_current();
if (IsEmpty(listName))
listName = ‘UsersMapData’;
var oList = clientContext.get_web().get_lists().getByTitle(listName);

var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(‘<View><Query><Where><And><IsNotNull><FieldRef Name=”Country” /></IsNotNull><And><IsNotNull><FieldRef Name=”City” /></IsNotNull><IsNotNull><FieldRef Name=”PersonName” /></IsNotNull></And></And></Where><OrderBy><FieldRef Name=”ID” Ascending=”True” /></OrderBy></Query></View>’);
this.collListItem = oList.getItems(camlQuery);


clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));


 // When the data retrieval from the list succeeds this function is called. Here the needed data is then retrieved and parsed. Then passed on to be used later

function onQuerySucceeded(sender, args) {

var listItemInfo = [];

var listItemEnumerator = collListItem.getEnumerator();

// Here the data from SharePoint is went through and items are retrieved to container objects to be used later

while (listItemEnumerator.moveNext()) {

var oListItem = listItemEnumerator.get_current();
var newUserData = { id: oListItem.get_id(),
name: oListItem.get_item(‘PersonName’),
country: oListItem.get_item(‘Country’),
city: oListItem.get_item(‘City’),
imageLocation: oListItem.get_item(‘UserImageLocation’)

return (listItemInfo);

function onQueryFailed(sender, args) {

alert(‘Request failed. ‘ + args.get_message() + ‘\n’ + args.get_stackTrace());

SharePoint 2013 Blog – Change the author of the post with a custom selected user

This is a sample JS to use with the posts webpart in the SharePoint blog(JSLink webpart property). Originally I wanted to the blog.xsl but I simply could not get it to world desirably in SharePoint 2013. Well it worked in a different manner that what it used to be in SharePoint 2010.

Here is the code with comments:

var userID = 0;
var globalListItemIDs = [];
var spjsLoaded = false;
var listName = “Viestit”;
var customUserFieldInternalName = “PostOwner”;

// Main function – Start point
(function () {

var overrideCtx = {};

overrideCtx.Templates = {};

// Register a template override for the author field
overrideCtx.Templates.Fields = {‘Author’:{‘View’:CBody}};


function CBody(ctx) {

// Load SP client context, ote async event
SP.SOD.executeFunc(‘sp.js’, ‘SP.ClientContext’, sharePointReady);

// create a point of focus where to add the loaded information from the post item user field, Notice taht we are using the list item ID as an identifier where to put our user data
var ret = “<b><span class=’Blog_userTemplateContextData’ id=’userTemplateContextData” + ctx.CurrentItem.ID +”‘></span></b>”
var newListItemData = { id: ctx.CurrentItem.ID };


//var ret = ctx.CurrentItem.Body;

return ret;


function sharePointReady() {
if(spjsLoaded == true)
spjsLoaded = true;

clientContext = SP.ClientContext.get_current();
website = clientContext.get_web();

var oList = clientContext.get_web().get_lists().getByTitle(listName);

// Check if a specific post list item is specified, this would mean that the user is viewing a sigle post
var listItemID = getParameterByName(‘ID’);

// If no single post id is found then load all available posts and their custom users to be used instead of the author(TODO: Optimize for displayed posts only)
if(listItemID === null || listItemID === “”)
/*for (var iter = 0; iter < globalListItemIDs.length; iter++)
listItemID = globalListItemIDs[iter].id;
MakeNewDataCall(oList, clientContext, listItemID);
var camlQuery = new SP.CamlQuery();

camlQuery.set_viewXml(‘<Query><OrderBy><FieldRef Name=”Created” Ascending=”False” /></OrderBy></Query>’);
this.collListItem = oList.getItems(camlQuery);


clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
} else
// Only a single post is needed
MakeNewDataCall(oList, clientContext, listItemID);
var newListItemData = { id: listItemID };



function MakeNewDataCall(oList, clientContext, listItemID)
var camlQuery = new SP.CamlQuery();

camlQuery.set_viewXml(‘<Query><Where><Eq><FieldRef Name=”ID” /><Value Type=”Counter”>’ + listItemID + ‘</Value></Eq></Where><OrderBy><FieldRef Name=”Created” Ascending=”False” /></OrderBy></Query>’);
this.collListItem = oList.getItems(camlQuery);


clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

function onQuerySucceeded(sender, args) {

var listItemInfo = [];

var listItemEnumerator = collListItem.getEnumerator();

// Get the post data(single or many) and process it
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
var listItemID = oListItem.get_id();

// Seek the SharePoint generated posts and seek if the current item is something we want to process
var userDataDiv = document.getElementById(“userTemplateContextData” + listItemID);
if(!(userDataDiv === null))
var author = oListItem.get_item(‘Author’);
// IF so then get the custom user information
var personOwner = oListItem.get_item(customUserFieldInternalName);
if(!(personOwner === null))
var name = personOwner.get_lookupValue();

// Put default data that is going to be used if a user image is not found, Notice that we define a user image location
userDataDiv.innerHTML = “<span class=’Blog_postUserData’ id=’postUserData” + personOwner.get_lookupId() +”‘>” + name + “</span>”;
var context = SP.ClientContext.get_current();
var web = context.get_web();
var userInfoList = web.get_siteUserInfoList();

// Make a call to the user profile information for this user to see if there is a user image available
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(‘<View><Query><Where><Eq><FieldRef Name=”ID”/><Value Type=”Number”>’ +personOwner.get_lookupId()+ ‘</Value></Eq></Where></Query><RowLimit>1</RowLimit></View>’);
this.listItems = userInfoList.getItems(camlQuery);
context.executeQueryAsync(Function.createDelegate(this, this.onProfileSuccessMethod), Function.createDelegate(this, this.onQueryFailed));

function onProfileSuccessMethod(sender, args) {
var item = listItems.itemAt(0);
var firstName = item.get_item(‘FirstName’);
var lastName = item.get_item(‘LastName’);
var userId = item.get_id();
// Get the location where the user image is to be inserted
var userDataDiv = document.getElementById(“postUserData” + userId);
if(!(userDataDiv === null))
// If there is an image then use it, if no image is provided do nothing and display the user full name instead.
var picture = item.get_item(‘Picture’);
if (picture!=null) {
userDataDiv.innerHTML = “<img class=’Blog_userDataImgClassStyle’ src='” + picture.get_url() +”‘ height=’42’><span class=’Blog_postUserDataName’ id =’postUserDataName’>” + firstName + ” ” + lastName + “</span>”;

function onQueryFailed(sender, args) {

alert(‘Request failed. ‘ + args.get_message() + ‘\n’ + args.get_stackTrace());

function getParameterByName(name) {
name = name.replace(/[\[]/, “\\[“).replace(/[\]]/, “\\]”);
var regex = new RegExp(“[\\?&]” + name + “=([^&#]*)”),
results = regex.exec(;
return results === null ? “” : decodeURIComponent(results[1].replace(/\+/g, ” “));

Lessons learned from WebAPI and MVC Implementations

My Notes on a painful journey to learn, make and publish a Azure hosted MVC, Sinlge-Page application, Android client app and a WebAPI working with-one another. Software technology can be real pain in the ass!!!

JSON and Self referencing loop

If you get the following error:

Self referencing loop detected for property ‘your model’ with type ‘System.Data.Entity.DynamicProxies


Loop Reference handling in Web API

My Solution:

I used [JsonIgnore] attribute to tell the proper inheritance to JSON serialization.

using Newtonsoft.Json;

public partial class Set
public Set()
this.Exercises = new HashSet<Exercise>();

public long Id { get; set; }
public string Name { get; set; }
public string UserId { get; set; }

public virtual ICollection<Exercise> Exercises { get; set; }

public partial class ExerciseRecord
public long Id { get; set; }
public double Record { get; set; }
public System.DateTime Date { get; set; }
public System.DateTime StartDate { get; set; }
public System.DateTime EndDate { get; set; }
public long ExerciseId { get; set; }

public virtual Exercise Exercise { get; set; }

public partial class Exercise
public Exercise()
this.ExerciseAttributes = new HashSet<ExerciseAttribute>();
this.ExerciseRecords = new HashSet<ExerciseRecord>();

public long Id { get; set; }
public string Name { get; set; }
public double Target { get; set; }
public long SetId { get; set; }
public virtual Set Set { get; set; }
public virtual ICollection<ExerciseAttribute> ExerciseAttributes { get; set; }
public virtual ICollection<ExerciseRecord> ExerciseRecords { get; set; }


MVC loads older script files

This is due to browser script caching. The easiest solution for this is to set the browser which you are using to debug to retrieve the newest versions of web page content on each time you visit a webpage.

Missing Key definition from Model when creating a controller

You might get an error like this: EntityType ‘your type’ has no key defined. Define the key for this EntityType.

To fix such problems simply add this namespace definitions:

using System.ComponentModel.DataAnnotations;

And then define in your data model a key like this:

public class ColumnDataHighChart
public int ID { get; set; }
public String Title { get; set; }
public String SubTitle { get; set; }
public IList<String> xAxisCategories { get; set; }
public String yAxisTitle { get; set; }
public IList<SeriesDataHighChart> Series { get; set; }



Intercepting web requests


I have two ways of doing this:

  1. A delegation handler
  2. Or an action filter for a controller.

Delegation handler

DelegatingHandler Class

Sample code:

public class AuthHandler : DelegatingHandler
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
// Call the inner handler.
var response = await base.SendAsync(request, cancellationToken);
return response;

Action filter for a controlle

Notice that for MVC and Web API there are two different sets of action filter definitions:

MVC Sample:

public class AuthenticationActionFilterHelper : ActionFilterAttribute
public override void OnActionExecuting(ActionExecutingContext filterContext)
if (HttpContext.Current != null && HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
if (SessionHelper.LoggedInUser<AspNetUser>(HttpContext.Current.User.Identity.Name) == null)
//SessionHelper.UserSessionID = user.Id;
AspNetUsersController aspUserCon = new AspNetUsersController();
var sessionUser = aspUserCon.GetUser(HttpContext.Current.User.Identity.Name);
//SessionHelper.UserSessionID = user.UserName;
SessionHelper.LoggedInUser<AspNetUser>(sessionUser, sessionUser.UserName);


WebAPI Sample:

public class AuthenticationActionFilterHelper : ActionFilterAttribute
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)

public override System.Threading.Tasks.Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, System.Threading.CancellationToken cancellationToken)
return base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);

public override void OnActionExecuting(HttpActionContext actionContext)
if (HttpContext.Current != null && HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
if (SessionHelper.LoggedInUser<AspNetUser>(HttpContext.Current.User.Identity.Name) == null)
//SessionHelper.UserSessionID = user.Id;
AspNetUsersController aspUserCon = new AspNetUsersController();
var sessionUser = aspUserCon.GetUser(HttpContext.Current.User.Identity.Name);
//SessionHelper.UserSessionID = user.UserName;
SessionHelper.LoggedInUser<AspNetUser>(sessionUser, sessionUser.UserName);

public override System.Threading.Tasks.Task OnActionExecutingAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
return base.OnActionExecutingAsync(actionContext, cancellationToken);


Lambda Expression “Magic” 🙂

Retrieve distinct parent from child elements

As the title suggests I needed to retrieve the parent from a multilevel data set:


First I needed to get the child elements and in this exmaple it is assumed that you have the child elements retrieved.

Once you have the child elements it is time to get the distinct parent elements. for this I needed a way to group the distinct parent from the child elements. Here are my steps:

  • Get child elements:

ExerciseRecordsController exerciseRecordsController = new ExerciseRecordsController();
var exerciseRecordsData = exerciseRecordsController.GetExerciseRecords().Where(er => er.Date > startDate && er.Date < endDate && er.Exercise.Set.UserId.ToLower().CompareTo(this.user.Id.ToLower()) == 0);

  • Define a custom extension named “DistinctBy”

public static class LambdaExtensions
public static IEnumerable<t> DistinctBy<t>(this IEnumerable<t> list, Func<t, object> propertySelector)
return list.GroupBy(propertySelector).Select(x => x.First());
} Original code from:

  • Apply the new extension on the data set

var setsData = exerciseRecordsData.DistinctBy(o => o.Exercise.SetId).Select( o => o.Exercise.Set);

How to create/populate a collection with data with an unknown data type

You may ask yourself why would anyone needs this? Well I do not why would others needs this but I came into a situation where I needed this.

I had a solution where I needed to be able to create data from a back-end server WebAPI to a JS HighCharts JS library without knowing what kind of data I would be processing, also I wanted to have the possibility to extend the back-end code so that it can return any kind of data to the client and let the client figure out what to do with the data.

So how to do this?

In a human language it goes something like this: Use LINQ in your code to go through the data set, select your data and return it as and array of objects, then create a new collection by passing to the constructor your processed data as an array of objects. Ofcourse your collection must store objects as well. The data type information is going to be stored because every class in C# is a descendant of the Object class.

public class SeriesDataHighChart
public long ID { get; set; }
public String Name { get; set; }
public IList<object> Data { get; set; }


// One series corresponds to one set and data for each month
SeriesDataHighChart seriesData = new SeriesDataHighChart();

seriesData.ID = chartSet.Id;
seriesData.Name = chartSet.Name;
var seriesMonthsActivityCountData = (from monthActivityCount in chartSet.ChartSetMonthsData
select new object[] { monthActivityCount.ActivityCount as object });
seriesData.Data = new List<object>(seriesMonthsActivityCountData.ToArray());



You could also return an array of more complex object such as a key value pairs:

var sd = from d in unparsedData
select new object[] { d.Key as object, d.Value as object };

newSeries.Data = new Data(sd.ToArray());

Avoiding “Sequence contains no elements” exception in object initializers

If you have something like this in your code:

chartExercise.ChatMonthsData.Add(new ChartExerciseMonthData
ActivityCount = exercise.ExerciseRecords.Where(m => m.Date.Month == month && m.Date >= startDate && m.Date <= endDate).Count(),
StartDate = DateTime.Now.StartOfMonth(month),
EndDate = DateTime.Now.EndOfMonth(month),
MonthRecordAverage = exercise.ExerciseRecords.Where(m => m.Date.Month == month && m.Date >= startDate && m.Date <= endDate).Average(a => a.Record)



The Average lambda expression will throw the above exception error message because the Where clause may return Zero elements back(Notice that for example the Count expression will not throw a similar exception).

To fix(go around the problem, yes there might be other solutions but this was mine at the moment 🙂 ) I created an anonymous function that checks if there are elements returned by the clause and only then perform the Average operation on the elements. The solution is highlighted with the green color.

chartExercise.ChatMonthsData.Add(new ChartExerciseMonthData
ActivityCount = exercise.ExerciseRecords.Where(m => m.Date.Month == month && m.Date >= startDate && m.Date <= endDate).Count(),
StartDate = DateTime.Now.StartOfMonth(month),
EndDate = DateTime.Now.EndOfMonth(month),
MonthRecordAverage = new Func<double>(() => {
double averageRecord = 0;
var exerciseRecordByDateRange = exercise.ExerciseRecords.Where(m => m.Date.Month == month && m.Date >= startDate && m.Date <= endDate);
if (exerciseRecordByDateRange.Count() > 0)
averageRecord = exerciseRecordByDateRange.Average(a => a.Record);

return (averageRecord);

 Get the count for a complex data structure/hierarchy, tree like

A rather simple implementation, choose to retrieve any records inside your main records set with a where:

set.Exercises.Where(o => o.ExerciseRecords.Any(m => m.Date.Month == month)).Count()

Update Azure SQL Database via SQL Server management studio and Generated scripts

  1. Mouse second button on database > Taskas > Generate Scripts > Choose your objects (Chose objects view) > Select “Advanced” button, then in the “Script for the database engine type” select option Windows Azure SQL Database
  2. Next open the database connection with management studio to your Azure SQL Database.
  3. Create a new empty database
  4. Open a new query windows and simply add the generated script to this window and run the script against the new empty database. This will create the structure and data if you selected so.

After deploying your WebAPI you get a following error when accessing your database data “There is already an open DataReader associated with this Command which must be closed first.”

To fix this error simply add the following to your connection strings used in your web api in Azure MultipleActiveResultSets=true.

Enable WebAPI Cross-Origin Resource Sharing (CORS)

You might run into problems after deploying your WebAPI to Azure and trying to access your api from different origins. Here is a solution:

Summary of the article above: Install the following nuget package in your WebAPI project: Microsoft.AspNet.WebApi.Cors

In your webapiconfig add the following(in green):

public static class WebApiConfig
public static void Register(HttpConfiguration config)
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

var cors = new EnableCorsAttribute(“*”, “*”, “*”);

// Web API routes

name: “DefaultApi”,
routeTemplate: “api/{controller}/{id}”,
defaults: new { id = RouteParameter.Optional }

config.MessageHandlers.Add(new Handler.AuthHandler());

Next add the following to your ApplicationOAuthProvider.GrantResourceOwnerCredentials function:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
context.OwinContext.Response.Headers.Add(“Access-Control-Allow-Origin”, new[] { “*” });
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
//SessionHelper.UserSessionID = user.Id;
AspNetUsersController aspUserCon = new AspNetUsersController();
var sessionUser = aspUserCon.GetUser(user.Id);
//SessionHelper.UserSessionID = user.UserName;
SessionHelper.LoggedInUser<AspNetUser>(sessionUser, user.UserName);
if (user == null)
context.SetError(“invalid_grant”, “The user name or password is incorrect.”);

ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,

AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);


Notice that these changes may have undesired effects. Find out if these are suitable to your needs.

Alter or Style SharePoint List forms (New, Edit and Display)

With the JS code below you can modify a SharePoint form view to your wishes. I commented what is important and highlighted such code and HTML with the green color.

In the example below there is one part that I have to explain a little better:

$(“.ms-formtable tr a[name=’SPBookmark_your_field_id’]”).parent().parent().parent().children(“”)

The “parent.parent.parent.children” part means that we need to get the cell with the actual value. The reason why I did not try to directly to get the value with jquery but went to the value through a work around is because I had problem getting the value. The value is populated by SharePoint javascript meaning that I was not able to find a good way to identify the exact table cell where a particular value of a field resided. If you have a better solution please let me know in the comments, thx :).

JQuery code to find and perform styling and possible data alteration to a Display form table cell(s):

var SPFormsFunctionalities = {
AlterAccountsLedgerDisplayForm: function () {
// Make sure that we only operate on SP Display Forms and nothing else
if (window.location.href.indexOf(“DispForm.aspx?ID=”) > -1) {

// Remove any SharePoint adittional comments in the TD to get to the actual datetime value
$(“.ms-formtable tr a[name=’SPBookmark_your_field_id’]”).parent().parent().parent().children(“”).contents().filter(function () {
return this.nodeType == 8;

// Get the value and remove any whitespaces to make sure that there is actual data or if we want to process that data
var creditStoppageValue = $.trim($(“.ms-formtable tr a[name=’SPBookmark_your_field_id’]”).parent().parent().parent().children(“”).html());

// If the value is not empty then highlight it
if (!SPFormsFunctionalities.empty(creditStoppageValue)) {
$(“.ms-formtable tr a[name=’SPBookmark_your_field_id’]”).parent().css(“color”, “red”);
$(“.ms-formtable tr a[name=’SPBookmark_your_field_id’]”).parent().parent().parent().children(“”).css(“color”, “red”);
// Make sure that we only operate on SP Edit Forms and nothing else
} /*else if (window.location.href.indexOf(“EditForm.aspx?ID=”) > -1) {
alert(“found EditForm”);

empty: function (data) {
if (typeof (data) == ‘number’ || typeof (data) == ‘boolean’) {
return false;
if (typeof (data) == ‘undefined’ || data === null) {
return true;
if (typeof (data.length) != ‘undefined’) {
return data.length == 0;
var count = 0;
for (var i in data) {
if (data.hasOwnProperty(i)) {
return count == 0;

if ($) {
function () {

The HTML upon which the JQuery code above would operate on

<table class=”ms-formtable” style=”margin-top: 8px;” border=”0″ cellpadding=”0″ cellspacing=”0″ width=”100%”>

<td nowrap=”true” valign=”top” width=”113px” class=”ms-formlabel“><h3 class=”ms-standardheader”><a name=”SPBookmark_sp_internal_field_name_goes_here”></a>your field title is here</h3></td>
<td valign=”top” class=”ms-formbody” width=”350px” id=”SPFieldDateTime”>
<!– FieldName=”SP field name is here”
FieldInternalName=”sp internal field name is here”
<span id=’WPQ2da070d16-f172-4faf-8060-029b2a734fc6sp_internal_field_name_goes_here’ data-sp-control=’SPFieldDateTime’ data-sp-options='{&quot;mode&quot;:1,&quot;source&quot;:&quot;sp_internal_field_name_goes_here&quot;}’></span>



The empty function is from:


Notice: That this example was tested against SharePoint 2010

Good to Know: Windows Azure and Web Services functionality


Here is my knowledge source listing for Windows Azure and Web Services functionality. Hope it helps someone:

Accessing Data
.NET Framework Data Providers
ADO.NET Entity Data Model Designer
ADO.NET Entity Data Model Designer
ADO.NET Entity Data Model Tools
Advanced using OData in .NET: WCF Data Services
ASP.NET Application State Overview
ASP.NET Session State Overview
CacheDependency Class
CacheItemPolicy Class
CacheItemPriority Enumeration
ChangeMonitor Class
Code First to an Existing Database
CommandType Enumeration
Configuring Parameters and Parameter Data Types
Create Database Wizard (Master Data Services Configuration Manager)
DataAdapter Class
DataAdapter.AcceptChangesDuringFill Property
DataContractAttribute Class
DataSet Class
DataSet Class
DataTable Class
DbContext Class
DBContext vs ObjectContexts
DbContext.SaveChanges Method
DbContext.Set<TEntity> Method
DbDataAdapter.Fill Method (DataSet)
DbDataAdapter.Update Method (DataSet)
Demystifying Entity Framework Strategies: Loading Related Data (Eager Loading,  Lazy Loading, Explicitly Loading)
EdmEntityTypeAttribute Class
EF Designer TPT Inheritance
Entity Data Model Wizard
Entity Framework
Entity Framework – Database First
Entity Framework (EF) Documentation
Entity Framework 5: Controlling automatic query compilation
Entity Framework- Code First to a New Database
EntityCommand Class
EntityConnection Class
EntityObject Class
EntityTransaction Class
How to: Use Lazy Loading to Load Related Objects
HttpContext.Cache Property
Improve Performance with Entity Framework 5
IsolationLevel Enumeration
LINQ (Language-Integrated Query)
LINQ to Entities: Basic Concepts and Features
LINQ to Objects
LINQ to XML [from BPUEDev11]
LINQ to XML Overview
Loading Related Entities (Eager Loading,  Lazy Loading, Explicitly Loading)
Model-First in the Entity Framework 4
ObjectCache Class
ObjectContext Class
ObjectContext management
ObjectQuery Class
ObjectQuery.ToTraceString Method
ObjectQuery<T> Class
Object-relational impedance mismatch
OData protocol
Open Data Protocol by Example
Plain Old CLR Object(POCO)
Precompiling LINQ Queries
Queries in LINQ to Entities
Relational database management system
Retrieving Data Using a DataReader
SerializableAttribute Class
SQL Server Connection Pooling (ADO.NET)
SqlCommand Class
SqlCommand.CommandText Property
SqlCommand.ExecuteReader Method
SqlCommand.ExecuteScalar Method
SqlConnection Class
SqlConnectionStringBuilder Class
SqlDataAdapter Class
SqlDataReader Class
SqlDataReader.Read Method
SqlParameter Class
SqlTransaction Class
System.Data.EntityClient Namespace
System.Data.SqlClient Namespace
System.Transactions Namespace
System.Xml Namespaces
Table-per-Type vs Table-per-Hierarchy Inheritance
The ADO.NET Entity Framework Overview
TransactionScope Class
Understanding ASP.NET View State
Understanding Service-Oriented Architecture
Update Model Wizard (Entity Data Model Tools)
Using the DbContext API
Using the REST Interface
Walkthrough: Mapping Table-per-Hierarchy Inheritance in Dynamic Data
WCF Data Services 4.5
WCF Data Services Overview
Working with Datasets in Visual Studio
Working with POCO Entities
XElement Class
XML Documents and Data
XmlDocument Class
XmlReader Class
XmlWriter Class
XPath Examples
Designing and implementing WCF Services – Create, Configure, Secure, Consume
Accessing Services Using a WCF Client
Azure Service Bus
Basic [WCF Samples]
BasicHttpBinding Class
BinaryMessageEncodingBindingElement Class
Binding [WCF Samples]
Chapter 7: Message and Transport Security
Choosing a Message Exchange Pattern
CompositeDuplexBindingElement Class
Configuration Editor Tool (SvcConfigEditor.exe)
Configuring Services Using Configuration Files
Creating the Web Service Proxy
Custom Binding Samples
Custom Bindings
Data Contract Known Types
DataContractAttribute Class
DataMemberAttribute Class
Difference between BasicHttpBinding and WsHttpBinding
Endpoints: Addresses, Bindings, and Contracts
EnumMemberAttribute Class
Extending Dispatchers
Extensibility [WCF Samples]
Fault Contract
Fault Contract – Handling Errors in WCF and A Very Simple WCF Service Implementation
Getting Started Tutorial
Host WCF in an Azure worker role (CSAzureWCFWorkerRole)
Hosting WCF Services
How to: Create a Transactional Service
How to: Create a Windows Communication Foundation Client
How to: Expose a Metadata Endpoint
How to: Implement a Windows Communication Foundation Service Contract
How to: Inspect or Modify Messages on the Client
How to: Set the Security Mode
How to: Use the ChannelFactory
IClientMessageInspector Interface
IDispatchMessageInspector Interface
KnownTypeAttribute Class
Message Inspectors
Message Patterns in WCF Services
Message Security in WCF
MetadataExchangeBindings Class
MtomMessageEncodingBindingElement Class
NetMsmqBinding Class
NetNamedPipeBinding Class
OneWayBindingElement Class
OperationBehaviorAttribute Class
OperationContractAttribute Class
Programming WCF Security
Publishing Metadata
Reliable Sessions Overview
ReliableSessionBindingElement Class
Scenario [WCF Samples]
Securing and Authenticating a Service Bus Connection
SecurityBindingElement Class
Service Bus Bindings
Service Bus Queues, Topics, and Subscriptions
ServiceBehaviorAttribute Class
ServiceContractAttribute Class
ServiceHost Class
ServiceModel Metadata Utility Tool (Svcutil.exe)
Sessions, Instancing, and Concurrency
Simplified Configuration
Simplified Configuration for WCF Services
SslStreamSecurityBindingElement Class
Status codes
System-Provided Bindings
TextMessageEncodingBindingElement Class
TransactionFlowBindingElement Class
Transactions in WCF Services
Types Supported by the Data Contract Serializer
Using Data Contracts
WCF Configuration Tools
WCF Extensibility – IParameterInspector
WCF Extensibility: Parameter Inspectors
Versioning Strategies
Windows Communication Foundation Endpoints
Windows Communication Foundation Tools
WindowsStreamSecurityBindingElement Class
WSHttpBinding Class
Creating and consuming Web API-based services – Design, Implement, Secure, Host and Manage, Consume
A WebAPI Basic Authentication Authorization Filter
AcceptVerbsAttribute Class
ActionFilterAttribute Class
Add Models and Controllers
Async Streaming in ASP.NET Web API
Asynchronous Programming with Async and Await (C# and Visual Basic)
Authentication and Authorization in ASP.NET Web API
Basic Authentication in ASP.NET Web API
Content Negotiation in ASP.NET Web API
Cross-Site Request Forgery (CSRF)
Dependency Injection in ASP.NET Web API 2
Enabling Cross-Origin Requests in ASP.NET Web API 2
Enabling CRUD Operations in ASP.NET Web API 1
Forms Authentication in ASP.NET Web API
Getting Started with ASP.NET Web API 2 (C#)
How to host your web API.
HTTP Authentication: Basic and Digest Access Authentication
HttpClient Class
HttpClient.GetAsync Method (String)
HttpMessageHandler Class
HttpResponseException Class
HttpResponseMessage Class
Integrated Windows Authentication
JSON and XML Serialization in ASP.NET Web API
Makecert.exe (Certificate Creation Tool)
Media Formatters in ASP.NET Web API 2
Media Formatters in ASP.NET Web API 2
Parameter Binding in ASP.NET Web API
Preventing Cross-Site Request Forgery (CSRF) Attacks in ASP.NET Web API
Preventing CSRF Hacks in ASP.NET WebAPI
Routing Service
Routing Services [WCF Samples]
synchronous Streaming in ASP.NET WebApi
Using Asynchronous Methods in ASP.NET MVC 4
Working with SSL in Web API
Deploying web applications and services
Azure Guest OS Releases and SDK Compatibility Matrix
Azure Service Definition Schema (.csdef File)
Configuring a Web Server for Web Deploy Publishing (Remote Agent)
Configuring Parameters for Web Package Deployment
Configuring Step 1: Install IIS and ASP.NET Modules
Continuous Delivery for Cloud Services in Azure
Continuous delivery to Azure using Visual Studio Online
Export a Package through IIS Manager
Get Started with Azure Cmdlets
Get started with Azure Websites and ASP.NET
How to Configure Cloud Services
How to Deploy an Azure Website
IIS Information
Installing and Configuring Web Deploy on IIS 7
Installing NuGet
Manage Deployments in Azure
NetworkConfiguration Schema
Nuspec Reference
Package Manager Console Powershell Reference
Reference for the Web Application Package
Shadow Copying Assemblies
Step 1: Examining the Configuration Files
Swap Deployment
Team Build + Web Deployment + Web Deploy + VS 2010 = Goodness
Web Deploy Command Line Syntax
Web Deployment Overview for Visual Studio and ASP.NET
Web.config Transformation Syntax for Web Project Deployment Using Visual Studio

SharePoint SummeryLinks Webpart JQuery modifications – Make it into a “drop down” menu

Here is a small JQuery piece of code that you can use to minimize the space required on a page with summary links webpart. This will collapse the links listing under the webpart title. To make the links visible again you have to press the webpart title again.


jQuery(“table .dfwp-list”).slideUp();

jQuery(“table .dfwp-list”).closest(‘table’).hover(

The JQuery code above is tested on SharePoint 2010. The most important piece in this code is the CSS class named dfwp-list. When targeting this class you are targeting an UL LI HTML structure where the links exist. With a little modification you can use this code to add the each LI borders, colors and other styling to make it look more like a drop down menu.

Good To Know: ASP .NET MVC Reference Guide


This is my collection of sources of the most “relevant” information on ASP .NET MVC. Hope this helps you if you need information on MVC and web development with Microsoft Tools.

Design the application architecture – Application Layers, Azure, State Management, Caching, WebSocket, HTTPModules
ASP.NET MVC 4 Content Map
.NET On-Premises/Cloud Hybrid Application Using Service Bus Relay
A Beginner’s Guide to HTTP Cache Headers
ASP.NET MVC Views Overview
ASP.NET Routing
ASP.NET State Management Overview
Beginners guide to HTML5 Application Cache API
Caching in .NET Framework Applications
Controllers and Action Methods in ASP.NET MVC Applications
Differences Between ASMX and WCF Services
Distributed Cache
Donut Caching and Donut Hole Caching with Asp.Net MVC 4
Donut Caching with ASP.NET MVC 4
Entity Framework
Extending ASP.NET Processing with HTTP Modules
Getting Started with ASP.NET Web API 2
Global.asax File
HOW TO: Write a Simple Web Service by Using Visual C# .NET
HTML5 Web Storage
HTTP Handlers and HTTP Modules Overview
IHttpModule Interface
Improving Performance with Output Caching (C#)
INFO: ASP.NET Configuration Overview
Introducing “Razor” – a new view engine for ASP.NET
Introducing WebSocket HTML5
Introducing Windows Azure
Introducing Windows Azure AppFabric Applications
Introduction to HTTP Modules
Learn About ASP.NET Web API
patterns & practices: Data Access Guidance
Run Startup Tasks in Windows Azure
The WebSocket API
Two Ways of Passing HTML5 Web Storage Data to ASP.NET
Use AppCmd.exe to Configure IIS at Startup
Using an Asynchronous Controller in ASP.NET MVC
WCF Web HTTP Programming Model
Windows Azure Execution Models
Windows Azure Jump Start (03): Windows Azure Lifecycle, Part 1
Windows Azure Jump Start (04): Windows Azure Lifecycle, Part 2
Design the user experience – User Interface Design and Implementation
About Font Embedding
AjaxExtensions.BeginForm Method
ASP.NET MVC 4 Content Map
Compatibility tables for support of HTML5, CSS3, SVG and more in desktop and mobile browsers.
CSS Media Types
CSS Reference
DisplayModeProvider Class
EditorExtensions.EditorFor Method
How To Test ModelState.IsValid In ASP.NET MVC
How to: Implement Remote Validation in ASP.NET MVC
How to: Validate Model Data Using DataAnnotations Attributes
HTML DOM innerHTML Property
Html.BeginForm() vs Ajax.BeginForm() in MVC3
HTML5 New Input Types
HtmlHelper Class
JavaScript prototype Property
JavaScript Tutorial
jQuery Documentation
jQuery Mobile
jQuery Mobile Framework
jQuery UI
JsonRequestBehavior Enumeration
JsonResult Class
Kendo UI Mobile
LinkExtensions.ActionLink Method
ModelStateDictionary.IsValid Property
Partial View in ASP.NET MVC 4
Rendering a Form in ASP.NET MVC Using HTML Helpers
Sencha Touch
Simplifying HTML generation in code using Razor templates
Styles.Render Method
System.Web.Mvc.Ajax Namespace
System.Web.Mvc.Html Namespace
Understanding JavaScript Prototypes.
Using the viewport meta tag to control layout on mobile browsers
ValidationExtensions.ValidationMessageFor Method
ValidationMessageFor HTML Helper in MVC3 Razor
Vendor-specific Properties
Views and UI Rendering in ASP.NET MVC Applications
Develop User Experience – Search Engine Optimization, Globalization and Localization, Routes, Application Behaviour, Network Optimization
13 ASP.NET MVC extensibility points you have to know
Action Filtering in ASP.NET MVC Applications
ActionResult Class
ActionResult.ExecuteResult Method
An Introduction to ASP.NET MVC Extensibility
ASP.NET Globalization and Localization
ASP.NET MVC – Basic overview of different view engines
ASP.NET MVC Custom Model Binder
ASP.NET MVC Model Binding and Data Annotation
ASP.NET MVC Routing Overview (C#)
ASP.NET Routing
Attribute Usage Guidelines
BindAttribute Class
Bundling and Minification
Configuring HTTP Compression in IIS 7
CultureInfo Class
Custom Controller Factory in ASP.NET MVC
FilterAttribute Class
HandleErrorAttribute Class
How to: Set the Culture and UI Culture for ASP.NET Web Page Globalization
HTML 5: The Markup Language (ARIA Edition)
Mage.exe (Manifest Generation and Editing Tool)
Microsoft Ajax Content Delivery Network
MVC 4 Part 4 – Bundles and Optimisation
MvcRouteHandler and MvcHandler in ASP.NET MVC Framework
ResourceManager Class
Search Engine Optimization Toolkit
Subscriber Locale Codes
The Features and Foibles of ASP.NET MVC Model Binding
Thread.CurrentUICulture Property
Using CDN for Windows Azure
Using Value Providers in ASP.NET 4.5
Walkthrough: Organizing an ASP.NET MVC Application using Areas
WebPart.AuthorizationFilter Property
What’s the Difference Between a Value Provider and Model Binder?
ViewResultBase Class
VirtualPathProviderViewEngine Class
Troubleshoot and debug web applications – Runtime issues, Exception handling, Testing, Debuging
AppDomain.FirstChanceException Event
Assert Class
Beginners Guide to Performance Profiling
Code Contracts
Code Contracts
Code Contracts for .NET
Collect Logging Data by Using Windows Azure Diagnostics
Configuring Performance Sessions for Profiling Tools
Configuring Windows Azure Diagnostics
Controller.OnException Method
Create and Use Performance Counters in a Windows Azure Application
customErrors Element (ASP.NET Settings Schema)
Debugging a Cloud Service in Visual Studio
Debugging Cloud Services
HandleErrorAttribute Class
How To Put Your Toe Into ASP.NET MVC Integration Testing
How to: Break When an Exception is Thrown
How to: Handle Application-Level Errors
How to: Receive First-Chance Exception Notifications
Integration Testing Your ASP.NET MVC Application
Invariants and Inheritance in Code Contracts
Isolating Code Under Test with Microsoft Fakes
Logging Error Details with ASP.NET Health Monitoring (C#)
MVC: Error Page implementation
Performance and Diagnostics Hub in Visual Studio 2013
Performance Profiler in Visual Studio 2012
Quick Start: Test Driven Development with Test Explorer
Record and run a web performance test
Remote Debugging a Window Azure Web Site with Visual Studio 2013
System.Diagnostics.Contracts Namespace
TraceListener Class
Tracing in ASP.NET MVC Razor Views
Understanding Web Tests
Unit Testing in ASP.NET MVC Applications
Use the Windows Azure Diagnostics Configuration File
Walkthrough: Using TDD with ASP.NET MVC
What is a First Chance Exception?
Windows Performance Monitor
Working with Web Tests
Design And Implement Security – Authentication, Authorization, Data Integrity, Hacks and Security, Communication
A Beginner’s Tutorial on Custom Forms Authentication in ASP.NET MVC Application
A Custom SqlRoleProvider for “Authenticated Users”
Anti-Cross Site Scripting Library
Apple Secure Coding Guide
ASP.NET Impersonation
ASP.NET MVC Authentication – Global Authentication and Allow Anonymous
Asp.Net MVC With the ValidateAntiForgeryToken For Cross Site Request Forgeries
ASP.NET Web Application Security
Authenticating Users with Windows Authentication (C#)
AuthorizeAttribute Class
Basic Security Practices for Web Applications
Client Certificates vs. Server Certificates – What’s the Difference?
Configure ASP.NET Impersonation Authentication (IIS 7)
Create an ASP.NET MVC 5 App with Facebook and Google OAuth2 and OpenID Sign-on (C#)
CryptoStream Class
Custom Authentication and Authorization in ASP.NET MVC
Custom Authentication with MVC 3.0
Custom Membership Providers
Custom Membership Providers – Task Manager
Custom Role Providers
DpapiProtectedConfigurationProvider Class
FormsIdentity Class
How to Authenticate Web Users with Windows Azure Active Directory Access Control
How to configure Custom Membership and Role Provider using ASP.NET MVC4
How to Create an Intranet Site Using ASP.NET MVC
How to: Create a WindowsPrincipal Object
How to: Create GenericPrincipal and GenericIdentity Objects
How To: Encrypt Configuration Sections in ASP.NET 2.0 Using RSA
How To: Use Membership in ASP.NET 2.0
HtmlHelper.AntiForgeryToken Method
HttpEncoder Class
Microsoft Web Protection Library
OAuthWebSecurity.Login Method
OAuthWebSecurity.VerifyAuthentication Method
patterns & practices Improving Web Services Security – Now Released
Programming WCF Security
Provider Model Design Pattern and Specification, Part 1
RequireHttpsAttribute Class
Role-Based Authorization (C#)
RSACryptoServiceProvider Class
RsaProtectedConfigurationProvider Class
SAML 2.0 tokens and WIF – bridging the divide
Securing Your ASP.NET Applications
Security Practices: ASP.NET Security Practices at a Glance
Seed Users and Roles with MVC 4, SimpleMembershipProvider, SimpleRoleProvider, Entity Framework 5 CodeFirst, and Custom User Properties
SqlMembershipProvider Class
SqlRoleProvider Class
System.Security.Cryptography Namespace
System.Threading.Thread.CurrentPrincipal vs. System.Web.HttpContext.Current.User or why FormsAuthentication can be subtle
Thread.CurrentPrincipal Property
Understanding and Using Simple Membership Provider in ASP.NET MVC 4.0
Understanding the Forms Authentication Ticket and Cookie
Understanding Windows Identity Foundation (WIF) 4.5
Using IIS Authentication with ASP.NET Impersonation
Using OAuth Providers with MVC 4
Walkthrough: Using Forms Authentication in ASP.NET MVC
WCF Security Fundamentals
WCF Using Windows Authentication and SqlRoleProvider over basicHttp
WebSecurity Class
Windows Communication Foundation Security
WindowsIdentity Class
WS-Trust 1.3 OASIS Standard

Programatically forcing print styles to a web page in SharePoint

If you have a situation where you want to force print styling(or any other styling) on a page request made from any machine or application you have two options:

1. You identify the HTTP request header information(user agent) and see what application/source has requested this page request.

2. Specify a query string parameter that when encountered in a page request the wanted styling will be applied.

Basically both options have the same code which I will explain below. They only differ in the way the recognition of the printing request is done. In this example I will show the option number two.

A simple approach is to use a master page code or you could do it with a HttpHandler but a mater page approach is faster to do.

The code is rather simple:

  1. Identify the query string key and get the value
  2. Insert in the PlaceHolderAdditionalPageHead content placeholder control your CSS registration. This will add your CSS registration in the header of the HTML output. Notice that you gotta make sure your content placeholder is preferably just before the ending of the </head> HTML tag. This is to make sure that you CSS will overwrite anything else done before.

Here is the code:

String qsID = Request.QueryString[“myquerystingkey”];

            if (!String.IsNullOrEmpty(qsID))


                switch (qsID.ToLower())


                    case “print”:


                            if (this.PlaceHolderAdditionalPageHead != null)


                                this.PlaceHolderAdditionalPageHead.Controls.Add(new Literal() { Text = “<link rel=’stylesheet’ type=’text/css’ media=’all‘ href=’printer.css’>” });


                        } break;





Basically you can apply this to any form of web application just replace the page header control with some other method of inserting your CSS file reference. Also take notice that for this to work the media attribute on the link reference requires to be in the ALL mode not print. If it is set to print then you would have to make a print request to the browser. to do this you could do one of the following:

  1. Create a link button to perform the print: <A HREF=”javascript:window.print()”>Print me</A>
  2. Or you can do something similar what we did above with the CSS and insert a javascrip block with the invocation of the print request:

<script type=”text/javascript”>

Sharepoint: Hide alternative text from webparts with JQuery


This is a rather simple tip for those who might want to hide the alternative text from their webparts header. Add the following to your javascript file that is included into your environment:

$j(“.ms-WPTitle”).attr(“title”, “”);

What it does is simple. Searches for a class named ms-WPTitle that exist in the sharepoint webparts header. Then replaces all title attributes with an empty text.

SharePoint Language specific CSS loading

Today I worked on a annoying problem where I had to figure out how to do a language specific CSS file loading during header load from a Master Page.

The solution is as following in our case:

Our code deploys under the LAYOUTS folder our project style sheets, js files etc. We created for each language ID it’s own folder and under each language folder the css file that we wanted to use for a each language.

Next we addedthe following line inside the <HEAD> element and the right CSS file based on the language ID was loaded:

<SharePoint:CssRegistration name=”<% $SPUrl:/_layouts/projectname/styles/~language/master.css %>” runat=”server”/>

In the definition above what is in bold and in blue is what you MUST add for the reference to work. What is in green and not in bold is your path where your CSS file is located. Change it to fit your needs.

What is the most interesting part is the “~language” definition in the URL. This will retrieve the proper language ID(example for English-US: en-US). The final URL reference will look something like this: