Thursday, November 15, 2012

sharepoint event receiver before after properties

Working with the SharePoint event handlers is the one of the regular requirement we need to work on.

There is lot of confusion while working with EventHandlers about the before and after properties values.

For this reason i am giving here tabular structure of the details below :

** This reference i have taken from the other Microsoft blogs **

Happy coding !!!

SharePoint User Profile Synchronization stuck on Starting

This is the one of the strange issue when you are working with sharepoint.

For me this error occured on of a sudden, last week. It took 2 days to find a resolution for this error.

Finally got the solution today.

I am not able to browse my web application and trying to find the root cause of the issue finally i figured out that User Profile Service synchronization is stuck on starting.

User profile synchronization service stuck on starting as below

Basically sharepoint user profile service is dependent on active directory and lot of other stuff. Managed meta data service is one of them.

When managed metadata service and user profile services run on paralally this will cause a dead lock situation. Because of this Forefront Identity manager service might be disabled as shown below

Solution :

Below are the resolution steps for this issue :

1. Delete the User profile service from CA

Open Central Admin -> Click on Manager Service Applications -> Delete the User profile service

2. Configure and start the managed metadata service

3. Re configure the user profile service

4. Start user profile synchronization service

5. Restart IIS Service

NOTE : Step 2 and 3 are optional if you really using Managed metadata service

Thank you !!

Tuesday, November 6, 2012

Increase session timeout in SharePoint

While working with the sessions in SharePoint we will get session time out exception for some times to over come this we have to increase session time out period of the web application.

This can be done in Central Admin

Follow the below navigation

Open Central Administration -> Application Management -> Manage web application -> Select Your web application -> Click on General Settings -> Here in web page security validation section you can set the session time out period as shown below :

sharepoint SPLongOperation

Usually when you are working with sharepoint, we have to create site programatically or any other operations programatically which will take more time than the usual.

This kind of srenarios rather than depending on the browser processing we can use the sharepoint beauty i.e SPLongRunOperation.

Here is the way to use this.

protected void btnSubmit_Click(object sender, EventArgs e)

     using (SPLongOperation longOperation = new SPLongOperation(this.Page))
         longOperation.LeadingHTML = "";
         longOperation.TrailingHTML = "Please wait your changes are processed";
         string URL = SPContext.Current.Web.Url + "/Pages/OperationDone.aspx";

This will give you a screen like below :

Thank you !!

BDC Service application Business Data Connectivity Service is not accessible SharePoint

Here is the issue working with sharepoint.

he BDC Service application Business Data Connectivity Service is not accessible

Causes for the issue :

There are 2 possible reasons for this issue those are listed below

1. Business Data Connectivity service is not configured properly

2. SharePoint Web Service application is down to access the data

Resolution :

Open Internet Information Manager ( IIS ) and Expand the Sites

Click on SharePoint Web Serves and click on Authentication in IIS section as shown in the below diagram :

And make sure that you should set all the properties as shown in the below image :

Except Annonymous authentication and Widnows authentication rest all should be disabled.

And also follow the instruction given in the other thread after this ( This will also be the other reason for the same issue So, It is mandatory )

Thank you !!!

SharePoint DateTimeControl validation

Here i am explaining how to validate a sharepoint datetime control with required field validator.

Datetime control is a very easy to use but internally it is having a drawback of required validation property.

It has a property called IsRequiredField But it will not work for date format validation when you are working with Visual web parts or web parts.

For this we have to use classical ASP.NET required field validator to validate control

Internally the DateTimeControl of SharePoint is just a calendar dropdown and a text box. Also, they already implemented a simple required field validation by just using the IsRequiredField property.

However, if you try to put an validator (i.e.: CompareValidator, RegularExpressionValidtator, etc…) on it, it says it can’t find the control. This is happening because the DateTimeControl is just a wrapper around this textbox and if you set the Validator ControlToValidate property to the DateTimeControl it isn’t smart enough to know to really validate against the actual textbox

Here is the way you need to define


NOTE : Here ControlToValidate property you need to set as {DateControlID}${DateControlID}Date then only it will work otherwise it will through error

Thank you !!!

Monday, November 5, 2012

this solution contains resources scoped for a web application

This is one more issue you will get when you try to deploy the sharepoint template project.

This is because of the targeted scope and deployment of the application is at Web application level.

Couple of fixes for this in different scenarios :

In Case of Solution Deployment from VS :

Go to Properties of the project by clicking on F4

Change the Change the assembly Deployment Target value to GlobalAssemblyCache / Web Application based on your deployment target.

In Case of Stsadm :

i. If you scoped your solution to WebApplication and deploy the solution in WebApplication level use as below

STSADM -o deploysolution -name SolutionFileName -local

ii. If you scoped your solution to WebApplication and deploy the solution in Globally use as below

STSADM -o deploysolution -name SolutionFileName -url http://servername/ -local

In Case of ECMA Script :

Install-SPSolution -Identity Agilent.ECMS.Rad.CSVPortal.wsp -WebApplication "https://localhost:9000" -GACDeployment 

