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

Wednesday, June 1, 2011

Adding Events and EventHandlers in SharePoint Website

There are two type of event handlers in SharePoint.
1.Synchronous
2.Asynchronous
Synchronous are those who before the action is committed. E.g. Deleting, updating
Asynchronous are those which performed after the action completed. Deleted , Updated
 Creating Events for SharePoint website is done after doing various steps, first create event
and second attach them to you website. Both are different process;  now I am describing
the first step:
Create a class library Project. Reference the C:\Program Files\Common Files\Microsoft
Shared\web server extensions\12\ISAPI\SharePoint.dll from the 12 hives.

 Inherit SPItemEventRecevier in the class as: 

namespace B1.Events
{
    public class ListReceiver:SPItemEventReceiver
    {
    }
}

Now  override the  ItemAdded method of SPItemEventReceiver Class and write your code
 for the Event. Here I am going to creating an event for my custom list of website name Demo List.
public override void ItemAdded(SPItemEventProperties properties)
        {
          // base.ItemAdded(properties);
        }
now write the code in this method that fire after adding an item in the list.
My Website's custom List have columns as in the Figure:
Figure 1

public override void ItemAdded(SPItemEventProperties properties)
        {
            //base.ItemAdded(properties);
            SPListItem item = properties.ListItem;
            String title = item.GetFormattedValue("Title");
            String desc = item.GetFormattedValue("Desc");

            //read Title and Desc and write in the Result when Item
            // is added to list
            item["Result"] = "Title is : " + title + " and desc is : " + desc;
            item.Update();
        }
        public override void ItemDeleting(SPItemEventProperties properties)
        {
            //base.ItemDeleting(properties);
            SPListItem item = properties.ListItem;
            String status = item.GetFormattedValue("Status");
            if (status.ToLower() == "in progress")
            {
                properties.Cancel = true;
                properties.ErrorMessage = "You can not deleted "+
                   this item, the status is in progress!!";
}
}
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            //base.ItemUpdated(properties);
           
// this.DisableEventFiring() revoke to Update event firing Loop
           
// if you are adding an item then it will call update event
           
// again and again.

            this.DisableEventFiring();
            SPListItem item = properties.ListItem;
            item["Result"] = "Updated...";
            item.Update();
            //
            this.EnableEventFiring();
        }
Build the solution.
Now Sign in the class library to publish it to the GAC (Global Assembly Cache) using these steps:

Right click on the project in Solution Explorer and select properties.
Select Signing in left side list
Click the check box 'Sign the assembly'
Create New Key and give key file name as in the Figure

Figure 2

Again Build the solution.
Now use the GACUTIL utility to put this dll to the GAC as:
gacutil –i B1.Events.dll
Figure 3


To test/ Debug the event and the solution select Attach to Process from the Debug Menu and select the
process as in the Figure:

Figure 4


and now add some item in list of your website. That will not add  test in the Result column now. You have to attach these to the your website using some Program. To do so create a Console Application and start writing the following statements to attach these events to SharePoint website:

Create new console Application named AttachListEvents and add reference to Microsoft.Sharepoint from 12 hives.
Now open your website and get the reference of you list in as SpList variable as:

SPSite spSite = new SPSite("http://temple:44/");
               SPWeb spWeb = spSite.OpenWeb();
                SPList list = spWeb.Lists["Demo List"];

to add these events you need to get the assembly information of your created events class library (DLL) that you have to placed in the GAC. You need the PublicKeyToken of that assembly. To get this go run in the start menu and type assembly and find your placed library. Open properties of this dll by double clicking it or selecting properties after right click it. Now you will get the all information that you need to attach with your website. You should know the class name of your DLL. You have specify this also.
Figure 5
Here you will get the Version information , Public Key Token etc.
Use the following statement to attact the event with your list.
list.EventReceivers.Add(SPEventReceiverType.ItemAdded,
"B1.Events, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=eb5915b1dbd1037d"
,
                    "B1.Events.ListReceiver"); 
