Thursday, 17 October 2013

C# The Handle is Invalid

I have been given a task to debug a SharePoint event receiver as it wasn't doing what was meant to do, so I started by looking at event viewer logs. 

Event viewer error didn't helped much other then saying;

Error loading and running event receiver **Assembly Details**. Additional information is below.
: The handle is invalid

Searched google lot but couldn't find anything relevant in SharePoint context, but somehow figured out, this error "The handle is invalid" comes up when user doesn't have enough permissions to perform a task and in my case it was when event receiver tried to create a new event log or even when try to write a log to already created event log.

Fixed the issue by putting code within   SPSecurity.RunWithElevatedPrivileges(delegate(){  }); block, however couldn't figure out which exact permission was required to let user to write event logs but adding above fixed the issue for me, so all good.

Tuesday, 1 October 2013

Mass unfollow on twitter using chrome

Simply go to and then inspect any element, find console tab and type this script line 


It will press all the unfollow buttons for you, if you want to unfollow all then use page down key so all people you are following will become visible on page then run above script in console.

Friday, 20 September 2013

Directory Services Restore Mode NightMare

In short, I got a development virtual machine I run on my PC using virtual box, it's a stand alone SharePoint 2007 box along with SQL Server 2005 and K2 server 2003.

I was testing something which actually hanged my VPC machine and as a result I had to power off it which is veryyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy veryyyyyyyyyyyyyyyyyyyyyyyyyyy bad practice, but since I am using it for development and got out dated backup copies so wasn't a big issue for me. Anyway when i restarted it gave me this error,

I almost tried 100's of articles on Internet and couple of hours to fix the issue but couldn't but at-last I fixed it by following this MSDN article,

How To Use Ntdsutil to Manage Active Directory Files from the Command Line in Windows Server 2003

You also might find it useful to read this information about active directory files which helped me fix the issue and understand what happened but I won't going to explain it in here,

Active Directory files and their functions

and this link also helped even though it's for Exchange edb but applies to active directory edb recovery as well,

How to Solve Exchange Dirty Shutdown Error

To be continued if I get time I will explain a bit more or just add comment if you need help...

Friday, 13 September 2013

Getting SPUser using Login Name

Today I came across a situation where I had to let user input user name(s) and add them to people picker field within a list, unfortunately it has to be done using web services as user is interacting with SharePoint throw iPad.

Problem ?

User can input anything (any string) so I need to validate if user name(s) exists or not,  if user with login name provided has access to site collection page and at end if all previous are true then get SPUser object and add it to people picker field of custom list.


Assuming you already got or know how to get reference to SPSite, SPWeb, SPList and SPListItem objects

SPUser user = null;

if (!string.IsNullOrEmpty(userLogin))
           // statement below will throw exception if user doesn't exists
           if (site.RootWeb.DoesUserHavePermissions(userLogin, SPBasePermissions.Open))
                    user = site.RootWeb.SiteUsers[userLogin];
               catch (Exception ex)
                   string other = string.Format("EXCEPTION! UserName '{0}' provided doesn't has permissions to root web", userLogin);
                   throw new SoapException(other, SoapException.ServerFaultCode, ex);
       catch (Exception ex)
            string other = string.Format("EXCEPTION! UserName '{0}' provided doesn't exists", userLogin);
            throw new SoapException(other, SoapException.ServerFaultCode, ex);

       SPFieldUserValueCollection uvCollection = new SPFieldUserValueCollection();
       SPFieldUserValue uValue = new SPFieldUserValue(web, user.ID, user.LoginName);

//Now update item just by item["People PIcker Field Name"] = uvCollection;

That's it, above code worked for me so it should work for you.

Lesson learned

I tried to use RootWeb.Users[userLogin] but it didn't worked for me as it does not return users who have access through a group whereas I had some user's given access to root web through groups only.

