Pages

Wednesday 22 April 2015

Site level Workflow

In this article, we will see how to automate business process by designing workflows using SharePoint Designer 2010. We will also see how to design and integrate InfoPath 2010, which is introduced in SharePoint Designer 2010 with our workflow.
Scenario – To understand the integration better, let us take an overview of a scenario where we will evaluate a new customer which will get registered with our Purchase Order System. This evaluation of the customer will be done by the company employees. They will write their evaluation comments using InfoPath form.
The steps to create a SharePoint Site using a Template ‘Team Site’ remains the same as shown in my previous article SharePoint Dashboard with Common Filters using PerformancePoint Services 2010.
Now that you have created a SharePoint site with ‘Team Site’ template, let’s add a list. To create a list, click on ‘Lists’ link from the left hand navigation pane and click on ‘Create’ button. The ‘Create’ dialog box will appear as shown below –
Sharepoint create dialog box
Once we create a list with the name ‘New Customer Review’, we need to add a couple of columns as described in the table given below. To create a column, click on list settings from the top ‘Ribbon’ as shown below –
Sharepoint List Settings
Now click on ‘Create Column’ link from the ‘List Settings’ page as shown below –
Sharepoint List Settings
Now create the lists as described below. Also add some sample data in the lists –
Customers List –
clip_image005
Now let’s edit the site in SharePoint Designer 2010. Open SharePoint Designer 2010 and click on ‘Open Site’ button. Now paste the URL of your site and click ‘Open’ as shown below –
Sharepoint Open Site
You will see all the site contents in the left hand side section ‘Navigation’. So to create a workflow, click on ‘Workflows’ in the navigation section. You will see a ‘Workflows’ ribbon on top. Now you can create three types of workflow in SharePoint 2010 using SharePoint Designer 2010 –
  1. List Workflow – associated with a specific list in SharePoint.
  2. Reusable Workflow – we can be associate this workflow with multiple lists or content types.
  3. Site Workflow – this workflow is not associated with any lists or site content types.
Click on Site Workflow as shown below –
Sharepoint Site Workflow
Once you click on the ‘Site Workflow’ button, it will ask you the name of the workflow and the description of the workflow. Let’s give a name to the workflow as ‘Customer Review’ and description as ‘Check the customer background’ as shown below –
Create Site Workflow
Click the ‘OK’ button. This will show you workflow editor window in which it shows you the first step with the name ‘Step 1’ as shown below –
Workflow Editor
Now let’s have a look at a few things. Pay particular attention to the Workflow ribbon.
  1. Save button – Now you can save the workflow. This facility was not available in SharePoint Designer 2007.
  2. Publish button – By clicking publishing button, you can publish the workflow to the site.
  3. Conditions – You can implement the conditions in our workflow.
  4. Action – You can add multiple actions when a specific condition occurs in the workflow.
  5. Initiation Form Parameters – Now in SharePoint Designer 2010, you can design InfoPath forms for taking the data from the end users. You can also modify the form design using InfoPath Form designer 2010 if it is installed on your machine.
