Saturday, September 20, 2014

Client Object Model sample codes

Hi there,

I worked for few items in the client object model using ECMA script and here are the sample codes I am sharing for the example.

The below code gives you the web title and web id.


The below code adds the new list to the site with updating the list title, description, template and then added to the web,




SharePoint Master Page Dynamic footer using Delegate controls

Hi there,

I had worked on the requirement to display the custom information like site owner, contact number, email and last date modified in the master page footer information.

So all the data related to the site owner, contact number, email are dynamic and when the new person takes the site owner role, our code should be smart enough to update this information rather than changing the master page file.

Here we used the delegate controls to get the information from the custom list where the items contains the site owner name, contact, email so that the delegate control is able to render this information in the master page footer control.

For adding the delegate controls in the master page, first we have to create the user control and then reference it in the master page with attribute ControlID.


Create the user control with mapping the ControlTemplates folder in the visual studio and then deploy this control with specifying the path using module and elements.xml.

Here is the elements.xml from the module file.

See the attributes Id mapped to the delegate control in the master page.

Now the FooterControl.ascx file has its own custom logic to fetch the information from the  custom list based on the current web context and able to render the same on the master page.

Here is the sample code used for Footer user control page load method. Here the custom list is located in the root web and it is named as SiteOwner with fields Web title, owner name, email, contact.

Final output:





Custom Timer Job Adding new items for the custom list on the schedule time

Hi there,

I worked on the small requirement to add the items for a custom list with predefined schedule.

Here we used the base class SPJobDefinition which is part of SharePoint, Administration namespace.
So we need to make sure to add the reference Microsoft.SharePoint.Administration reference and the namespace as well.

our custom timer job class needs to inherit the base class SPJobDefinition and then it has to override the method Execute().

Here is the sample code we have to write for our business logic and then associate this class with feature receiver.



Regarding the feature scope, since this job runs under the central administration, we need to activate this feature at the web application level for which our custom list is getting updated





Add publishing pages and web parts to the site programatically

Hi Guys

I had got the chance to work for adding the publishing pages to the given site through feature activation so that when the custom solution got deployed, the share point site is automatically associated with the custom web parts along with these publishing pages.

This is the sample code I wrote for my development purpose.
Please make sure that the publishing feature is activated on the site collection level and the site level.
In the code snippet, we need to use PublishingWeb class, which is component of Microsoft.SharePoint.Publishing.dll.
Make sure to add that dll and that namespace as well in your code to work as expected.




Here is the next code to add the specific web part to the existing page programatically.
Here we used the SPLimitedWebPartManager class to add the web part to the existing page.

Sunday, June 22, 2014

Disable Throttling Limit for specific lists

Hi All,

Recently, we had the requirement to disable the large query window for entire web application as it is having some performance issues over content database.

But, we have some large lists used by business, which is stopping us to enable the throttling setting at the web application level.

We have the propery at the list level to disable throttling limit for disabling throttling limit so that these lists will not have any impact though we disable the large window time at web application level.

The propery name is "EnableThrottling" which we need to set it to false.

Here is the simple powershell script with the example.

 
$web=get-spweb http://sitecollectionurl
$list=$web.Lists[“ListName”];
$list.EnableThrottling=$false;
$list.update();

Workflow Instance Report across site collection using Powershell script

Hi All,

I have written the script to retrieve the workflow instances that associated across a specific site collection.

The script will iterate through each item in the list/library for all sub sites in the site collection and provides the workflows associated with the status, status url, item id, workflow name, workflow instance id.

 
param ([boolean] $writeToFile = $true)
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
Add-Type @'
 public class workflowItem
 {
   public string weburl;
   public string ListURL;
   public string Item;
   public string workflowname;
   public string status;
   public string InstanceId;
   public string url;
 }
'@

$itemsCollection = New-Object 'System.Collections.Generic.List[System.Object]';
$exportfile = $currentdatetime = get-date -format "yyyy-MM-d.hh-mm-ss";
$exportVersionLocation=$exportfolder+"\workflowstats"+$exportfile+".csv"

#Counter variables
 $webcount = 0
 $listcount = 0
 $associationcount = 0

$sitename =  Read-Host "Enter site collection url"
$site=Get-SPSite -Identity $sitename

$webs=$site.Allwebs