RootWeb.AllUsers[userLogin] is a dangerous function as  it returns list of all users who ever had access to web (even ones who don't have access to web anymore now).

web.EnsureUser() method creates a user if not exists already which I couldn't use in this scenario as client input is being used to validate SPUser object.

Monday, 9 September 2013

Stored Procedure to query data using list parameter

Working on this task required me to create a stored procedure which will get a list of strings, do some processing on them and then return some data. Since SQL Server 2000 don't support arrays object so I had to find a different approach. After a bit of googling i figured out I can send list by building a string out of it and then in SQL Server use function "IN" to do processing as required.

Here'e the Stored Procedure,

USE [DataBaseName]


Create PROCEDURE [dbo].[StoredProcedureName]
@listParameter varchar(8000)   -- this is because SQL Server don't support "Max" --

exec('SELECT  *
FROM TableName
WHERE ColumnaName IN (' +@PasswordPolicyGroups+ ')   -- checks for list of values --
and CoumnaNameB= 1')

Now I am providing list as

List<String> myListData = GetListData(); // or your logic
string tempListData = string.Empty;

foreach(string data in myListData)
     data += "'" + myListData + "',";

// now just pass data as your parameter and call stored procedure

Tuesday, 3 September 2013

How to check if a SPWeb exists within a SPSite

SharePoint objects get bit tricky when it comes to check if an objects exists or not specially in SharePoint 2007. Today I came across a situation where I had to check if a web exists or not, so I tried using this code,

using (SPSite site = new SPSite(""))
using (SPWeb web = site.OpenWeb())
                //Do this

Above code complied perfectly and didn't threw any error at all, however it didn't worked as I was expecting an error e.g. "Web doesn't exists". So I did realized you give any address to SPSite() method it will try to get site collection object regardless of full URL provided exists or not, okay it's something that might does makes sense, but when it tries to open web using OpenWeb() method, it should open the web URL has been provided to, for example this URL,

It will opens SubSites web, and if URL is

It still opens up SubSites as SPWeb object.

I was expecting it to throw an error however it didn't so I got "true" for web.exists.

I did some research and figured out another way to find out if SPWeb actually exists for supplied URL or not,

public static void DoesWebExists()
       string tempUrl = "";
       Uri u = new Uri(tempUrl);

       using (SPSite site = new SPSite(tempUrl))
       using (SPWeb web = site.OpenWeb(u.AbsolutePath.ToString(), true))

Above example has been tested and works fine as far as SPSite object exists for provided Url.

How to check Assembly related errors using Fusion Log utility

One of most annoying exceptions we developer get is assembly found doesn't match with loaded assembly, even though we put right assembly in GAC. There can be tens of reason as why assembly loaded doesn't match and that's where fusion log utility helps.

In order to use this utility you need to have installed Microsoft SDKs or it gets installed when you installed visual studio. I have installed Visual Studio 2008 on Windows Server 2003 so my guide will be based on it.

Open Visual Studio 2008 command prompt and navigate to directory

C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin>

Now type fuslogvw.exe and you will see a windows appears as shown below,

Click on settings and check box Log all binds to disk as shown, you can also select "Custom log path" but make sure directory exists.

If your log was disabled before then you might need to do a IIS reset to make it start working. (it took mine around 30 minutes to pick up errors because of unknown reasons).

You will see logs as shown in picture below,

And clicking on any log will open it in browser as it's a html file, as shown below.

Make sure to disable log afterwords as otherwise they will take a lot of space within short time.

How to return Primary Key of just Inserted record into SQL Datatable using Strongly Typed DataSet

Inserting data directly into SQL data table isn't recommended because of security reasons, which is why most of us use Strongly Typed data-sets, it provides our solution with a secured layer to interact with database, enhancing security.

Saying that strongly data-sets are better way of interacting with database but they can sometime become hectic and consume time while debugging them specially when you use TableAdapter Query Configuration Wizard as it doesn't always configures your data-sets the way they should be.

Back to problem SCOPE_IDENTITY() not returning right value, as we use it to return the primary key generated by table when we try to insert some records into the specified table. Most of us simply use return SCOPE_IDENTITY() as it works sometimes and on some servers but it doesn't work other times (and that's when debugging takes ages).

Best way I recommend of getting back primary key of inserted record is by using OUTPUT Parameter in your stored procedure as it will make sure your strongly typed data-set get's the right value.

Here's an example of how your Stored Procedure for inserting a record should look like,

USE [DataBaseName]


CREATE procedure [dbo].[StoredProcedureName]
          @ColumnA int,
          @ColumnB int,
          @NewID int

INSERT Into tableName

In this article I will assume you already know how to create a data-set or have it ready, but if you don't know then you can find instructions at How to Create a DataSet ?.

Once your data-set is ready just drag and drop table or stored procedure into designer class from Server Explorer. Now if you drag and drop table which I would recommended you  can add a query and select your stored procedure using TableAdapter Query Configuration Wizard. Thing that you need to take care of is to select

"A Single Value - A typed function will be...."

Then name your stored procedure as you desire and finish the wizard. Your method will look something like this,

public int InsertDataMethod(solution.myRow details)
      int? output = 0;
      TableName_TableAdapter tableAdapter = new TableName_TableAdapter();
      using (tableAdapter.Connection = new SqlConnection(ConnectionString))
         tableAdapter.StoredProcedureDataSet(details.ColumnA, details.ColumnB, ref output);
       return Convert.ToInt32(output);

Make sure dataset's ExecuteMode property is Scalar otherwise it might doesn't return right ID.

Thursday, 8 August 2013

Preventing multiple events from triggering when adding a list item or document to a SharePoint list

Normally what happens is developer's use both Item Added and Item Updated events when they want to execute some specific code across just added list item, in result multiple list events triggers.

For example when a user adds a document to a document library first event triggers is Item Added when document is added to list, whereas second event occurs when user is forwarded to /Forms/EditForm.aspx?Mode=Upload  and user can change item's meta data.

You can prevent it by checking if added item is changed after being added to library/list or not using SPItemEventProperties.Versionless property.

For example (SharePoint 2007):

    class myEventReceiverClass: SPItemEventReceiver
        public override void ItemUpdated(SPItemEventProperties properties)

                // Only Execute if item hasn't been changed in edit form
                if (!properties.Versionless)

For SharePoint 2010 and 2013 it is recommended to use EventFiringEnabled for getting and setting event firing as shown in example below;

         public override void ItemUpdated(SPItemEventProperties properties)
            this.EventFiringEnabled = false;
            this.EventFiringEnabled = true;

Wednesday, 17 July 2013

How to check error's on K2 Black Pearl working in a SharePoint environment

When you deploy processes to K2 Black Pearl workflow server you can check process state as what stage it is on and if there's any error.

In order to view flow of process follow steps below,
  • Open Internet explorer on your K2 BP workflow server and navigate to this URL given below,

  • Make sure you use the right Server Name, once the page is loaded, click on Process Overview on left navigation as shown in picture below,

  • Now if you click on any process in Process Name column, it will take you to Process Instances window as shown in screenshot below. On this window you will be able to see some details about every single processes that has been initialized whether using ASP.NET application forms or a though a SharePoint web part. You are able to see who originated this process or if it's still running or complete.

  • If something go wrong then process instance will be in error state and it's process status will be "Error". You can view process flow by clicking on image within orange box in screenshot above. It will exactly show you place where process stopped. In K2 BP you can do Real Time Monitoring which isn't available in K2 2003 work-space. Real Time Monitoring will update process workflow without need of refreshing page again and again. Screenshot below showing example workflow,

  • If you want to see data related to process instance e.g. Data or XML fields then go back to previous page and click on it's Process's Folio e.g. Empty Folio in this case, you can set process instance's folio in process to be more specific e.g. have some title or id instead of Empty Folio. Clicking on process instance Folio will display further details e.g. Activity Name, Status, and then Duration which is a great feature for monitoring performance. An example screenshot is shown below,

  • Further clicking on Data in above screenshot will display data fields and there values, same with XML Data as it will display XML data that we may had used. Further clicking on Activity Name will display Event Name that are within that specific Activity. It will provide same details for events as we get for activities and an extra Destination which can be a role or activity.
  • K2 Black Pearl logs all errors that come up while running a process instance, you can view all processes errors by going to,

    >> Management ( Top Navigation Tab) >> Management Console >> K2 Black Pearl Server (Left Navigation Tab) >> WorkFlow Server >> Error Profiles >> All

  • You can also add new error profiles as if you have 10's of processes and you want to see errors related to a specific process only. Once you see the error, you can take steps you need to fix it.
  • After fixing the issue you can click on Retry to assume process from where it was stopped but sometimes you need to modify K2 black pearl process and redeploy it to see the changes. Check my blog post for how to deploy K2 BP process.
Note: Some of the screenshots used in this article has been picked up from Google search.

Thursday, 4 July 2013

Deploying K2 Black Pearl Project to INT or Production

Developing and deploying K2 black pearl on a development machine doesn't take a lot of effort but just few clicks, however when you want to deploy project to integration or production server you will need to create a deployment package. Once you get deployment project files you can use MSBUILD.exe to deploy it on Production server.

You can also deploy it remotely to production server as far as you are trying to deploy it within domain and port 5555 is enabled to communicate with other servers as other wise you will get connection refused or lost errors while deploying.

Follow steps below to create a package using Visual Studio 2010 and deploy it on Integration server with just K2 Black Pearl on it using MSBUILD,

  • Build your project so that you get the latest DLLs in your debug or release folder.

  • Right click on project and then click on "Create Deploy Package" as shown in picture below, you only get this option if you would had installed K2 BP extension for Visual Studio 2010.

  • Above steps will create a deployment package at directory,

    Directory To Your Project\Project Folder Name\Project Process Files\obj\Release
    //if your build is release then deployment project will be created or updated in release folder

  • Release folder has all the files you need for deployment so take it your K2 BP production server (with K2 BP already installed on it) and open Visual Studio command prompt or check this post out to see how to open VS command prompt.
  • Execute following commands one by one to deploy package to server,

    cd C:\Windows\Microsoft.NET\Framework\v2.0.50727

    MSBUILD "C:\Users\deploymentAccount\Desktop\Release\Deployment\myDeploymentFile.msbuild" /p:Enivronment=INT

Now if you receive this error,

C:\Users\deploymentAccount\Desktop\Release\Deployment\myDeploymentFile.msbuild(235,5): error : SmartObject Server Exception: Could not publish SmartObject Definition to server: Error refreshing Service Instance 'WorkflowReportingService'. Service returned : 'Workflow Reporting SO Service: MSDTC on
 server 'Database Server' is unavailable.
C:\Users\deploymentAccount\Desktop\Release\Deployment\myDeploymentFile.msbuild(235,5): error : '.
C:\Users\deploymentAccount\Desktop\Release\Deployment\myDeploymentFile.msbuild(235,5): error : . SmartObject: [My Project (20) Process Instances]
C:\Users\deploymentAccount\Desktop\Release\Deployment\myDeploymentFile.msbuild(235,5): error :
0 Warning(s)
1 Error(s)

Then remove following lines from file with MSBUILD extension in your deployment folder only if you didn't used smart objects,


In our environment, we are not using smart objects but while creating deployment package it just adds above lines and while deploying errors, so removing above lines result in successful deployment.

Wednesday, 19 June 2013

Convert WSDL file to a C# class and then DLL

Today I was trying to update a web reference of custom web services in my project but because of some reason visual studio 2010 wasn't getting the latest methods I added even though I could see them using browser. Hence to get around problem I converted WSDL file into C# class and then into a dll.

You can target dll to any framework you would like. In order to get DLL in .Net 4.0 framework try following steps;

For getting you library dll in.Net 4.0 framework you will require Visual Studio 2010 tools installed on your machine, however for it in .Net 3.5 framework you will need Visual Studio 2008.

  1. Open Visual Studio Command prompt as a administrator by going to Start menu > All Programs > Microsoft Visual Studio 2010 > Visual Studio Tools > Visual Studio Command Prompt (2010).
  2. Put your WSDL file in somewhere accessible e.g. in this case I will put it in my C drive and getting output CS class in C drive too but you can change it. Type this command and press okay,

    C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC>wsdl /l:C# /out:C:\OutPutClassName.cs C:\myWebService.wsdl
  3. Above command will generate a CS class in your C drive, now if you want to convert this class into dll in .Net 4.0, type this command;

    C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC>csc /target:library /r:System.Data.dll /r:System.Data.Services.Client.dll /out:C:\OutPutClassName.dll C:\OutPutClassName.cs

    Above command will get you class library dll in .Net 4.0 framework.
  4. In order to get ..Net 3.5 use this command,

    C:\Program Files\Microsoft Visual Studio 9.0\VC>csc /target:library /r:System.Data.dll  /out:C:\OutPutClassName.dll C:\OutPutClassName.cs
MSDN Reference:

Wednesday, 5 June 2013

Right way of installing assembly into GAC in Windows Server 2012

In previous version's of Windows Server we were able to simply drag and drop assemblies into GAC folder which wasn't recommended at all, however being in a development environment (Windows Server 2012) when I tried to drag and drop a DLL into GAC, I received this error,

Now if you want to install assembly to GAC following steps,

  1. Assuming you are new to Windows Server 2012, Move your mouse pointer to right bottom of your screen just next to Date & Time.
  2. Click on "Search" tile.
  3. Now enter "cmd" in search text box.
  4. Most likely you will see two apps named as "Command Prompt" and "Visual Studio Command Promp...".
  5. If you will right click on "Visual Studio Command Promp.." it will give you few options at bottom of screen as show in picture below,

  6. Click on "Run as administrator" and press "Yes" for typical dialogue appears each time you try to start       a processes as administrator as security confirmation.
  7. Now type down this command,

    cd C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC
  8. Copy your assembly to folder directory,

    C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC
  9. Once assembly is copied you can use following syntax to install assembly to GAC,

    gacutil /i mySolution.myProject.dll
    an IIS reset will be produced as a result of above command so be careful as if you might break any on going process

That's it. Your assembly is installed, you can follow the procedure as many times as you want.

For more information please check this MSDN link out:

Tuesday, 28 May 2013

SQL Sever 2008 R2 has an unsupported version error in SharePoint product configuration wizard

I was trying to create a SharePoint 2013 development VM and came across this nasty error,

SQL server at "SQLSERVERNAME" has an unsupported version at "" (IP address). Please refer to for more information on the minimum required SQL Server Versions and how to download them.

I also tried PowerShell to create a configuration database but got same error,

PS C:\Users\Administrator> New-SpConfigurationDatabase
cmdlet New-SPConfigurationDatabase at command pipeline position 1
Supply values for the following parameters:
DatabaseName: SharePoint_Config
DatabaseServer: MSSQLSERVER
Passphrase: myPass

I fixed the error by installing update for SQL Server by Microsoft to make it work with SharePoint 2013. I downloaded Microsoft® SQL Server® 2008 R2 Service Pack 1 from

Running this setup will update your SQL Server R2 to SP1 which is requirement for SharePoint 2013.

Upgrading your MCITP : SharePoint Administrator 2010 to SharePoint 2013 Solution Expert

If you already earned MCITP : SharePoint 2010 Administrator certification then you can easily upgrade it to SharePoint 2013 Solution Expert by passing 417, 331 and 332 exams, as shown in picture below,

Source :

There isn't any upgrade path came out yet(28-05-2013) for MCPD : SharePoint 2010 Professional developers to upgrade and get certified in SharePoint 2013.

Thursday, 23 May 2013

Capturing iPad or iPhone traffic using Fiddler2

Recently I have been given a task to find out why iPad application isn't getting the "correct" data from our SharePoint environment. I don't know much about how iPad has been developed but I been told it's consuming custom web services. Hence I downloaded Fiddler2 to analyse iPad traffic and see what has been requested by iPad and what is it getting in return.

Once you downloaded Fiddler2 on your computer, you can add proxy details to your iPad as shown in picture below,

Enter IP address of your computer in front of Server Make sure your port number matches one on Fiddler2 by default it's "8888". You can change default port by going to Tools > Fiddler Options > Connections > Fiddler listens on port:  as shown in picture below,

Now if you also want to capture HTTPS (secured) traffic then check boxes as shown in picture below,

Next step would be clicking on "Export Root Certificate to Desktop" and sending certificate you just exported on desktop to your iPad through email. Once you received it on your iPad just try opening the certificate and install it.

That's it, you can start capturing traffic now, one thing I would like to mention is that my iPad and Computer has been connected to same intranet network while I was debugging.

Tuesday, 21 May 2013

Restricting picture size in ItemAdding event receiver for SharePoint picture library

If you want to restrict user from uploading a picture larger then specified size (width x height) then you can use code below.

Please note it only works when user uploads a single picture file, when user uploads multiple files, SharePoint opens Microsoft picture manager to upload several pictures hence HTTP Context comes as null. I tried to find a fix for it but I couldn't so if someone reading this post please comment the solution. Until then you can disable multiple picture uploads to library.

Ways around would be create a custom list definition and then a custom upload form with all of code logic behind, you can make it work for single files or several files but depends on your code behind logic and requirements.

class PicLibraryImageSize : SPItemEventReceiver
        HttpContext _current;
        public PicLibraryImageSize()
            _current = HttpContext.Current;

        public override void ItemAdding(SPItemEventProperties properties)

                if (IspicTooLarge())
                    properties.Cancel = true;
                    properties.ErrorMessage = "Picture Too large to upload !";
            catch (Exception ex)
                //Log it

        private bool IspicTooLarge()
            HttpFileCollection cFiles = _current.Request.Files;

            HttpPostedFile pFile = cFiles[0];

            using (System.Drawing.Image image = System.Drawing.Image.FromStream(pFile.InputStream))
                if (image.Width > 800 ||  image.Height > 600)
                    return true;
                    return false;

Wednesday, 24 April 2013

Copying GAC before deployment on SharePoint Production WFEs servers

Few days back I needed to deploy few projects on production server's, since our SharePoint 2007 is properly customized and GAC is packed with custom solutions assemblies, and these solutions do get updated regularly. These DLLs depends on each other so if I update GAC with wrong version of a custom DLL it will break customized SharePoint which I don't want to happen therefore need a backup of GAC as part of backup plan.

Of course we have SharePoint Team foundation and we document each change, but when your farm is broken because of your newly deployed project solutions (which also updated few customized DLLs) you want to roll back quickly and without taking any risk of "wrong documentation" or if someone updated production server and forgot to update TFS somehow.

Copying DLLs out of GAC isn't really a difficult task and is really helpful when it comes to roll back. Follow these steps to backup everything in GAC folder or only the DLLs you think you need,

  • Click on Start and then on Run.
  • Put this command in text box and click "OK", as shown in figure below.

  • A window will appear with several folders but only folders you might need are ones shown in picture below,

  • Now you can copy all folders for backup or just find particular DLLs you need using search box. 
I personally copy all of folders and then once everything get's deployed perfectly, I delete the backup.

Wednesday, 10 April 2013

Get user's Name and there SID using CMD command

I created a windows form application to test one of custom web services I created but web services were getting IUSR_ESHAREDEMO  when I tried to get UserId using code given below,

string userID = HttpContext.Current.Request.LogonUserIdentity.User.Value;

I managed to get user I wanted by disabling the anonymous access for the web application in IIS Manager. However I used following CMD command to check login users on a server (there names and SID).

wmic useraccount get name, sid

Tuesday, 26 March 2013

Adding details to database table using SharePoint List event receiver

Here's a sample code to give you idea about how to add item details to database table using SQL stored procedure and ItemAdded event receiver,

    class myClass : SPItemEventReceiver
        public override void ItemAdded(SPItemEventProperties properties)

            catch (Exception ex)
                //log here

private void AddEntryToDataBase(SPItemEventProperties properties)
using (SqlConnection con = new SqlConnection(dc.Con))
using (SqlCommand cmd = new SqlCommand("sp_Add_ListItem", con))
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Title", SqlDbType.VarChar).Value = properties.ListItem.Title.ToStrinng;
cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = properties.ListItem.Name.ToString;


Check this link on MSDN for more information or just leave a comment below,

Wednesday, 20 March 2013

Random STSADM commands

I will be adding random STSADM commands for future references,

Getting deployment jobs 
stsadm -o enumdeployments

Cancelling a deployment job
stsadm -o canceldeployment -id

Executing deployment jobs
stsadm -o execadmsvcjobs

Tuesday, 19 March 2013

Web Method of custom SharePoint 2007 web services not getting update

Web Method of custom SharePoint 2007 web services not getting update

I created custom web services for SharePoint 2007 which I am going to consume in K2 2003 Server work flow. I added a new web method to custom web services (How to create custom web services) and then to make it work in my SharePoint 2007 environment I followed following steps,

  • Created a new virtual directory for web services in IIS Manager web services application with application pool that has been used for services.
  • When you are updating or adding something new to your web services solution, you will have to delete bin folder of the solution and re-compile solution in both debug and release mode or as required.

  • Point virtual directory to your web services solution, mine is on desktop as I am developing and debugging instead of developing, building and then putting files in virtual directory and I think most developers do same.
  • Run disco Commands in Visual Studio 2008 Command Prompt e.g.

    C:\Program Files\Microsoft Visual Studio 9.0\VC>disco http://localhost:99999/mySharePointLists2.asmx
  • Above command will get you two files in same folder directory as above.

In both files, replace the XML instruction:

<?xml version="1.0" encoding="utf-8"?>


<%@ Page Language="C#" Inherits="System.Web.UI.Page" %>

<%@ Assembly Name="Microsoft.SharePoint, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Import Namespace="Microsoft.SharePoint.Utilities" %>

<%@ Import Namespace="Microsoft.SharePoint" %>

<% Response.ContentType = "text/xml"; %>

In the .disco file, replace the <contractRef> tag with one using virtualised URLs:

<contractRef ref="http://localhost/web/customWebservice.asmx?wsdl" docRef="http://localhost/web/customWebservice.asmx" xmlns="" />


<contractRef ref=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request) + "?wsdl"),Response.ContentType = "text/xml"; %>
And update the <soap address> tags to use virtualised URLs and the correct method bindings and XML namespace:

<soap address="http://localhost/web/customWebservice.asmx" xmlns:q1="" binding="q1:CustomWebserviceSoap" xmlns="" />

<soap address="http://localhost/web/customWebservice.asmx" xmlns:q2="" binding="q2:CustomWebserviceSoap12" xmlns="" />


<soap address=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %>

xmlns:q1="" binding="q1:CustomWebserviceSoap" xmlns="" />

<soap address=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %>

xmlns:q2="" binding="q2:CustomWebserviceSoap12" xmlns="" />

In the .wsdl file, replace the <soap address> tags with virtualised versions:

<wsdl:service name="CustomWebservice">

<wsdl:documentation xmlns:wsdl="">Web Service Description here...</wsdl:documentation>

<wsdl:port name="CustomWebserviceSoap" binding="tns:CustomWebserviceSoap">

<soap:address location="http://localhost/web/customWebservice.asmx" />


<wsdl:port name="CustomWebserviceSoap12" binding="tns:CustomWebserviceSoap12">

<soap12:address location="http://localhost/web/customWebservice.asmx" />




<wsdl:service name="CustomWebservice">

<wsdl:documentation xmlns:wsdl="">Web Service Description here...</wsdl:documentation>

<wsdl:port name="CustomWebserviceSoap" binding="tns:CustomWebserviceSoap">