If you see in the above figure, it shows you a horizontal line with ‘Orange’ color where you can start typing the Steps by double clicking.
So first of all, we will design an Initiation form. This form will be used by an Employee who will fill up the information about customer review. So click on ‘Initiation Form Parameters’ button. This will show you a dialog box. Let’s click on the ‘Add’ button to add the different fields on our ‘Initiation Form’ as shown below –
InfoPath Initiation Form
Let’s add the following fields –
clip_image012
Now we are ready with our ‘Initiation Form’. If you observe, our form is similar to our list which we have created in  the above steps. So we will use this initiation form to fill data in our list. To add the data from our ‘Initiation Form’ to our ‘New Customer Review’ button, let’s add an ‘Action’ in our workflow as shown below. To add an ‘Action’ in our workflow, click on ‘Action’ dropdown list and make a choice of ‘Create List Item’ from the ‘List Actions’ section as shown below –
Sharepoint List Action
This will show you the following screen –
clip_image014
Click on ‘this list’ which brings up the ‘Create New List item’ dialog box. From the list dropdown, choose our list ‘New Customer Review’ and click on the ‘Add’ button. This will bring up the ‘Value Assignment’ dialog box. In this dialog box, we will set the field of our list. Choose our first field ‘CustomerID’ and click on ‘To this value’ button as shown below –
Sharepoint Value Assigment
In the ‘Lookup for Integer’ dialog box, choose ‘Data Source’ as ‘Workflow Variables and Parameters’ and set ‘Field from source’ to ‘Parameter: CustomerID’ as shown above. Repeat this step for all the fields of ‘New Customer Review’ list fields. Once done, the ‘Create List item box’ should look like below –
Create New List Item
Now let’s add another action in to our workflow. Go to ‘Core Actions’ group and choose ‘Send an Email’ action as shown below –
Infopath Send Email
Now click on ‘These Users’ link and you will see the ‘Define E-Mail Message’ window. In the ‘To’ section, click on the address button and make a choice of ‘Owner’ group. In the ‘Subject’,  to write a message click on ‘Add lookup button’ to add a lookup item. Now write a message ‘Customer Reviewed by – ‘ and then click on ‘Add or Change Lookup’ button. This pops up a pop up box ‘Lookup for String’. Choose ‘Workflow variables and Parameters’ in the Data source section and choose ‘Employee Name’ in the ‘Field from Source section’ as shown below –
Define EMail Message
Now in the Message box, write a message ‘Customer Ratings are –‘ and then click on the ‘Add or Change lookup button’. Then choose ‘Workflow variables and Parameters’ in the Data source section and choose ‘Ratings’ in the ‘Field from Source’ section. The final window should look like the following –
Define EMail Message
Now ‘Save’ your workflow. Click on the ‘Publish’ button. Once your workflow has been published, click on the ‘Customer Review’ workflow from the navigation section as shown below –
Navigation Section
If you check the above diagram, you will see all the details of the workflow with the initiation form. If you observe carefully, your initiation form is now ‘InfoPath Form’. Click on ‘Customer Review.xsn’ form and it will get edited in the InfoPath form designer.
Let’s modify this form a bit –
  • Add a title to our form as Customer Review Report.
  • Format the titles of each field. Make it bold.
  • Change the title of ‘Start’ button to ‘Submit Review’.
Please note that InfoPath form is a very powerful tool which you can use to retrieve data from heterogeneous systems like ‘Web Services’, ‘Databases’, ‘SharePoint Lists’ etc. Now your form should look like the following –
Infopath 2010 Form
Now save your form locally. To make this modified form available to our workflow, you will have to publish this form. The steps to publish this form are –
  1. Click on the File menu and go to Publish sub menu.
  2. On the right hand side, you will see the actual address of the form from where it got downloaded in to our InfoPath form designer tool.
  3. Click on the ‘Workflow’ button. This will publish the form and shows you a message at the end.
Publish Infopath 2010 Form