if($webs.count -ge 1)
{

foreach($web in $site.Allwebs)
{


 write-host $web 
 #Grab all lists in the current web
 $lists = $web.Lists
 foreach($list in $lists)
 {
 $associations = @()
    #Get all workflows that are associated with the current list
             foreach($listassociation in $list.WorkflowAssociations)
 {
 $associations += $($listassociation.name)
 }
 $listcount +=1

 if($associations.count -ge 1 -and $list.items.count -ge 1)
 {

 foreach($item in $list.items)
  {

foreach($wf in $item.workflows)
    {

     $wfItem = New-Object workflowItem
     $wfItem.weburl=$web.url
     $wfItem.ListURL=$list.Title
     $wfitem.Item=$item.Title
     $ass1=$wf.parentassociation
     $wfItem.workflowname=$ass1.Name
     $wfItem.status=$wf.InternalState
     $wfitem.InstanceId=$wf.InstanceID.Tostring()
     $wfitem.url=$wf.StatusUrl
     $itemsCollection.Add($wfItem);
     
    }
 
   }

 
 }

 }
}
 $webcount +=1

 $web.Dispose()
 }

$itemsCollection | export-csv "$exportVersionLocation" -noType
 
The csv file will be generated in the root directory where the script placed and executed,

Large List items paging using ListItemCollectionPosition

Hi All,

I got the requirement to iterate large list items which are above throttling limits. Since we get the throttling exception when try to retrive items using caml query through standard process using server object model.

I used the "ListItemCollectionPosition" object to show items in the paging view.


 
$weburl=Read-Host "Enter site url"
$web = Get-SPWeb -Identity $weburl
$listname=Read-Host "Enter the list name"
$list = $web.Lists["$listname"]
if($list -ne $null)

{
write-host $list.Title
$spQuery = New-Object Microsoft.SharePoint.SPQuery
$spQuery.ViewAttributes = "Scope='Recursive'";
$spQuery.RowLimit = 10
$caml = '' 
$spQuery.Query = $caml 

do
{
    
    $listItems = $list.GetItems($spQuery)
    
    Write-Host $listItems.ListItemCollectionPosition.PagingInfo
    $spQuery.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
    foreach($item in $listItems)
    {
        Write-Host $item.Title
        
    }
}
while ($spQuery.ListItemCollectionPosition -ne $null)
}

else
{
write-host "List does not exist"
}

Cancel Workflow Instances using powershell script

Hi All,

Recently, I worked on the requirement to terminate the running workflow instances associtated to the specific list using powershell script.

I used WorkflowManager and then Cancel method with passiing the workflow instance class,

Here  I terminated the workflows for which the workflow status is running.

here is the script.

 
#Site URL
$siteurl=Read-Host "Enter Site URL"
$web = Get-SPWeb $siteurl
$web.AllowUnsafeUpdates = $true;    

#List Name
$listname=Read-Host "Enter list Name"
$list = $web.Lists["$listname"];

