Monday, August 27, 2012

SharePoint 2013 – New Event Receiver for Groups,Users,Roles,Inheritance

SharePoint 2013 has Introduced a New and much needed Event Receiver class “SPSecurityEventReceiver”. Using this class you can add Event Handlers around SharePoint Groups, Users, Roles and Permission Inheritance.
Here is the list of events that you can handle in SharePoint 2013 Preview.
You can Handle the following SharePoint Group Events -
    • GroupAdded
    • GroupAdding
    • GroupDeleted
    • GroupDeleting
    • GroupUpdated
    • GroupUpdating
You can Handle the following SharePoint User Events -
      1. GroupUserAdded
      2. GroupUserAdding
      3. GroupUserDeleted
      4. GroupUserDeleting
      5. RoleAssignmentAdded
      6. RoleAssignmentAdding
      7. RoleAssignmentDeleted
      8. RoleAssignmentDeleting
      9. RoleDefinitionAdded
      10. RoleDefinitionAdding
      11. RoleDefinitionDeleted
      12. RoleDefinitionDeleting
      13. RoleDefinitionUpdated
      14. RoleDefinitionUpdating
You can Handle the following Inheritance Events -
    1. InheritanceBreaking
    2. InheritanceBroken
    3. InheritanceReset
    4. InheritanceResetting

Custom Rss feed webpart in Sharepoint 2010

Here are the steps and the code snippet for creating a custom webpart to display items or news via rss feed.
1. Open the VS and add a new blank solution.
2. Now in your Solution say “RssFeedPackage” add a new item then choose add a webpart. Lets name it as RSSFeedWebPart.
Please note : You can directly create a webpart solution and do not necessarily have to add it as an item. I did this because I wanted to add some more features in the same solution.
3. Next, you need to add some logic to the RSSWebPart WebPart. Edit the RSSWebPart.cs class to include the code below. I have added a custom property to receive the Rss feed url for the webpart.
Code goes like this :
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
namespace RssFeedPackage
{
[ToolboxItemAttribute(false)]
public class RSSFeedWebPart: WebPart
{
[WebBrowsable(true)] [Personalizable(PersonalizationScope.Shared)]
public string RSSUrl
{
get; set;
}
protected override void RenderContents(HtmlTextWriter writer)
{
RSSFeed feed = new RSSFeed(RSSUrl);
HyperLink newLink = new HyperLink();
foreach (RSSItem singleRssItem in feed)
{
newLink.Text = singleRssItem.Title;
newLink.NavigateUrl = singleRssItem.Href;
newLink.Target = “rssSite”;
newLink.RenderControl(writer);
writer.WriteBreak();
}
base.RenderContents(writer);
}
}
}
//Code for RSSFeed class
internal class RSSFeed : List
{
internal RSSFeed(string RssURL)
{
try
{
XmlDocument rssDoc = new XmlDocument();
XmlTextReader xRead = new XmlTextReader(RssURL);
rssDoc.Load(xRead);
XmlNodeList xNodes = rssDoc.SelectNodes(“./rss/channel/item”);
foreach (XmlNode xNode in xNodes)
{
this.Add(new RSSItem(xNode)) ;
}
}
catch (Exception)
{
this.Add(new RSSItem());
}
}
}
//Code for RSSItem
internal class RSSItem
{
public string Title { get; internal set; }
public string Href { get; internal set; }
internal RSSItem()
{
Title = “Feed not available at this time” ;
Href = “~” ;
}
internal RSSItem(XmlNode xNode)
{
Title = xNode.SelectSingleNode(“./title”).InnerText;
Href = xNode.SelectSingleNode(“./link”).InnerText;
}
}
4. Now build and deploy the webpart.
5. Finally, Insert the webpart in your webpart page and specify the Rssurl in Edit this WebPart -> RssUrl box

Custom Rss Feed WebPart

I created a WebPart where RSS feed form a SharePoint Blog Posts list was consumed and modified to display, the two recently updated blog posts. Also, the post opens up in a new window on Click of the Post title.

"rss_text" in the below code will return your feed (two recently updated posts).

So here is the code to extract data from feed.

First,
1. Create a WebPart.
2. In CreateChildControls Call the Below method DisplayRSS() and pass the Posts list Rss Feed url( Get the RSS feed link from "View RSS" option in the Posts lists).