Testing the WorkFlow
Once your form has been published, let’s go back to our SharePoint site and test our Workflow. To test the workflow, go to ‘Site Action’ menu and click on ‘View All Site Contents’ menu. This displays two link buttons on the top. First one is ‘Create’ and second is ‘Site Workflows’. Click on ‘Site Workflows’ button and you will see your workflow ‘Customer Review’ as shown below –
Customer Review Workflow
Now click on the ‘Customer Review’ workflow and you will see the ‘Initiation Form’ which we designed to add the customer review item in the list ‘New Customer Review’. Fill in the information and then click on ‘Submit Review’ button as shown below –
Customer Review Workflow
Check the ‘New Customer Review’ list and you should see the item in that list. But the problem is now we cannot ask users to go everytime to ‘View All Site Contents’ from the ‘Site Action’ menu. So let’s make it convenient for the end user by adding a link web part on our home page. Follow these steps:
1. ‘Edit’ the ‘Home’ page.
2. Go to ‘Insert’ ribbon and click on  ‘Web Part’ button. From the web part group, choose ‘Lists and Libraries’ and then choose ‘Link’ web part. Click on the Add button. Now save your page.
3. Click on ‘Site Action’ - ‘View All Site Content’. Click on ‘Site Workflows’ link button. Now right click ‘Customer Review’ and click on ‘Copy Shortcut’.
4. Now go to home page and click on ‘Add New Link’ button under ‘Links’ web part. Paste the link which we just copied. In the description, write ‘Customer Review Form’ and click ‘Save’ button. This should look like the following –
clip_image026
Test the link and now you have successfully created a workflow with an Initiation form using SharePoint Designer 2010.
Summary – In this article, we have seen how to automate business processes by designing workflows using SharePoint Designer 2010. We have also seen how to design and integrate InfoPath 2010 which is introduced in SharePoint Designer 2010 with our workflow.

Sunday 12 April 2015

Enhancements in event receivers in SharePoint 2010

Enhancements in event receivers in SharePoint 2010

Before learning new enhancements in sharepoint2010, we have to know why they were enhanced. So that we can remember new features easily, below are the limitations on sharepoint2007 what I covered in my development career.
  • Cannot hook the events to a particular SharePoint lists.
  • Need to use standard pre-defined error page when canceling the events, which is not so intuitive for the end users
  • No JavaScript alert instead of redirecting to pre-defined error page
  • No events for SPWeb object.
Enhancements in event receivers:
       Custom Error Pages: SharePoint 2010 provides developers to create/redirect to custom error pages when the events are cancelled.  This gives developers a great flexibility to provide more information on the custom error pages.  The redirection will applicable only for the pre-synchronous events and not for post-synchronous events like ListAdded, etc., below shows the code snippets to redirect to custom error page.

properties.Cancel = true;
properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
properties.RedirectUrl = "/_layouts/CustomErrors/error.aspx";

      Event Registration Feature: With new event registration enhancement, developers are able to hook the event to a particular SharePoint list in the elements.xml file using ListUrl node by passing relative URL of the list.  Developers are now able to scope the events either at Site or Web levels and also set the property RootWebOnly in Receivers node, if the event receiver only works for root site.

      Impersonation Improvements:  Developers are able to elevate the privileges in the event receivers in order to perform some tasks, which current user who triggered the event does not have adequate permissions to do so using SPSecurity.RunWithElevatedPrivileges method.  In SharePoint 2010, there are new properties namely OriginatingUserTokenUserDisplayName and UserLoginName which help the developers to revert back to the original user who triggered the event very easily.

Reduced the usage of “Feature Stapling” functionality by implementing “A site is being provisioned and A site was provisioned”
"Feature Stapling means, let’s say we create one simple feature of creating list with few columns and if we want to have this list created every time blank site or team site is created, then we can register this feature to be used in team site and blank site, so that whenever we create team site or blank site, the list gets created"

If you want detailed explanation on "feature stapling", please refer this linkhttp://sharepointmagazine.net/articles/introduction-to-sharepoint-feature-stapling-part-1

Master Page

  • v4.master - This is default master page
  • Default. Master - this is used to support the 2007 user interface
  • Minimal. Master
  • Simple. Master- it is used for accessdenied.aspx, confirmation.aspx, error.aspx, login.aspx, reqacc.aspx, signout.aspx & webdeleted.aspx pages
V4.master:  Default master page for most non-publishing sites in SharePoint 2010. It is also the default system master page in both SharePoint Foundation and SharePoint Server.
Default.master: Helpful from upgrading MOSS 2007 sites to SharePoint 2010 sites.
Minimal.master: page is best suited for pages with minimal branding and navigation. The minimal.master is used with search pages and Office web applications.
Simple.master: Master page used for error and login pages. It lives in the fi le system and is not available in the master page gallery.
MWSDefaultv4.master: Found in the master page gallery of meeting workspace sites.
Nightandday.master: page contains controls specialized for publishing web content management.

V4.master: Default team site master page. Provides ribbon bar and other UI changes.
Characteristics:
  • Site actions are updated for 2010 and appear on left.
  • Ribbon bar is available
Default.master: Sites upgraded from SharePoint 2007 use this unless they are changed to use a v4 version.
Characteristics:
  • Site actions on right side and are same as SharePoint 2007 version
  • No ribbon bar
What is Page Layout? 
Page layout dictates the overall look and feel of a web page. A page layout relies on a content type to determine the kind of content that can be stored on pages. Page layout contains field controls and web part.

Master pages and page layouts dictate the overall look and feel of your SharePoint site.
Differences are
Master pages contain controls that are shared across multiple page layouts, such as navigation, search, or language-preference for multilingual sites. Page layouts contain field controls and Web Parts
Page layouts can be used by all page instances that are based on that page layout. Master pages can be used by all page instances in a site.

Site navigation provides the primary interface for site users to move around on the sites and pages on the site. 


  1. Navigation controls on master pages
    1. Top link bar navigation
    2. Quick Launch navigation
    3. Breadcrumb navigation
    4. Tree view navigation
    5. Metadata navigation
  2. Navigation controls on page layouts
    1. Summary Links
    2. Table of Contents
    3. Content Query
  3. Navigation Web Parts
    1. Categories
    2. Site Aggregator
    3. Site in Category
    4. Tag Cloud
Ribbon Interface act as the UI enhancement in the product. It provides the commands to be executed in the form of Icons and tabs.

Select Empty Sharepoint template as a project template and select the module item for master page and css.
<Module Name="CustomMaster" Url="_catalogs/masterpage">  <File Path="CustomMaster\custommaster.master" Url="custommaster.master" Type="GhostableInLibrary" />
"Url="_catalogs/masterpage"" means this will be deployed to the master page library in SharePoint.
<Module Name="CustomCSS" Url="Style Library"><File Path="CustomCSS\DAVCSS.css"  Url="CustomCSS/yourfile.css" Type="GhostableInLibrary" />
"Url="Style Library"" means this will be deployed to the style library in SharePoint.
Now add the following code in the feature receiver class file that contains above modules. Right click on the feature and click "Add Event Receiver"
public override void featureactivated(spfeaturereceiverproperties properties)
  {
      spsite currsite = (spsite)properties.feature.parent;
      spweb curweb = currsite.rootweb;
     uri masteruri = new uri(curweb.url + "/_catalogs/masterpage/custommaster.master");
     curweb.masterurl = masteruri.absolutepath;
     curweb.custommasterurl = masteruri.absolutepath;curweb.update();
   }
   This will apply the master page on activation of the feature.
  public override void featuredeactivating(spfeaturereceiverproperties properties)
  {
         spsite currsite = (spsite)properties.feature.parent;
        spweb curweb = currsite.rootweb;
       uri masteruri = new uri(curweb.url + "/_catalogs/masterpage/v4.master");
       curweb.masterurl = masteruri.absolutepath;
      curweb.custommasterurl = masteruri.absolutepath;
       curweb.update();
    }

3 steps involved to add the user control
Create and deploy user control
Register user control in the target
<%@ Register TagPrefix="MyUserControl"  TagName="UserName" Src="~/_controltemplates/MyUserControl/MyUserControl.ascx" %>
Insert the user control wherever required.
<MyUserControl:UserName id="MyUserControl1" runat="server" />
Note: For webpart (Page.LoadControl method)
Use SharePoint designer. Register the namespace of the web part class using <% Register directive. Then use the specified tag prefix from "Register" directive to add the instance of Web part class. Web parts outside the web part zones are referred as static web parts and behave as normal web control.
Register the custom css file as below .
<SharePoint:CssRegistration name="<% $SPUrl:~SiteCollection/Style Library/Custom/styles.css %>" After="corev4.css" runat="server"/>
In CSS, we can wirtie the style for attaching image
background:url(../images/mainBG.jpg)