Thank you !!!

Wednesday, October 31, 2012

Error occurred in deployment step 'Activate Features': Cannot start service SPUserCodeV4 on computer

This error will be occured only when you are working with Sanbox solutions.

Cause for the issue :

This is because all the sandbox solution will work under SPUserCodeV4 process.

By default this process will be not active. If you want to work with Sandbox solutions you need to manually start this service or you can do the same with Scripting also.

Solution :

Here is the solution to start the service from Central administration

Go to

Central Asministartion -> System Settings -> Services on Server -> Activate the service Microsoft SharePoint Foundation Sandboxed Code Service

Error occurred in deployment step 'Activate Features': Feature with Id '' is not installed in this farm, and cannot be added to this scope

Strange error in sharepoint.

Struggled a lot to get the solution for this error finally one of my team member helped on solving this issue.

Cause for the error :

This error comes because of unused server in the multiple farm server environment.

In my case we are using multiple servers with the one of the server giving error on the central administration.

Solution :

Remove the unwanted / Error causing server from the server or fix the error

from the below section in Central administration site

Open the Central Administration -> System Settings ->Servers -> Manage Servers in this farm

Thanks !!!

http error 503 service unavailable sharepoint 2010

This is the kind of error which will frustrate you sometimes.

There are multiple reasons for this error and i am listing out some of the causes for this error and workarounds.

Please check these given steps to come over the issue.

1. Check wether your service account password changed in recent past and not upgraded properly in SP.

2. Check all the service account have the required admin permissions in the system.

3. Check the Application pool of the web application is up and the App Pool account is reflected the correct password.

4. Check all the sharepoint services are running in Services.msc

i. SharePoint 2010 Administration

ii. SharePoint 2010 Timer

5. Check weather the World Wide Web Publishing service is running.

Thank you !!!

sharepoint 2010 new web application disabled

This is because of some permissions issue in sharepoint.

Reason : Usually when you open the central administration that will be opened with your windows account.

There are chances that windows account doesn't have full permission on development environment

Solution : Open central administration as Administrator

Click on Start menu -> Right click on SharePoint 2010 Central administration Run as Administrator

Thank you !!

Tuesday, October 30, 2012

The solution cannot be removed when a job is scheduled or running

This is one of the strange issue when working with sharepoint script files.

Cause for the issue

Usually when we are working with deployment

all the script operation will be executed one after other till the completion of the deployment on the same batch file or powershell file.

This will cause this error because after performing the uninstall or remove wsp file from sharepoint it will take couple of minutes to complete the process.

Untill the operation should be paused.


This can be handled with the powershell script given below :

function WaitForJobToFinish([string]$SolutionName1)
    $JobName = "*solution-deployment*$SolutionName1*"
    $job = Get-SPTimerJob | ?{ $_.Name -like $JobName }
    if ($job -eq $null)
        Write-Host 'Timer job not found'
        $JobFullName = $job.Name
        Write-Host -NoNewLine "Waiting to finish job $JobFullName"
        while ((Get-SPTimerJob $JobFullName) -ne $null)
            Write-Host -NoNewLine .
            Start-Sleep -Seconds 2
        Write-Host  "Finished waiting for job.."

Monday, October 29, 2012

Request for the permission of type 'Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c' failed

This is the one of the strange errors when working with sharepoint.

Cause for he error :

This is because sharepoint by default is provided with the minimal trust permission level.

For some operations we need trust from the security policy.

Solution :

This requires change in the Trust Level in Web.Config file of the Web app.

Go to web.config file of the web application usually this will be located in

C:\inetpub\wwwroot\wss\VirtualDirectories\[Web application directory]

and open the web.config and change the

trust level="WSS_Minimal" to trust level="WSS_Medium"


trust level="WSS_Minimal" to trust level="Full"

Happy coding !!

sharepoint web part display mode

Sometimes we need to check the web part mode i.e Is web part is in Edit mode or Display mode.

Based on this condition we have to do some coding..

For this SP has provided a property to check the mode of the web part.

SPContext.Current.FormContext.FormMode == SPControlMode.Edit;

Here we have four types of modes those are listed below

1. New

2. Edit

3. Display

4. Invalid

Happy coding !!!

Download wsp from central admin sharepoint

Here is the situation where we need to take the backup of the deployed wsp file in sharepoint.

For this, We can do this with the PowerShell scripting.

Following are the PowerShell script code to take the backup and restore it is local folder with .wsp externsion.

$farm = Get-SpFarm
$file = $farm.Solutions.Item("FileName.wsp").SolutionFile

Thanks !!

Get and Set values in people picker control sharepoint

Sometimes we need to get all the people or groups information which is entered in People picker control of a sharepoint programatically.

For this we need to take the SPFIeldUserValue object to read that information.

Here is the sample code to do the same programatically.

