Thursday, 18 July 2013

SharePoint 2010: Create Custom Timer Jobs

Introduction
In this article we can try to create a custom Timer Job in SharePoint. The tools we are going to use are the following:

Visual Studio 2010
SharePoint DevTools from CodePlex
We can start with analyzing what a Timer Job is.

What is a Timer Job?
A Timer Job is a periodically executed task inside SharePoint Server. It provides us a task execution environment.


For example, we can execute tasks like: sending emails every hour, data updating every day, creating reports every week, etc.

Default Timer Jobs inside SharePoint
There are many timer jobs inside SharePoint which do internal tasks like:

Send emails
Validate sites
Delete unused sites
Health analysis
Product versioning
Diagnostics
These tasks will having execution periods like:

Minute
Hour
Day
Week
Month

Manage Timer Jobs
You can see all Timer Jobs from Central Administration > Monitoring > Manager Timer Jobs.
Following is the list of some Timer Job definitions:



You can select each Job Definition and change the schedule or disable it.


Creating a Custom Timer Job Definition
Now we are ready with the basics to proceed with creating a Custom Timer Job.

Scenario
        We have a list named Products which is custom template. Any new product arriving has to be posted to an SQL Server database so that the company website can show it to potential customers.

So the activities involved are the following:

  1. Create Products List inside SharePoint
  2. Create Product Table inside Database
  3. Create the Timer Job Definition
  4. Create Event Receiver
  5. Create the Database Insert method
  6. Deploy the Timer Job
  7. View the Results 

(Please note that the same scenario can be done through a combination of Workflow / Events / SSS)  

Step 1: Create Products List inside SharePoint

Here is the List Definition: (the list template with data is attached with the article)

You can see that the core columns of the list are:
ColumnDescription
TitleThe name of the Product
DescriptionAbout the Product
PriceThe price of the Product
The HasPosted column determines whether the item is copied to the Products database. 
After installing the list from template you will can see it is having two items:




Step 2: Create Product Table inside Database

Now we need to create the destination database and table.  Following is the table definition. (The table SQL is attached with the article.)


Step 3: Create the Timer Job

In this step we can go ahead and create the Timer Job.  For this you require Visual Studio 2010 and the SharePoint templates installed.
Open Visual Studio and create a new Empty SharePoint Project as shown below:


 In the next page select your server and use Deploy as Farm solution option:



 Click the Finish button after entering the options.
Now add a new class and derive it from SPJobDefinition as shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;

namespace SPTimerJobExample
{
    public class ProductsJobDefinition : SPJobDefinition
    {
    }
}


Now replace the above file with the following content:
  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;

namespace SPTimerJobExample
{
    public class ProductsTimerJob : SPJobDefinition
    {
        public ProductsTimerJob()
            : base()
        {

        }

        public ProductsTimerJob(string jobName, SPService service, 
               SPServer server, SPJobLockType lockType)
               : base(jobName, service, server, lockType)
        {
            this.Title = "Products Timer Job";
        }

        public ProductsTimerJob(string jobName, SPWebApplication webapp)
            : base(jobName, webapp, null, SPJobLockType.ContentDatabase)
        {
            this.Title = "Products Timer Job";
        }

        public override void Execute(Guid targetInstanceId)
        {
            SPWebApplication webapp = this.Parent as SPWebApplication;
            SPContentDatabase contentDb = webapp.ContentDatabases[targetInstanceId];

            SPList list = contentDb.Sites[0].RootWeb.Lists["Products"];

            CopyItems(list);
        }

        private void CopyItems(SPList list)
        {
            foreach (SPListItem item in list.Items)
            {
                bool hasPosted = (bool)item["HasPosted"];

                if (!hasPosted)
                {
                    new DbManager().Insert(item);

                    item["HasPosted"] = true;
                    item.Update();
                }
            }
        }
    }
}