With the help of delegate control, we can take any OOB control of SharePoint and replace with our custom control without any modification in the SharePoint page. So that new custom control overrides the existing one.
So the delegate control provide one of the option to add control (either server control or user control) on a SharePoint page
For example : In master page SearchBox control is included as  <SharePoint:DelegateControl runat="server" ControlId="SmallSearchInputBox" />
This delegate control object uses features to locate the control which is specified in ControlId.
We can overwrite the above delegate control by presenting the below code in Element file of feature  <Control Id = "GlobalNavigation" Sequence="90"  ControlSrc="~/_ControlTemplates/ucGlobNavDelegateControl.ascx" />

AdditionalPageHead,  GlobalSiteLink(), GlobalSiteLink1, GlobalSiteLink2, SmallSearcgInputBox,
TopNavigationDataSource, PublicConsole, QuickLaunchDatasource
Searching through the main master page, Seattle.master, I’ve found these three new DelegateControls:
PromotedActions
SuiteBarBrandingDelegate
SuiteLinksDelegate
 
You can enable a Web Provisioned event receiver
using (SPWeb childSite = properties.Web)
 {   using (SPWeb topSite = childSite.Site.RootWeb)
  {    childSite.MasterUrl = topSite.MasterUrl;
       childSite.CustomMasterUrl = topSite.CustomMasterUrl;
      childSite.Update();
   }
 }
Using the SharePoint web interface or SharePoint Designer 2010
Using a master page
Using a page layout
Using a Content Editor Web Part
This has to be done in the site definition file system. I don't think there is an Interface for that, but it can be via SPD though.

List Attribute Id= 116

Changes in topnavigation control in  master page.
Ref: http://erikswenson.blogspot.in/2010/11/update-hide-first-tab-in-sp-2010.html

Master page and page layouts options missing in the left navigation in SharePoint designer2010
Users having site ownership privileges are able to view the site's Collection Administration pages but will not see the link enabling them to make the appropriate settings change.
Site collection administrators will enable the “Enable SharePoint Designer “(Site Actionsà SiteSettingsàselect SharePoint designer settings under site collection Administration category)

Conditionally renders the contents of the control to the current user only if the current user has permissions defined in the PermissionString.
<Sharepoint:SPSecurityTrimmedControl runat="server" PermissionsString="XYZ">
</Sharepoint:SPSecurityTrimmedControl>

Copy/Move items from one list to another list in sharepoint

Copy/Move items from one list to another list in sharepoint

Scenario:
List AA fields: Name, Title, User Name, Religion, Qualification.
List BB fields: Name, Title, User Name, Qualification, Designation, Salary and Description
Common field names: Name, Title, user name, Qualification
Now, I want to copy the common field values from List AA to List BB.

Approach:
//Read the list item values by ID and add the common field values as new item into the another list
SPListItem spLstItemsAA = listNameAA.GetItemById(ItemID); //ItemID of List AA
SPListItem spLstItemBB = list.Items.Add();
foreach (SPListItem spLstItemAA in spLstItemsAA.ListItems)
{
       for (int i = 0; i < spLstItemAA.Fields.Count; i++)
       {
          if ((!spLstItemBB.Fields[i].Hidden) && (!spLstItemBB.Fields[i].ReadOnlyField) &&    
                                  !(customfields.Contains(item.Fields[i].Title)))
           {
               spLstItemBB [item.Fields[i].Title] = spLstItemAA [item.Fields[i].Title];
             }
        }
 }
 spLstItemBB ["Salary"] = "50k";spLstItemBB ["Description"] = "sharepointquicksolutions.blogspot.in ";spLstItemBB.Update();