private SPFieldUserValueCollection GetPeopleFromPickerControl(PeopleEditor people, SPWeb web)
  SPFieldUserValueCollection values = new SPFieldUserValueCollection();
  if (people.ResolvedEntities.Count > 0)
    for (int i= 0; i< people.ResolvedEntities.Count; i++)
        PickerEntity user = (PickerEntity)people.ResolvedEntities[i];
        switch ((string)user.EntityData["PrincipalType"])
          case "User":
            SPUser webUser = web.EnsureUser(user.Key);
            SPFieldUserValue userValue = new SPFieldUserValue(web, webUser.ID, webUser.Name);
          case "SharePointGroup":
            SPGroup siteGroup = web.SiteGroups[user.EntityData["AccountName"].ToString()];
            SPFieldUserValue groupValue = new SPFieldUserValue(web, siteGroup.ID, siteGroup.Name);
    return values;

Happy coding !!!

Monday, October 15, 2012

error occurred in deployment step 'activate features' the field with id defined in feature

This is the problem with VSSPHost4 process.

we have a solution for this is from Share point power shell

Execute the following command.

stop-process -processname vssphost4 -force

Happy coding !!!

Friday, October 12, 2012

SPWeb.RootFolder.WelcomePage not working

You cannot set the welcome page of a non publishing site with the following code :

teamWeb.RootFolder.WelcomePage = rootFolder.Name + "/" + myPage;

Don't know the exact reason why it will not work.

But it will not work as it expected to work on.

Here is the code which you can set the welcome page of a non publishing site.

You can set this only with the SPFOlder object, Then only it will work.

SPFolder folder = context.Web.RootFolder;
folder.WelcomePage = rootFolder.Name + "/" + myPage;

Thank you !!

Wednesday, July 18, 2012

The SDDL string contains an invalid sid or a sid that cannot be translated SharePoint 2013

Here is the one more issue with the installation of SharePoint 2013.

The SDDL string contains an invalid sid or a sid that cannot be translated

When you run with sharepoint 2013 installation majorly you will get with 2 issues.

1. Service running under Network Service account in workgroup environment is not supported

Solution for this is explained in the preious post you can find it here

2. The SDDL string contains an invalid sid or a sid that cannot be translated

Solution this is :

To fix this error, login with your Administrator account and create a search service user and add them to the WSS_ADMIN_WPG group.

To do this :

1. Open SharePoint 2013 PowerShell

2. Paste the below code

$SearchServ = Get-Credential [Your Search Account]

New-SPManagedAccount -Credential $SearchServ 

After executing these steps you need to do one more thing.

Go to "C:\Program Files\Microsoft Office Servers\15.0\Data\Office Server" in your server and find the

folder that starts with "Analytics" this looks something like Analytics_GUID

NOTE: If you find multiple Analytics folder choose the latest one.

Right click properties on the folder -> Sharing -> Advanced Sharing

Check the Share this folder check box and leave the name alone and click on permissions..

Here leave the Everyone as Read only ( Default )

Then Add the Search Service Account user you created and give Full Control

Then Add WSS_ADMIN_WPG group and give the Full control for this also.

3. After this try running the configuration wizard it will run seccuesfully..

Njoy SharePoint 2013

Thank you !!

Service running under Network Service account in workgroup environment is not supported SharePoint 2013

Here is the one of the strange issue you will be getting when you install SharePoint 2013 Preview version.

Service running under Network Service account in workgroup environment is not supported

This one is pretty easy to interpret and get around since you really only need to change where AppFabric is running.

So, The resolution for this error is :

1. Open SharePoint PowerShell

2. Navigate to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\BIN

NOTE : SharePoint 2013 is using 15 hive folder in installation ( You have older 14 hive also )

3. psconfig.exe -cmd Configdb create SkipRegisterAsDistributedCacheHost 

Run the above script and you will be proceed with the installation. After this Error fixed you will be come up with the new issue Service running under Network Service account in workgroup environment is not supported This also i have explained in the other post find here

Thank you !!

Install PDF IFilters for Sharepoint ( Not able to search pdf content in search results )

Here is the one more article on SharePoint where i cannot able to retrieve the content of the PDF file in search results.

Please find the below steps to get it done.

1) Install PDF iFilter 9.0 (64 bit) from

2) Download PDF icon picture from Adobe web site and copy to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\IMAGES\

3) Add the following entry in docIcon.xml file, which can be found at: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\XML within tags

4) Navigate to CA -> Manage Service Application -> Search Service Application, Add pdf file type on the File Type page

5) Open regedit

6) Navigate to the following location: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office Server\14.0\Search\Setup\ContentIndexCommon\Filters\Extension

Right-click > Click New > Key to create a new key for .pdf

7) Add the following GUID in the default value {E8978DA6-047F-4E3D-9C78-CDBE46041603}

8) Restart the SharePoint Server Search 14

9) Reboot the SharePoint Server

10) Perform FULL crawl to get search results

Thank you !!

sharepoint code to get SPUser from username string

String UserName= “Srikanth Kancharla”;

SPUser User= SPWeb.EnsureUser(UserName);

SPWeb.EnsureUser(): This mehtod will checks whether the specified user name belongs to a valid user of the website, and if the logon name does not already exist, adds it to the website.

Tuesday, July 17, 2012

SharePoint 2013 download

