Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Tuesday, 22 October 2013

Attaching Event Handler To A SharePoint List

Attaching an event handler / event receiver to a custom list in SharePoint can be done programmatically. You can create a console application so that every time you require to attach an event handler to a list, you just need to run that console application.

Below is the full code of the sample console application that will attach an event handler to a SharePoint list via code. Basically, the console application only supports the following type of event:

  • ItemAdding - An event that occurs before an item has been added.
  • ItemAdded - An event that occurs after an item has been added.
  • ItemUpdating - An event that occurs before an item is updated.
  • ItemUpdated- An event that occurs after an item has been updated.
  • ItemDeleting - An event that fires before an item is deleted.
  • ItemDeleted - An event that occurs after an item has been deleted.

Also, the console application requires four input parameters as listed below:
  1. Site URL (the full URL of the SharePoint site)
  2.          e.g. http://www.abc.com/log
  3. List Name (the display name of the list)
  4.          e.g. ListName
  5. Event Receivers (The type of event receivers separated by ';')
  6.          e.g. itemadded;itemupdated
  7. Assembly Path (the location path of the assembly)
  8.          e.g. C:\\Sample.dll

When you run the console application, the format should be:

AttachEventHandlerToSPList <site url> <List Name> <Event Receivers> <Assembly Path>

Example:

AttachEventHandlerToSPList http://www.abc.com/log ListName itemadded;itemupdated C:\\Sample.dll




Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Reflection;

namespace AttachEventHandlerToSPList
{
    class Program
    {
        static void Main(string[] args)
        {
            string strClassName = string.Empty;
            string strAssembly = string.Empty;
            try
            {
                if (args.Length != 4)
                {
                    Console.WriteLine("ERROR: Invalid no. of parameters. \n");
                    usage();
                    Environment.Exit(1);
                }


                string siteURL = args[0]; // "http://www.abc.com/sites/DomainRequest"; //
                string listName = args[1]; // "Branch";  //   "Domain Account Request Application";
                string eventReceivers = args[2]; // "itemadded;itemupdated"; //   "itemadding";
                string path = args[3]; // "C:\Documents and Settings\Administrator\Desktop\.net workflow\DomainRequest\DomainRequestEventHandler\bin\Release\DomainRequestEventHandler.dll"
                //AssemblyName assemblyName = AssemblyName.GetAssemblyName(@"C:\Documents and Settings\Administrator\Desktop\.net workflow\DomainRequest\DomainRequestEventHandler\bin\Release\DomainRequestEventHandler.dll");
                Assembly assembly = Assembly.LoadFrom(@path);
                strAssembly = assembly.FullName;
                Type[] types = assembly.GetTypes();
               

                foreach (Type type in types)
                {
                    if (type.BaseType.Name == "SPItemEventReceiver")
                        strClassName = type.FullName;
                }


                if (!string.IsNullOrEmpty(eventReceivers))
                {
                    string[] events = eventReceivers.ToLower().Split(';');

                    int nCnt = events.Count();

                    if (nCnt > 0)
                    {
                        using (SPSite site = new SPSite(siteURL))
                        {

                            using (SPWeb web = site.OpenWeb())
                            {
                                SPList list = web.Lists[listName];

                                foreach (string eventType in events)
                                {
                                    DeleteEventHandler(list, eventType, strClassName);

                                    switch (eventType)
                                    {
                                        case "itemadding":
                                            {
                                                list.EventReceivers.Add(SPEventReceiverType.ItemAdding,
                                                    strAssembly,
                                                    strClassName);
                                                list.Update();

                                                Console.WriteLine(string.Format("EventHandler (ItemAdding) has been added correctly in {0}!", listName));
                                                break;
                                            }
                                        case "itemadded":
                                            {
                                                list.EventReceivers.Add(SPEventReceiverType.ItemAdded,
                                                    strAssembly,
                                                    strClassName);
                                                list.Update();

                                                Console.WriteLine(string.Format("EventHandler (ItemAdded) has been added correctly in {0}!", listName));
                                                break;
                                            }
                                        case "itemupdating":
                                            {
                                                list.EventReceivers.Add(SPEventReceiverType.ItemUpdating,
                                                    strAssembly,
                                                    strClassName);
                                                list.Update();

                                                Console.WriteLine(string.Format("EventHandler (ItemUpdating) has been added correctly in {0}!", listName));
                                                break;
                                            }
                                        case "itemupdated":
                                            {
                                                list.EventReceivers.Add(SPEventReceiverType.ItemUpdated,
                                                    strAssembly,
                                                    strClassName);
                                                list.Update();

                                                Console.WriteLine(string.Format("EventHandler (ItemUpdated) has been added correctly in {0}!", listName));
                                                break;
                                            }
                                        case "itemdeleting":
                                            {
                                                list.EventReceivers.Add(SPEventReceiverType.ItemDeleting,
                                                    strAssembly,
                                                    strClassName);
                                                list.Update();

                                                Console.WriteLine(string.Format("EventHandler (ItemDeleting) has been added correctly in {0}!", listName));
                                                break;
                                            }
                                        case "itemdeleted":
                                            {
                                                list.EventReceivers.Add(SPEventReceiverType.ItemDeleted,
                                                    strAssembly,
                                                    strClassName);
                                                list.Update();

                                                Console.WriteLine(string.Format("EventHandler (ItemDeleted) has been added correctly in {0}!", listName));
                                                break;
                                            }
                                    }


                                }
                            }

                        }
                      
                    }
                    else
                    {
                        Console.WriteLine("Please input EventReceivers Type (separated by ';' if multiple)");
                    }
                }
            }

            catch (Exception ex)
            {

                Console.WriteLine("Error! stack:" + ex.StackTrace);

                Console.WriteLine("Error! message:" + ex.StackTrace);

                Console.WriteLine("press any key to exit ...");

                Console.Read();

            }

        }


