SP Web Application Get Central Administration

With this code you can get the central administration webapplication.

   1:  private static SPWebApplication GetCentralAdministrationWebApplication()
   2:  {
   3:      SPWebService cS = SPWebService.ContentService;
   4:      var service = cS.Farm.Services.GetValue<SPWebService>("WSS_Administration");
   5:      SPWebApplicationCollection webApplications = service.WebApplications;
   6:      foreach (SPWebApplication webApplication in webApplications)
   7:      {
   8:          return webApplication;
   9:      }
  10:      return null;
  11:  }

If you have better solution, just tell me !

Collection Of using SPSiteDataQuery in whole site

To set up a query across a whole site collection you can use the SPSiteDataQuery object.

The following method fetches all .doc files from all doclibs of the site collection and prints out a list of urls to those items.

public void TestSiteDataQuery()
using (SPSite site = new SPSite("http://localhost"))
using (SPWeb web = site.OpenWeb("/"))
SPSiteDataQuery query = new SPSiteDataQuery();

// Search in doclibs only
query.Lists = "<Lists BaseType='1' />";

// Only .doc files
query.Query =
<FieldRef Name='DocIcon' />
<Value Type='Computed'>doc</Value>

// Select only needed columns: file reference
query.ViewFields = "<FieldRef Name='FileRef' />";

// Search in all webs of the site collection
query.Webs = "<Webs Scope='SiteCollection' />";

// Perform the query
DataTable table = web.GetSiteData(query);

// Generate an absolute url for each document
foreach (DataRow row in table.Rows)
string relativeUrl =
row["FileRef"].ToString().IndexOf("#") + 1);
string fullUrl = site.MakeFullUrl(relativeUrl);

// Write urls to console

If you have better solution, just tell me !

Get URL parameters & Using jQuery

In this post, I would like to share a little jQuery code snippet that makes getting URL parameters and their values more convenient.

Recently, while working on one of my projects, I needed to read and get parameter values from URL string of the current page that was constructed and sent by PHP script. I came across this short and sweet JavaScript code snippet by Roshambo that does just that.

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
hash = hashes[i].split('=');
vars[hash[0]] = hash[1];
return vars;

The function returns an array/object with your URL parameters and their values. For example, consider we have the following URL:


Calling getUrlVars() function would return you the following array:

"me" : "myValue",
"name2" : "SomeOtherValue"

To get a value of first parameter you would do this:

var first = getUrlVars()["me"];
// To get the second parameter
var second = getUrlVars()["name2"];

To make the script syntax to look more jQuery like syntax I rewrote it as an extension for jQuery:

getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
hash = hashes[i].split('=');
vars[hash[0]] = hash[1];
return vars;
getUrlVar: function(name){
return $.getUrlVars()[name];

Now you can use it in the following way:

// Get object of URL parameters
var allVars = $.getUrlVars();

// Getting URL var by its nam
var byName = $.getUrlVar('name');

If you have better solution, just tell me !

To Check whether to see a string is empty

There are several ways to check a string to see if it’s empty. However, you should try to always use the following method. It’s faster, and uses less resources. This may seem like a minimal piece of code -

string strAmIEmpty = "";

if (strAmIEmpty.Length == 0)


// empty so do something


But if you were checking strings through out your application, it all adds up in the end.

If you have better solution, just tell me !

Lookup fields and event lists - JQuery and SharePoint

JQuery to change the width of a mulitvalued lookup field in SharePoint and to hide the Workspace field in an event list.

The script to change the width of multivalued lookup fields:

<script type="text/javascript">

The script to hide the workspace checkbox in an event list:

This first bit of script hides the ‘Workspace’checkbox in the NewForm and the EditForm. The script to hide the workspace field from the DispForm.aspx:

<script type="text/javascript">

<script type="text/javascript">

There are several ways to add the script to the pages. For the Lookup fields I used the I descibe in this blog post. For the Event list, I created custom EditForm, NewForm and DispForm pages and added the script to those pages directly.

If you have better solution, just tell me !

Select Options Sorting and dropdown Using jQuery

There are probably a dozen ways to skin this cat, but this is how I did it (I was already using jQuery on this site):

// get the select
var $dd = $('#select-id');
if ($dd.length > 0) { // make sure we found the select we were looking for

// save the selected value
var selectedVal = $dd.val();

// get the options and loop through them
var $options = $('option', $dd);
var arrVals = [];
// push each option value and text into an array
val: $(this).val(),
text: $(this).text()

// sort the array by the value (change val to text to sort by text instead)
arrVals.sort(function(a, b){
return a.val - b.val;

// loop through the sorted array and set the text/values to the options
for (var i = 0, l = arrVals.length; i < l; i++) {

// set the selected value back

The above code will only work if the option values are numbers. If the values are alphanumeric and we are doing an alphabetical sort, then the sort function should be replaced with:

arrVals.sort(function(a, b){
return 1;
else if (a.val==b.val){
return 0;
else {
return -1;

If you have better solution, just tell me !

How To Change the Default EditForm, NewForm and DispForm


You’ve developed some custom new, edit and display application pages that are stored in the _layouts directory. Let’s assume the filenames are newform.aspx, dispform.aspx and editform.aspx. You now want to change the properties of your custom list so that any new, edit or display requests point to your custom pages.
If you open up your site within SharePoint Designer and expand the Lists folder, from there you can access the properties of that custom list by right clicking on it and selecting Properties. Once the List Properties pane is open, click on the Supporting Files tab.

You’ll see there that you can actually choose what display, edit and new forms you want your list to be using. So if you’ve developed something custom, you would click Browse…, point to your new location and select the file. Here is where it starts to fail, I am only able to browse within the site itself and cannot navigate to my _layouts directory to select the files I mentioned above.


I suspected this was a limitation of the SharePoint Designer UI and not actually a limitation of the Object Model. I did a bit of fiddling with my SPList object and was not able to find anything that let me change those properties. If you look at the screenshot above, there is a key piece of information that’ll make the light turn on (at least it did for me). The Supporting Files tab has a drop down selector for the Content type specific forms. If you think about that a moment, you’ll remember that ALL lists within SharePoint inherit from a default content type.

So armed with that knowledge, I created an SPContentType object and took a look at it’s properties and methods. Sure enough, there are 3 properties I can set to change these forms: EditFormUrl, NewFormUrl and DisplayFormUrl. Here is some sample code I used to change the forms for my custom list called ‘My List’ that inherits from the Item content type:

So in the example code above, I had to determine what default content type my list inherited from. In this case it was the Item content type.
So in the example code above, I had to determine what default content type my list inherited from. In this case it was the Item content type.


If you need to change the content type directly, you can definitely do that, however, I did a bit of testing and found that any lists ALREADY inheriting from that content type did not pickup my changes to the form locations. Any NEW list that I created that was inheriting from that content type did pickup the changes. In order for me to change the form locations for the existing list I had to use the code above. For reference, here is how you would change the content type directly. The code has only a subtle difference.

SPWeb web = SPContext.Current.Web;

web.AllowUnsafeUpdates = true;

SPContentType ct = web.ContentTypes["Name Of Your Content Type"];

ct.EditFormUrl = "_layouts/editform.aspx";
ct.NewFormUrl = "_layouts/newform.aspx";
ct.DisplayFormUrl = "_layouts/dispform.aspx";


As always, any questions, let me know!

SuperLoad jQuery Plugin

This plugin adds the ability to update multiple elements with a single Ajax response.

$.superLoad( options );

The options are the same as taken by the jQuery.ajax( ) method, with
the following observations:
dataType: defaults to 'html'
success: will be called after the content is updated on the page.

Expected response format:

<div class="ajax-response">

<div class="ajax-content" title="!update #div1">
Anything inside this div will be used to update the #div1 element
like $('#div1').html( $(thisDiv).html() );

<div class="ajax-content" title="!appendTo #div2">
Anything inside this div will be appended to the #div2 element
like $('#div2').append( $(thisDiv).html() );

<div class="ajax-content" title="!prependTo #div3">
Anything inside this div will be prepended to the #div3 element
like $('#div3').prepend( $(thisDiv).html() );

<div class="ajax-content" title="#div4">
if the !command is not given, !update will be assumed

<div class="ajax-content" title="!replaceWith #div5">
Replaces #div5 with this P element

//each script tag will be evaluated after the content has been applied.


The title attribute: 
  • The ajax-content element's title attribute is used to determine what to do with the content:
  • The format is: "!command selector"
  • "!command": defaults to !update
  • !update: replaces the inner HTML of the selected element(s) with the inner HTML of the ajax-content
  • !prependTo: adds the inner HTML of the ajax-content to the top of the inner HTML of the selected element(s)
  • !appendTo: adds the inner HTML of the ajax-content to the bottom of the inner HTML of the selected element(s)
  • !other: Beyond the above 3 standard !commands, one can also simply pass the name of any valid jQuery command (default of from a plugin) as long as the command is able to be applied to the selected element(s) and takes the new content as its argument.

Ajax Progress Bar Control

Published a ProgressBar AjaxToolKit control

View live demo

<!-- Continuous Mode / 150px wide -->
<mb:ProgressControl ID="ProgressControl1" runat="server" Mode="Continuous" Width="150px" />
<!-- Manual Mode / 70px wide -->
<mb:ProgressControl ID="ProgressControl12" runat="server" Mode="Manual" Width="70px" />

Modifing behavior control from UI Client using JQuery:

Play continous control $find('ProgressControl1').play();

Stop continous control $find('ProgressControl1').stop();

Set Percentage value control $find('ProgressControl1').set_percentage(62);

Increment percentage value control $find('ProgressControl1').set_percentage('+15');

The progressbar control support skins.


If you have better solution, just tell me !

JQuery and JSON Web Service

Use JQuery to consume JSON Web Services is a lightweight method, for increment performance in your website.

If you want call a JSON Web Service from your javascript code, you should : use HTTP POST and content-type "application/json; charset=utf-8″. Asp.Net Ajax make this for you transparently.

$(document).loadMyContent(function() {
type: "POST",
url: "myService.asmx/GetMyContent",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {

Insert javascript code after content for best performance.

JQuery Pluggins

JQuery Pluggins is a mechanism for adding in methods and functionality. You can found a lot of available pluggins. Read more about pluggin developing.

A simple example :

jQuery.fn.mypluggin = function() {
return this.each(function(){
Using our developped pluggin : $("div p").mypluggin ();

Combining javascript file

howto combine javascript files in 3.5 and 4.0.

<asp:ScriptManager runat="server">
<asp:ScriptReference Name="WebForms.js" Assembly="System.Web, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
asp:ScriptReference Name="MicrosoftAjaxWebForms.js" Assembly="System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<asp:ScriptReference Name="MicrosoftAjax.js" Assembly="System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
In 4.0 <asp:ScriptManager runat="server" EnableCdn="true"/>

If you have better solution, just tell me !

How to Add a ToolTip to the Telerik Ajax RadEditor

This one was not immediately obvious to me so I’m posting the solution here. I’m using a Telerik Ajax RadEditor on my page as follows:

<telerik:RadEditor ID="rhfNotes" EditModes="Preview" runat="server" ToolsFile="ToolsFile.xml">

Now, after doing a bit of inspection, I discovered there was a property I could set on the RadEditor called ToolTip that seemed to just require a string value as follows:


<telerik:RadEditor ID="rhfNotes" EditModes="Preview" runat="server" ToolTip="Some message to the user" ToolsFile="ToolsFile.xml">

I assumed this would produce exactly what I needed. Unfortunately, after testing the above out, I got nothing, no tool tip. Doing a search on the forums turned up nothing useful, not even an explanation as to what the ToolTip property was really for. However, I did come across an entirely separate control in the Ajax suite of controls called RadToolTip.

That’s clever I thought, perhaps I’ll just give that a go. I was hoping there would be some sort of property I would set that would allow me to specify what control to tie this tool tip to. Guess what! There is! My final solution was as follows:

<telerik:RadToolTip ID="rttNotes" runat="server" TargetControlID="rhfNotes" Text="Some message to user"></telerik:RadToolTip>
<telerik:RadEditor ID="rhfNotes" EditModes="Preview" runat="server" ToolsFile="ToolsFile.xml">

There you have it. I haven’t played around with all the properties and options I have available to me with the RadToolTip, but I’m sure there are some useful ones in there!

If you have better solution, just tell me !

Code Translation for .NET (C#<->VB.NET)

This service will translate the code for you, just start typing the code or upload a file to convert it.

For now it only supports from VB.NET to C# and from C# to VB.NET.

VB.NET to C# and from C# to VB.NET Click Here

To use it you can either:

  1. Start typing your code.
  2. Copy and Paste the code in the Code Text Box.
  3. Translate an entire file using the file upload.

No copy is done whatsoever of the code that you either type, or upload for translation. Everything is processed in the server in memory and returned immediately to the browser.

Copying an instance of a class object

I recently had a need to copy the instance of a fairly complex class object. More specifically what wanted was to load and instance of the object, from a data source. The object had about 40 properties some of which where collections of other classes.

So creating a new instance of the object then setting each property would be more time consuming and less elegant that I would like. Doing as standard set would just set a reference to the first object. So changes on the second object would made on the first instance. This was not the behavior I wanted either.

After doing a Google search and combining a few examples this what I cam up with.

PublicSub CopyObject( _
ByVal pObjectType As Type, _
ByVal pOriginalObject As Object, _
ByRef pNewObject As Object)

Dim ArPoperties() As Reflection.PropertyInfo = _
pObjectType.GetProperties(Reflection.BindingFlags.Public Or _
Dim ObjPropItem As Reflection.PropertyInfo
For Each ObjPropItem In ArPoperties
If ObjPropItem.CanWrite Then
ObjPropItem.SetValue(pNewObject, _
ObjPropItem.GetValue(pOriginalObject, Nothing), Nothing)
End If
As is the goal if this blog. I hope you find this useful.