Thursday, February 28, 2013

Custom page not found page in SharePoint

Though SharePoint is almost very good for maintaining links but still there may be a chance where the link might be broken at any point of time in entire site hierarchy.

You may have any document link on the page and then the document is deleted or a link which points to the page and that page has been moved to some other page or deleted, then user end up navigating to the page not found.

Wouldn't that be nice if a user gets some nice message with some proper image and message.

We can do this by creating custom page for the web application which will act as a custom page not found page.

See what happens when a user tries to navigate to a page which does not exist.

Remember we can set a custom page not found at the web application level. we cannot have that at site or site collection level.

The best way to do this is copy the existing 14\TEMPLATE\LAYOUTS\1033\custom404.html and rename it to another name. Open the page in HTML complaint editor or in Visual Studio and edit the page with image or content as per your choice.

Copy the page at the same location under 1033.

Following is the script that will do this job.

$webapp = Get-SPWebApplication {web application URL}
Write-Host $webapp.Name
$webapp.FileNotFoundPage = "Custom404.html"
Write-Host $webapp.FileNotFoundPage

So now go ahead and try to open the page from site which does not exist.

You can also set the page not found via feature. Ideally have a web application level feature because this setting is for the web application and cannot be customized for the site collection or the web.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
         SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
         if (webApp != null)
             webApp.FileNotFoundPage = "custompagenotfound.html";

I hope this helps.

Monday, February 25, 2013

Change Search result page URL using PowerShell

You can change the search result page URL using PowerShell. You may require this depending on configuration you might do at the time of deployment.

All you have to do is use below line in PowerShell script and you are good to go

 Now go to site settings page and under site collection administration click on search settings. You will find that your search result page has been changed.

Make sure that you add search refinement panel and search core results web part on the new search result page.

Thursday, February 21, 2013

Adding note board web part programmatically in SharePoint 2010

If you want to add note board web part by object model, here is a simple way to add it. I have one web part page.

To demonstrate I have added this code in button click.

       private void button3_Click(object sender, EventArgs e)
            using (SPSite site =
new SPSite("{Site URL}"))
                using (SPWeb web = site.OpenWeb())

                    SPLimitedWebPartManager webPartManager = web.GetLimitedWebPartManager("SitePages/NoteBoard.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

                    SocialCommentWebPart noteboardwp =
                    new SocialCommentWebPart();

                    webPartManager.AddWebPart(noteboardwp ,
                     "MiddleZone", 0);

and here is what you get out of it

Saturday, February 16, 2013

Get choice values of choice column through PowerShell

If you have a choice site column or even a field in list , library and want to get the choices values that is present in that field , here is how you can get that.

To demonstrate, I have one site column with name US States which holds US state names. 

Let's write PowerShell to get this site column reference and then take out all the choice values in it.

If you would like to know what this PowerShell initial few lines are all about,  I would recommend reading Get Values From Configuration post and then continue.

Now run the script

and here is the result. you get each choice value in the choice column.

I hope this helps.

Wednesday, February 13, 2013

Content type hubs in SharePoint 2010

Before getting into the details of content type hub let us take a step back and think why content type hub is introduced and what was available in MOSS 2007.

Let us say you have created a content type in web application 1 and now you need to reuse that content type in web application 2.

so here you do not have any options other than recreating the same content type in another web application 2 when we worked with MOSS 2007.

But now with SharePoint 2010 we can create one specific web application which serves as a content type publisher and other web applications consumes those content types as a consumer from the main web application which is considered as a content type hub.

So content type hub is nothing but a dedicated web application which contains all the content types that want to reuse across many web applications and serves as a hub - the publisher.
Content type hub publishes and other web application consumes.

The advantage is you can make a change in content type at the hub level and you can push down those changes at all the web applications where they are consumed.

Let us see it in action how we can create content type hub and how we can consume it from the web application.

We first need to create web application and top level site which will serve as a publisher content type hub.

Now click on the manage service applications in applications management.

Locate for managed metadata service and click on properties.

Scroll down and enter the site collection URL that you have just created.

Now come back to the previous screen and this time select the managed metadata service connection. This is listed just below the option which you selected earlier and then click on properties again.

and this brings to the screen where you need to select all options.

Now let's get back to the site collection site that we have created earlier - the content type hub site collection.

Open the site in browser, go to the site settings then galleries and sites content types.
Create one content type. I  have one content type called order.

Now check for an option manage publishing for this content type on content type settings page.

Publish must have selected by default,  click on ok button. as you can see right now last publish date is empty.

You can go back and check the publish date. It must be set this time.

Now we need to move our eye to timer jobs. There are two times jobs of interest.

1)  Content Type Hub
2) Content Type Subscribe