The above code is performing the following activities:
1. Get the list of items from Products where HasPosted is false.
2. Insert the Product into database.
3. Mark the item HasPosted to true.
We need to include the DbManager class file and will be done in the upcoming step.

Step 4: Create Event Receiver

Now we have to create an event receiver which performs the installation or un-installation of the Job Definition.
In the Solution Explorer right click on Feature and use the Add Feature item.


In the appearing dialog change the title to Products Job Definition and the Scope to Site.




Now right click on the Solution Explorer > Feature 1 and click Add Event Receiver




Inside the class content of Feature1.EventReceiver.cs place the following code:

const string JobName = "Products Timer Job";


public override void FeatureActivated(SPFeatureReceiverProperties properties)

{
    SPSite site = properties.Feature.Parent as SPSite;

    DeleteJob(site); // Delete Job if already Exists


    CreateJob(site); // Create new Job

}

private static void DeleteJob(SPSite site)

{
    foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
       if (job.Name == JobName)
            job.Delete();
}

private static void CreateJob(SPSite site)

{
    ProductsTimerJob job = new ProductsTimerJob(JobName, site.WebApplication);

    SPMinuteSchedule schedule = new SPMinuteSchedule();

    schedule.BeginSecond = 0;
    schedule.EndSecond = 5;
    schedule.Interval = 5;

    job.Schedule = schedule;

    job.Update();
}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)

{
    DeleteJob(properties.Feature.Parent as SPSite); // Delete the Job

}

You need to add the using as well:


using Microsoft.SharePoint.Administration;



Step 5: Create the Database Insert Method

In this step we can complete the DbManager class file.  Here we are using Entity Framework associated with .Net 3.5 version.
For this add a new Entity Data Model into the project and map to the Product table which we have created in previous step.



Now create a class file named DbManage.cs and replace it with the following content:

using System;

namespace SPTimerJobExample
{
    public class DbManager
    {
        public void Insert(Microsoft.SharePoint.SPListItem item)
        {
            using (ProductionModel context = new ProductionModel(GetConnectionString()))
            {
                Product product = new Product();
                product.Title = item["Title"].ToString();
                product.Description = item["Description"].ToString();
                product.Url = item["Url"].ToString();
                product.Price = (double)item["Price"];
                product.PostedOn = DateTime.Today;

                context.AddToProducts(product);

                context.SaveChanges();
            }
        }

        public string GetConnectionString()
        {
            string connectionString = new System.Data.EntityClient.EntityConnectionStringBuilder
            {
                Metadata = "res://*",
                Provider = "System.Data.SqlClient",
                ProviderConnectionString = new System.Data.SqlClient.SqlConnectionStringBuilder
                {
                    InitialCatalog = "YOUR-DB-NAME-HERE",
                    DataSource = @"YOUR-SERVER-NAME-HERE",
                    IntegratedSecurity = false,
                    UserID = "YOUR-USER-ID-HERE",   
                    Password = "YOUR-PASSWORD-HERE",          
                }.ConnectionString
            }.ConnectionString;

            return connectionString;
        }
    }
}
The above code contains the Insert() method to insert new record into the Product table.

For the time being I am hard coding the connection string.  You need to specify the correct user credentials in the GetConnectionString() method.

Note: Please note that the connection string is loaded from the executing application’s configuration file.  In the case of Timer Jobs the configuration file will be OWSTIMER.exe.config residing in the 14hive folder.

Step 6: Deploy the Timer Job

Now we are ready to deploy the Timer Job into the SharePoint Site.  For this right click on the solution and click the Deploy option.


 If you get the Deploy Succeeded message we are good.

Step 7: View the Results

Now we can go to the Central Administration to see our Timer Job.  For this open Central Administration web site and go to Monitoring > Review Job Definitions


On clicking the Review Job Definitions link you can see our item as shown below:
Click on the item and in the appearing page click the button Run Now