Hi Friends,

As of now we are working with Sharepoint 2010 and it's time to check with SP2013 preview version.

This is the preview version for Sharepoint 2015.

Lot of new features added in this version and also good upgrades are added in Sharepoint 2013

Here you can find the download link for SP 2013 Preview

SharePoint 2013 Preview

Lots of new features added in SP 2013 and also App store is also available in SP 2013

Microsoft Rocks !!!

Monday, July 16, 2012

rename sharepoint farm server

There are some situations where we need to rename the sharepoint server once everything is configured and working.

We have 2 options to do this

1. Using Powershell

2. Using STSADM


1. Go to Computer properties and change the name of the computer

2. Open command prompt and go to 14 hive folder using STSADM utility execute the following command.

stsadm -o renameserver -oldservername -newservername

3. Open central administration from the IIS and change the alternate access mappings of Central admin site and any other existing site ( Change the url from Old Server name to New Server name ).

4. Restart server and check for Central admin site


1. Open Sharepoint powershell command and execute the following command

Rename-SPServer [-Identity] -Name

2. Go to Computer properties and change the name of the computer

3. Open central administration from the IIS and change the alternate access mappings of Central admin site and any other existing site ( Change the url from Old Server name to New Server name ).

4. Restart server and check for central admin site

NOTE : 1. If anything goes wrong with this process after restarting machine please run the Sharepoint wizard once to fix the issues automatically. 2. If you have multiple servers in the farm repeat the same steps for all the other servers.

Thank you !!!

Monday, July 9, 2012

Sharepoint model dialog from ribbon button

Here i am going to explain how to open model dialog box from ribbon button control.

1. Create empty sharepoint project either with sandbox or farm solution.

2. Add feature for the solution and add Empty element file for that as show below :

3. Now your solution will looks something like this.

4. Add this below given peace of code in Elements.xml file :

Here you can modify your code and test the application according

As per the testing purpose i am taking Task list template so, this peace of code will work only with Task list template. If you need this for the other templates you need to change the template number

5. Final verification is to check wether the Element file is attached to feature and the feature is added to the solution.

do this verification as below :

a. Double click on .Feature file name and check the referenced ELements file is listed there or not :

b. Double click on Package and check our package is listed under the packages section.

6. Finally deploy the solution and create a list with Tasks template and click on Items tab, There you will find the new button "Open model popup"

7. Click on that button you will get Settings.aspx model popup page.

Here for demo purpose i am using default settings page. In real time you can change this on fly.

Thank you !!!

Enable inline editing in sharepoint list

Sharepoint 2010 has one more beatiful feature which is JSGrid implmenetation in sharepoint list view thais is called Inline editing.

For any sharepoint list we can enable Inline editing at view level.

1. Open your sharepoint list

2. In Ribbon click on List -> Modify this view

3. In the options expand Inline editing and check Allow inline editing check box.

Here is the output

Thank you !!!

Friday, July 6, 2012

Running a SQL Stored Procedure from Excel with Dynamic Parameters

Here is the interesting article about how to generate report from stored procedure to Excel sheet.

This is called as Pivot reports.

Here we can also call the stored procedures with input parameters.

Below are the step by step process to do the same :

1. Open Excel ( Start -> Excel )

2. In Tabs Click on Data -> Connections

3. In Workbook Connections wizard click on Add and select your database server/ Instance name and Add that to workbook and then close the wizard.

<< So far we are done to make the connection with the DB server >>

4. After this again in the Data tab From other sources and select From microsoft query.

5. In choose data sources wizard select the appropriate database name and click on OK.

6. This will open up a Query wizard to select the parameters.

7. Here select any of the dummy parameters from the existing values ( we dont use this in future but select a dummy values ) and then click on Next button

8. Query Wizard Filter data -> click Next

9. Query Wizard Sort Order -> click Next

10. Query Wizard Finish -> select "View data or edit query in microsoft query" -> click on Finish

11. In Microsoft query window click on SQL button on Top as show in the below screen shot.

12. In the SQL Statement window place your Stored Procedure with dummy parameter what ever you want ( This we can configure it later as dyncamic )

13. Then click on OK. This will prompt you with warning message saying "SQL query cannt be represented graphically" ignore this warning continue anyway and close the wizard window.

14. Then it will open Import data wizard.

15. Click on Properties -> in connection properties windows select Definitions tab.

16. Here in CommandText section you will find your query with the dummy parameter. Here replace the parameter with ?

17. Click OK and close the wizard window.

18. After this excel sheet will prompt you for the input. Provide the input and click on OK, Here is the result


1. Inputs can be configured from the Excel sheet cell also.

2. Reports can be converted in to graphics also

3. Reports can be configured as auto refresh on periodic basis.

Thank you !!!

key filters sharepoint

Sharepoint 2010 has lot of OOTB features added without writing single line of code.

One of them is Key filtering for sharepoint list.

This is one of the beauty of sharepoint due to its efficiency and look and feel.

Please follow the steps below to enable the Key filterings.

1. Open sharepoint list

2. Click on List in Ribbon control.