<soap:address location=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %> />


<wsdl:port name="CustomWebserviceSoap12" binding="tns:CustomWebserviceSoap12">

<soap12:address location=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %> />



Rename the two files to have an .aspx extension, e.g. customWebservicedisco.aspx and customWebservicewsdl.aspx
Deploy the .asmx, disco and wsdl files to 12\ISAPI. Check the NTLM permissions!
Deploy the DLL to the GAC and to the web applications /bin directory (check the NTLM permissions again). DO NOT know why both are necessary… Probably a CAS thing, you could probably get the same result by installing to the \bin directory only and raising the trust level on the server to full; or by creating a custom CAS policy
Reset IIS
Should be able to access the web service at

Tuesday, 5 March 2013

Random SQL Queries statements

I will be adding scripts or queries for future references that I sometimes have to use while working on SQL Server Management to interact with database,

Adding a new column to database table and populating value for records that are already there

Alter Table Table_Name Add Column_Name ColumnType


Update Table_Name Column_Name = Value

Disabling controls within a CSS class

I am working on a task where I needed to disable all of controls within a class. I have tried several ways but only one worked for me which is,

$(".myCSSClassName:input").attr('disabled', true);

This will definitely work when you have a div with class named as "myCSSClassName:input" it will disable all controls within this specific class.