You can see that the Timer Job is set for 5 Minutes according to our code.
Now we can go back to the Products list and see that the HasPosted is set to True.

Going to the SQL Server Table we can see both the records are inserted there.


Troubleshooting Tips

While developing timer jobs, you might need to delete the assembly and feature as well.  Please note the following points for troubleshooting guidance:
  • Features are deployed to the 14hive folder
  • The assembly gets deployed to GAC folder
  • You can use RETRACT option from  Visual Studio
  • You can use GACUTIL to uninstall the assembly
  • You can remove the Feature from 14hive folder

For troubleshooting the Farm Solutions or User Solutions you can use:
  • Central Administration > System Settings > Manage Farm Solutions
  • Central Administration > System Settings > Manage User Solutions
You can Retract or undo the last Retract schedule there.
For checking the Job Status or History you can use:
  • Central Administration > Monitoring >  Check Job Status > Timer Job Status
  • Central Administration > Monitoring >  Check Job Status >  Timer Job History
These screens will show the Success / Failure status of the jobs and any errors associated.  For example an invalid connection string problem is identified as shown below:

Debugging Tips

In some cases the Timer Service hold the old version of assembly.  So the new changes you have done through Visual Studio may not get reflect immediately.  You can change the assembly version and view the GAC to ensure the correct version was deployed.



Plus you can restart the SharePoint 2010 Timer Service from services.msc


Note: In the case of Integrated Security as True in connection strings, the authenticated user would be the Service Account user assigned in the service.

Summary

In this article we have explored the Timer Job feature of SharePoint and creating a custom timer job.  Following are the key points to be remembered:
  • Timer Jobs can be scheduled for automating jobs inside SharePoint 2010
  • SPJobDefinition is the base class for Timer Job
  • Create Event Receiver Feature to create or delete the timer job
  • SPFeatureReceiver is the base class for the event receiver
  • The feature gets deployed in the 14hive folder
  • OWSTIMER.EXE is the process executing Timer Jobs
The associated source code along with the list template with data is attached.  You can download and try running it.


Tuesday, 16 July 2013

SharePoint Interview Questions for WebParts

Microsoft SharePoint WebPart Interview Questions and Answers


This page contains the collection of Microsoft SharePoint WebPart Interview Questions
and Answers / Frequently Asked Questions (FAQs) under category Microsoft SharePoint.
These questions are collected from various resources like informative websites, forums,
 blogs, discussion boards including MSDN and Wikipedia. These listed questions can surely
 help in preparing for Microsoft SharePoint WebPart interview or job.


What is web part? 
Web Parts are the fundamental building blocks for Share Point user interface, and with
them we can build and integrate many different types of applications.


How many types of webparts available? 
These are the following types of webpart :
1. Content Editor Web Part
2. Data View Web Part
3. List View Web Part
4. Image Web Part
5. Members Web Part
6. Page Viewer Web Part


While creating a Web part, which is the ideal location to Initialize the web controls? 
Override the CreateChildControls method to include web controls. You can control the
exact rendering of your controls by calling the Render method.


What are the two base classes a WebPart can inherit from? 
There are two base classes that a WebPart consumed by SharePoint can inherit from,
either the SharePoint WebPart Base class or the ASP.NET 2.0 WebPart base class.


What are the differences between the SharePoint WebPart Base class and ASP.NET 2.0 
WebPart base class? 
Microsoft.SharePoint.WebPartPages.WebPart base class is meant for backward compatibility
with previous versions of SharePoint. The benefit of using the SharePoint WebPart base class
is it supported:
1. Cross page connections
2. Connections between Web Parts that are outside of a Web Part zone
3. Client-side connections (Web Part Page Services Component)
4. Data caching infrastructure
ASP.NET 2.0 WebParts are generally considered better to use because SharePoint is built upon
 the ASP.NET 2.0 web architecture.