the comlete code file of attaching these events is as:
namespace AttachListEvents
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Starting .....");
                SPSite spSite = new SPSite("http://temple:44/");
 
               SPWeb spWeb = spSite.OpenWeb();
                SPList list = spWeb.Lists["Demo List"];
                list.EventReceivers.Add(SPEventReceiverType.ItemAdded,
                            "B1.Events, Version=1.0.0.0, Culture=neutral,
                                            PublicKeyToken= eb5915b1dbd1037d "
,
                               
                        "B1.Events.ListReceiver");

                list.EventReceivers.Add(SPEventReceiverType.ItemUpdated,
                                "B1.Events, Version=1.0.0.0, Culture=neutral,
                                          PublicKeyToken= eb5915b1dbd1037d "
,
                                                         "B1.Events.ListReceiver");
                Console.WriteLine("Successfully done!!!");
                Console.Read();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.Read();
            }
        }
    }
}

Run this Code and you will see this out screen if everything is correct.
Figure 6
restart the IIS and then check your list for the changes:
to restart IIS use the iisreset command.
Now check this and add a new row in the list.

Figure 7


and the result is:
Figure 8.



you add your event and remove these event using this program. You need not to run this code to attach events
to the website. It is only one time work. Once done no need to repeat again.

Hope this will be helpful to you..  Happy Programming!!

Sunday, April 10, 2011

Sharepoint Object Model

The Microsoft.Office.Server namespace is the root namespace of all Office Server objects and Microsoft.SharePoint
 
is the root namespace for all WSS objects.

Figure 1 illustrates some of the key classes contained in each of these namespaces, as well as to which functional
area they belong. The namespace of each group of classes is shown in parentheses next to the functional area.
For example, all list-related functionality is handled within the
Microsoft.SharePoint namespace.

FIGURE 1 Key classes in the SharePoint object model, segmented by functional area.

Object Model                                                                       Corresponding Microsoft Class for these
Web application                                                                  
Site Collections                                                                    SPSiteCollectioin
Site Collection                                                                      SPSite
Sites                                                                                       SPWebCollection
Site                                                                                         SPWeb
Lists                                                                                        SPListCollection
List/Library                                                                            SPList
Items/Rows                                                                           SPListItemCollection
Item/Row                                                                               SPListItem

A Simple Program to demonstrate SharePoint Object Model.

Create a list in your website and create three columns named: Title, Desc, Status

1.Create a Windows application and a form in it.
Figure :  Object Model Form
2. now code it is code for this application to work with list items of your SharePoint Website:
sing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint;

namespace SPObjectModel
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadData();
        }
/* this is like bind function in asp.net databinding with gridview */
        private void LoadData()
        {
            try
            {
//first create your main site- in yello box write your sharepoint website url
                using (SPSite spSite = new SPSite("http://s-e0912c86c85d4:40/"))
                {   //now create get the object of your website that have list
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        lstItems.Items.Clear();
                        //create object or get your list from database using this. 
                        SPList list = spWeb.Lists["Employee"];
                        foreach (SPListItem item in list.Items)
                        {
                            lstItems.Items.Add(item.Title);
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }
        }

        private void lstItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                using (SPSite spSite = new SPSite("http://s-e0912c86c85d4:40/"))
                {
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        SPList list = spWeb.Lists["Employee"];

                        SPQuery spQuery = new SPQuery();
                        spQuery.Query = "<Where><Eq><FieldRef Name='Title' />"
                            + "<Value Type='Text'>" + lstItems.SelectedItem + "</Value></Eq></Where>";

                        SPListItemCollection items= list.GetItems(spQuery);
                        SPListItem item = items[0];

                        txtTitle.Text = Convert.ToString(item["Title"]);
                        txtDesc.Text = Convert.ToString(item["Desc"]);
                        txtStatus.Text = Convert.ToString(item["Status"]);
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite spSite = new SPSite("http://s-e0912c86c85d4:40/"))
                {
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        SPList list = spWeb.Lists["Employee"];

                        SPListItem item = list.Items.Add();

                        item["Title"] = txtTitle.Text;
                        item["Desc"] = txtDesc.Text;
                        item["Status"] = txtStatus.Text;

                        item.Update();

                        txtTitle.Text = "";
                        txtDesc.Text = "";
                        txtStatus.Text = "";

                        LoadData();
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite spSite = new SPSite("http://s-e0912c86c85d4:40/"))
                {
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        SPList list = spWeb.Lists["Employee"];

                        SPQuery spQuery = new SPQuery();
                        spQuery.Query = "<Where><Eq><FieldRef Name='Title' />"
                            + "<Value Type='Text'>" + lstItems.SelectedItem + "</Value></Eq></Where>";

                        SPListItemCollection items = list.GetItems(spQuery);
                        SPListItem item = items[0];

                        item["Title"] = txtTitle.Text;
                        item["Desc"] = txtDesc.Text;
                        item["Status"] = txtStatus.Text;

                        item.Update();

                        LoadData();
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite spSite = new SPSite("http://s-e0912c86c85d4:40/"))
                {
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        SPList list = spWeb.Lists["Employee"];

                        SPQuery spQuery = new SPQuery();
                        spQuery.Query = "<Where><Eq><FieldRef Name='Title' />"
                    + "<Value Type='Text'>" + lstItems.SelectedItem + "</Value></Eq></Where>";

                        SPListItemCollection items = list.GetItems(spQuery);
                        SPListItem item = items[0];

                        item.Delete();

                        LoadData();
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }
        }
    }
}