        static void DeleteEventHandler(SPList splist, string eventtype, string strClassNme)
        {
            SPEventReceiverType type = (SPEventReceiverType)Enum.Parse(typeof(SPEventReceiverType), eventtype, true);

            for (int i = 0; i < splist.EventReceivers.Count; i++)
            {
                if (splist.EventReceivers[i].Class == strClassNme)
                {
                    if (splist.EventReceivers[i].Type == type)
                    {
                        splist.EventReceivers[i].Delete();
                        splist.Update();
                        Console.WriteLine(eventtype + " Event deleted to " + splist.Title + " list.");
                    }
                }               
            }
        }


        public static void usage()
        {
            Console.WriteLine("Format: AttachEventHandlerToSPList <site url> <List Name> <Event Receivers> <Assembly Path> \n" +
                              "<site url>             -  The sharepoint site url \n" +
                              "<List Name>            -  The display name of the list \n" +
                              "<Event Receivers>      -  The type of event receivers \n" +
                              "                          separated by ';'. (e.g. itemadded;itemupdated) \n" +
                              "<Assembly Path>        -  The location path of the assembly.");

            Console.WriteLine("e.g. Attach the eventhandler in the List: \n" +
                              "AttachEventHandlerToSPList http://www.abc.com/log ListName itemadded;itemupdated C:\\Sample.dll ");
        }
    }
}




Wednesday, 9 October 2013

Set Value To A Lookup Field By Using Name

The following example shows how to set value to a SharePoint lookup field by using name.

The example method or function accepts two parameters. The first one is SPList which is equal to your lookup list and the second one is a string which is equal to the name of your lookup item. This method will find the item from the lookup list by using Name. If the item is found, it will be used in creating SPFieldLookupValue category using the item id & item title. SPFieldLookupValue category will then be returned by the method and it can be used now as a value of the lookup field.



static SPFieldLookupValue GetCategory(SPList list, string lookupitemName)
    {
        SPFieldLookupValue category = null;
        //get id from Categories List
        for (int ItemNum = 0; ItemNum < list.Items.Count; ItemNum++)
        {
            SPListItem listItem = list.Items[ItemNum];

            if (Convert.ToString(listItem["Title"]).Trim().ToLower() == lookupitemName.Trim().ToLower())
            {
                category = new SPFieldLookupValue(listItem.ID, listItem.Title);
                break;
            }
        }

        return category;

    }


Here is the sample code on how to use the above method:

listitem["Category"] = GetCategory(CategoriesList, "Admin Matters");




Thursday, 3 October 2013

Remove Workflow Column from SharePoint List View

When you attach a workflow to a SharePoint list, the workflow column will be added automatically to the default view of the list. This column shows the status of the workflow and when you click on the status, you will be redirected to the Workflow Status page. Usually, this information is of no practical use for end users therefore you don't want this column to appear in the list view. So in order to achieve it, you need to write a custom code that will remove the workflow column programmatically.


