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.

Wednesday, December 2, 2009

Add Menu Bar To Blogger Blog


I was able to add a nice multilevel dropdown menu to my blog. In this post I’m going to discuss how you also can add it to your blogger blog. Here I’m using pure CSS multilevel menu generated by Free CSS Drop Down Menu Generator.



You can’t use the code directly in blogger without some modifications; I’ll describe how you can edit the code to use it in blogger to get a menu bar like above picture (Figure 1).

Create the Menu

First get the following code and save it as .html file. Then edit the styles and links as you want. If you like this style, you only need add links for menus and sub menus.

Note : If you use the above mentioned Menu Generator in the HTML code you must replace "<![if gt IE 6]></a><![endif]>" using "<!--[if gt IE 6]><!--></a><!--<![endif]-->", otherwise it will not work in the Blogger.

View Code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
ul.cssMenu ul{display:none}
ul.cssMenu li:hover>ul{display:block}
ul.cssMenu ul{position: absolute;left:-1px;top:98%;}
ul.cssMenu ul ul{position: absolute;left:98%;top:-2px;}
ul.cssMenu,ul.cssMenu ul{
 margin:0px;
 list-style:none;
 padding:0px 2px 2px 0px;
 background-color:#d8d8d8;}
ul.cssMenu table {border-collapse:collapse}ul.cssMenu {
 display:block;
 zoom:1;
 float: left;}
ul.cssMenu ul{
 border-left:2px solid #444444;
 border-bottom:1px solid #444444;
 border-right:1px solid #444444;
 border-top:0px;
 z-index:9999;}
ul.cssMenu li{
 display:block;
 margin:2px 0px 0px 2px;
 font-size:0px;}
ul.cssMenu a:active, ul.cssMenu a:focus {outline-style:none;}
ul.cssMenu a, ul.cssMenu li.dis a:hover, ul.cssMenu li.sep a:hover {
 display:block;
 vertical-align:middle;
 background-color:#d8d8d8;
 text-align:left;
 text-decoration:none;
 padding:4px;
 _padding-left:0;
 font:normal 11px Verdana;
 color: #444444;
 text-decoration:none;
 cursor:default;}
ul.cssMenu span{
 overflow:hidden;
 font-weight:bold;
 background-position:right center;
 background-repeat: no-repeat;
 padding-right:11px;}
ul.cssMenu li {    float:left;}
ul.cssMenu ul li {float:none;}
ul.cssMenu ul a {
 text-align:left;
 white-space:nowrap;}
ul.cssMenu li.sep{
 text-align:center;
 padding:0px;
 line-height:0;
 height:100%;}
ul.cssMenu li.sep span{
 float:none;    
 padding-right:0;
 width:5;
 height:16;
 display:inline-block;
 background-color:#AAAAAA;    
 background-image:none;}
ul.cssMenu ul li.sep span{width:80%;height:3;}
ul.cssMenu li:hover{position:relative;}
ul.cssMenu li:hover>a{
 background-color:#eeeeee;
 font:normal 11px Verdana;
 color: #000000;
 text-decoration:none;}
ul.cssMenu li a:hover{
 position:relative;
 background-color:#eeeeee;
 font:normal 11px Verdana;
 color: #000000;
 text-decoration:none;}
ul.cssMenu li.dis a {color: #AAAAAA !important;}
ul.cssMenu img {border: none;float:left;_float:none;margin-right:4px;width:16px;height:16px;}
ul.cssMenu a:hover ul,ul.cssMenu a:hover a:hover ul,ul.cssMenu a:hover a:hover a:hover ul{display:block}
ul.cssMenu a:hover ul ul,ul.cssMenu a:hover a:hover ul ul{display:none}
</style>
</head>
<body>
<ul class="cssMenu">
 <li><a href="#" title="test title"><span>SEO</span><!--[if gt IE 6]><!--></a><!--<![endif]--><!--[if lte IE 6]><table><tr><td><![endif]-->
  <ul>
   <li><a href="#" title="test title">Your Site in Google</a></li>
   <li><a href="#" title="test title">Selecting Good Title</a></li>
  </ul>
 <!--[if lte IE 6]></td></tr></table></a><![endif]--></li>
 <li><a href="#" title="test title"><span>Blogger Tips</span><!--[if gt IE 6]><!--></a><!--<![endif]--><!--[if lte IE 6]><table><tr><td><![endif]-->
  <ul class="cssMenum">
   <li><a href="#" title="test title">Expandable Blogger Posts</a></li>
   <li><a href="#" title="test title">Blogger Title Tip</a></li>
   <li><a href="#" title="test title">Adding META Tags</a></li>
  </ul>
 <!--[if lte IE 6]></td></tr></table></a><![endif]--></li>
 <li><a href="#" title="test title"><span>SharePoint</span><!--[if gt IE 6]><!--></a><!--<![endif]--><!--[if lte IE 6]><table><tr><td><![endif]-->
  <ul class="cssMenum">
   <li><a href="#" title="test title">What is SharePoint</a></li>
   <li><a href="#" title="test title"><span>Create Custom Features</span><!--[if gt IE 6]><!--></a><!--<![endif]--><!--[if lte IE 6]><table><tr><td><![endif]-->
    <ul class="cssMenum">
     <li><a href="#" title="test title">Removing Features</a></li>
    </ul>
   <!--[if lte IE 6]></td></tr></table></a><![endif]--></li>
   <li><a href="#" title="test title">CAML in SharePoint</a></li>
   <li><a href="#" title="test title">User Groups</a></li>
  </ul>
 <!--[if lte IE 6]></td></tr></table></a><![endif]--></li>
</ul>
</body>
</html>

Add Menu to Blog

1. Now you have to edit the HTML in your blogger template. To do that first go to "Edit HTML" (Figure 2). (Before editing your template, download the full template)



Find "b:section class='header'" and set the value of "maxwidgets" to 3, if it is less than it (Figure 2). Set "showaddelement" to "true",

2. Then Find the </head> tag in your template and paste the styles just before that tag. Make sure you should include <style type="text/css"> and </style> tags.

3. Now you can add new "HTML/JavaScript" Gadget to your blogger header and paste the code between <body> and </body> from the .html file you created using my code given in the top of this post (Figure 3). There do not give a Title for the Gadget.



Now every thing is ok and view your blog to see the new Gadget.

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".

Thursday, November 5, 2009

How to Select a Title for My Article


Your article title plays major role to driving long term search engine traffic. For the Title you have to give the overall idea of your article in simple phrase. The most important thing in article is making sure the title contains a strong keyword phrase.

Here I’m going to show you very simple way to select a best title for your article which contains a strong keyword phrase. I always use Query Suggestions in Google when selecting a title for my articles.

For example if I want to select a title for my article on developing SharePoint web part in visual studio, I’ll first search terms related to my article in Google. There as following picture you will be able to see what the things people search most are.



Then based on those results you can select the perfect title for your article by combining them. You can make this easier by using Google Keyword Tool. In the above example I selected my title as SharePoint Web Part Development Tutorial which contains most of keywords.

Wednesday, November 4, 2009

How To Make My Site Appear In Google Search

Search Engine Optimization (SEO) Techniques

If you search the above topic, in many articles you will see the same things like content is king, write unique content, get more back links etc. I was able to get significant traffic in to my blog within a 3, 4 weeks after starting it, because I used something really different than what you saw in other articles about SEO. This is how I did it.

Is the Content King?

Content is impotent but the king is website optimization. So you have to consider on both to get more traffic. You need to have good content but there the important thing is it should be different.

How to Optimize Your Pages?

First consider about Title tag of a particular page, your articles in that page should have a topic containing same key words appear in the Title. You can use bold and italics to highlight the keywords that are relevant to the article. If it is possible try to add those key words in to your main page.

If you are going to add META description tag and the META keywords tag they should have the same keywords that are relevant to the article's topic. Put your article related keywords in between H1, H2 and H3 tags. Use the ALT tag for images is always best practice.

Select the Correct Title for your Article

Here you should consider more about tour article’s title, keywords and header tags. They should match popular search keywords. I have discussed a simple way to do this in my article How to select a Title for my Article.

Back links, How I can Get Them?

Here one way back links plays major role in increasing link popularity. Two way links might be useful but one way back links have much higher weight. By submitting your website to forums, comments on blogs and using social networking websites you can get back links for your web site freely. I will write separate article on this topic soon.

Internal Linking

Internal links are very important. Here the tip is to let the internal link's anchor text contain the same keywords your original article has. For example when linking to your article that is called “ABC” from another page give the same link title as “ABC”.

Frequency of Update, Is It Important?

Yes, search engines give very high weight to frequently updated pages. Your search engine ranking will increase if your website gets updated frequently. More content gives more traffic, which is always true.

My Article Is New; Will It Appear in Search Result?

Yes, time doesn’t matter. You can see some new websites showing up in the top of Google search results after 3 or 4 weeks of their creation, you also can follow these things to achieve that. But remember old pages are always respected by search engines than newer ones.

Thursday, October 29, 2009

Event Handling In Android

In my previous article I discussed about how to create user interfaces in Android. Here I’m going to show you how you can add event handler to that UI. To do that, first add these two lines between package and class declaration.

To do that, first add these two lines between package and class declaration.

import android.view.View;
import android.widget.Button;

Now replace your onCreate method using following code.

import android.view.View;
import android.widget.Button;

public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.testview);
 Button ok = (Button)findViewById(R.id.btn_testview_ok);
 ok.setOnClickListener(new View.OnClickListener() {
  public void onClick(View v){
   moveToMain();
  }
 });
}
private void moveToMain() {
 // TODO Auto-generated method stub
 setContentView(R.layout.main);
}