if($list -ne $null)
{
# Iterate through all Items in List and all Workflows on Items.         
foreach ($item in $list.Items) {
foreach ($wf in $item.Workflows) {

#Cancel Workflows      

if($wf.InternalState - eq 'Running')
{  
[Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($wf);      
}
}
}
$web.Dispose();
}
else
{
 write-host "List does not exist"
}

Specific feature Activated sites report using Powershell

Hi All,

when you got the requirement to know the list of site collections where a specific feature got activated at the site collection level, the below script will be helpful.

For example, to know the list of site collection where the Nintex wokrflow got activated, use the below script.

 
$GC = Start-SPAssignment

$sites=$GC | Get-SPSite -Limit All


foreach($site in $sites)

{

$feature=Get-SPFeature -Site $site | Where-object {$_.DisplayName -eq "NintexWorkflow"}

if($feature -ne $null)
{
  write-host "Feature activated at site" $site.Url

}
$site.dispose()
}

Stop-SPAssignment $GC
 
If you want the spcific publishing feature or custom feature activated site collection list, replace the feature display name with the custom one.
 
 

Tuesday, September 24, 2013

SharePoint Health Analyser automated mail using Powershell

Hi guys,

Got a requirement to send the farm health report to the farm adminstrators group to get the updates automatically throgh the mail.

After some research, I found the basic power shell script which pulls the data from Health Reports list in the central administration web application

I modified and updated the script to get the severity incidents in the HTML tabular form ,

We can execute the script with task scheduler for automation.

Content Query web part --Querying multiple specific lists

Hi guys,

How to query the data from multiple lists in SharePoint using content query webpart?

 I have a simple requirement to display the latest 5 document links from multiple document libraries in the current site.

 In general, share point out of the box feature provides the way to query the data from a particular list or all the lists/document libraries in a site or entire site collection.

 If you want to query the data from multiple specific lists, you have to do in in the below way.

 Add the content query webpart to the page,by editing the page and it comes in Content Roll up category. Note- if you are not able to see content query webpart in content roll up category, then your site's publishing feature is not activated. Activate that feature at the site collection level and also at the site level [make sure you have site collection administrator rights.]

 In the content query web part tool box section, select the radio button, that shows "select all the lists/document libraries in the site" and do the remaining filter and sort options, presentation things as per your requirement.

 Finally click Apply button ,then save the page and do the export web part.

 Open the .webpart file after you export it, modify the .webpart file in designer and then find the below property "ListsOverride ".

Get the List GUIDs from the list settings page, for which you want to query the lists.

 Modify that tag similar to the below one.









SharePoint 2010 List color codes indiacator using HTML calculated columns

Hi guys,

I have the requirement to build the dashboard designer based on the data from the list. After research on the google, I am able to find the simple way to achieve it using html calculated columns.

Below is the brief description about it for reference.

For example, you have the choice field to show the field "Kickoff" status to green for in progress, red for delay and yellow for hold on.

I created the calculated column to name it as "KICKOFF" and wrote the calculated formula as follows.

KICKOFF: ="
•
"

Once the user selects the Kickoff field to green from choice dropdown, the dashboard field will be updated with green bullet.

Similarly for other fields, you can write the html calculated fields easily based on the choice specified in the original field.

PRESENT: ="
•
"

In above one ,if the choice field "Final presentation" selected by user is Red, the calculated field show red bullet in dash board.

Once you insert the list view webpart in the page, modify the view of list to display the calculated fields .

After that , your job is not completely done.  You have to modify the columns value in sharepoint designer.

Open the list view webpart in designer and select the calculated field, then go to properties and then write

xsl:value-of disable-output-escaping="yes"

Save and close the page. Refresh the page in webpage and see the color dashboard.

Saturday, September 14, 2013

Dataform webpart throws error XSLT timeout error

In the data form webpart, if the xslt transformation takes more than one second, the stack overflow exception would be thrown and error message displayed to the user.

To increase the transformation time out, the below power shell script is required.



Activating FAST search feature using power shell script

Hi Guys,

I had a chance to check whether the fast search feature is activated on your site collection or not using power shell script.

If you navigate to the below url, then you are able to find the fast search feature status
http://sitecollectionurl/_layouts/contextualkeywordmanagement.aspx



Fast search feature is the hidden one, where you need to activate that one using power shell console only through farm administration rights.

Here is the powershell command to know the features activated on your site collection

Get-SPFeature -site siteurl |sort displayname.

If you do not find the feature named "Search Extensions" in the activated features list, you need to activate the hidden feature manually using Fast search feature GUID.

Enable-SPFeature -ID "5EAC763D-FBF5-4d6f-A76B-EDED7DD7B0A5" -site sitecollectionurl










SharePoint List item do not update modified time and modified user

Hi,

I had a requirement to not update the modified user and modified date on the list items with the ability to update the items in the list.

This situation comes like in the production sharepoint sites, the documents modified time and modified by fields are updated by business users and while doing code executions on these items, those modified fields on the lists items should not be updated with system account and latest time.

For this, we used the item.systemupdate(true/false) method.

Here is the script, we had to run on each item in the document library in the entire site collection to make the item update , but without updating modified by and modified time.

Our requirement was to delete the minor versions in the entire site collection, so we recommended the approach of enabling version history with setting "Keep the following no of minor versions" to 1 or 2 or 3.

So if we set 1 for the setting, only the current published minor versions other published versions will exist and all other minor versions will be deleted.
But this job will be done only the item has to be checked out with check in /discard checkout action.

To avoid manual action on each item, we prepared the following script.



Sunday, April 21, 2013

Permissoins required for doing backup job in SharePoint 2010

Hi All, The below permissions are required on the backup folder you created to complete the required backup job.
1. Sharepoint timer service account --i.e on which account the timer jobs are running in your farm --> go to services.msc and check the service properties

2. SQL server service instance -- i.e. on which account, the sql service is running in your database server -->go to services.msc and check the service properties

3. The user who is doing the backup job--

These above users should have full control on the backup folder

For better performance, create the backup folder in the sql server itself, so that the network speed would not be a problem.Later you can copy the content to network drive for restore operation.

Saturday, April 20, 2013

Modify Webpart Title Color, background color, Header background,

Hi All, Recently I had to work on some custom css changes in my team site home page. I need to change the Color of the Webpart titles, background color of the total webpart and header. To achieve these things easily ,I first had to go to developer tools (short cut : F12 or Tools -->Internet options -->Developer Tools) of the required page and then understood what the css classes were written in CoreV4.css file for existing styles of the web part and the page. We need to override these css classes in our custome code in master page or CEWP. Here is my work for different categories.

Code for changing the color of Webpart title

 <style type="text/css">
  
 .ms-WPTitle {
  
      COLOR: #d47600; FONT-WEIGHT: bold
  
 }
  
 .ms-WPTitle A:link {
  
      COLOR: #d47600; FONT-WEIGHT: bold
  
 }
  
 .ms-WPTitle A:visited {
  
      COLOR: #d47600; FONT-WEIGHT: bold
  
 }
  
 }
  