What are the inherit benefits of using ASP.NET 2.0 WebPart base class? 
Inheriting from the ASP.NET 2.0 base class offers you features that inherit to ASP.NET 2.0, such
as embedding resources as opposed to use ClassResources for deployment of said types.


What is the WebPartManager sealed class? What is its purpose? 
The WebPartManager sealed class is responsible for managing everything occurring on a WebPart
page, such as the WebParts (controls), events, and misc. functionality that will occur in WebPartZones.
For example, the WebPartManager is responsible for the functionality that is provided when you
are working with moving a WebPart from WebPartZone to WebPartZone. It is known as the �the
central class of the Web Part Control Set.


What is a web part zone? 
Web part zones are what your web parts reside in and help categorize your web parts when designing
a page.

WebParts in Shareponint 2010

Web Parts:
Web Parts are reusable components that display content on Web pages in SharePoint 2010.

A fantastic new feature in SharePoint 2010 is that you can insert a Web Part in the text of one of the Rich Text Editor zone available in the new Wiki Page. (To add, remove, or rearrange the text zones, use the "Text Layout" menu in edit mode)

When you create a team site, the home page is a wiki page. You should be able to move the web parts by Editing (Page tab > Edit) then drag/dropping the web parts to where you'd like them to go. The wiki page won't really have web part zones, but instead you can choose a "Text Layout" to arrange your page as desired. Again you can drag and drop between the layout zones.

Also, when inserting a web part, the web part is added where your cursor is. To make sure you have it in the correct location, open the web part adder first (Edit Page > Insert Tab > Web Part), then click on the page where you want it to go, and then click Add in the web part adder.

Remember points:
We can dropped webparts into anywhere inside the main content area, without having to put it into a WebPartZone (This is all happening behind-the-scenes through a dynamic zone that pushes Webparts into placeholders).

Make sure your webpart is added into Safe Control list in Web.config file.
Open your .webpart file in your visual studio - Make sure type element name has proper namespace & class name.

Difference Between .dwp and .webpart
  1. Dwp was the file extension used in version 2 of SharePoint and .webpart is a new extension used in version 3
  2. Version number on the xmlns attribute is different [2->2003, 3-> 2007]
  3. The main difference is that all properties passed to the web part are specified with a property element and a name attribute in version 3. Version 2 uses different element names for everything.
Visual Webparts:
  1. The new important feature introduced in SharePoint on webparts is Visual webpart. It’s a combination of user control (.ascx) and assembly (.dll)
  2. Since a Visual Web Part loads a User Control (.ascx) from the SharePoint Root it needs access to run the ASP.NET method LoadControl and file system access to the ControlTemplates folder in the SharePoint Root – and this is not allowed by a Sandboxed Solution.
  3. Visual webpart cannot be deploying using sandbox solutions.

Visual sandboxed web part:

The Microsoft Visual Studio team has released the Visual Studio 2010 SharePoint Power Tools. These tools extend the existing SharePoint 2010 project templates and provide the Sandboxed Visual Web Part template that enables you to create Web Parts that can be deployed as sandboxed solutions. The use of these templates also enables designer support for designing the Web Parts.
 Difference between asp.net webparts and SharePoint webparts? 

ASP.NET Web Parts: 
These Web Parts are built on top of the ASP.NET Web Part infrastructure. The ASP.NET-style Web Parts have a dependency on System.Web.dll and must inherit from the WebPart base class in the System.Web.UI.WebControls.WebParts namespace.

These Web Parts can be used in ASP.NET applications as well as in SharePoint Foundation, making them highly reusable.

SharePoint-based Web Parts:

These Web Parts have a dependency on Microsoft.SharePoint.dll and must inherit from the WebPart base class in the Microsoft.SharePoint.WebPartPages namespace.

These Web Parts can only be used in SharePoint Web sites.

Webpart life cycle:

OnInit: This method handles initialization of the control.
OnLoad: This event handles the Load event. This is also used for initialize the control but is not intended for loading data or other processing functionality.

