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.

Create Android Database

This sample code illustrates how we can use Android SQLite Database to store data in Android.

Following example will give output as Saranga/22 since I have created a text view and set the out put to it. If you want to add your own fields, first drop the existing table using given source code.

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class DBTest extends Activity {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  SQLiteDatabase myDB= null;
  String TableName = "myTable";

  String Data="";

  /* Create a Database. */
  try {
   myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);

   /* Create a Table in the Database. */
   myDB.execSQL("CREATE TABLE IF NOT EXISTS "
     + TableName
     + " (Field1 VARCHAR, Field2 INT(3));");

   /* Insert data to a Table*/
   myDB.execSQL("INSERT INTO "
     + TableName
     + " (Field1, Field2)"
     + " VALUES ('Saranga', 22);");

   /*retrieve data from database */
   Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);

   int Column1 = c.getColumnIndex("Field1");
   int Column2 = c.getColumnIndex("Field2");

   // Check if our result was valid.
   c.moveToFirst();
   if (c != null) {
    // Loop through all Results
    do {
     String Name = c.getString(Column1);
     int Age = c.getInt(Column2);
     Data =Data +Name+"/"+Age+"\n";
    }while(c.moveToNext());
   }
   TextView tv = new TextView(this);
   tv.setText(Data);
   setContentView(tv);
  }
  catch(Exception e) {
   Log.e("Error", "Error", e);
  } finally {
   if (myDB != null)
    myDB.close();
  }
 }
}

You can download source code here.

Password: sara

Tested with Android 2.3.3 Platform SDK.

If you are interested please refer Android User Interface Design to learn simple way to Designing interfaces.

VanCafe, My Android Project

Using Andriod we have built a solution for delivery van based Cafeteria. The overall process that targeted here is as follows. There is a main center cafe and there are delivery vans which would be assigned to different places. They sell goods to customers and the customers can order things via the mobile network using their smart phones. The vans are delivering the goods to the appropriate location.

Main focus on this system is towards a cafeteria which possesses number of delivery vans which do selling within different service areas and in the same time provides the customer with the facilities to make orders through their smart phones.

The Cafeteria has multiple delivery vans to sell and deliver food items to customers within the service area. Cafe Manager defines the service area which is fixed for a longer period of time. Vans are filled every morning and are allowed to come to the Cafeteria at any time to do refilling. Vans are expected to stay within their service area and an “Area Boundary Notification” shall be generated when the van crosses the defined boundary.

Customers can use the mobile device to view available items, view promotions and to order items. The customer location shall be automatically sent with the order. When an order is placed it shall be assigned to the van closest to the customer, depending on the stock availability. In addition to the order delivery vans can do direct sales on the road. Vans can also take orders from customers on the road.

The main features of this system is the usage of the facilities in the mobile environment. In spite of that, consumer friendly applications would be implemented to help the customer and the business (i.e. delivery van or the manager) with their day-to-day activities.