protected string DisplayRSS(string ListRssUrl)
{
try
{
string rss_text = "";
string title = "";
string link = "";
string description = "";

XPathDocument doc = new XPathDocument(ListRssUrl);
XPathNavigator nav = doc.CreateNavigator();
XPathNodeIterator items = nav.Select("//item");

int items_to_show = 2;
int count = 0;
while (items.MoveNext() && count < items_to_show)
{
XPathNavigator navCurrent = items.Current;

try
{
title = navCurrent.SelectSingleNode("title").InnerXml;
link = navCurrent.SelectSingleNode("link").InnerXml;
description = navCurrent.SelectSingleNode("description").InnerXml;

}
catch{ }

CleanUp(ref title,ref description); // Calling a FeedClean Function

if (description != "")
{
description = "- " + description;
description += "...";
}

rss_text += "<a href='" + link + "' target='_blank'>" + title + "</a> " + description;

if (count < items_to_show - 1)
rss_text += "<br/><br/>";

rss_text += "</div>";

count++;
}
return rss_text;
}
catch
{ }
}

protected void CleanUp(ref string title,ref string description)
{
title = title.Replace("\n", " ");
title = title.Replace("\r", " ");

description = description.Replace("<", "<");
description = description.Replace(">", ">");

description = Regex.Replace(hover_description, @"<(.\n)*?>", string.Empty); // To Remove all the html tags from the RSS feed.

title = title.Trim();
description = description.Trim();
}

Friday, August 24, 2012

Workflows in Sharepoint 2010

Introduction



Based natively on the Workflow Foundation engine, Sharepoint 2007 was the first version of SharePoint that made usage of workflows quite popular among Microsoft end users and .Net developers.
With SharePoint 2010, Microsoft has privileged robustness by choosing to use the .Net framework 3.5 sp1 (and thus Workflow Foundation 3.5), even if a new version of Workflow Foundation 4.0 (with an improved architecture and designer) is provided with .Net 4.
Despite this, SharePoint 2010 provides a set of welcome improvements. These include workflows that can be associated to web sites (and not just to lists); new options in “out of the box” workflows; the possibility to create workflows with Visio 2010, , as well as a new version of SharePoint Designer 2010 that can create real professional workflows which can then be used out of the box. Furthermore, it is now possible to generate workflow forms in Visual Studio 2010 to allow for a better and more flexible communication channel between the workflow and the outside world.
Site workflows
 
Previous versions of SharePoint did not allow for the association of a workflow to a specific list or indirectly to one or several lists via a content type. With SharePoint 2010 we can now associate one or several workflows to a SharePoint web site, which is pretty handy if the workflow needs to monitor actions happening in several places across the site.
 
What’s new in the “Out Of the Box” new features
 
Compared to SharePoint 2007, a number of important improvements have been added. For instance in the new version of the Approval workflow or of the Collect feedback workflow, it is possible to assign tasks by stages, or even to assign tasks to all members of a SharePoint group. As can be seen in the example below, illustrated in figure 1, two tasks can be assigned to users Amy Alberts and Brian Cox in serial; two other approval tasks are assigned in parallel to Alan Brewer and Alan Steiner ; and in the next step , all members of the “Devoteam Managers” group will be assigned a task .
 
image
Figure 1.Assigning tasks by stages and to all members of a group
 
Authoring workflows with Visio 2010
 
Visio 2010 has now a set of workflow shapes and can easily generate workflows .
An information worker can therefore author a workflow with Visio 2010 before giving it to a developer who will customize it; this can be done in both 2 directions: from SharePoint Designer 2010 to Visio 2010 and from Visio 2010 to SharePoint Designer 2010 (don’t forget that SharePoint Designer is free!).
This is illustrated in figure 2, where we see how an expense report approval process can quickly be designed in Visio 2010.
 
image
Figure 2. Creation of a SharePoint workflow with Visio 2010.
Visio 2010 goes beyond the workflow design: it also generates real workflow code (xoml) that can be reused and customized in a tool like SharePoint Designer 2010. In fact,  Visio 2010 can export the design into a file with a .vwi format (Visio Workflow Interchange) which is actually a zip file containing files  recognized by Workflow Foundation (.xoml and .rules files), but also a .vdx file for the pure Visio part (shape layouts).
image

Figure 3.Workflow files generated by Visio 2010
Creating a workflow with Sharepoint Designer 2010: what’s new
 
The 2010 version of Microsoft SharePoint Designer has now become an essential tool for a wide range of users like business analysts, designers and SharePoint developers. We strongly suggest investing time in becoming familiarized with it.
 
Let’s take a look at the new and improved workflow features of SharePoint Designer 2010.
 
1.       Importing a Visio generated workflow is straightforward and allows for customization by a designer or a developer
 
image
 
Figure 4.Importing a Visio 2010 generated workflow
 
The workflow designer illustrated in the next picture is also more intuitive than in the previous version. The annotations provided in Visio 2010 (like “Expense Report too expensive” and “Approve it”) can be retrieved in SharePoint Designer 2010 as illustrated in the next figure :
 
image

Figure 5.SharePoint Designer Edition of a Visio 2010 workflow.
 
2.       Reusing and customizing “out of the box” workflows
Out of the box workflows, like Collect Feedback and Approval, can be reused in customized workflows : it is a functionality we made use of in Visio 2010 (see figure 2) under the label “Assign item for approval”. Given that most custom collaborative workflows will use some kind of approval functionality, which is sometimes very complicated to program even for skilled Workflow Foundation .Net developers, this is a major improvement.
 
3.       The Office task brings a touch of flexibility in the behavior of the out of the box workflow tasks; it allows us to assign specific behavior to individual tasks, or to the whole approval session. For instance, we can implement the following requirements:
a.       If 50% of users approved, the system approves the item
b.      If the user is not available, assign the task to his manager
c.       As soon as an approval starts or completes, start a specific action (like sending an e-mail for instance)
d.      As soon as when a task is assigned to a user or is complete, start a specific action.
   
4.       Content types & site workflows
 
Probably the weakest feature of SharePoint designer 2007 workflows is that they had to be associated with specific lists and couldn’t be reused. This is a thing of the past: workflows generated with SharePoint Designer 2010 can now be associated with Content Types (which is generally considered as good practice) , or can be associated with a site.
As illustrated in figure 6, it is possible to create 3 types of workflows in SharePoint Designer 2010:
 
·         Workflows associated to a specific list
·         Workflows associated to a content type
·         Workflows associated to a site
 
image
 
Figure 6.SharePoint Designer can create 3 types of workflows.
 
5.       Security : Impersonation Step
Other improvements have been made to security. Previously, declarative workflows generated by SharePoint Designer 2007 were based on the identity of the user who initiated the workflow, which could be a problem if we wanted to access some unauthorized resources; on the other hand, workflows created with Visual Studio 2010 run in full trust mode (with the application pool user identity).
With SharePoint Designer 2010 we now have a kind of hybrid mode: we can run part of the workflow with the identity of the user who published the workflow (typically the Designer) by using the Impersonation step action as illustrated in figure 7.
 
image
 
Figure 7.Impersonation Step
 
6.       Infopath workflow forms
 
Workflows forms for SharePoint Designer 2010 workflows are now Infopath forms by default (they were aspx forms in the previous version); they can therefore be visualized in the Office2007 or 2010 rich client and can easily be customized with the Infopath 2010 Designer.
 
7.       Workflow visualisation
 
Thanks to the new Visio services built in SharePoint 2010, we can now visualize the state of our workflows Figure 8 illustrates an approval process where Brian Cox has completed his task and the system is waiting for Amy Alberts to take action before assigning a task to Alan Steiner.
image
 
Figure 8.Visualisation of a workflow
 
8.       Sandbox
Workflows authored with SharePoint Designer 2010 can run in a protected environment called the sandbox where they cannot put the farm in danger; workflows generated with Visual Studio must run in the farm mode, but not in a sandbox environment.
 
Missing features in Sharepoint Designer 2010
 
Just as it was the case in Sharepoint Designer 2007, it is not possible to author state machine workflows as it is done in Visual Studio; even if most workflows are sequential workflows, there are some situations where we need to be able to move back to previous steps in the workflow. In that case, forget Sharepoint Designer 2010 and move to Visual Studio 2010!
 
Another missing feature is that lack of the looping mechanism in Sharepoint Designer workflows: for instance, we cannot loop through several list items without having to rely on (.Net) custom activities created with Visual Studio.
 
Creating Sharepoint workflows with Visual Studio 2010: what’s new
 
1.       Creating workflows with Visual Studio 2010 is far easier than before thanks to the new Feature Designer (for managing SharePoint features), the new Package Designer (for managing SharePoint solutions packages) and the automatic debugging experience: by clicking F5 the debugger is automatically attached to the corresponding worker process.
 
2.       Like before, we have 2 workflow projects templates: Sequential Workflow or State Machine Workflow (question from Ronnie, if this is like before, why is it mentioned here?)

image
Figure 9.Templates for creating workflows in Visual Studio 2010.
  
3.       No sandbox
Unlike declarative workflows authored with Sharepoint Designer, workflows created with Visual studio cannot run in a sandbox but only in full trusted “Farm Mode”; this is a serious limitation to take into account if we want to move our customizations to Sharepoint Online in the future.
 
4.       Still the old Designer
Since workflow Foundation 3.5 is the workflow engine (version 4.0 with the new Designer is not supported), we still have to use the old designer which is quite slow when we need to display many activities.
 
5.       Importing from SharePoint Designer : irreversible
It is now possible to easily import SharePoint designer 2010 generated workflow into Visual Studio 2010; however, the process is irreversible, contrary to going from Visio 2010 to Sharepoint 2010.
 
6.       List or site workflows
We can create workflows linked to a list or to a site.
 
7.       Workflow events
We can now handle events generated when a list workflow is starting, is started, is postponed, or is completed; this is also true for declarative workflows

image
Figure 10.Creating an event handler to listen to Workflow events
 
8.       Workflow association and initiation forms
 
Creating workflow association forms and initiation forms is now very easy thanks to two new templates that generate aspx pages, as well as code that provides an exchange mechanism between the forms and the workflow.
 
image
 
Figure 11.Creating association and initiation forms in Visual Studio 2010
 
The developer only needs to add specific controls into the aspx forms and must implement 2 methods: GetAssociationData and GetInitiationData().
Unfortunately there is no template provided to generate workflow tasks forms and workflow modification forms.
 
9.       Communication with the outside world
 
One of the biggest improvement in SharePoint 2010 workflows is the possibility to create Pluggable Workflow Services which is an efficient way for workflows to communicate asynchronously with the outside world: for instance a workflow might needs to invoke an external line of business application (“lob”))  like SAP; the answer coming from the lob might take 1 second, but also one hour, one day or much more.
 
What was the problem in Sharepoint 2007?
  
A typical scenario in Sharepoint workflows is to communicate with end users by creating tasks and by listening to any task action performed by the users. In this specific case, the tasks are created by using the CreateTask activity that calls the Sharepoint api; we can make the workflow listen to the tasks changes by using the OnTaskChanged activity, which like all activities with a name starting with “On”, are event based activities. When a workflow runs an event based activity he becomes idle.
An important feature of idle workflows is to be automatically suspended , removed from the host process (“dehydrated”) and serialized in a media (like the Sharepoint content database) and to be “rehydrated” when the event comes up.
The benefit of using event based activities is that since workflows lie dormant in the SharePoint content database when they wait for an event, we can therefore run thousands of workflows in parallel and achieve great scalability.
 
image

Figure 12.Event based workflow activities (in green)
  
In SharePoint 2007 however, we can only use a limited number of event based activities provided by Microsoft: that makes asynchronously calling LOB (Line of Business Applications like SAP) quite shaky by having to create tasks and by asking the LOB to communicate with the workflow by changing the tasks.
 
In Sharepoint 2010
 
Today it is no longer necessary to follow this complex pattern ; instead it is now  possible to  listen to any custom event and to use the HandleExternalEvent activity provided with Workflow Foundation 3.0 (see figure 12) and well known by .Net developers!
 
image

Figure 13.calling an external system
 
However, to achieve it it is still necessary to create a pluggable service by creating a custom class derived from the new SPWorkflowExternalDataExchangeService ; this custom class must be declared in the web.config.
 
Conclusions
 
Even though the workflow aspect of SharePoint 2010 is not revolutionary, it is now much, much easier to create workflows.
Sharepoint Designer and Visio 2010 provide major added value: workflows created with Sharepoint Designer can be reused, it is possible to customize and reuse out of the box workflows, and there is a better and scalable communication channel between Sharepoint and the outside world.

Thursday, August 23, 2012

Create Content Sources in SharePoint 2010 using PowerShell

Automating the Content Source creation in SharePoint 2010

 

We can create Content Sources for Enterprise Search Service Application in SharePoint 2010 from Central Administration.
Go to Central Administration => Application Management => Manage Service Applications => Enterprise Search Service Application.


On the Quick Launch Menu, go to Crawling and then click on Content Sources.




You could be able to see the Content Sources. By clicking on New Content Source link we can create a new Content Source.

Another way is we can create the content sources for Search Service Application using SharePoint Object Model.