Other possible ways of disabling controls within a CSS class are mentioned below but they didn't worked for me,


$('input.myClass').attr('disabled', '');

$("input.myClass").prop("disabled", true);

$('input.myClass').attr('disabled', 'disabled');

There are few other options that seems promising can view on this link.

Tuesday, 12 February 2013

How to use ULS Viewer in SharePoint environment

ULS Viewer a great tool that can be used by a SharePoint developer or Administrators to debug and find errors within a SharePoint environment. I personally use this tool when I am badly stuck somewhere while configuring or deploying a new feature and event receiver don't catch any meaningful error.

You can run this tool and try to do something with SharePoint, it will display logs for what's happening behind the scene. Here's a small guide on how to use ULS Viewer on a SharePoint server.

Download ULS Viewer using link given below,

Download ULS Viewer

Keep it "ULS Viewer.exe" somewhere you can easily access it, e.g. on Desktop.

Now Click on "File" > "Open From" > "ULS" or Simply press "Ctrl + U" as shown in picture below,

Another window will appear which will be pre-populated by directory for your ULS logs on SharePoint server, as shown in picture below,

Just click on "OK" and you will "Real Time" logs of what's happening behind the scenes in your SharePoint environment. By default it shows you all types of messages but you can only select "Show High Messages" which will trim down logs to display you errors with high priority.