In the above code "btn_testview_ok" is the id of the "Ok" button in previous article. When you click that button, the moveToMain(); method will be called and content view will changed as "main.xml". I will discuss more about this topic in my next posts.

Android User Interface Design

In one of my previous post I discussed about Creating Android Databases. In this tutorial I’ll discuss simple way to create Android UI using Eclipse and DroidDraw tool which support drag-and-drop of widgets like buttons, labels, text boxes, etc.

Displaying the user interface is done by Activity, the fundamental unit of an Android application. The setContentView() method of the Activity class load the XML UI located in the res/layout folder in the onCreate() event.

An Activity has Views and ViewGroups. Here View is a widget and collection of one or more View can be considered as ViewGroup. ViewGroup plays a major role by providing us layout to arrange the appearance and sequence of views. Well, let’s built our first User Interface in Android.

1. First create simple Android project.

2. Then using DroidDrow design your interface (show steps) and click "Generate" button at the top left corner.

First open DroidDrow and select AbsoluteLayout because using that layout you can easily place widgets as you want.

Then drag–and-drop widgets you want to the design surface.

You can change properties of your widgets using "Properties" tab. There if you want to change the Id, change the things after "@+id/".

Finally click "Generate" button to get the XML code to the "output" textbox.

3. Now add new XML file to "layout" folder as follows. There I’ll give the file name as "testview.xml". Don’t use capital letters for the name.

4. Then click on "testview.xml" tab and replace existing code by generated code from the DroidDrow tool.

5. Now replace the "setContentView(R.layout.main);" using "setContentView(R.layout.testview);". Now your "onCreate" method should appear as follows.

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.testview);
}

Finally save all and run the project to see your interface in Android.

If you are interested please refer Event Handling in Android to learn how to handle events for these widgets.

Tuesday, October 27, 2009

Add META Tags To Blogger

META tags provides information about a web page such as who created the page, what the page is about and which keywords represent the page content. They do not affect how the page is displayed. Many search engines use this information when building their indices.

By default blogger does not contain META tags. In this tutorial I’m going to tell you how you can add META tags to your blog without causing problems. If you simply add these tags you will get "Duplicate meta descriptions" HTML suggestion as following picture.

Let’s see how we can add these tags without causing problems.

1. First log into your blog and from dashboard go to the "Layout --> Edit HTML" page as follows;

2. Then locate the <b:include data='blog' name='all-head-content'/>, you can find it between <head > and </head> tags as following picture;

Then paste this code just after that code.

<b:if cond='data:blog.url == data:blog.homepageUrl'>
<meta content='Insert description here' name='description'/>
<meta content='Insert your keywords here' name='keywords'/>
<meta content='Insert Your Name' name='author'/>
</b:if>

Description : Limit it for maximum 200 characters.

Keywords : Do not repeat more than three times. The maximum number of keywords we recommend for this tag is 20.

Monday, October 26, 2009

Blogger Post Title Tip (SEO)

By default in blogger the blog title appears first before appear your post title. If you consider Search Engine Optimization (SEO) that is not a good practice. In this tutorial I’m going to show you how to make the blogger post title come first as following picture.

You can follow these simple steps to swap the title and post title in blogger for a better Search Engine Optimization.

1. First log into your blog and from dashboard go to the "Layout --> Edit HTML" page as follows;

2. Then locate the <title><data:blog.pageTitle/></title>, you can find it between <head > and </head> tags as following picture;

3. Then replace that code by following code; It is always good if you download the Full Template before editing.

<b:if cond='data:blog.pageType == "index"'>
<title><data:blog.title/></title>
<b:else/>
<title><data:blog.pageName/> | <data:blog.title/></title>
</b:if>

Finally save template and you will see the result immediately in your browser title and after few days in search results.

Saturday, October 24, 2009

Expandable Blogger Posts

This tip can be used in your blog or web site to hide long posts or articles. Inserted of navigating to another page, using this tip you can wrap things like screen shots and source codes that reader doesn’t want to see at the page load.

First go to "Edit HTML" page.

Then find the <head> and </head> tags.

First paste this code between <head> and </head> tags in your HTML code.

<style type='text/css'>
 .commenthidden {display:none}
 .commentshown {display:inline}
</style>
<script type='text/Javascript'>
function togglecomments (postid) {
 var whichpost = document.getElementById(postid);
 if (whichpost.className=="commentshown") {
  whichpost.className="commenthidden"; }
 else { whichpost.className="commentshown"; 
 }
}
</script>

Then put the things that you want to hide between following div tag.

<div class="commenthidden" id="yourDivId">
    your content goes here
</div>

Note: Here "yourDivId" should be unique one. That means if you are going to use this more than one time, you have to replace "yourDivId" using unique name.

Wednesday, October 14, 2009

Sort Object ArrayList in C#

You can easily sort an arraylist using its "sort()" method, but how can you sort an ArrayList of Objects? You can get this task done very easily with "IComparer" Interface.

As an example let’s get a "Person" object which contains two attributes called "ID" and "Name". Now we need to sort these objects by "ID" or "Name". By looking at the following picture, you can get very clear idea about what we are going to do now.

You may notice in "Sort 2" first I have sort by "ID" and then by "Name". I’ll give you the C# code for the above task using simple console application.

Create new class called "Person" and paste this code;

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

namespace SortArrayList
{
    class Person
    {
        private int id;
        public int ID
        {
            get { return id; }
            set { id = value; }
        }
        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public int CompareTo(Person psn2, ObjCompare.ComparisonType comparisonType, Person psn1)
        {
            int returnValue;
            if (comparisonType == ObjCompare.ComparisonType.ID)
            {
                if (psn1.ID == psn2.ID)
                {
                    returnValue = Name.CompareTo(psn2.Name);
                }
                else
                {
                    returnValue = ID.CompareTo(psn2.ID);
                }
            }
            else if (comparisonType == ObjCompare.ComparisonType.Name)
            {
                returnValue = Name.CompareTo(psn2.Name);
            }
            else
            {
                returnValue = ID.CompareTo(psn2.ID);
            }
            return returnValue;
        }
    }
}

Create new class called "ObjCompare" and paste this code;

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

namespace SortArrayList
{
    class ObjCompare : IComparer
    {
        public enum ComparisonType
        {
            ID, Name
        }
        private ComparisonType compMethod;
        public ComparisonType ComparisonMethod
        {
            get { return compMethod; }
            set { compMethod = value; }
        }
        public int Compare(object x, object y)
        {
            Person psn1 = (Person)x;
            Person psn2 = (Person)y;
            return psn1.CompareTo(psn2, ComparisonMethod, psn1);
        }
    }
}

Now update your "Programme.cs" as bellow;

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

namespace SortArrayList
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList lst = new ArrayList();

            Person psn = new Person();
            psn.Name = "Jack"; psn.ID = 15;
            lst.Add(psn);

            Person psn1 = new Person();
            psn1.Name = "David"; psn1.ID = 18;
            lst.Add(psn1);

            Person psn2 = new Person();
            psn2.Name = "Daniel"; psn2.ID = 12;
            lst.Add(psn2);

            Person psn3 = new Person();
            psn3.Name = "Owen"; psn3.ID = 20;
            lst.Add(psn3);

            Person psn4 = new Person();
            psn4.Name = "Colin"; psn4.ID = 16;
            lst.Add(psn4);

            Person psn5 = new Person();
            psn5.Name = "Aiden"; psn5.ID = 18;
            lst.Add(psn5);

            Console.Write(" ---before sort --- \n");
            foreach (Person item in lst)
            {
                int id = item.ID;
                string ttl = item.Name;
                Console.Write(id + " " + ttl + "\n");
            }
            /* sorting */
            ObjCompare objcom = new ObjCompare();
            objcom.ComparisonMethod = ObjCompare.ComparisonType.ID;
            lst.Sort(objcom);

            Console.Write(" ---after sort -- \n");
            foreach (Person item in lst)
            {
                int id = item.ID;
                string ttl = item.Name;
                Console.Write(id + " " + ttl + "\n");
            }
        }
    }
}

You will get the output as "Sort 2" in the picture. If you don't want to sort by "Name" you can do it by editing "Person" class. There I have check whether "psn1.ID == psn2.ID", by commenting that part you can get the result as "Sort 1".

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).