CreateChildControls: This is the most popular event in web part life cycle. This creates any child controls. So if you are adding any control to display then you have to write in this method.

When the page is being rendered for the first time the method generally occurs after the OnLoad() event. In case of postback, it is called before the OnLoad() event. We can make use of EnsureChildControls() - It checks to see if the CreateChildControls method has yet been called, and if it has not, calls it.

EnsureChildControls: This method ensures that CreateChildControls has executed.
EnsureChildControls method must be called to prevent null reference exceptions

SaveViewState: View state of the web part saved.

OnPreRender: This method handles or initiates tasks such as data loading that must complete before the control can render. 

Page.PreRenderComplete: The page fires the PreRenderComplete event after all controls have completed their OnPreRender methods.

Render: This method is used to render everything.

RenderContents: Renders the contents of the control only, inside of the outer tags and style properties.

OnUnload: Performs the final cleanup.

Webpart maintenance page
  1.  A webpart which is causing a problem in a webpart page can be removed using this page. Basically, a Webpart Maintenance page provides the list of all webparts added in a particular page and options to close or remove these webparts.
  2. Use of it: Sometimes after adding a webpart to the page, we get an error page with some message. But in this error page we won’t get any SharePoint controls (like the SiteActions, Ribbon Menu etc.,), so we cannot edit the page and remove the webpart. Then we usually go to the edit form of the page (through page library) and then click on the 'Open Web Part Page in maintenance view' link, which opens the WebPart Maintenance page to remove the webpart which is causing the problem.
  3. Shortcut to open:
  4. Instead of going to the Edit Properties form of the page, we can easily open the WebPart Maintenance page by just adding the following query string to the page URL : ?contents=1
  5. So, if your page URL is 'http://rams/pages/default.aspx' then after appending the query string it should look like ' http://rams/pages/default.aspx?contents=1'
  6. Using this approach, we can open the webpart maintenance page for all the forms pages (like /pages/forms/allitems.aspx?contents=1). But it’s not safe to remove or add any webparts in these pages, as they may affect the normal functionality.
  7. Note: This approach works on both MOSS 2007 and SPS 2010.

Difference web parts visual web parts and traditional web part?
  • The advantage of Web User Control is that you can use Visual Web Developer to design the web user control and in normal web parts all controls are created in the code itself i.e. on “CreateChildControls” method only.
  • Adding Web Part properties is cumbersome for Visual Web Parts as compared to traditional Web Parts. As you develop Web Parts, many times you will want to expose their properties so that users and administrators can supply the values for those properties.
  • Differences in Web Part Connections: This is easily achieved in a traditional Web Part because the logic code is contained in the Web Part itself.
  • Differences when Extending a Web PartYou can extend the traditional Web Part by inheriting from the WebPart class. You can then reuse the base Web Part functionality and extend it as desired. Visual Web Parts cannot be extended. Because this Web Part is a wrapper around a user control, it just contains the code to load the user control; the bulk of the Web Part code resides in the code-behind file of the user control.
  • Differences in Performance and Memory Footprint: Visual Web Parts have slightly larger memory footprints than code-only Web Parts. Visual Web Parts contain more parts (Web Part, user control) than traditional Web Parts.
  • Refer the below msdn article to get a clear idea: 

Main webpart base classes:

There are two base classes that a WebPart which is going to be consumed by SharePoint can inherit from, either the SharePoint WebPart Base class or the ASP.NET 2.0 WebPart base class. When inheriting from the SharePoint WebPart Base class your derived WebPart class will inherit from Microsoft.SharePoint.WebPartPages.WebPart. When inheriting from the ASP.NET 2.0 WebPart base class your derived WebPart class will inherit from System.Web.UI.WebControls.WebParts.WebPart. It is considered good practice to use the ASP.NET WebPart base class since the old base class is meant for backwards compatibility with previous version of SharePoint however there are four exceptions when it is better to leverage functionality from the SharePoint WebPart base class:
  1. Cross page connections
  2. Connections between Web Parts that are outside of a Web Part zone
  3. Client-side connections (Web Part Page Services Component)
  4. Data caching infrastructure.
 Note: If you create a webpart in SharePoint 2010 by default it is inheriting from Asp.Net webpart base class.

