Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Friday, 22 November 2013

How to Update People Picker Field Programmatically

People picker field is a SharePoint column that allows you to select users, distribution lists, and security groups within the SharePoint Foundation user interface. If you have a user's requirement that needs to update the people picker field programmatically, you can try the following solution.

In your ascx page, add a hidden SharePoint people picker field (where visible property is equal to false) by using the following syntax:

<spuc:PeopleEditor AllowEmpty="false" ValidatorEnabled="true" id="userPicker" runat="server" ShowCreateButtonInActiveDirectoryAccountCreationMode="true" SelectionSet="User" MultiSelect="false" Visible=false />

But in order to use this field in a page, you need to add a directive at the top of the page:

<%@ Register TagPrefix="spuc" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

In code behind, add the following:

PickerEntity entity = new PickerEntity();
entity.Key = vr.RName //display name;
entity.DisplayText = vr.RName //display name;
entity = userPicker.ValidateEntity(entity);
                       
PickerEntity entity2 = new PickerEntity();
entity2.Key = entity.Description;
entity2 = userPicker.ValidateEntity(entity2);

                       
SPFieldUserValue fuv = new SPFieldUserValue(web, Convert.ToInt32(entity2.EntityData[PeopleEditorEntityDataKeys.UserId]), entity2.Description);


// "RName" is the name of the sharepoint people picker field to update
listItem["RName"] = fuv;

HandleEventFiring eventFiring = new HandleEventFiring();
eventFiring.AccDisableEventFiring();
listItem.Update();
eventFiring.AccEnableEventFiring();


-------------------

public class HandleEventFiring : SPItemEventReceiver
        {
            public void AccDisableEventFiring()
            {
                this.DisableEventFiring();
            }

            public void AccEnableEventFiring()
            {
                this.EnableEventFiring();
            }
        }







    

Tuesday, 19 November 2013

How to Save a File to SQL Database

Here are the steps on how to save a file to sql database using LINQ.


  1. Define your table. In this sample we created an Attachments table having 3 fields FileID (int), FileName (nvarchar(100)) and FileContent (varbinary(MAX)). FileContent field will contain the bytes of our file. We set it to MAX to accommodate any file size.










  1. Add your table to your repository module. In this case I used a simple LINQ to SQL just to make it simple















I created a simple repository class to expose some methods like add, save and get.

public class AttachmentRepository
{
    private DataClassesDataContext db = new DataClassesDataContext();

       public AttachmentRepository()
       {
              //
              // TODO: Add constructor logic here
              //
       }

    public void Add(Attachment at)
    {
        db.Attachments.InsertOnSubmit(at);
    }

    public void Save()
    {
        db.SubmitChanges();
    }

    public List<Attachment> GetAllAttachments()
    {
        return db.Attachments.ToList();
    }
}


  1. Layout your UI. Here we have two controls asp FileUploader and asp Button.






  1. Add a button click event on your upload button. In the code below, we only add a file to the database if there is a file uploaded using .HasFile property. Since we already have a repository using LINQ to SQL we can directly assign the Filename and FileBytes to our attachment class.

protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUploadSample.HasFile)
        {
            AttachmentRepository atRepo = new AttachmentRepository();
            Attachment at = new Attachment();
            at.FileName = FileUploadSample.FileName;
            at.FileContent = FileUploadSample.FileBytes;
            atRepo.Add(at);
            atRepo.Save();
        }       
   }


  1. Verify your Database if the file was indeed saved.








Finally I added a gridview to show the uploaded data









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;

                   
                }
            }

           

        }
    }
}