3. Click on List settings

4. Go to metadata navigation settings

5. In this page you can select what are the fields required for the filtering. Here i am selecting 3 columns on Configure key filters section and click OK.

6. Go back to list, Here you will get your key filters at left navigation side.

NOTE : Event though it is very powerful it has its own pros and cons those are listed below.

Pros :

1. Very efficient as it is xml based at back end.

2. Easy to create and configure.

3. No coding is required.

Cons :

1. It will work only on list forms ( if you add the same list to any of the site pages this key filters will not work there )

2. It is difficult to package this key filters ( some coding is required to enable this feature at the time of deployment )

Thank you !!

enable developer dashboard sharepoint 2010

Usually when we are developing sharepoint application some times we found that page is taking lot of time to load the content.

In this kind of scinarios we need to figure out on which web part where it is taking long time to get the data to fix the performance issues.

Here sharepoipnt provided a good feature to calculate this kind of information called Developer dashboard.

steps to do this :

1. Enable developer dashboard through powershell

2. select developer dashboard and analyze your page health report.

Here is the Powershell script :

Dashboard : On

$service = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$addsetting =$service.DeveloperDashboardSettings
$addsetting.DisplayLevel = [Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::On

Dashboard : Off

$service = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$addsetting =$service.DeveloperDashboardSettings
$addsetting.DisplayLevel = [Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::Off

After this you can just go to your site home page or any other site pages. Here you will find a new image icon just beside the login account name control like

Click on that then you will get the complete report of the page like

1. how much time it is taking for each web part.

2. Stored procedures executing time.

3. Events load time etc..

Thank you !!

sharepoint powershell missing shortcut

This is the one more issue when we work with sharepoint powershell.

Issue : When you run sharepoint powershell command for the first time. Some times you will get an error saying that "Missing shortcut".

Here is the screenshot of the same :

Resolution :

1. Start -> Microsoft sharepoint 2010 products -> Sharepoint 2010 management shell.

2. Right click on this go to properties.

3. In Shortcuts tab change the Target value to %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -NoExit add-pssnapin microsoft.sharepoint.powershell

<< This required admin control on the server >>

<< Adding this snap-in you can do manually by running windows powershell also >>

4. Save and close the wizard.

Now Open your Sharepoint powershell will works fine.

Thank you !!

Tuesday, July 3, 2012

property bag in sharepoint 2010

Sharepoint Property bags :

This is one of the good feature in sharepoint. This feature is already there in MOSS 2007 and it is carried to the latest version Sharepoint 2010 also.

This is basically used to store the key and value pair in hashtable format.

This is something like app.config information in classic ASP.NET.

Property bags can be created / Modified / Deleted from sharepoint designer or using Object model.

Using sharepoint designer :

1. Open a site in SharePoint Designer

2. Go to Site menu click on Site options

3. Site Settings dialog box opens

4. Click on Parameters tab where you can see the list of existing properties

from the same place you can even perform add/modify/delete operations.

Using sharepoint object model :

using (SPSite RootSite = new SPSite(URL))
                using (SPWeb web= RootSite.OpenWeb())
                        web.AllowUnsafeUpdates = true;
                       // Get Property bag
                        if (web.AllProperties.ContainsKey("SiteID"))
                            var data = web.AllProperties["SiteID"].ToString();
                        // Set Property bag
                        web.Properties["SiteID"] = "GUID";
                        web.AllowUnsafeUpdates = false;                        
                    catch (Exception ex) 
                      //Throw Exception  

NOTE : Property bags can be handled @Farm level, @Web application level, @Site level.

Thank you !!!

sharepoint powershell run timer job

In sharepoint deployment automation is the one of the key parts of development.

One of the key features of sharepoint is to create timer job which will execute a process at regular intervals of time.

Here comes the interesting part is to automate the timer job deployment.

There are 2 options for that.

1. Using Sharepoint object model which we will execute from the Feature activation.

2. Using powershell script which we can put as deployment files.

Here is the peace of code.

$WebApp = Get-SPWebApplication http://siteurl
$job = Get-SPTimerJob | ?{$_.Name -match $JobName} | ?{$_.Parent -eq $WebApp}

Thank you !!

Monday, July 2, 2012

sharepoint event handler redirect page

Here is the one more requirement to redirect user from event handler.

You can redirect user to a custom message page with code.

Here is the code for that.

       /// An item is being added.
        public override void ItemAdding(SPItemEventProperties properties)
            // Any condition 
            if (properties.ListItem["Manager"] != SPContext.Current.Web.CurrentUser.LoginName)
                // Set the status property to CancelWithRedirectUrl this tells the event handler to cancel the operation
                properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
                // Get the application page generic with SPUtility 
                properties.RedirectUrl = SPUtility.GetGenericSetupPath("/MyProj/MyPage.aspx");


Thank you !!!

sharepoint programmatically change master page

This article i will give you the peace of code where we can change the sharepoint master page programatically.

Here is the code snippet for the same.

                       using (SPSite site = properties.Feature.Parent as SPSite)
                           using (SPWeb web = site.OpenWeb())
                               //Logging feature activation status in list
                               web.AllowUnsafeUpdates = true;

                               //Changing the master page
                               web.CustomMasterUrl = "/commerce/Custom/_catalogs/masterpage/Custom.master";
                               web.MasterUrl = "/commerce/Custom/_catalogs/masterpage/Custom.master";

                               //Setting the Navigation propertiers for web
                               web.AllProperties["__IncludeSubSitesInNavigation"] = "False";
                               web.AllProperties["__IncludePagesInNavigation"] = "True";


web.AllProperties methods will change the navigation source for the web application, This you can change according to business need.

Thank you !!

sharepoint designer access denied

Here is an interesting error you will get some times while working with Sharepoint designer i.e "Access denied"

Solution :

If you get this error make sure the attempted login user is a site collection if not add as site collection administrator.

Hope this will help !!!

Wednesday, June 20, 2012

One or more field types are not installed properly

Scenario : Basically while multiple people working on the same server. There are chances that someone has modified something in List / Document library that is not informed to others.

In this case your sharepoint web parts will be failed in Add/Update/Delete operations. saying error "One or more field types are not installed properly".

Or if you go to the List/Document library you will get the same error.

Resolution : Go to List settings and check weather all the column names are same what you are using in code or check any changes appended to the List definition.

Thank you !!!

sharepoint designer login as different user

Here is one more article on sharepoint designer

Scenario : While we are working with sharepoint designer ( workflows, content types etc ) there are scenarios where required to login with diffarent user.

Shareoint has this feature, But lot of people not aware of this.

Solution :

1. Open sharepoint designer form start menu ( cmd -> spdesign )

2. Open a site and login with any of the user

3. Please have a look at Left hand side botton corner of the Designer windows where you will find an ICON with user image.

4. Click on that, It will lead you to change login name

Thank you.

Specific file or folder name is too long in sharepoint

Here is the issue while we upload files or create folder to sharepoint document library.

Usually get an error saying that "Specific file or folder name is too long".

Reason : Every sharepoint file name has limited number of characters, It will check for this condition before upload file to sharepoint.

Solution : Sharepoint object model has provided a beauty of way to check for the file name validity.

Here is the code :


It will return weather all the conditions are passed before upload it to sharepoint.

Thank you

powershell change service account password sharepoint

Usually, We set all the sharepoint admin accounts or service account passwords with expiry period.

After that particular period passwords will be expired. At this point of time we need to update the passwords from either Central admin or Powershell.

Here is the powershell code to update password of a sharepoint account .

$version = $host | select version
if ($ver.Version.Major -gt 1)  {$Host.Runspace.ThreadOptions = "ReuseThread"}

# 1. Adding sharepoint snap-in
Add-PsSnapin Microsoft.SharePoint.PowerShell
Set-location $home

# 2. Provide the service account name
$ServiceAccountName = Read-Host 'Service Account'

$managedAccount = Get-SPManagedAccount $ServiceAccountName

# 3. Get and confirm the serice account new password
$password = Read-Host 'Enter Password' -AsSecureString
$passwordConfirmation = Read-Host 'Confirm Password' -AsSecureString

# 4. Command to change the password
Set-SPManagedAccount -Identity $managedAccount -NewPassword $password -ConfirmPassword $passwordConfirmation -SetNewPassword

Happy sharepoint coding

http error 503. The service is unavailable Sharepoint

Issue : Service unavailable

All of a sudden your Central administration is down and showing Service unavailable. Which is very common error while you are working with sharepoint. which looks something like :

Most possible reason for this : Farm admin password expired or changed.

Resolution :

Go to IIS ( cmd -> inetmgr ) of your Web front end server.

1. click on Application pools

2. Click on Central admin Application pool ( usually it is named as "Sharepoint Central admin v4" )

3. In right corner actions Click on Advanced settings

4. Find the "Identity" section click on that and set new password.

5. Finally you will come up with your recovered Central admin.

NOTE : If you still getting the same issue try run your Configuration wizard in sharepoitn section this will fix the issue or it will log the issue in the 14 hive LOG folder.

Thank you.

Monday, June 18, 2012

powershell get help command with example

For every command in powershell we can get the example sample script using Get-Help prefix.

Below is the script to get the example for Site back up command in Sharepoint :

Get-Help BackUp-SPSite -example

Output will be looks something like :

Dynamically Retrieve a Collection URL from a Timer Job during Deployment

Here is the big issue in Sharepoint. We can deploy all the other solution in the dynamically other than timer job.

Timer job is the one sharepoint items where we cannot deploy it directly with dyncamic URL.

But microsoft has provided a good turn around for this.

Here is the good technical article where we can take dynamic URL by using feature properties from Code behind.

Click here to get the blog..

Happy coding !!!

sharepoint 2010 get list items linq without SPMetal

Hi All,
There are some situations where we need to get the data form sharepoint list items with a query.

But as we are aware linq is the best way to get the sharepoint list items in fast and efficient way. But to work with sharepoint lists we need to create entity calss with SPMetal.exe

Without using the entity class also we can get the sharepoint list items using System.Linq

Here is the sample code to get the list items from Config list using small filter option.

Here we are trying to get the Config details from Config list.

var item = web.Lists["ConfigList"].Items.OfType().FirstOrDefault(it => it["Key"].ToString() == "ConnectionString");

Friday, June 15, 2012

c# check user exists in active directory

Here is the C# code to check if user exists in Active directory or not :

using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "DomainName"))
using (UserPrincipal user = UserPrincipal.FindByIdentity(context, "LoginName"))
     bool userExists = (user != null);
     if (userExists)
       Console.WriteLine("User exists");
      Console.WriteLine("User doesn't exist");