A Web Part or Web Form Control on this Page cannot be displayed or imported. The type is not registered as safe.”
The reason for this error is if we modify default namespace into custom namespace, Visual Studio 2010 Package is not generating webpart file properly.

When you made changes to default name space which is being generated by  visual studio, you may not see updated namespace in type element. So make sure your webpart name space name & webpart class name placed correctly in type element's name attribute
Access http://server/_layouts/newdwp.aspx  page and make sure webpart exist. If webpart not shown in the list, still your webpart name space/classname not matches to your safe control entry in web.config file. 
Access http://server/_catalogs/wp/Forms/AllItems.aspx . By clicking on webpart opens webpart in webpart preview page.

Add Web Part inside a Master Page in SharePoint 2010?
I have added the webparts in masterpage successfully by referring the below post. Thanks, SharePoint King.
Note: we cannot add webpart zones to the master page.

Out of box webparts in SharePoint?
Below are my best references to get knowledge on out of box webparts.
Some of important OOB features are listed below: 
CQWP:
  • The Content Query Web Part is a very handy tool in SharePoint Standard and SharePoint Enterprise only i.e. not available at SharePoint Foundation.
  • The CQWP is used to display the content by querying, filtering and sorting.
  • The CQWP can fetch the data based on content types.
  • By default, we can group and sort by only one field.
  • Minimum designer level permissions required.
  • CQWP is part of a bundle of features called “SharePoint Server Publishing Infrastructure”.
  • The Content Query Web part cannot fetch data across site collections. If you really need it, you can take a look at the Lightning Conductor Web Part.
  • Ref: http://sharepointlogics.com/2012/03/how-to-use-content-query-webpart-in.html
DVWP:
  • A Data View Web part is a great way to display data with filtering, grouping, and user desired formatting.
  • SharePoint Designer is required for developing DVWP.
  • DVWP can fetch data from data sources other than lists like xml files.
  • DVWP can fetch data from other site collection.
  • DVWP can merge data from more than one list.
CQWP:
  • The Content Editor Web Part (CEWP) allows you to add text, html, scripts or styles to a SharePoint page.
XSLT list Web part:
  • Introduced in SP2010.
  • In SharePoint 2010, all views in lists and libraries are XSLT list view web parts. This means that you can edit views from the browser or from SharePoint Designer 2010.
CSWP:
  • Introduced in SP 2013.
  • The Content Search Web Part (CSWP) is a Web Part that displays search results based on a search query.
Difference between user control and webpart?
Webparts are like user controls, user controls are added in code but webparts are added at runtime.
The advantage of Web User Control is that you can use Visual Web Developer to design the web user control and in normal web parts all controls are created in the code itself i.e. on “CreateChildControls” method only.

User Control
Web Part
User controls are based on Microsoft ASP.NET, and most developers are familiar with developing user controls. This improves productivity.
In general, developers are not familiar with creating child controls by writing the code from scratch.
User controls can be used with ASP.NET -based solutions. If you decide later to convert a project containing a user control to an ASP.NET -based solution, you should be able to use the control without making any changes.
Web Parts can be used in ASP.NET -based solutions only when the solution uses Web Parts pages.
The Visual Web Developer designer provides support for designing the UI by using drag-and-drop operations that gives the control a consistent look-and-feel, which results in faster development.
The controls in Web Parts must be added by using code.
User controls must be compiled before use, which adds to the time it takes to load the control.
Web Parts are precompiled and ready for use as soon as you need them.