Friday, 1 February 2013

Execute Timer Jobs in SharePoint 2007

Sometimes I want my custom SharePoint solutions to execute faster then normal or when they stuck, I use this STSADM command to execute timer jobs that are in waiting list,

stsadm -o execadmsvcjobs

However it will not trigger any custom timer job you deployed in your SharePoint 2007 Farm.

Tuesday, 22 January 2013

Links Missing in Central Admin SharePoint 2010

I am going through Microsoft Learning Kit for exam 60 - 667 and trying to practice SharePoint 2010 as recommended but when I installed User Profile Service using Farm wizard it installed and configured it properly however I am not able to start User Profile Synchronization service any more.

I have been given a free advise to log off and log again and I did it but when I tried to log in again and opened Internet explorer and tried to go to Central Administration using its URL I couldn't find few links, for example "Manage Services on Server" was missing.

I looked at Active directory and figured out account is in domain admins but figured out that if you don't open central administration as administrator, some links will be missing in SharePoint 2010 Configuration database version : 14.0.4762.1000.

I am still looking into why User Profile Synchronization service isn't starting at the moment and will make another post.

Source :

Monday, 21 January 2013

A control with ID 'topSiteMap' could not be found.

This morning I deployed a webpart to solution gallery using STSADM but it kept giving me error that a custom assembly isn't found even though it was in GAC.