Go to monitoring - timer job definition

As you can see you have one content type hub timer job which is for the publisher and you have other subscriber timer jobs for all web applications which can subscribe / consume that hub.
So go ahead and click on hub, click on run now. Click on the respective subscriber for web application from where you want to consume the content type, click on run now.

Again make a note that we are doing this manually only because we want to see the immediate change.

Now let's go to a site collection of consumer web application.

Go to a site settings and then to site content type.

You will see the content types from content type hub appearing here and can be used throughout web application.

Go back to the content type hub, add one more site column. call it price. keep update all content type inheriting from this content type checked.

Now go to the content type settings page. again click on manage publish for this content type. this time you would find republish button. Click on republish.

go ahead and run those two services again.

Go back to the consumer site collection and see that new column is also appearing in the list.

I hope this helps and you now have fair understanding of content type hub. 

Tuesday, February 12, 2013

Send list items to recycle bin

Let us see what happens when one deletes the list items. See the example below. I have few task list items.

And see the code below.

execute the code and check recycle bin of the site.

You will not find these deleted list items.

Let's add three more items and this time select three items and remove from the delete option from UI,

now go to the recycle bin and now you can see these three entries.

let's add three more items.

Let's change code a little.

run the code and the go to recycle bin. There you go, now you have the items in recycle bin which was deleted rather recycled programmatically.


Monday, February 11, 2013

Change Document Library folders title through Power Shell

In this post we will see how to change the title of the folders in document library.

Here is before running the script.

Here is the script. If you are not aware what is happening in this script, I would recommend reading get value from configuration file post.

[xml]$xmlfile = Get-Content ConfigFile.xml
 $site = ''
$web = ''
$listName = 'Shared Documents'
 foreach( $sitecoll in $xmlfile.Configuration.SiteCollection)
    $site = $              
 $spSite= Get-SPSite $site
 $web = $spSite.OpenWeb()
 Write-Host -foregroundcolor Green 'Site URL' $site
 foreach($folder in $list.Folders)
if($folder['Title'] -eq 'Folder1')
   $folder['Name'] = 'NewFolder1'
   $folder['Title'] = 'NewFolder1'
   } elseif($folder['Title'] -eq 'Folder2')
    $folder['Name'] = 'NewFolder2'
   $folder['Title'] = 'NewFolder2'
 elseif($folder['Title'] -eq 'Folder3')
    $folder['Name'] = 'NewFolder3'
   $folder['Title'] = 'NewFolder3'
 elseif($folder['Title'] -eq 'Folder4')
   $folder['Name'] = 'NewFolder4'
   $folder['Title'] = 'NewFolder4'
 elseif($folder['Title'] -eq 'Folder5')
    $folder['Name'] = 'NewFolder5'
   $folder['Title'] = 'NewFolder5'

we are opening the site and then taking the reference of the library and then iterate through all folders of the library and then compare the title of the folder and then change folder properties.

Once you run the script, all folders names and title will be changed. 

I hope this helps.

Thursday, February 7, 2013

Get template name of SPWeb

You may need to get the template type from which the SPWeb has been created. You must be thinking that to get this is really easy, there must be a property which gets us this value.

Well, it is really but there is no direct property. There is one property of SPWeb called WebTemplate. Let's try that.

and the result is

Now change it to this

1033 is for English. You may need to change it depending on the English.

and here we go

I hope this helps

Wednesday, February 6, 2013

Get values from configuration file in Power Shell script

When you write a Power Shell script sometimes you may require to get some parameter values from the configuration file. While deployment usually we need to passing some values from the configuration file.

You can create configuration file and take those values from it to the PowerShell script. Example we may need to create sub sites or lists / libraries or content types etc. To do this you need site URL to be passed to the script.

You may also need to pass in list name with site URL post deployment when the system is in use and later you want to make any changes.

We can create XML file which has data that can be passed to the PowerShell.

Let's create one configuration file.

 here we have create one XML file which has top level element as configuration. inside that we have site collection where we have passed one site collection URL.