Code for Changing webpart header background color
 <style type="text/css">
  
 .ms-WPHeader {

BACKGROUND-COLOR:Trasperant;

}
}
Code for Changing the Total Webpart background color: If you want to change the background color for a required webparts in the page, you should first locate the id of the webpart. This could be found by using again developer tools, open developer tools, select "Find Element by click" on menu, switch to your site page, then locate the webpart with mouse and then identify ID highlighted in Developer tools. Here is the script for that changing color:
 <style type="text/css">
  
 .s4-wpcell#MSOZoneCell_WebPartWPQ7 {

BACKGROUND-COLOR:blue
}
}
In the above snippet,.s4-wpcell is the css class for total webpart box and we are applying only for the webpart with the id "MSOZoneCell_WebPartWPQ7 ". if you want to change for all the webparts, you could directly use the single css code like here
 <style type="text/css">
  
 .s4-wpcell{

BACKGROUND-COLOR:blue
}
}
Code for removing the headers of list/document libraries
 <style type="text/css">
  
 .ms-viewheadertr{

 Display:none;
}
}  
Code for removing left quick launch panel
 <style type="text/css">
  
 #s4-leftpanel{

 Display:none;

}
}  
You can apply directly in CEWP for quick testing of these css snippets.
For adding the styles in master page, it would be recommended to maintain a separate style sheet in styles library of the top level site and give that style sheet reference in master page head tag like below.
 <link rel="stylesheet" type="text/css" href="../../style%20library/CustomCSS/Mystyles.css" />   

Add Background image to the site page

Hi Guys, I had a requirement from customer to add a background image to the existing site page. I just wrote a css style to achieve this through Content editor webpart. Here I noted downn my brief work . The Background image needs to be applied to the BODY tag of the page and here is my css script.
 <style type="text/css">
  
 BODY{
  
 background-image:url("/sites/yoursite/images/bgimage.jpg");
  
 background-position:center;
  
 background-repeat:no-repeat;
  
 }

.s4-ca {
 BACKGROUND-COLOR: transparent
}

  
In addition to the above code,you must add the background color transperent style to overcome the white background. Use this code in CEWP, if you have a requirement in only page, Otherwise, add the same style snippet in Master page head tag if you have enough permissions.

Sunday, January 20, 2013

SharePoint Content DB size mismatch

Hi, Once you enable the quota limit in central admin for a site collection and do check the _layouts/storman.aspx page, you are able to see the site storage space. But, you may find some difference in the actual content db size and the statistics shown in the above page. To recalculate it again, use the below power shell script. $site=get-spsite -identity http://sitecollectionurl $site.RecalculateStorageUsed()

Saturday, January 19, 2013

Back up the farm using power shell

I got a requirement from my client to take the backup of the farm on a weekly basis using automated scheduler.

we do have a standard powershell cmdlet, that helps us in taking the back up of farm using backup-spfarm cmdlet.

We could do the job on a dialy or weekly basis with power shell script and windows task scheduler.

After I searched for some time , I got an excellent blog from http://sharepointpolice.com/ .

Here is the same script , I used for my farm.