Condition#1: !spLstItemBB.Fields[i].ReadOnlyField
Condition#2: !spLstItemBB.Fields[i].Hidden
The above 2 conditions are used for to skip the read only and hidden fields.

Note: By default, every sharepoint list and library will have the below fields.


Friday 10 April 2015

Timer job

Creating Custom Timer Job in SharePoint 2010

CODE

Open Visual Studio 2010 >File > New >Project >SharePoint 2010>Empty SharePoint Project. >Name it Custom_TimerJob>Ok

Check Deploy as farm solution>Finish

create a class that inherits from the Microsoft.SharePoint.Administration.SPJobDefinition class. To implement this class, you need to create a few constructors and override the Execute() method as following
 
namespace DotnetFinder
{
    class ListTimerJob : SPJobDefinition
    {
         public ListTimerJob()

            : base()
        {

        }

        public ListTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)

            : base(jobName, service, server, targetType)
        {

        }

        public ListTimerJob(string jobName, SPWebApplication webApplication)

            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
        {

            this.Title = "List Timer Job";

        }

        public override void Execute(Guid contentDbId)
        {

            // get a reference to the current site collection's content database

            SPWebApplication webApplication = this.Parent as SPWebApplication;

            SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];

            // get a reference to the "ListTimerJob" list in the RootWeb of the first site collection in the content database

            SPList Listjob = contentDb.Sites[0].RootWeb.Lists["ListTimerJob"];

            // create a new list Item, set the Title to the current day/time, and update the item

            SPListItem newList = Listjob.Items.Add();

            newList["Title"] = DateTime.Now.ToString();

            newList.Update();

        }
}
}
As you can see this job just add a new item to a ListTimerJob list every time it’s executed
Now that you have the job built> Right click on the Features >Add Feature

Right click on the Feature1 ” you can rename the Feature1 to any name” > Add Event Receiver

As you can see the event Receiver class inherits from the Microsoft.SharePoint.SPFeatureReceiver and This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade. But we only need FeatureActivated & FeatureDeactivated event handler to install/uninstall our custom timer job as following
namespace DotnetFinder.Features.Feature1
{
[Guid("9a724fdb-e423-4232-9626-0cffc53fb74b")]
public class Feature1EventReceiver : SPFeatureReceiver
    {
        const string List_JOB_NAME = "ListLogger";
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            // make sure the job isn't already registered

            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {

                if (job.Name == List_JOB_NAME)

                    job.Delete();

            }

            // install the job

            ListTimerJob listLoggerJob = new ListTimerJob(List_JOB_NAME, site.WebApplication);

            SPMinuteSchedule schedule = new SPMinuteSchedule();

            schedule.BeginSecond = 0;

            schedule.EndSecond = 59;

            schedule.Interval = 5;

            listLoggerJob.Schedule = schedule;

            listLoggerJob.Update();

        }

        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            // delete the job

            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {

                if (job.Name == List_JOB_NAME)

                    job.Delete();

            }

}

   }

Before Deploying you should select the right scope of the Feature in other words in which scope you will activate the Feature(Farm,Site,Web,WebApplication) in our case we will activate Feature1 on Site which is mean Site Collection.

Note : if you trying to activate the feature in the wrong scope will get the following error

Now let us deploy our custom timer job >Right Click on Custom_TimerJob project > Click Deploy

Open now your SharePoint site and select ListTimerJob List and you should see something similar to the following image


Our custom timer job is working fine now you can go and check it and modify the schedule as following
Go to SharePoint 2010 central administration >Monitoring >in the Timer Jobs Section Select Review Job Definitions
and you should See our Custom Timer Job

Click on it and you should see Edit Timer Job Page ,Modify Timer Job schedule based on your requirement
Note : you can also modify schedule of your custom Timer Job from the code but you need to add one of the following class in FeatureActviated Event Handler as following

After Specific Minutes use SPMinuteSchedule class
Hourly use SPHourlySchedule class
Daily use SPDailySchedule class
Weekly use SPWeeklySchedule class