Search This Blog

Monday, May 13, 2013

How to create webpart custom properties in SharePoint 2010


In this article we will be seeing how to create webpart custom properties in SharePoint 2010.

Steps Involved:
  • Open Visual Studio 2010.
  • Create an "Empty SharePoint Project".
  • Right click on the solution and click on Add => New Item.
  • Select "Webpart" template from SharePoint 2010 installed templates.
  • Entire solution looks like the following

    share1.gif
     
  • Replace CustomProperties.cs file with the following code.
using System;using System.ComponentModel;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using Microsoft.SharePoint;using Microsoft.SharePoint.WebControls;
namespace CustomProperties.CustomPropertiesWP
{
    [ToolboxItemAttribute(false)]
    public class CustomPropertiesWP : WebPart    {
        private string _value;
        Label lblResult;
       Button btnClick;
         [System.Web.UI.WebControls.WebParts.WebBrowsable(true),
         System.Web.UI.WebControls.WebParts.WebDisplayName("Enter the Value"),
         System.Web.UI.WebControls.WebParts.WebDescription(""),
         System.Web.UI.WebControls.WebParts.Personalizable(
         System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
         System.ComponentModel.Category("anavijai Custom Properties"),
        System.ComponentModel.DefaultValue("")]
          public string _Value
        {
            get { return _value; }
            set { _value = value; }
        }
        protected override void CreateChildControls()
        {
            lblResult = new Label();
            btnClick = new Button();
            btnClick.Text = "Click";
            btnClick.Click += new EventHandler(btnClick_Click);
            this.Controls.Add(lblResult);
            this.Controls.Add(btnClick);
        }
        protected void btnClick_Click(object sender, EventArgs e)
        {
            lblResult.Text = _Value.ToString(); 
        }       
    }
}
  • Build and deploy the solution.
  • Go to the SharePoint Site =>Site Actions =>Edit Page =>Editing Tools => Insert =>Web Part =>Categories => Custom =>CustomPropertiesWP.

    share2.gif
     
  • Click on Add.
  • The web part looks like the following with a button.

    share3.gif
     
  • Edit the webpart you could see a new custom category in the webpart properties.

    share4.gif
     
  • Enter the value and click on Ok.

    share5.gif
     
  • In the CustomPropertiesWP click on the button.

    share6.gif

Wednesday, May 8, 2013

SharePoint – Custom approval workflow with Dynamic Approvers using SharePoint Designer


In this article I will walk you through on how to implement a custom document approval workflow using SharePoint Designer.
Assuming the person to approve is set through a metadata property of the document.
Below snapshot show how the Document library looks
WFL1
Let’s start the process by opening site in SharePoint designer. From Ribbon, click on List Workflow and select the document library.
WFL2
Enter workflow name and description
WFL3
Now add action “Start Approval Process” from ribbon
WFL4
Edit step by clicking “these users” link
WFL5
Here we are going to select the dynamic approver by picking the user from current item property
WFL6
WFL7
WFL8
WFL9
Click Ok. Now select “Workflow Settings” from ribbon
WFL90
From start options we should set “Start workflow automatically when an item is created”. This will ensure for all new document uploaded into the library will go through an approval process.
WFL91
Last step is to publish the new workflow.
WFL92
Lets test the workflow. Step 1 is to verify whether the workflow got associated properly. For that open up the document library setting and open the Workflow settings.
WFL93
Let’s upload a new document. Ensure to put a valid user in “Approver” field.
WFL94
Now the workflow will kick start and the status will be “In Progress”
WFL95
A new task should get created for the Approver.
WFL96
Clicking on the Task title will bring up the “Approve/Reject” option
WFL97
Clicking Approve will complete the workflow.

Monday, May 6, 2013

Customize Sharepoint 2010 Editform.aspx

Add the following code through sharepoint designer Or CEW. Below peiece of code is hiding the columns in edit form......................





 _spBodyOnLoadFunctionNames.push("hideRows");
 function hideRows()
 {
  var pageTables = document.getElementsByTagName('table');
        var cName = null;
        var formTables = null;
        for(var i=0; i < pageTables.length; i++){
         cName = pageTables[i].className;
            if (cName == "ms-formtable"){
             formTables = pageTables[i];
            }
        }
            var rows = formTables.rows;
            rows[rows.length-2].style.display = "none";
            rows[rows.length-3].style.display = "none";
            rows[rows.length-1].style.display = "none";
            rows[rows.length-4].style.display = "none";   
            rows[rows.length-5].style.display = "none";
              
 }


Sequential workflow using while and Ifelse


In this article we can explore using multiple activities in a Site Workflow created using Visual Studio 2010. The core activities we use here are:
  • Code Activity to execute custom code
  • While Activity to execute inner activities upon condition is true
  • IfElse Activity to execute branching activities based on condition
  • LogToHistoryList Activity to log information to Workflow internal history list
Scenario

A typical approval scenario is being addressed here. An Expenses list is given for approval. The entries having an amount lesser than 100 are approved. 

Pre-Requisites

Create a custom list named Expenses for using this example. Add some items into the new list as shown below:
Image 1.jpg

Create Workflow

Open Visual Studio 2010 and create a new Sequential Workflow Project as shown below:
Image 2.jpg

In the next page choose your site collection and click the Next button to continue.

In the page that appears choose Site Workflow as shown below:
Image 3.jpg

In the last page choose the option to start the workflow manually.
Image 4.jpg

Now you will be getting the Workflow designer with default activity inside it.
Image 5.jpg

Add Activities
Open Visual Studio. Now you can drag and drop the following activities from the Toolbox:
  • 1 Code Activity
  • 1 While Activity & IfBranch Activity
  • 2 Code Activity inside If, Else branches
  • 1 LogToHistory Activity
As shown below:
Image 6.jpg

Our idea is the following:
  • Create a property named CurrentItem of type object, Index of type integer
  • In the first Workflow activated, fetch all the Expenses items
  • In the Code Activity initialize the Index field
  • Set the While Activity condition until CurrentItem is not null
  • Set the If branch condition as Amount less than 100
  • Set the Else branch condition as Amount greater than or equal to 100
  • Set the Code Activity in an If branch, to update the status as Approved
  • Set the Code Activity in an Else branch, to update status as Rejected
  • Use the LogToHistory activity for logging the workflow completion informationâ€Æ’
Create Entity, Properties & Fields

Please create the following class to hold the Expense Item, to give an Object Oriented look and feel.
namespace ExpenseApprovalWorkflow{    public class ExpenseItem    {        public int ID;        public double Amount;    }}
Inside the Workflow class, add the following properties and fields.
namespace ExpenseApprovalWorkflow.Workflow1
{
    public sealed partial class Workflow1 : SequentialWorkflowActivity    {
        List<ExpenseItem> Expenses = new List<ExpenseItem>();
        int Index;
 
        ExpenseItem CurrentItem
        {
            get            {
                if (Index < Expenses.Count)
                    return Expenses[Index];
 
                return null;
            }
        }
    }
}
The Expenses list holds the ExpenseItem type items. The Index property represents the current index of the item being processed.

Initiation Code

Back to the workflow designer, double-click on the onWorkflowActivated step and add the following code:
private void onWorkflowActivated1_Invoked(object sender, ExternalDataEventArgs e)
{
    using (SPSite site = SPContext.Current.Site)
    {
        using (SPWeb web = site.OpenWeb())
        {
            var items = web.Lists["Expenses"].GetItems("ID""Amount");

            foreach (SPListItem item in items)
            {
                ExpenseItem expenseItem = new ExpenseItem();
                expenseItem.ID = (int)item["ID"];
                expenseItem.Amount = (double)item["Amount"];

                Expenses.Add(expenseItem);
            }
        }
    }
}
The code fetches all Expenses list items from SharePoint and adds them to the Expenses field of our workflow class.

Code Activity

Double-click on the Code Activity item from the Workflow Design View (second activity). In the code window that appears enter the following code:
private void codeActivity1_ExecuteCode(object sender, EventArgs e)
{
    Index = -1;
}
The code initializes the Index field to -1. This field will be incremented in the while loop later.

While Activity

Now select the While activity from the workflow design view and choose the Properties window. Choose the Condition property as Code Condition and set the Inner Condition property as WhileCodeCondition.

Image 7.jpg

The WhileCodeCondition represents the name of the method which evaluates the While condition and returns true or false to continue or terminate the workflow.

Paste the following code in the Workflow class view.
private void WhileCodeCondition(object sender, ConditionalEventArgs e)
{
    Index++;
 
    e.Result = (CurrentItem != null);
}

You can see the method name matches the property we have specified. The method receives the ConditionalEventArgs for specifying the condition for the while activity.

IfElse Activity

You can see that there are 2 branch activities for the IfElse activity.

Image 8.jpg

Select the first branch item and open the Properties window. Here we can specify the following properties:
  1. Condition as Declarative Rule Condition
  2. ConditionName as IfCondition
  3. Expression as this.CurrentItem.Amount < 100
You can see them in the Properties window as shown below:

Image 9.jpg

The ellipsis button as highlighted in red color can be used to create the Expression. There is an auto-completion enabled in the editor dialog that appears.

Image 10.jpg

Now select the second branch item and open the Properties window. Here we can specify the following properties:
  1. Condition as Declarative Rule Condition
  2. ConditionName as ElseCondition
  3. Expression as this.CurrentItem.Amount >= 100
Now our If and Else branches are ready to proceed with their Code activities.

Code Activity for If branch

Now double-click on the Code Activity for the If branch.

Image 11.jpg

In the code view that appears, enter the following code:
 
private void codeActivity2_ExecuteCode(object sender, EventArgs e)
{
    using (SPSite site = SPContext.Current.Site)
    {
        using (SPWeb web = site.OpenWeb())
        {
            var item = web.Lists["Expenses"].GetItemById(CurrentItem.ID);

            item["Status"] = "Approved";
            item.Update();
        }
    }
}

The code fetches the Expense Item by ID and updates the Status as Approved.

Code Activity for Else branch

Now double-click on the Code Activity for the Else branch.

Image 12.jpg

In the code view that appears, enter the following code:
 
private void codeActivity3_ExecuteCode(object sender, EventArgs e)
{
    using (SPSite site = SPContext.Current.Site)
    {
        using (SPWeb web = site.OpenWeb())
        {
            var item = web.Lists["Expenses"].GetItemById(CurrentItem.ID);

            item["Status"] = "Rejected";
            item.Update();
        }
    }
}

The code fetches the Expense Item by ID and updates the Status as Rejected.

LogToHistoryList Activity

This activity logs information into the History List of the site. Select the activity and set the following property:

Image 13.jpg

This list is a hidden list and is not shown in the Quick Launch or All Site Content.

To view the list you need to type the List Name in the address bar. For example:

http://SERVER/Lists/workflow%20history/AllItems.aspx

You can see various entries in the History List as shown below:

Image 14.jpg

Using the History List we can verify the workflow instances being executed and their log information for troubleshooting.

Deploy the Workflow

Now we are ready to execute our workflow. Build the project, right-click on the solution and Deploy it.

Inside SharePoint

Back in SharePoint choose the Site Workflows and start our workflow.

Image 15.jpg

Wait for a while for the execution to be completed.

Image 16.jpg

Back to the Expenses list you can see the Status column being updated for the items.

Image 17.jpg

You can open the Workflow History list to view the log entry as shown below:

Image 18.jpg

This concludes our playing with Workflow activities.

Sharepoint 2010 Sequential Workflow using Ifelse condition



using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.Linq;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WorkflowActions;

namespace IfElseCondition.Workflow1
{
    public sealed partial class Workflow1 : SequentialWorkflowActivity
    {
        public Workflow1()
        {
            InitializeComponent();
        }

        public Guid workflowId = default(System.Guid);
        public SPWorkflowActivationProperties workflowProperties = new SPWorkflowActivationProperties();

        int _pricevalue = 0;
        public int PriceValue
        {
            get
            {
                return this._pricevalue;
            }
            set
            {
                this._pricevalue = value;
            }
        }
        public bool iresult = true;

        private void Ifcodeexecute(object sender, EventArgs e)
        {

            try
            {
                workflowProperties.Item["Status"] = "Good";
                workflowProperties.Item.Update();
            }
            catch (Exception ex)
            {

            }
         
        }

        private void elseCodeExecute(object sender, EventArgs e)
        {

            try
            {
                workflowProperties.Item["Status"] = "Bad";
                workflowProperties.Item.Update();
            }
            catch (Exception ex)
            {

            }

         
        }

        private void onWorkflowActivated1_Invoked(object sender, ExternalDataEventArgs e)
        {
            if (iresult == false)
            {

            }


        }

        private void CodeActivityforIfelse(object sender, EventArgs e)
        {
            try
            {
                this._pricevalue = Convert.ToInt32(workflowProperties.Item["Price"].ToString());
            }
            catch (Exception ex)
            {

            }
        }

        private void FinalOutput(object sender, EventArgs e)
        {

         
        }
    }
}