Here we will be seeing about automating the content source creation using powershell script.


Steps Involved:


1. Create the input xml file which contains the inputs for content source creation.
2. Create ps1 file which contains the script for content source creation.

CreateContentSources.xml


<?xml version="1.0" encoding="utf-8" ?>
<ContentSources>
<SSAName>EnterPrise Search Service Application</SSAName>
<ContentSource Name="Sample1 SharePoint Sites" />
<ContentSource Name="Sample2 SharePoint Sites" />
<ContentSource Name="Sample3 SharePoint Sites" />
</ContentSources>


CreateContentSources.ps1

#----------------Get the xml file---------------------------------------------------------------
[xml]$xmlData=Get-Content "C:\Users\Desktop\ContentSources\CreateContentSources.xml"

 #----------------Create New Content Source function---------------------------------------------

function CreateNewContentSource
{
$flag=0
$ssa=Get-SPEnterPriseSearchServiceApplication -Identity $xmlData.SSAName
$ssaContent = new-object Microsoft.Office.Server.Search.Administration.Content($ssa)
$xmlData.ContentSources.ContentSource | ForEach-Object {
$contentSourceName=$_.Name
foreach ($availableContentSource in $ssaContent.ContentSources)
{
if ($availablecontentSource.Name.ToString() -eq $contentSourceName)
{
write-host -f Yellow $contentSourceName "content source already exists"
write-host -f Yellow Deleting $contentSourceName content source
$availablecontentSource.Delete()
write-host -f Green $contentSourceName content source is deleted successfully
write-host -f yellow Creating $contentSourceName
$ssaContent.ContentSources.Create([Microsoft.Office.Server.Search.Administration.SharePointContentSource], $contentSourceName)
write-host -f green $contentSourceName "content source is added successfully"
$Flag=1break
}
}
if($Flag -eq 0)
{
write-host -f yellow Creating $contentSourceName
$ssaContent.ContentSources.Create([Microsoft.Office.Server.Search.Administration.SharePointContentSource], $contentSourceName)
write-host -f green $contentSourceName "content source is added successfully"
}
}
}

 

#----------------Calling the function---------------------------------------------
CreateNewContentSource

Run the Script:

1. Go to Start.
2. Click on All Programs.
3. Click on Microsoft SharePoint 2010 Products and then click on SharePoint 2010 Management Shell.
4. Run the C:\Users\Desktop\ContentSources\CreateContentSources.ps1

Output:
And in the Central Administration you could see the newly added content sources as shown in the following
Thanks for reading.

Hope this article was useful, keep reading my forthcoming article of this series

INFOPATH

I have created a custom list named “Custom” which has the following columns

For this list I am going to create an InfoPath form which will be used as New/Edit form in the list. New  form for the list looks like the following

Note: None of the columns is mandatory in Custom list

Create an InfoPath form:

1. Open Microsoft InfoPath Designer 2010.
2. Go to File =>New  => Click on SharePoint List from Available Form Templates

3. Data Connection Wizard will popup, enter the site URL.

4. Click on Next.
5. Select Customize an existing SharePoint list and then select Custom which is a custom list.

6. Click on Finish.

7. You could see the InfoPath form with the following columns

Publish the InfoPath form to SharePoint:

1. Go to File =>Info and then click on Quick Publish.

2. Publishing...

3. Form template is successfully published.

InfoPath form in SharePoint Edit or New form:

1. Open the SharePoint Site.
2. Go to Custom List and add a new item.
3. New form will be an InfoPath form as shown in the following.

How to use the Default SharePoint form:

1.  Go to List Settings.
2. In the General Settings, click on Form Settings.

3. You can select the Default SharePoint form or you can modify the existing InfoPath form.



Thanks for reading.
Hope this article was useful, keep reading my forthcoming article of this series.

Creating a Custom SharePoint Form using SharePoint Designer

  • Create a custom list with the necessary fields
  • Open SharePoint designer and navigate to the site hosting this custom list
  • Expand the lists folder until you see your list and the DispForm.asxp, EditForm.aspx, and NewForm.aspx.
clip_image001
  • Create a new ASPX page
clip_image002
  • Add the SharePoint Custom List Form control (Warning! Don’t mix this form up with the List Form Control
clip_image003
  • Choose the proper list (Warning! If you don’t see the content type you didn’t follow the instructions, look at the step I show above!!!)
clip_image004
  • Your form will appear as it does below
clip_image005