Showing posts with label SharePoint. Show all posts
Showing posts with label SharePoint. Show all posts

Monday, December 28, 2009

ADD|Update|Delete Item SharePoint Web Services


In one of my previous article I discussed how we can retrieve data in a SharePoint List Using its Web Services. In this post I’m going to discuss how we can update a SharePoint list using Web Services. Please refer my previous article on "SharePoint List Web Service GetListItems" to learn how to add Web References to your project. Then you can use the following sample codes to Update SharePoint lists.

Updating Existing Items

In the following code I have update the "Tasks" list, there I have update the title of two items which has the ID 7 and 10.
    public void updateListItemsWS()
    {
        WS_Lists.Lists myservice = new WS_Lists.Lists();
        myservice.Credentials = System.Net.CredentialCache.DefaultCredentials;
        myservice.Url = "http://mermoss:5050/testsara/_vti_bin/Lists.asmx";
        try
        {
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            System.Xml.XmlElement elBatch = xmlDoc.CreateElement("Batch");

            elBatch.SetAttribute("OnError", "Continue");
            elBatch.SetAttribute("ListVersion", "1");

            string strBatch = "<Method ID='1' Cmd='Update'>" +
                  "<Field Name='ID'>7</Field>" +
                  "<Field Name='Title'>Sara1</Field></Method>" +
                  "<Method ID='2' Cmd='Update'><Field Name='ID' >10</Field>" +
                  "<Field Name='Title'>Sara2</Field></Method>";

            elBatch.InnerXml = strBatch;
            myservice.UpdateListItems("Tasks", elBatch);

        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
Delete Items

To delete item, use following phrase in the above code, this will delete the item which has ID of 10.

string strBatch = "<Method ID='1' Cmd='Delete'>" +
"<Field Name='ID'>10</Field></Method>";

Add New Item

To add item, use following phrase in the above code,

string strBatch = "<Method ID='1' Cmd='New'>" +
"<Field Name='ID'>New</Field>"+
"<Field Name='Title'>TestTitle1</Field>"+
"</Method>";

Thursday, December 17, 2009

SharePoint List Web Service GetListItems


In this post, I’ going to discuss how we can retrieve data from a SharePoint List using its Web Services. First to know about SharePoint Web Services please refer this. We can user List Web Service which provides methods for working with SharePoint Lists, Content Types, List Items, and Files to read a List. Here we are going to use GetListItems method.

To use the above method we should know the GUIDs of the target list and view. Please follow my article on SharePoint List GUIDs to see how we can get them.

This is how you can Add Web Reference; I’ll get created Web Site Project in Visual studio to illustrate. Actually it is simple, first click on Add Web Reference and give the URL to the Web Service.





This is a sample code to read SharePoint list,
    public void getListData()
    {
        WS_Lists.Lists myservice = new WS_Lists.Lists();
        myservice.Credentials = System.Net.CredentialCache.DefaultCredentials;
        myservice.Url = "http://merdev-moss:5050/testsara/_vti_bin/Lists.asmx";
        try
        {
            /* Assign values to pass the GetListItems method*/
            string listName = "{5C65CB1A-2E1B-488A-AC07-B115CD0FC647}";
            string viewName = "{75E689B4-5773-43CB-8324-58E42E1EB885}";
            string rowLimit = "100";

            // Instantiate an XmlDocument object
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            System.Xml.XmlElement query = xmlDoc.CreateElement("Query");
            System.Xml.XmlElement viewFields = xmlDoc.CreateElement("ViewFields");
            System.Xml.XmlElement queryOptions = xmlDoc.CreateElement("QueryOptions");

            /*Use CAML query*/
            query.InnerXml = "<Where><Gt><FieldRef Name=\"ID\" />" +
            "<Value Type=\"Counter\">0</Value></Gt></Where>";
            viewFields.InnerXml = "<FieldRef Name=\"Title\" />";
            queryOptions.InnerXml = "";

            System.Xml.XmlNode nodes = myservice.GetListItems(listName, viewName, query, viewFields, rowLimit, null, null);

            foreach (System.Xml.XmlNode node in nodes)
            {
                if (node.Name == "rs:data")
                {
                    for (int i = 0; i < node.ChildNodes.Count; i++)
                    {
                        if (node.ChildNodes[i].Name == "z:row")
                        {
                            Response.Write(node.ChildNodes[i].Attributes["ows_Title"].Value + "</br>");
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
In the above code I have use CAML queries to get the result. It will return all the result because I’m searching for Items which has ID greater than 0. It is always true. If you want to know how to write CAML quires easily please refer my article on CAML & SPQuery in SharePoint.

Wednesday, December 16, 2009

SharePoint List GUIDs, How to Find?


In this post I’m going to discuss about an easiest way to find GUID of a SharePoint list and a View. If you are using the MOSS 2007 there is straight forward way to get the List GUID, these are the steps.

1. Access the list via your browser.

2. Go to Settings --> List Settings and right-click on the "Information management policy settings" links and choose Copy Shortcut.

3. Paste the URL and you can see the GUID surrounded with "{" and "}".

If you are using WSS 3.0 follow these steps, you can use this method to find the View GUID in MOSS 2007

1. Access the list via your browser and select the View you want to find the GUID.

2. Select "Modify this View" and copy the URL.

3 You will get a URL like this,

http://mysite:5050/testsara/_layouts/ViewEdit.aspx?List=%7B5C65CB1A%2D2E1B%2D488A%2DAC07%2DB115CD0FC647%7D&View=%7B75E689B4%2D5773%2D43CB%2D8324%2D58E42E1EB885%7D&Source=http%253A%252F%252Fmysite%253A5050%252Ftestsara%252FLists%252FTasks%252FAllItems%252Easpx

There you can find,

List=%7B5C65CB1A%2D2E1B%2D488A%2DAC07%2DB115CD0FC647%7D
View=%7B75E689B4%2D5773%2D43CB%2D8324%2D58E42E1EB885%7D

Replace "%7B" with "{"
Replace all "%2D" with "-"
Replace "%7D" with "}"

You are now left with the GUIDs, in the above example;

List ID is {5C65CB1A-2E1B-488A-AC07-B115CD0FC647}
View ID is {75E689B4-5773-43CB-8324-58E42E1EB885}

You can use SharePoint Tips Utility Pack if you need to get the GUID of List columns. There in menu bar, select "List Management --> Change Field Settings" and load your site.

Thursday, December 10, 2009

Add User To SharePoint Group Programmatically


Let’s see how we can programmatically add a user to existing SharePoint user group . You can use the following method which has two string parameters, one for group name and other for user login name for get the above task done.
public void addUserToGroup(string groupName, string userLoginName)
{
    string strUrl = "http://mysite:5050/";
    using (SPSite site = new SPSite(strUrl))
    {
        using (SPWeb web = site.OpenWeb())
        {
            try
            {
                web.AllowUnsafeUpdates = true;
                SPUser spUser = web.EnsureUser[userLoginName];

                if (spUser != null)
                {
                    SPGroup spGroup = web.Groups[groupName];
                    if (spGroup != null)
                    spGroup.AddUser(spUser);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                web.AllowUnsafeUpdates = false;
            }
        }
    }
}
Here you should provide the login name in correct format (DomainName\UserName). For example you can call this method like follow,

addUserToGroup("Test Group", "SA\\saranga.rathnayaka");

Wednesday, December 9, 2009

Add Item To List With LookUp Column Programmatically


In my previous posts on "Working With SharePoint List" I have discussed how we can Read, Add and Update SharePoint List. If you have to add new Item to a list which has lookup column, you have to follow a different procedure.

If you look at the following figure, you can easily understand what I'm going to do. I'm going to add a new record to List_B, which has a lookup column from List_A's Title Field.



This is a sample code to get the above task done,
        
    public void addToLookUp()
    {
        /* open the web */
        SPSite site = new SPSite("http://merdev-moss:5050/testsara");
        SPWeb web = site.OpenWeb();

        string targetList = "List_B";
        string sourceList = "List_A";
        string sourceListField = "Title";

        /* we are going to add new row to List_B,
        * It (List_B) has a lookup column called "A_Column",
        * It (A_Column) get data from Title field of List_A.
        * (List_A has value called "test2" in Title field)
        */

        SPListItemCollection listItems = web.Lists[targetList].Items;
        SPListItem item = listItems.Add();
        item["Title"] = "New Title";
        int ID = get_ID(web, sourceList, sourceListField, "test2");
        if (ID != 0)
            item["A_Column"] = ID;
        item.Update();
    }

    public static int get_ID(SPWeb web, string list, string field, string itemname)
    {
        int id = 0;
        SPList sharedDocumentList = web.ServerRelativeUrl.Equals("/") ? web.GetList(web.ServerRelativeUrl + list) : web.GetList(web.ServerRelativeUrl + "/" + list);
        SPListItemCollection listItems = sharedDocumentList.Items;
        foreach (SPListItem item in listItems)
        {
            if (item[field].ToString() == itemname.ToString())
                id = item.ID;
            break;
        }
        return (id);
    }

Tuesday, December 8, 2009

Create SharePoint List View Programmatically


In this post I’m going to describe how you can programmatically add a view to SharePoint list or Document Library. You can get this work done by using SPViewCollection.Add Method (Microsoft.SharePoint), here is a sample code,
        public void createListView()
        {
            SPSite site = new SPSite("http://merdev-moss:5050/testsara");
            SPWeb web = site.OpenWeb();
            SPList list = web.Lists["Tasks"];

            SPViewCollection allviews = list.Views;
            string viewName = "Test View";

            System.Collections.Specialized.StringCollection viewFields = new System.Collections.Specialized.StringCollection();
            viewFields.Add("Title");
            viewFields.Add("Priority");

            string myquery = "<Where><Gt><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Gt></Where>";
            allviews.Add(viewName, viewFields, myquery, 100, true, false);
        }
Above code creates a view in the collection with the specified name "Test View" and added view fields. Query string will return all items, because always ID is greater than 0. Row limit is 100 and the view displays items page by page. Last Boolean mean it is not the default view.

Please refer my article on CAML & SPQuery in SharePoint to find out easy way to write CAML quires used in above code.

Add View Using Existing View

You also can create new List View with the help of existing one, this sample code will create new View which has another field using above created View.
        public void _createListView()
        {
            SPSite site = new SPSite("http://merdev-moss:5050/testsara");
            SPWeb web = site.OpenWeb();
            SPList list = web.Lists["Tasks"];

            SPViewCollection allviews = list.Views;
            string viewName = "New Test View";

            System.Collections.Specialized.StringCollection viewFields = list.Views["Test View"].ViewFields.ToStringCollection();
            viewFields.Add("Status");

            string myquery = "<Where><Gt><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Gt></Where>";
            allviews.Add(viewName, viewFields, myquery, 100, true, false);
        }

Add Permission Level To SharePoint User Group


In this post I'm going to discuss how you can add a permission level (Read, Contribute, Full Control, etc) to a SharePoint user group. Here is a sample code,
        public void addPermissionToGroup()
        {
            SPSite site = new SPSite("http://mysite:5050/");
            SPWeb spWeb = site.OpenWeb();
            string permissionName = "Read";
            string groupName = "Project Manager";

            try
            {
                spWeb.AllowUnsafeUpdates = true;
                SPRoleAssignment roleAssignment = new SPRoleAssignment(spWeb.SiteGroups[groupName]);
                roleAssignment.RoleDefinitionBindings.Add(spWeb.RoleDefinitions[permissionName]);

                if (!spWeb.HasUniqueRoleAssignments)
                    spWeb.BreakRoleInheritance(false);

                spWeb.RoleAssignments.Add(roleAssignment);
                spWeb.Update();
            }
            catch (Exception _exception)
            {
                throw _exception;
            }
            finally
            {
                spWeb.AllowUnsafeUpdates = false;
            }
        }
You can view RoleDefinitions defined for your site by visiting to Site Settings --> Advanced Permissions.

Thursday, November 26, 2009

Add Lookup Column to SharePoint List Programmatically


In one of my previous article I discussed how to create a SharePoint list programmatically in C#. There I didn’t discuss how we can add lookup field for our newly created list. Let’s see how, this is a sample code.
        public void createList()
        {
            // choose your site
            SPSite site = new SPSite("http://merdev-moss:5050");
            SPWeb web = site.OpenWeb();
            SPListCollection lists = web.Lists;

            // create new Generic list called "My List"
            lists.Add("My List", "My list Description", SPListTemplateType.GenericList);

            SPList newList = web.Lists["My List"];

            // create Text type new column called "My Column"
            newList.Fields.Add("My Column", SPFieldType.Text, true);

            /*create lookup type new column called "Lookup Column"
            * Here I am going to get the information from the "Title"
            * column of a list called "User Roles"
            */
            SPList targetList = web.Lists["User Roles"];

            newList.Fields.AddLookup("Lookup Column", targetList.ID, false);
            SPFieldLookup lkp = (SPFieldLookup)newList.Fields["Lookup Column"];
            lkp.LookupField = targetList.Fields["Title"].InternalName;
            lkp.Update();

            // make new column visible in default view
            SPView view = newList.DefaultView;
            view.ViewFields.Add("My Column");
            view.ViewFields.Add("Lookup Column");
            view.Update();
        }
In the above code I have created Generic list and lookup column. You can use whatever list type and field type according to your requirement. To learn more about SharePoint lists, follow "SharePoint List C# Part 1".

Monday, November 23, 2009

Remove Event Receiver in Sharepoint List


In this post I’m going to describe how you can remove an Event Receivers from SharePoint List programmatically. This will be very useful if you have deployed and active custom features, because if you create a custom feature for a custom list, that feature will be added to all the custom lists. Then if you want to create list dynamically and don’t want to add those features you can use this code to remove unwanted events.
public void  removeEvents()
{
 // choose your site
 string strUrl = "http://mysite:5050/";
 using (SPSite site = new SPSite(strUrl))
 {
  using (SPWeb web = site.OpenWeb())
  {
   SPListCollection lists = web.Lists;
   SPList list = web.Lists["My List"];
      
   SPEventReceiverDefinitionCollection erdc = list.EventReceivers;
   List <SPEventReceiverDefinition> eventsToDelete = new List <SPEventReceiverDefinition>();
      
   foreach (SPEventReceiverDefinition erd in erdc)
   {
    if (erd != null)
    {
     try
     {
      eventsToDelete.Add(erd);
     }
     catch (Exception e)
     {
      Console.Write(e.ToString());
     }
    }
   }
   foreach (SPEventReceiverDefinition er in eventsToDelete)
   {
    //if(er.Type == SPEventReceiverType.ItemAdded)
    er.Delete();
   }  
  }
 }
}
Before delete the Event Receiver, if you want you can check the type and delete. In the above code I have commented that part. So if you use the above code as it is, it will remove all the Event Receivers.

Friday, November 13, 2009

SharePoint charting (Chart inside web part)


In my article on "SharePoint Web Part Development Tutorial" I discussed how we can develop and deploy custom SharePoint web part with visual designing. Now let’s see how we can add a chart for that web part. Finally you will be getting a result like following picture.



To create the above chart I’m getting data from a SharePoint list as follow.



You can see I’m showing the chart inside my custom web part called "My first custom Web Part". There I used the code from "Free Google Chart SharePoint Web Part" and customized it as I want. These are the steps to add nice chart to your web part for free.

First Create your custom web part, don’t deploy at this stage.

Then add a Class called “Chart.cs” and replace the code using following code.

View Code

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Microsoft.SharePoint;

namespace ProjectView{
public class Chart{

protected string _BGColor = "FFFFFF";
protected string _ChartColor = "0099ff,ff0000";
protected int _ChartHeight = 400;
protected LegendPositions _ChartLegend;
protected string _ChartTitle = "Burn Down Chart";
protected ChartTypes _ChartType;
protected int _ChartWidth = 720;
protected string _DataField = "Planned Effort,Actual Effort";
protected string _LabelField = "Title";
protected string _ListName = "";
protected string _SiteName = "http://merdev-moss:5050/";
protected string _ViewName = "";

public enum ChartTypes{
Line,
VerticalBar,
Pie,
Pie3D,
HorizontalBar
}
public enum LegendPositions{
horizontal_top,
vertical_left,
horizontal_bottom,
vertical_top,
vertical_bottom,
vertical_right
}
public string createChartString(string listName){
_ListName = listName;

string str = "";
string str2 = "";

SPSite site = new SPSite(this._SiteName);
SPWeb web = site.OpenWeb();
try{
if (!string.IsNullOrEmpty(this._ListName)){
SPList list = null;
SPListItemCollection items = null;
try{
string[] strArray3;
int num5;
list = web.Lists[this._ListName];
if (!string.IsNullOrEmpty(this._ViewName)){
SPView view = list.Views[this._ViewName];
items = list.GetItems(view);
}
else{
items = list.Items;
}
string str3 = "";
float num2 = 0f;
int num3 = 0;
bool flag = true;
char[] separator = new char[] { ',', ';' };
string[] strArray = this._DataField.Split(separator);
string[] strArray2 = new string[strArray.Length];
foreach (string str4 in strArray){
str2 = str2 + "<br>Series=" + str4;
if (!list.Fields.ContainsField(str4)){
str = str + "<p>Data List column not specified or not found:" + str4 + "</p>";
flag = false;
}
}
if (!list.Fields.ContainsField(this._LabelField)){
str = str + "<p>Label List column not specified or not found:" + this._LabelField + "</p>";
flag = false;
}
if (!flag){
goto Label_0868;
}
foreach (SPListItem item in items){
num3++;
try{
int index = 0;
foreach (string str5 in strArray){
string[] strArray7;
IntPtr ptr2;
float num = Convert.ToSingle(item[str5]);
if (num > num2){
num2 = num;
}
if (!string.IsNullOrEmpty(strArray2[index])){
string[] strArray6;
IntPtr ptr;
(strArray6 = strArray2)[(int)(ptr = (IntPtr)index)] = strArray6[(int)ptr] + ",";
}
string str6 = num.ToString().Replace(",", ".");
(strArray7 = strArray2)[(int)(ptr2 = (IntPtr)index)] = strArray7[(int)ptr2] + str6;
index++;
}
}
catch{
str = str + "<p>Data column error:" + this._DataField + "</p>";
}
try{
if (str3 != ""){
str3 = str3 + "|";
}
if ((this._LabelField != "LinkTitle") && (item.Fields[this._LabelField].FieldValueType == typeof(DateTime))){
str3 = str3 + ((DateTime)item[this._LabelField]).ToString("MMM yyyy");
}
else if (item[this._LabelField] != null){
str3 = str3 + item[this._LabelField].ToString();
}
continue;
}
catch{
str = str + "<p>Label column error:" + this._LabelField + "</p>";
continue;
}
}
string str7 = "";
string str8 = "";
string str9 = "";
string str10 = "";
string str11 = "";
string str12 = "";
string str13 = "";
if (!string.IsNullOrEmpty(str3)){
str3 = str3.Replace("&", "%26");
}
string str14 = num2.ToString().Replace(",", ".");
switch (this._ChartType){
case ChartTypes.Pie:
str7 = "p";
str9 = str3;
str12 = "0," + str14;
goto Label_051D;

case ChartTypes.Pie3D:
str7 = "p3";
str9 = str3;
str12 = "0," + str14;
goto Label_051D;

case ChartTypes.Line:
str7 = "lc";
str8 = "x,y";
str10 = "0:|" + str3;
str11 = "1,0," + str14;
str12 = "0," + str14;
goto Label_051D;

case ChartTypes.VerticalBar:
str7 = "bvg";
str8 = "x,y";
str10 = "0:|" + str3;
str11 = "1,0," + str14;
str12 = "0," + str14;
str13 = "a";
goto Label_051D;

case ChartTypes.HorizontalBar:
str7 = "bhg";
str8 = "x,y";
strArray3 = str3.Split(new char[] { '|' });
str3 = "";
num5 = strArray3.Length - 1;
goto Label_04DE;

default:
str7 = "p";
goto Label_051D;
}
Label_04AE:
if (str3 != ""){
str3 = str3 + "|";
}
str3 = str3 + strArray3[num5];
num5--;
Label_04DE:
if (num5 >= 0){
goto Label_04AE;
}
str10 = "1:|" + str3;
str11 = "0,0," + str14;
str12 = "0," + str14;
str13 = "a";
Label_051D:
if (str == ""){
object obj2 = str;
str = string.Concat(new object[] { obj2, "?chs=", this._ChartWidth, "x", this._ChartHeight });
if (!string.IsNullOrEmpty(this._ChartTitle)){
string str15 = this._ChartTitle.Replace(" ", "+");
str = str + "&chtt=" + str15.Replace("&", "%26");
}
str = (str + "&cht=" + str7) + "&chts=000000,17" + "&chd=t:";
int num6 = 0;
string[] strArray8 = strArray;
for (int i = 0; i < strArray8.Length; i++){
string text1 = strArray8[i];
if (num6 > 0){
str = str + "|";
}
str = str + strArray2[num6];
num6++;
}
str = str + "&chf=bg,s," + this._BGColor;
if (this._ChartColor != ""){
str = str + "&chco=" + this._ChartColor;
}
if (str9 != ""){
str = str + "&chl=" + str9;
}
if (str8 != ""){
str = str + "&chxt=" + str8;
}
if (str10 != ""){
str = str + "&chxl=" + str10;
}
if (str11 != ""){
str = str + "&chxr=" + str11;
}
if (str12 != ""){
str = str + "&chds=" + str12;
}
if (str13 != ""){
str = str + "&chbh=" + str13;
}
str = str + "&chg=" + ((100.0 / ((double)num3))).ToString("F") + ",20";
if (strArray.Length > 1){
str = str + "&chdl=";
int num7 = 0;
foreach (string str16 in strArray){
if (num7 > 0){
str = str + "|";
}
str = str + str16;
num7++;
}
str = str + "&chdlp=";
switch (this._ChartLegend){
case LegendPositions.horizontal_top:
str = str + "t";
break;

case LegendPositions.horizontal_bottom:
str = str + "b";
break;

case LegendPositions.vertical_top:
str = str + "tv";
break;

case LegendPositions.vertical_bottom:
str = str + "bv";
break;

case LegendPositions.vertical_left:
str = str + "l";
break;

case LegendPositions.vertical_right:
str = str + "r";
break;
}
}
str2 = str2 + "<br>" + str.Replace("&", "<br>&");
str = "http://chart.apis.google.com/chart" + str;
}
}
catch{
str = this._ListName + ": Sharepoint List not found!";
}
}
else{
str = "No Sharepoint List defined!";
}
}
catch (Exception){
str = "<br>Site not found:" + this._SiteName;
}
Label_0868:
return str;
}
}
}

Now change the variable names according to your site, list and columns.

Then Add this line to your .ascx file.

Now replace your "Page_Load" method as follows.

Now you can built and deploy your web part to see the result. You can get VerticalBar,Pie,Pie3D and HorizontalBar charts by changing the "ChartType" in the above code.

Create SharePoint list programmatically C#


In this article I’m going to discuss how we can create a SharePoint list programmatically in c# and how we can add columns to the created list. Actually this is very simple task; this is a sample code.
        public void createList()
        {
            // choose your site
            SPSite site = new SPSite("http://merdev-moss:5050");
            SPWeb web = site.OpenWeb();
            SPListCollection lists = web.Lists;

            // create new Generic list called "My List"
            lists.Add("My List", "My list Description", SPListTemplateType.GenericList);

            SPList list = web.Lists["My List"];

            // create Text type new column called "My Column" 
            list.Fields.Add("My Column", SPFieldType.Text, true);

            // make new column visible in default view
            SPView view = list.DefaultView;
            view.ViewFields.Add("My Column");
            view.Update();
        }
In the above code I have created Generic list and normal Text column. You can use whatever list type and field type according to your requirement. To learn more about SharePoint lists, follow "SharePoint List C# Part 1".

If you want to add lookup columns please refer "Add Lookup Column to SharePoint List programmatically".

To learn how to create List View, refer "Create SharePoint List View Programmatically".

Tuesday, November 10, 2009

Use Custom Workflow Actions in SharePoint Designer


In my previous article on "SharePoint Workflow Actions for Designer in Visual Studio" I discussed how to create and deploy a custom workflow action to use in the SharePoint designer.In this article I’m going to discussed how you can use the added action in the SharePoint Designer.

First open your site in the SharePoint Designer and create new workflow as shown in following figure.

new workflow

Then select the SharePoint list that the workflow should attached to and selects the start option of the workflow as following figure.



Now you can find the newly deployed custom action in the "Extras" category. Chose it and click the "Add" button. Then you have to specify the parameters if your custom action asked for them as follow.





Now everything is done and you can test your work flow. To do this, go to selected list and click on the arrow appear when you put the mouse on title of a list item. Then select the "Workflows" option.



Follow my article on "SharePoint Workflow Actions for Designer in Visual Studio" to learn how to create and deploy a custom workflow action to use in the SharePoint designer.

Friday, November 6, 2009

SharePoint Workflow Actions for Designer in Visual Studio


Using Microsoft Office SharePoint Designer 2007, you can design workflows without writing custom code. Microsoft has provided an article on Create a Workflow which helps you to get started by explaining some key design considerations and providing a basic procedure, but the problem is there are only few limited actions available in SharePoint Designer 2007 to develop your custom workflows (Figure 1).



You can develop custom actions using Microsoft Visual Studio 2005 or higher and deploy in your SharePoint server. Then you will see your custom action when you click More Actions (Figure 1).

In this article I’m going to show you how to add custom actions to SharePoint site and use it in SharePoint Designer 2007 to develop SharePoint workflows. For your ease here I have included all the necessary screen shots and coding step by step.

Building Custom Workflow

First create new project in Microsoft Visual Studio, there select Project Type as workflow and template as Workflow Activity Library (Figure 2). I have given "MyFirstWorkflow" for the name.



Then Add reference to the "Microsoft.SharePoint.dll" and "microsoft.sharepoint.WorkflowActions.dll". They can be found in your SharePoint server’s ISAPI folder (Figure 3 & 4).





You should copy those files from the same directory to a directory on your local computer if you are developing your project on a machine not having SharePoint or MOSS.

Now you can give a name to your Activity, Here I gave "SampleActivity" as Figure 5 and drag-and-drop codeActivity from Toolbox (Figure 6).





Now replace your Activity1.cs file using following code. If you are using different name spaces and class names, you have to change this code according to those names.
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 System.Diagnostics;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WorkflowActions;

namespace MyFirstWorkflow
{
    public partial class SampleActivity : SequenceActivity
    {
        SPList _list;
        private EventLog _log;

        public SampleActivity()
        {
            InitializeComponent();
        }
        public static DependencyProperty __ContextProperty = DependencyProperty.Register("__Context", typeof(WorkflowContext), typeof(SampleActivity));

        [DescriptionAttribute("__Context")]
        [BrowsableAttribute(true)]
        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        public WorkflowContext __Context
        {
            get
            {
                return ((WorkflowContext)(base.GetValue(SampleActivity.__ContextProperty)));
            }
            set
            {
                base.SetValue(SampleActivity.__ContextProperty, value);
            }
        }

        public static DependencyProperty ListIdProperty = DependencyProperty.Register("ListId", typeof(string), typeof(SampleActivity));

        [DescriptionAttribute("ListId")]
        [BrowsableAttribute(true)]
        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        public string ListId
        {
            get
            {
                return ((string)(base.GetValue(SampleActivity.ListIdProperty)));
            }
            set
            {
                base.SetValue(SampleActivity.ListIdProperty, value);
            }
        }

        public static DependencyProperty ListItemProperty = DependencyProperty.Register("ListItem", typeof(int), typeof(SampleActivity));

        [DescriptionAttribute("ListItem")]
        [BrowsableAttribute(true)]
        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        public int ListItem
        {
            get
            {
                return ((int)(base.GetValue(SampleActivity.ListItemProperty)));
            }
            set
            {
                base.SetValue(SampleActivity.ListItemProperty, value);
            }
        }

        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            _log = new EventLog("Add Description");
            _log.Source = "Share Point Workflows";

            try
            {
                //Execute method as a elevated method
                SPSecurity.CodeToRunElevated elevatedExecuteMethod = new SPSecurity.CodeToRunElevated(ExecuteMethod);
                SPSecurity.RunWithElevatedPrivileges(elevatedExecuteMethod);
            }
            catch (Exception ex)
            {
                _log.WriteEntry("Error" + ex.Message.ToString(), EventLogEntryType.Error);
            }
            return ActivityExecutionStatus.Closed;
        }

        private void ExecuteMethod()
        {
            try
            {
                //retrieveing the Site object
                SPSite _site = new SPSite(__Context.Site.Url);

                //retrieveing the Web object
                SPWeb _web = (SPWeb)(__Context.Web);

                //retrieveing the list object
                _list = _web.Lists[new Guid(this.ListId)];

                //retrieveing the list item object
                SPListItem _listItem = _list.GetItemById(this.ListItem);

                _site.AllowUnsafeUpdates = true;
                _web.AllowUnsafeUpdates = true;

                _listItem["Description"] = "This is sample description";

                _listItem.Update();
                _list.Update();

                _site.AllowUnsafeUpdates = false;
                _web.AllowUnsafeUpdates = false;
            }
            catch (Exception ex)
            {
            }
        }
    }
}
In the above code you can see some methods to get the current Site, Web, List and List Item. You don’t need to change those things. In the above simple example I have fill the "Description" column using my custom action written inside the "ExecuteMethod()" method. You can write any custom event which cannot be done using given actions in SharePoint designer.

Signing your Project

To deploy this custom workflow to GAC and the Microsoft Office SharePoint Server, we should assign a Strong Name key and sign the control.

To do this, right click the "MyFirstWorkflow" node in Solution Explorer and select Properties. Then select the Signing tab from the choices on the left. Check the "Sign the assembly" box and select from the "Choose a strong name key file" drop down list (Figure 7).



There give a key file name and click ok. Now you can build your project and ready to deploy.

Deploying to Server

To deploy your custom workflow action to the SharePoint server, follow these simple steps.

Drag and drop the compiled DLL (You can find it in your project folder's bin folder) into the Global Assembly Cache. The Global Assembly Cache is a special folder located at %WINDIR%\assembly where %WINDIR% is the full path to your Windows folder (e.g. C:\Windows or C:\Winnt).

Get the publicKeyToken property of our assembly. You can find it by right click on the file and select properties in "assembly" folder (Figure 8).



Update the "web.config file" by inserting fillowing line between <authorizedTypes> and </authorizedTypes> tags. (You can find your site’s web.config file in SharePoint server’s "C:\Inetpub\wwwroot\wss\VirtualDirectories\<your_site_port>" directory).
<authorizedtype Assembly="MyFirstWorkflow, Version=1.0.0.0, Culture=neutral, PublicKeyToken=8f2766b10f337a33" Namespace="MyFirstWorkflow" TypeName="*" Authorized="True" />
Update the WSS.ACTIONS file by adding following line between

<Actions Sequential="then" Parallel="and"> and </Actions> tags. (You can find WSS.ACTIONS file in SharePoint server’s "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\1033\Workflow" directory).
<action Name="Add Description"
ClassName="MyFirstWorkflow.SampleActivity"
Assembly="MyFirstWorkflow, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=8f2766b10f337a33"
AppliesTo="all"
Category="Extras">

<ruledesigner Sentence="Add Description to %1">
<fieldbind Field="ListId,ListItem" Text="this list" Id="1" DesignerType="ChooseListItem" />
</RuleDesigner>

<parameters>
<parameter Name="__Context" Type="Microsoft.SharePoint.WorkflowActions.WorkflowContext" Direction="In" />
<parameter Name="ListId" Type="System.String, mscorlib" Direction="In" />
<parameter Name="ListItem" Type="System.Int32, mscorlib" Direction="In" />
</Parameters>
</Action>
Now deploying is completed, reset IIS and you can use your newly added custom action in the SharePoint Designer by going to "More Actions…" (Figure 1) when creating a workflow.

If you want more details on how to use custom actions when creating workflows follow my article "Use custom actions in SharePoint Designer".

Monday, October 12, 2009

Hide Columns in SharePoint Part 2

Note : Before going to use this method you have to make sure all the columns are added to the list.Otherwise you have to remove the added custom form the SharePoint Designer (described in the post) and add it again after adding new column. It is better to use this way if you want hide and change control modes of fields. Also keep in mind to add at least one list item before use this method.

You can try SharePoint Tips Utility Pack if you are not sure whether you need to add columns in future or not.

In the first part of this post I discussed how to hide a column in SharePoint list. By using "Content Types" you cannot hide column in single form. Here I’m going to discuss how you can hide a column only in one (Edit, Display or New) mode using Microsoft SharePoint Designer 2007.

As an example I’m going to use the "Tasks" list and there I’ll remove "Due Date" column in Edit Mode.

First open your site using Microsoft SharePoint Designer 2007 as in Figure 1 (File --> Open Site…, in Site Name field give URL to your site without “default.aspx”. e.g. http://mysite:5050/testsite).

Then double click the displaying window and mark the "layout" hidden as in figure 2.

Then click once on area 1(Figure 3) and insert your custom list form. There select "Tasks" and "Edit item form", because we are going to change the edit form of task list (Figure 4).

Then select the row you want to hide and comment the HTML code (Figure 5).

Further if you want to display the raw in edit mode and you don’t want to allow editing it, you can change the Control mode property (Figure 6).

There keep in mind you can change control mode, if the column is not default one. That mean, to change the control mode using SharePoint Designer, you have to create your own column using "Settings –> Create Column".

Now save all and see, you will see the "Due Date" column is hidden and you cannot edit "Test Col" column (Figure 7).

Hide Columns in SharePoint Part 1

In SharePoint lists, sometimes we have to use hidden columns for our programming purposes. In this tutorial I’m going to discuss, how you can hide a column in SharePoint.

First let’s see how to hide a column in any list view. Here you should have permission to see some menus, if you cannot see them; you have to contact your administrator.

Open your list and go to List Settings (Figure 01).

At the bottom of the page select your view, which you want to hide a column (Figure 02). I'm going to select "All Items" view.

Then unmark all columns you want to hide in that view and click OK (Figure 03).

Now you can see, unmarked columns are not shown in "All Items” view.

Note : By selecting manage content type item in list settings, you can hide a column in New, Edit and Display forms. To do that go to the content type item and select the field you want to remove from your forms. Then choose “This column is hidden (will not appear in forms)”.

To hide a column in New, Edit or Display mode using Microsoft SharePoint Designer 2007 please refer second part of this post.

Tuesday, October 6, 2009

Delete item from SharePoint List

In my previous post SharePoint List C# Part 1 I discussed how we can add items to SharePoint list. We also have to delete items from a list.

Following C# code can be used in your custom webpart or feature to delete item from SharePoint list. Here I am going to find the items to delete using CAML query.

public void  DeleteListItem()
{
 // choose your site
 string strUrl = "http://mysite:5050/";
 using (SPSite site = new SPSite(strUrl))
 {
  using (SPWeb web = site.OpenWeb())
  {
   SPList list = web.Lists["List_A"];
   SPListItemCollection itemCollection;
 
   SPQuery oQuery = new SPQuery();
   oQuery.Query = "<where><eq><fieldref Name='Title' /><value Type='Text'>ABC</Value></Eq></Where>"; 
   itemCollection = list.GetItems(oQuery);
 
   List<splistitem> valuesToDelete = new List<splistitem>();
 
   foreach (SPListItem item in itemCollection)
   {
    valuesToDelete.Add(item);
   }
   web.AllowUnsafeUpdates = true;
   foreach (SPListItem itm in valuesToDelete)
   {
    itm.Delete();
   }
   list.Update();
   web.AllowUnsafeUpdates = false; 
  }
 }
}

In the above example I have use a CAML query to delete items in the Task list which title equal to ABC. As above you have to maintain separate list to stote items that you are goint to delete, otherwise it will not work.

Monday, October 5, 2009

What is SharePoint ?

SharePoint, the fastest-growing product in the history of Microsoft is a collection of products and software elements which can be configured to run Intranet, Extranet and Internet sites.

WSS stands for Windows SharePoint Services and it is light document management system which helps you to organize your documents inside your organization using file sharing and intranet. MOSS stand for Microsoft SharePoint server and it contain all the things in WSS and more advanced things like people search, workflows, site templates and business intelligence.

There are many applications like Portals, Content Management, Indexing, Search, Business Intelligence and Collaboration built in to SharePoint and Sites, Pages, Lists, Libraries and webparts can be considered as building blocks.

SharePoint most commonly use as intranet portals and it allow users to login to their intranet web site and see the information like announcements and news. Using SharePoint you can build a collaboration environment quickly and easily. That will improve team productivity while managing documents and ensuring integrity of content.

Friday, October 2, 2009

CAML & SPQuery in SharePoint

Using Collaborative Application Markup Language (CAML)  queries with SPQuery and SPSiteDataQuery is a faster and more efficient way of retrieving items based on known criteria compare with for each on the SPListItemsCollection and checking for the criteria.

In this tutorial I’m going to discuss how you can write CAML queries for retrieving items in SharePoint List.

Operators

These are some common operators you can use with CAML queries.

  1. Eq--Equals
  2. Neq--Not equal
  3. Gt--Greater than
  4. Geq--Greater than or equal
  5. Lt--Lower than
  6. Leq--Lower than
  7. IsNull--Is null
  8. BeginsWith--Begins with
  9. Contains--Contains

Get All Items

This is discussed in SharePoint List C# Part 1. There you can write the query as follows. There you can get all the items in the list.

myquery.Query = "";

Single Criteria

Using following query you can get all the tasks where “ID” is equal to 5.

<Where>
<Eq>
<FieldRef Name='ID' />
<Value Type='Counter'>5</Value>
</Eq>
</Where>

You can get Value Types for different common type of columns using following list

e.g. Use Value Type "Text" for column type "Single line of text".

  1. Single line of text--Text
  2. Multiple lines of text--Note
  3. Choice (menu to choose from)--Choice
  4. Number (1, 1.0, 100)--Number
  5. Date and Time--DateTime
  6. Lookup (information already on this site)--Lookup/LookupMulti
  7. Yes/No (check box)--Boolean
  8. Person or Group--User

Using AND

This will give you the items where ID = 5 and Title =  "ABC".

<Where><And>
<Eq>
<FieldRef Name='ID' />
<Value Type='Counter'>5</Value>
</Eq>
<Eq>
<FieldRef Name='Title' />
<Value Type='Text'>ABC</Value>
</Eq>
</And></Where>

OR

This will give you the items where ID = 5 or Title =  "ABC"

<Where><OR>
<Eq>
<FieldRef Name='ID' />
<Value Type='Counter'>5</Value>
</Eq>
<Eq>
<FieldRef Name='Title' />
<Value Type='Text'>ABC</Value>
</Eq>
</OR></Where>

It is different if you want to use more than one "AND" or "OR" operator. As a example if you want to get items where ID = 5 and Title = "ABC" and created by "John", then you can write this.

<Where>
<And>
<And>
<Eq>
<FieldRef Name='ID' />
<Value Type='Counter'>5</Value>
</Eq>
<Eq>
<FieldRef Name='Title' />
<Value Type='Text'>ABC</Value>
</Eq>
</And>
<Eq>
<FieldRef Name='Author' />
<Value Type='User'>John</Value>
</Eq>
</And>
</Where>

To get the correct FieldRef Name write accurate queries you can use U2U CAML Query Builder.

Remember though you rename a column the FieldRef Name will hold same value.

SharePoint User Groups

Check User Group in SharePoint

To store and manage permissions we can create User Groups in SharePoint. In this article I’ll discuss how you can check whether the current user is in a particular group using C#. This method will return Boolean value "true" if the user in the given group. You can use this method in your custom webpart.

        public bool isMemberInGroup(string groupName)
        {
            string siteUrl = "http://mysite:5050/";
            SPSite site = new SPSite(siteUrl);
            SPWeb web = site.OpenWeb();

            bool memberInGroup = web.IsCurrentUserMemberOfGroup(web.Groups[groupName].ID);

            return memberInGroup;
        }

If you want to compare the current user in "Person or Group" column type, then you can also get the current user’s user name using  "web.CurrentUser.Name".

Thursday, October 1, 2009

Deleting Features from SharePoint

In one of my previous article I discussed about creating and deploying custom features to SharePoint server. Here I’m going to describe how you can remove a feature from SharePoint.

First log into your server and go to SharePoint central administration site (Figure 1).

Then move to "Operations" tab and select "Solution management" (Figure 2).

Now you can select the feature that you want to remove. If it its status is "Not Deployed", you can simply click "Remove Solution" (Figure 4) and for the “Deployed” solutions first you have to click “Retract Solution” (Figure 3) and then remove.


To me it didn’t work when I remove my solution and redeploy using same name.