Feb 3, 2012

Site WorkFlow in Sharepoint 2010 using Visual studio 2010

In This article we will discuss about site workflows.
Site work flow is not to a specific list or library you can run on any one of those.
In this example we will create a new Custom List Called Product List and take the data of existing Product List to the new Product list as a backup.
Prerequisite: Make sure that your site is having Product List.

Open visual studio.
Open File-- > New-- > project.
From SharePoint -- > 2010 -- > Select Sequential Workflow.
Give name as Site workflow.



Deploy as form solution.



Click Next.
Select Site workflow.
Give the workflow name which you like.



Click Next.



Click Next.
Here you can see only manually started option available.



Click Finish. It will show the below project structure.



If you want to change the URL of site to deploy, go to properties of the project (F4). Change the Site URL property.



Create Class1 from toolbox and drag and drop below onworkflowactivated.
Open the class1.cs file and paste the below code.

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

namespace Product Backup
{
  public class Class1 : System.Workflow.ComponentModel.Activity
  {
      public Class1()
      { }

protected override System.Workflow.ComponentModel.ActivityExecutionStatus Execute(System.Workflow.ComponentModel.ActivityExecutionContext executionContext)
      {
          try
          {
              SPSite site = SPContext.Current.Site;
              SPWeb web = site.OpenWeb();
              SPList aList = web.GetList("/Lists/ Product s");
              try
              {
                  SPList bList = web.GetList("/Lists/ ProductsBackup");
                  bList.Delete();
              }
              catch
              { }
              Guid newAnnID = web.Lists.Add("ProductsBackup", "A backup Product s list.", SPListTemplateType.GenericList);
              SPList bakList = web.Lists[newAnnID];
            foreach (SPListItem item in aList.Items)
              {
                  SPListItem newAnnItem = bakList.Items.Add();
                  foreach (SPField field in aList.Fields)
                  {
                      if (!field.ReadOnlyField)
                          newAnnItem[field.Id] = item[field.Id];
                  }
                  newAnnItem.Update();
              }
              bakList.OnQuickLaunch = true;
              bakList.Update();
          }
          catch (Exception errx)
          {
            }
          return base.Execute(executionContext);
      }
  }
}

Build and deploy the solution.
Observe the output window.



Open the site URL and check, you will have a ProductsBackup list created with the Products List data.

Hope you found this useful.

SharePoint-Journey for Administrators, Developers and users

1 comment: