Monday, October 12, 2009

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.

Wednesday, September 30, 2009

SharePoint Web Part Development Tutorial

It is hard to find out simple way to create SharePoint web parts with visual designing. After looking at custom features, in this article I'm going to show you how to create custom SharePoint web part using Web User Control in Visual Studio.

Creating the Web Part

First Create New Project called "ProjectView" and select ASP.NET Web Application (Figure 1 & 2). Don’t use shortcuts.


Then Add new Web User Control called "ProjectViewControl" to your project (Figure 3 & 4).


Then Add reference to the “Microsoft.SharePoint.dll”. It can be found in your sharepoint server’s ISAPI folder (Figure 5 & 6).


You should copy this file along with “Microsoft.SharePoint.Search.dll” and “Microsoft.SharePoint.Search.xml” 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.

Then go to your SharePoint site’s folder (You can find it in SharePoint server) and create a folder called “usercontroles” if does not exist (Figure 7).

Find your site’s “Web.config” file within the same folder and open it (Figure 7).

Then add new Class called “WebControl.cs” which inherits from “WebPart” Class to your project (Figure 8) and paste this code there.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;

namespace ProjectView
{
    public class WebControl : WebPart
    {
        protected string UserControlPath = @"~/usercontrols/";
        protected string UserControlName = @"ProjectViewControl.ascx";

        private ProjectViewControl mycontrol;
        private string exceptions = "";

        protected override void CreateChildControls()
        {
            try
            {
                mycontrol = (ProjectViewControl)this.Page.LoadControl(UserControlPath + UserControlName);
                Controls.Add(mycontrol);
            }
            catch (Exception CreateChildControls_Exception)
            {
                exceptions += "CreateChildControls_Exception: " + CreateChildControls_Exception.Message;
            }
            finally
            {
                base.CreateChildControls();
            }
        }
        protected override void RenderContents(HtmlTextWriter writer)
        {
            try
            {
                base.RenderContents(writer);
            }
            catch (Exception RenderContents_Exception)
            {
                exceptions += "RenderContents_Exception: " + RenderContents_Exception.Message;
            }
            finally
            {
                if (exceptions.Length > 0)
                {
                    writer.WriteLine(exceptions);
                }
            }
        }
    }
}

There don’t forget to add following two lines to the top, now your “WebControl.cs” Class should like above.

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;

Then drag and drop a text box and two buttons to ProjectViewControl.ascx. Double click those buttons to add custom code (Figure 9 & 10).


Signing your web part project

To deploy this Web Part and Web User Control 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 “ProjectView” 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 11).

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

Deploying the Web Part and Web User Control

Here is deploying steps;

1. Copy the "ProjectViewControl.ascx" file to the created usercontroles folder (Figure 7).

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

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

4. Update the "Web.config file"

4.1 Insert these three lines between <SafeControls> and </SafeControls> tags.

<SafeControl Assembly="ProjectView, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9a73871474819663" Namespace="ProjectView" TypeName="WebControl" Safe="True" />
<SafeControl Assembly="ProjectView, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9a73871474819663" Namespace="ProjectView" TypeName="ProjectViewControl" Safe="True" />
<SafeControl Assembly="ProjectView, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9a73871474819663" Namespace="ProjectView" TypeName="*" Safe="True" />

4.2 Insert this line between <assemblies> and </assemblies> tags.

<add assembly="ProjectView, Version=1.0.0.0, Culture=neutral,PublicKeyToken=9a73871474819663" />

5. Insert new XML file called "myprojectview.webpart" (Figure 13) and paste this code.

<?xml version="1.0" encoding="utf-8" ?>
<webParts>
    <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
        <metaData>
            <type name="ProjectView.WebControl, ProjectView, Version=1.0.0.0,Culture=neutral,PublicKeyToken=9a73871474819663" />
            <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
        </metaData>
        <data>
            <properties>
                <property name="Title" type="string">My first custom Web Part</property>
                <property name="Description" type="string">
                    webpart created by using web user controles
                </property>
                <property name="ChromeType">TitleOnly</property>
                <property name="ChromeState">Normal</property>
                <property name="ItemLimit" type="int">15</property>
                <property name="ItemStyle" type="string">Default</property>
            </properties>
        </data>
    </webPart>
</webParts>

6. Upload the "myprojectview.webpart" file to Share Point's Web Part gallery. (You should have permission to see the Site Action tab and upload) (Figure 14, 15, 17, 18 & 19)





Use your Web Part

To use your Web Part in a page, follow these steps;

1. Edit a SharePoint page (Figure 19, 20 & 21)

2. Select a zone into which you want to place your Web Part

3. Add the Web Part to the zone

4. Exit from the Edit mode



Remember that you cannot copy DLL from MyDocument folder. So first copy the DLL to some location in SharePoint Server and then drag and drop it into assembly folder.

If you are interested you can try SharePoint charting (Chart inside web part) to see how you can add nice chart inside to this web part. Also try custom features.

Tuesday, September 29, 2009

Creating SharePoint Features

In this article I’m going to describe how to create SharePoint feature before look at custom web parts . Here I’m going to use Visual Studio 2008 and Visual Studio 2008 extensions for Windows SharePoint Services 3.0 to create my feature.

Creating the Feature

First create new SharePoint Empty project as shown in Figure 1. There select Fully Trust (Deploy to GAC) when prompt.

Then Add new SharePoint Event Receiver as shown in Figure 2 & 3.


And select the list to add event receiver. Here I’ll select Custom List (Figure 4).

Then open ItemEventReceiver.cs to write whatever you want when something happen, like Add new item, Update item and Delete item from the list. You can find commented methods for insert your code. I’ll show how you can get the ID of newly added item (Figure 5).

Deploying the Feature

Using Visual Studio 2008 extensions for Windows SharePoint you can easily deploy your feature to the SharePoint server. To do this you have to be in the server and you can deploy by right clicking on the project (Figure 6).

Then activate the "ProjectUpdateEventItemEventReceiver" at Site Settings --> Site Features.  

To me, it did not work when I tried to change the code and redeploy it. I had to use different name when I want to change the code.

After Deploying the feature you can check the result using EventReceiver-Installer for SharePoint.

You may notice new feature is activated for all the custom lists as above picture, now you can use same EventReceiver-Installer to delete unwanted events in other custom lists.

SharePoint List C# Part 2

In my previous post SharePoint List C# Part 1, I wrote how to retrieve data from SharePoint list. In this post also I'm going to show you how to retrieve data from SharePoint list which has look up fields. You can use this code in your custom webpart ot feature.

        
  public void getData()
        {
            // choose the site
            SPSite site = new SPSite("http://mysite:5050/");
            SPWeb web = site.OpenWeb();

            // choose the list "Task Categories"
            SPList list = web.Lists["Task Categories"];
            SPListItemCollection itemCollection;

            // pass query to get status
            SPQuery oQuery = new SPQuery();
            // get all items
            oQuery.Query = "";
            itemCollection = list.GetItems(oQuery);

            foreach (SPListItem item in itemCollection)
            {
                if (item != null)
                {
                    // get data in "Sub Category(s)" lookup column
                    if (item["Sub Category(s)"] != null)
                    {
                        SPFieldLookupValueCollection subItemColl = ((SPFieldLookupValueCollection)item["Sub Category(s)"]);
                        foreach (var subitem in subItemColl)
                        {
                            // do something
                        }
                    }
                }
            }
        }

SharePoint List C# Part 1

Here I'm going to show you how you can use the SharePoint object model to read sharepoint list using C#.

To do this in your custom webpart or feature first you have to add the reference to Microsoft.Sharepoint.dll (Then in your code use "using Microsoft.Sharepoint;"). And also if you are going to run the program, you have to be in the server.

Read SharePoint List

public void getData()
{
    // choose your site
    string strUrl = "http://mysite:5050/";
    using (SPSite site = new SPSite(strUrl))
    {
        using (SPWeb web = site.OpenWeb())
        {
            // choose the list
            SPList list = web.Lists["insert your list Name"];

            SPQuery myquery = new SPQuery();
            myquery.Query = "insert your query here";

            // if you dosent insert query (myquery.Query ="") you will get all items

            SPListItemCollection items = list.GetItems(myquery);

            foreach (SPListItem item in items)
            {
                // check the item for null
                if (item != null)
                {
                    // do something
                }
            }
        }
    }
}

Adding Item

string strUrl = "http://mysite:5050/";
            using (SPSite site = new SPSite(strUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPListItemCollection listItems = web.Lists["List_Name"].Items;
                    SPListItem item = listItems.Add();
                    item["Title"] = "New Item Title";

                    item.Update();
                }
            }

You can use U2U CAML Query Builder to write queries you want.

If you want to get information from lookup field, please refer SharePoint List C# Part 2, for delete items please refer Delete items from SharePoint list.