Thursday, March 3, 2011

Installing Microsoft SharePoint Server 2010 on Windows 7 x64

It is much simple to do this. Just a little work and your SharePoint Installation ready to work on Windows 7
64 bit Client OS.
You can simply install SharePoint Server 2010 on your client OS just by modifying a config file.
Copy CD contents to a folder on your hard drive and Follow following steps:

*Go to the Files folder
*Go to the Setup folder
*Open config.xml

*Add the following line before the closing </configuration> tag
<Setting Id="AllowWindowsClientInstall" Value="True"/>
Save the file and Run the Setup.exe. now it will work fine. 

Remember: These lines are Case Sensitive so Write them correct.


  • O
    n Windows 7, install the following additional prerequisites required before running Setup.exe:
    o    Microsoft FilterPack 2.0. At a command prompt, type the following:
    installation directory folder\PrerequisiteInstallerFiles\FilterPack\FilterPack.msi
    o    Chart Controls (this is not required if you are going to install SharePoint Foundation 2010).
    o    SQL Server Analysis Services - ADOMD.Net (this is not required if you are going to install SharePoint Foundation 2010).
     






  • Tuesday, December 14, 2010

    Getting Started with Windows SharePoint Services

    System administrators: can use this article to setup a SharePoint server on their network for test purposes, to get used to the features of SharePoint and also learn how to create and manage collaborative team sites.
    Developers: Windows SharePoint Services is the DotNet Framework for developing collaborative applications, you need to have a SharePoint environment (server) where you can deploy and test your applications. For example WebParts have to be installed on a SharePoint server. This article will help developers new to SharePoint setup their test environment.
    In addition, this article is part of a series of articles I will be writing to talk extensively about SharePoint Products and Technologies, right from the beginning to more advanced topics.

    Importance of Windows SharePoint Services (WSS)

    To appreciate the importance of WSS, we need to understand what Collaborative Applications are.
    Collaboration refers to interaction between two or more individuals that may involve actions like information sharing, communication, problem solving, cooperation and many others.
    Therefore Collaborative Applications can be defined as software that allows a group of users to communicate, share information and processes and to cooperate.

    Windows SharePoint Services is a component of the Windows Server 2003 information worker infrastructure and provides team services and sites to Microsoft Office System and other desktop programs. It is also a platform for collaborative application development. WSS provides resources such as portals, team workspaces, e-mail, presence awareness, and Web-based conferencing. WSS enables users to locate distributed information quickly and efficiently, as well as connect to and work with others more productively. For more on WSS click here
    WSS Overview.
    To me, WSS is the core of the entire SharePoint Products and Technologies, and I believe the best way to get started with SharePoint is by setting up a server running WSS.

    System Requirements for Windows SharePoint Services

    Reference http://www.microsoft.com/windowsserver2003/techinfo/sharepoint/sysreqs.mspx
    Component Description
    Server Hardware
    • Intel Pentium III-compatible processor
    • 512 megabytes (MB) of RAM
    • 550 MB of available hard disk drive space
    Server Software One of the following Operating Systems:
    • Windows Server 2003 Standard Edition
    • Windows Server 2003 Enterprise Edition
    • Windows Server 2003 Datacenter Edition
    • Windows Server 2003 Web Edition (requires full version of Microsoft SQL Server)
    A Web application server with the following components:
    • Microsoft ASP.NET
    • Internet Information Services (IIS) 6.0 with the following components:
      • Common files
      • Simple Mail Transfer Protocol (SMTP) service
      • World Wide Web service
    Server Databases One of the following versions of SQL Server:
    • SQL Server 2000, with the latest service pack
    • SQL Server 2000 Enterprise Edition, with the latest service pack
    • SQL Server 2000 Desktop Engine (Windows) (WMSDE)
    Network Multiple server configurations must be members of a Microsoft Windows NT 4.0, Windows 2000, or Windows Server 2003 domain.
    Browser Client One of the following browsers:
    • Microsoft Internet Explorer 5.01 with Service Pack 2
    • Internet Explorer 5.5 with Service Pack 2
    • Internet Explorer 6
    • Netscape Navigator 6.2 or later
    • Mozilla 1.4 or later

    Setting up your Windows SharePoint Services Environment

    One question that may arise when it comes to this and the System requirements, is do I have a Windows 2003 server in place?
    Well if your answer is yes, then all you have to do is make sure all the prerequisites as mentioned in the requirements table above are installed. Next you can download WSS and install on the Windows 2003 Server.
    If you have no Windows 2003 Server in place, especially for developers who usually use laptops (code from anywhere), I recommend the use of Microsoft Virtual PC. You may download a trial version of Microsoft Virtual PC from this link http://www.softpedia.com/get/System/OS-Enhancements/Microsoft-Virtual-PC.shtml
    Note: This article is not about setting up Microsoft Virtual PC, so I will not go into the details.
    Assuming you have your server ready with the following components:
    • Windows 2003 Server
    • Microsoft ASP.NET
    • Internet Information Server 6.0 (with Common files, SMTP Service, WWW Service)
    • SQL Server 2000 with the latest service pack (This may exist on another server on the network).
    Then you should be good to go with the Windows SharePoint Services installation.
    You can start by downloading WSS from this link � WSS Download
    • Run the stsv2.exe file downloaded.
    • Accept the agreement, and wait for the installation files to be copied to your PC.
    • Next you have to choose the Installation type as in the screen below.
      Typical Installation is the most basic installation you can do, and this option installs Microsoft SQL Server Desktop Engine (MSDE) to store the site content and configuration data. It also sets up the Default website in ISS as the SharePoint team site.
      In this exercise I chose Server Farm as the installation type because this option enables you to configure one or more front-end web servers, and you have to set the path to the MSSQL server, and set up the SharePoint sites by yourself.
    • If your installation is successful, the Windows SharePoint Services configuration page will be opened, and this looks as below.
    • Select the Use an existing application pool option, and leave the existing StsAdminAppPool(NT AUTHORITY\NETWORK SERVICE) as the application pool.
    • Select the Security Configuration � For this I decided to use NTLM, which is the recommended security configuration to use with Integrated Windows authentication, if no other IIS applications are being run on the virtual server.
    • On the page that follows, follow the instruction to restart IIS and click OK.
    • Next you have to configure the virtual server settings using a screen similar to the one below.
    • Click the Configure virtual server settings link, and on the window that appears click on Default Website. The Screen below will be displayed, here you can take the link Extend and create a content database. This option will enable you to create the Top level WSS site for the virtual server.
    • On the screen that follows below, select the option Use an existing application pool, type your username as the site owner if no name appears, type the custom URL. For example my custom URL is /FirstSite. This means you will be able to access the site by typing the url: http://servername/FirstSite/
    • Click OK on the window that appears next, wait for about 3 minutes for the content database to be created then test the created site by typing the URL http://server_name/FirstSite/. This should take you to the Template Selection page as shown below.
    • At this level you are presented with different site templates provided by Windows SharePoint Services.
    • For now we will select the Team Site template and click OK.
    • Finally you should be looking at your First WSS team site as shown below.
    • You can see the features provided by this site:
      • Documents: A document Library to enable members of the site to share documents.
      • Pictures: Allows easy uploading of pictures to the site
      • Discussions:Default discussion forum for members of the site to exchange ideas
      • Surveys: You can create surveys and team members can fill the surveys online (these may include questionnaires, Feedback forms and many others).
      • Announcements
      • Events
      • Links
      • Tasks and many other features.
    Well if you have gotten to the point of browsing the top level site, then your server is ready and you can start playing with WSS. Now that your sever is setup, you can visit this link for more info and resources on SharePoint Products and Technologies. http://www.microsoft.com/sharepoint/.