I thought it might be a good idea to reference assembly and use WSP builder to deploy webpart again, so I retracted/removed using Central Admin and deployed it again using WSP builder as soon as I deployed it, I started getting this error,

Exception information:     Exception type: HttpException     Exception message: The DataSourceID of 'TopNavigationMenu' must be the ID of a control of type IHierarchicalDataSource.  A control with ID 'topSiteMap' could not be found. 
Request information:     Request URL: 

Any page I go to I get same ugly error, I looked at web application's web.config and figured out it has been recently modified, so I assumed its WSP builder that did some dirty work. I copied old back of web.config but nothing changed. I tried removing webpart completely and then add again using STSADM but still nothing changed it.

At end I started monitoring ULS logs and found multiple errors

Delegate Control: Exception thrown while building custom control 'Microsoft.SharePoint.SPControlElement': Microsoft.SharePoint.WebPartPages.WebPartPageUserException: A critical error has occurred on this page. Contact your system administrator if this problem persists.  at Microsoft.SharePoint.ApplicationRuntime.SafeControls.RethrowExceptionIfNeeded ()  at Microsoft.SharePoint.ApplicationRuntime.SafeControls.IsSafeControl (Type type, String & unsafeErrorMessage)  at Microsoft.SharePoint.Utilities.SPUtility.CreateServerControlFromAssembly (sControlAssembly String, String sControlClass)  at Microsoft.SharePoint.SPControlElement.BuildCustomControl (Template Control tctlPage, sControlAssembly String, String sControlClass, sControlSrc String, XmlNode xnElementDefinition, SPFeatureDefinition featdefElement, String sElementId)  at Microsoft.SharePoint.SPControlElement.BuildCustomControl (Template Control tctlPage)  at Microsoft.SharePoint.WebControls.DelegateControl.BuildCustomControlResilient (SPControlElement ctlelemDefinition)