Failed to post back after export file sharepoint

In Sharepoint if you implement functionality to generate report in new .doc or .excel or any other office file in button click.

Issue : You cannot generate report multiple times because after first click on Genrate report button your form post backs will be blocked automatically.

To overcome this issue you need to add a simple Javascript code in page load for the button. Please find the below ;

this.btnGenerateReport.OnClientClick = "_spFormOnSubmitCalled = false;_spSuppressFormOnSubmitWrapper=true;";

                            -or -

this.btnGenerateReport.OnClientClick = "javascript:History.Back()";

sharepoint get lookup value programmatically

Here is the C# code to get the Lookup field value :
SPList list = web.Lists["Tasks"];

                            SPListItem existingBranch = list.Items[0];

                            SPFieldLookupValue group = new SPFieldLookupValue(existingBranch["Food Coupons"].ToString());

                            string lookedUpItemTitle = group.LookupValue;
Here is the C# code to Set the Lookup field value :
 SPList list = web.Lists["Tasks"];

                            SPListItem newBranch = list.Items.Add();

                            newBranch["Title"] = "New lookup";

                            SPFieldLookupValue newValue = new SPFieldLookupValue(14, "Test");

                            newBranch["Sample"] = newValue;


Powershell script to wait for Job to finish

When you deploy the sharepoint solution using powershell script it will always says that the solution is not yet deployed kind of issues.