Let's now create one power shell script and get the value from XML file to the script.

What we have done is we took the xml file reference and then declared one variable in which we will store site URL.

After that we get the value of that specific site collection URL. We have written loop here because you can also define multiple <name> inside <site collection> tag.

As of now we are considering one single site collection.

and then we print the site URL in green color with Write-Host options.

Now open the SharePoint 2010 management shell.

and execute the script by typing ./PowerShellScript.ps1

and here is what you get.
In the same way, you can define as many tags as you like in XML file and can take those values inside the power shell script.

I hope this helps.

Tuesday, February 5, 2013

Get SharePoint Health Analyzer data programmatically

SharePoint health analyzer is a functionality which highlights the problems that are there with the servers in the farm.

As you can see, it highlights as a top notification with view these issues link.

It highlights the problem in different categories like availability, security, performance and configuration.

It also shows if it's the error or it is the warning. If it is the error , it highlights as a red circle with cross in it, if it is warning it shows as a yellow triangle with exclamation mark.

There are certain rules that are already written in Analyzer which can also be enabled or disabled. You can also select should it repair automatically or not. You can also see the schedule defined for that rule. We can also create our own rule and add it here.

When these rules execute, SharePoint health analyzer creates the report and writes it to the list called SPHealthReportsList. This is just a speciall type of list created for the SharePoint health related issues.

The default view for the health issues is set to not to show anything than the severity is not equal to 4 - success.

Now we will have a look on how we can access the information of health report of SharePoint programmatically.

I am showing this as a part of button click, you can write it the way you want.

private void btnHealthAnalyzer_Click(object sender, EventArgs e)
                SPHealthReportsList lstHealth = SPHealthReportsList.Local;

                if (lstHealth != null)
                    SPQuery queryHealthData = new SPQuery();

                          queryHealthData.Query =
                        "<OrderBy><FieldRef Name=\"Created\" /></OrderBy>";

                    SPListItemCollection healthresults
                        = lstHealth.GetItems(queryHealthData);
                    DataTable dt = new DataTable();
                    dt.Columns.Add(new DataColumn("Title"));
                    dt.Columns.Add(new DataColumn("Created"));
                    dt.Columns.Add(new DataColumn("Category"));
                    dt.Columns.Add(new DataColumn(gtfcvb 3"Remedy"));
                    dt.Columns.Add(new DataColumn("FailingService"));
                    dt.Columns.Add(new DataColumn("Severity"));

                    if(healthresults.Count > 0)
                        foreach (SPListItem item in healthresults)
                            DataRow dr = dt.NewRow();
                            dr["Title"] = item["Title"];
                            dr["Created"] = item["Created"];
                            dr["Category"] = item["Category"];
                            dr["Remedy"] = item["Remedy"];
                            dr["FailingService"] = item["Failing Services"];
                            dr["Severity"] = item["Severity"];

                        bindingSource1.DataSource = dt;
                        dataGridView1.DataSource = bindingSource1;                                             
            catch (Exception ex)
                throw ex;

and here is the output that you get

I hope this helps.

Sunday, February 3, 2013

Get SharePoint Web Application URL and path programmatically

Sometimes you may would like to get the URL of the SharePoint web application. Assume that you have a web application created but yet you have not created the site collection.

There may be a case to get the URL and even sometimes the port on which your web application is running programmatically.

You do not get these information directly via SPWebApplication object property. You can get this like shown below.

Hope this helps.

Saturday, February 2, 2013

SPFarm returns null

Have you ever been into a situation when you have written a code which initiate a SPFarm with simple line of code and when you execute, you get SPFarm as null though you are running windows application on the server itself. What went wrong?

So go to the project properties and check for the build version. When you create a project, there are chances that the project is created in the x86 environment, so go ahead and change it to x64 because SharePoint code cannot run in x86 set up.

Problem must be solved now.

Share your SharePoint Experiences with us...
As good as the SharePointKings is, we want to make it even better. One of our most valuable sources of input for our Blog Posts comes from ever enthusiastic Visitors/Readers. We welcome every Visitor/Reader to contribute their experiences with SharePoint. It may be in the form of a code stub, snippet, any tips and trick or any crazy thing you have tried with SharePoint.
Send your Articles to with your Profile Summary. We will Post them. The idea is to act as a bridge between you Readers!!!

If anyone would like to have their advertisement posted on this blog, please send us the requirement details to