I created another site collection for same web application and was getting errors for out of box webparts too.

While monitoring ULS randomly I found an error saying one of our custom utilities dll is missing, I checked gac and it wasn't there adding this custom dll in GAC and AJAXControlToolKit dll back in Web App's bin folder solved the problem.

Don't forget to do a IISReset after putting dll to gac otherwise it won't going to work.


Be careful while using WSP Builder for some reason when you try to "Uninstall" a solution it removes dlls from gac and web app bin's folder, not sure about web.config but you should always keep a backup copy of it.

Friday, 18 January 2013

Certificate for SharePoint website with SSL

HTTPS SSL Certificate on SharePoint Web Application

If you need SSL(Https) on your sharepoint web application you will need to have a certificate installed on your site, now if your site is required to be used within Local Intranet then instead of purchasing a certificate you can just install certificate role on your server and issue your website a certificate which can be installed by each member on there PCs. Now there might be a better way of doing it but this is what I did to fix certificate problem on our development server. 

I followed this blog post for installation of Certificate but you can just go to control panel, then add remove programs and then add system compnent or something like that, select certificate role. Go through wizard give your certificate authority some kind of name like CADevelopmentServer. Now you can issue a certificate using Certificate authority and get one on your web application by going through IIS web application properties, I will let you find out rest of it with pictures in this blog post,

Installing Certificate and getting Https for a website sounds like a hard task but its seems easier then anything and few clicks get you there.

Thursday, 17 January 2013

Updating Resources in 12 Hive

Updating Resources in 12 Hive

When we update resources in 12 hive Resources, we need to do a IIS reset to make changes get picked up by SharePoint. I was trying to create a new site using a custom Site Definition but because of wrong resource name of a list I was getting exception however when I changed resource and tried to create site again it didn't worked until I performed a IIS reset.