This is the place where we need to wait for the next operation to complete the previous one.

Here is the code sample for the same :

function WaitForJobToFinish([string]$SolutionName1)
    $JobName = "*solution-deployment*$SolutionName1*"
    $job = Get-SPTimerJob | ?{ $_.Name -like $JobName }
    if ($job -eq $null) 
        Write-Host 'Timer job not found'
        $JobFullName = $job.Name
        Write-Host -NoNewLine "Waiting to finish job $JobFullName"
        while ((Get-SPTimerJob $JobFullName) -ne $null) 
            Write-Host -NoNewLine .
            Start-Sleep -Seconds 2
        Write-Host  "Finished waiting for job.."

C# code to get claims user name sharepoint 2010


IClaimsPrincipal claimsPrincipal = Page.User as IClaimsPrincipal;
                    if (claimsPrincipal != null)
                        IClaimsIdentity claimsIdentity = (IClaimsIdentity)Thread.CurrentPrincipal.Identity;
                        if (claimsIdentity != null)
                             foreach (Claim item in claimsIdentity.Claims)


Thursday, June 14, 2012

Sharepoint 2010 Claims check user name

// Comment
IClaimsPrincipal claimsPrincipal = Page.User as IClaimsPrincipal;
                    if (claimsPrincipal != null)
                        IClaimsIdentity claimsIdentity = (IClaimsIdentity)Thread.CurrentPrincipal.Identity;
                        if (claimsIdentity != null)

                            Logger.Instance.LogInfo("CreateChildControls", "User not found", false);

powershell activate feature sharepoint

  write-output $_ 
  exit 1 
# define variables for script
$webApp  =$args[0]

# 1. check to ensure Microsoft.SharePoint.PowerShell is loaded
    $snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
    if ($snapin -eq $null) 
        Write-Host "Loading SharePoint Powershell Snapin"
        Add-PSSnapin "Microsoft.SharePoint.Powershell"

# 3. Add solution to SharePoint Solution Store

        Write-Host "Getting Faeture for ID" + $featureId   

 $feature= Get-SPFeature -Identity $featureId
    $site=Get-SPSite $webApp 

     $sitefeature= $site.Features[$feature.Id]
  if($sitefeature -ne $null)
   Write-Host "Feature Already activated in this site"
   Write-Host "Disabling the Feature"
         Disable-SPFeature -Identity $feature.Id -Url $webApp  -confirm:$false -force
       Write-Host "uninstalling the Feature"
         uninstall-spfeature -identity $feature.Id  -confirm:$false -force

   Write-Host "installing the Feature"
   install-SPFeature -Path $feature.RootDirectory -confirm:$false -force
       Write-Host "Enabling the Feature"
  Enable-spfeature -Identity $feature.Id -Url $webApp -confirm:$false -force 
Write-Host "Done"

Create external list with powershell

 [string] $SiteUrl = $null

write-host "Adding Snapin"
Add-PsSnapin Microsoft.SharePoint.PowerShell
write-host "Added"

$BusinessListName = "BusinessList"
$ConfigListName = "Config"