Below is the sample code of a console application that removes workflow column from the default view of the SharePoint list:

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

namespace RemoveWorkFlowColumnFromSPView
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 4)
            {
                Console.WriteLine("Please input parameters.");
                Console.WriteLine("Format: <site url> <list name> <view name> <workflow template name>");
                return;
            }

            string workflowColName = string.Empty;
            string siteUrl = args[0]; // "http://www.vpc.com/sites/PFW"; //
            string listName = args[1]; // "Perimeter Firewall Request"; //
            string viewName = args[2]; // "All Requests"; //
            string workflowName = args[3]; // "FirewallRequestWorkFlow"; //


            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;

                    SPView objView = web.Lists[listName].Views[viewName];

                    //static name of the workflow column is equal to 8_character_name_of_workflow_column,
                    // without space and is case sensitive.
                    workflowColName = workflowName.Substring(0, 8);

                    if (objView.ViewFields.Exists(workflowColName))
                    {
                        objView.ViewFields.Delete(workflowColName);
                        objView.Update();

                        Console.WriteLine(string.Format("{0} column: {1} has been removed successfully from the {2} view",
                            workflowName,
                            workflowColName,
                            viewName));
                    }

                   

                    web.AllowUnsafeUpdates = false;

                   
                }
            }

           

        }
    }
}





Wednesday, 2 October 2013

Change Default Form Per Content Type

By default in SharePoint list, the following things happen:

  • When you click New Item, you will be redirected to /NewForm.aspx page.
  • When you click Edit Item, you will be redirected to /EditForm.aspx page.
  • When you click View Item, you will be redirected to /DispForm.aspx page.

If you don't want to use these default forms and you want to use a different form, you need to change the default form per content type of the SharePoint list. Basically, you can do it by using SharePoint designer but sometimes it is not working that's why I prefer doing it programmatically. And since I'm doing it always, I already created a console application (exe program) in order to change it via code.


The console application requires five input parameters as listed below:
  1. Full URL of the site
  2.          e.g. http://www.xc.com/sites/domain
  3. Name of the SharePoint list
  4.          e.g. Domain Account Request Application
  5. Name of the content type
  6.          e.g. Request
  7. Type of the form that you want to change. (You need to input here either new, edit or display.)
  8.          e.g. new
  9. Name of the different form
  10.          e.g. NewForm2.aspx


Here is the code that I used:


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

namespace ChangeDefaultFormPerContentType
{
    class Program
    {
        static void Main(string[] args)
        {

            if (args.Length != 5)
            {
                Console.WriteLine("Incomplete parameter");
                Console.WriteLine("Input the parameters. Format: <full site url> <listName> <content type Name> <Form Type: new | edit | display> <Form Name>");
                Console.WriteLine("e.g. http://www.abc.com/sites/Firewall Perimeter Request new NewForm2.aspx");
                return;
            }

            string siteUrl = args[0];  // "http://www.xc.com/sites/domain"; //
            string listName = args[1]; // "Domain Account Request Application"; //
            string contenType = args[2]; // "Request"; //
            string formType = args[3]; // "new"; //
            string formName = args[4]; // "NewForm2.aspx"; //

            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    SPList list = web.Lists[listName.Trim()];
                    string sz = list.RootFolder.Url;
                    SPContentType ct = list.ContentTypes[contenType.Trim()];

                    switch (formType.Trim())
                    {
                        case "new":
                            {
                                ct.NewFormUrl = sz + "/" + formName.Trim();
                                ct.Update();
                                list.Update();
                                Console.WriteLine(string.Format("NewFormUrl of {0} content type was updated successfully into {1}", contenType, formName));
                                break;
                            }
                        case "edit":
                            {
                                ct.EditFormUrl = sz + "/" + formName.Trim();
                                ct.Update();
                                list.Update();
                                Console.WriteLine(string.Format("EditFormUrl of {0} content type was updated successfully into {1}", contenType, formName));
                                break;
                            }
                        case "display":
                            {
                                ct.DisplayFormUrl = sz + "/" + formName.Trim();
                                ct.Update();
                                list.Update();
                                Console.WriteLine(string.Format("DisplayFormUrl of {0} content type was updated successfully into {1}", contenType, formName));
                                break;
                            }
                    }


                }
            }

        }
    }
}