$spweb = Get-SPWeb $SiteUrl
$ListGUID = ""
$ListUrl = "Lists/{0}"
  Write-Host "Creating and Configuring SPListDataSource"
  $ds = New-Object -TypeName Microsoft.SharePoint.SPListDataSource
  $ListCollection = $spweb.Lists
   $ds.SetProperty("LobSystemInstance", "db")
   $ds.SetProperty("EntityNamespace", "Business")
   $ds.SetProperty("Entity", "BusinessList")
   $ds.SetProperty("SpecificFinder", "GetBusinessListRead Item")
    Write-Host "Checking for list instance existence"
    $list =  $spweb.Lists[$BusinessListName];

      Write-Host "List exists - " + $BusinessListName + " - deleting the list"
      Write-Host "Creating " + $BusinessListName + " list with Data Source.."
        $ListGUID = $spweb.Lists.Add($BusinessListName, "", [String]::Format($ListUrl, $BusinessListName), $ds)
     Write-Host "List created successfully.." + 
     $list =  $spweb.Lists[$ConfigListName];

     Write-Host "List exists - Config - deleting the list"

create external list external content type

1. Open central administration and click on Manage Service application in Application management

2. Click on Business Data connectivity service link

3. Then click on Import button in Ribbon on top 4. Next screen browse the BDC model (*.bdcm ) file and click on Import. 5. Ignore the error message and click OK to complete the process. Create External list with the BCS Source: 1. Open web application -> click on Site settings -> view All Site Content -> Click on Create link 

2. In the given list templates select External List template and click on Create 3. In Create screen provide the information required like Name, Description and In Data Source Config section click on Select External Content Type icon to list all the bdcm sources shown below :

4. Then Select RadBusinessList in the pop up and click on OK



Done, Finally External List looks like this :

Tuesday, March 27, 2012

sharepoint get username javascript

Below is the code snippet to get the current login user name in web part or you can use Client object model..

var sLoginUserName ="";

sLoginUserName =document.getElementById('ctl00_LoginCtrl').innerText;

sharepoint xml intellisense

While we are working with Sharepoint xml files like Feature.xml, Elements.xml or ONET.xml files we wont get any intellicense by default.

But for any developer it is hard to remember all these information. So, here is the easiest way to get the intellisence

1. Open your xml file in Visual studio.

2. Go to properties pane of the xml file and click on schema and browse for the file.

3. locate file named "wss.xsd" from C:/Program Files/Common Files/Microsoft Shared/web server extensions/12/TEMPLATE/XML/wss.xsd

Note : this file will have all the xml defined functions which is easily recognized by the visual studio.

Then you will get the intellisece for the sharepoint solution..

Javascript code to get Query string value in sharepoint

var paramID=GetValue('ID');

function GetValue(name)
   name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
   var regexS = "[\\?&]"+name+"=([^&#]*)";
   var regex = new RegExp( regexS );
   var results = regex.exec( unescape(window.location.href) );
   if( results == null )
     return "";
    return results[1];

Wednesday, January 25, 2012

Error occurred in deployment step 'Recycle IIS Application Pool':Cannot connect to the SharePoint site: http://sps01/sites/test/. Make sure that this is a valid URL and the SharePoint site is running on the local computer. If you moved this project to a new computer or if the URL of the SharePoint site has changed since you created the project, update the Site URL property of the project.

Visual studio uses the following process to deploy your solution: vssphost4.exe Open your task manager and find the process in the list; take a note of the User Name under which this process is running, let’s say it’s myadmin_account

Now, open your SQL Management Studio and ensure this Username is added as a DBOWNER to the following databases:

SharePoint Site Content DB

sql permissions
Close and Open your Visual Studio again, this will ensure the service is recycled; this should fix above deployment error. If you’re still having same issue, End the process in taskmanager and then re-start VS 2010.

sharepoint send email with attachment

While we working with SMTP in sharepoint projects. It is mandatory to provide SMTP server name to send emails or we can use SPUtility.SendMail().

But it is strongly recommended to use Object model for getting SMTP server name for good coding practice.

Below is the peace of code to do the same :

string smtpServer = SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address;

string smtpFrom = SPAdministrationWebApplication.Local.OutboundMailSenderAddress;

MailMessage message = new MailMessage(smtpFrom, "");

message.Subject = "Happy Birthday";

WebClient client = new WebClient();
client.Credentials = CredentialCache.DefaultNetworkCredentials;

string imagePath = web.Url + "/_layouts/images/BirthdayImage.gif";
LinkedResource image1 = new LinkedResource(SPUtility.GetGenericSetupPath("TEMPLATE\\LAYOUTS\\IMAGES\\BirthdayImage.gif"));

image1.ContentId = "birthdayimage";

AlternateView avHtml = AlternateView.CreateAlternateViewFromString("
" + "Have a blast with frineds and family!!! Have a great day!!!", null, MediaTypeNames.Text.Html);



message.IsBodyHtml = true;

SmtpClient smtpClient = new SmtpClient(smtpServer);

Happy coding !!!