Showing posts with label sharepoint list. Show all posts
Showing posts with label sharepoint list. Show all posts

Friday, 22 November 2013

Display List Header of a List View Web Part

When you add a custom list view web part on a page, the list header is not displaying by default unlike the other web parts namely Categories, Other Blogs and Links.








In order to add a list view web part on a page with list header (for example, you want to use your custom list as a left navigation menu, similar to Categories web part in SharePoint blog site), replace the <ListViewXml> with the item below and then change the View Name value equal to the listview webpart id (__WebPartId).

<ListViewXml xmlns="http://schemas.microsoft.com/WebPart/v2/ListView">&lt;View Name="{D5DE4857-09A5-49CC-8EB3-5D26EDC40238}" Type="HTML" Hidden="TRUE" DisplayName="" Url="/blog/default.aspx" Level="1" BaseViewID="4" ContentTypeID="0x"&gt;&lt;Toolbar Type="None"/&gt;&lt;ViewHeader&gt;&lt;HTML&gt;&lt;![CDATA[ &lt;div class="ms-WPBody"&gt; &lt;div class="ms-navheader"&gt;]]&gt;&lt;/HTML&gt;&lt;HTML&gt;&lt;![CDATA[&lt;a ]]&gt;&lt;/HTML&gt;&lt;HTML&gt;&lt;![CDATA[ id="defviewurl]]&gt;&lt;/HTML&gt;&lt;Counter Type="View"/&gt;&lt;HTML&gt;&lt;![CDATA["&gt;]]&gt;&lt;/HTML&gt;&lt;ListProperty Select="Title" HTMLEncode="TRUE"/&gt;&lt;HTML&gt;&lt;![CDATA[&lt;/a&gt;]]&gt;&lt;/HTML&gt;&lt;HTML&gt;&lt;![CDATA[&lt;/div&gt; &lt;table cellpadding="0" cellspacing="0" border="0" class=""&gt;]]&gt;&lt;/HTML&gt;&lt;/ViewHeader&gt;&lt;ViewEmpty&gt;&lt;HTML&gt;&lt;![CDATA[ &lt;div class="ms-WPBody"&gt; &lt;div class="ms-navheader"&gt;]]&gt;&lt;/HTML&gt;&lt;HTML&gt;&lt;![CDATA[&lt;a ]]&gt;&lt;/HTML&gt;&lt;HTML&gt;&lt;![CDATA[ id="defviewurl]]&gt;&lt;/HTML&gt;&lt;Counter Type="View"/&gt;&lt;HTML&gt;&lt;![CDATA["&gt;]]&gt;&lt;/HTML&gt;&lt;ListProperty Select="Title" HTMLEncode="TRUE"/&gt;&lt;HTML&gt;&lt;![CDATA[&lt;/a&gt;]]&gt;&lt;/HTML&gt;&lt;HTML&gt;&lt;![CDATA[&lt;/div&gt; &lt;table cellpadding="0" cellspacing="0" border="0" class="ms-navSubMenu2"&gt;]]&gt;&lt;/HTML&gt;&lt;HTML&gt;&lt;![CDATA[&lt;tr&gt;&lt;td&gt;&lt;div class="ms-BlogEmptyListText"&gt;]]&gt;&lt;/HTML&gt;&lt;HTML&gt;There are no items in this list.&lt;/HTML&gt;&lt;HTML&gt;&lt;![CDATA[&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;]]&gt;&lt;/HTML&gt;&lt;HTML&gt;&lt;![CDATA[&lt;/table&gt;&lt;/div&gt;]]&gt;&lt;/HTML&gt;&lt;/ViewEmpty&gt;&lt;ViewBody&gt;&lt;HTML&gt;&lt;![CDATA[&lt;tr class="ms-CategoryTitleRow"&gt;&lt;td class="ms-CategoryTitleCell" id="lnkurl]]&gt;&lt;/HTML&gt;&lt;Column Name="ID" URLEncode="TRUE"/&gt;&lt;HTML&gt;&lt;![CDATA["&gt;]]&gt;&lt;/HTML&gt;&lt;Field Name="URL"/&gt;&lt;HTML&gt;&lt;![CDATA[&lt;/td&gt;&lt;/tr&gt;]]&gt;&lt;/HTML&gt;&lt;/ViewBody&gt;&lt;ViewFooter&gt;&lt;HTML&gt;&lt;![CDATA[&lt;/table&gt;&lt;/div&gt;]]&gt;&lt;/HTML&gt;&lt;/ViewFooter&gt;&lt;RowLimitExceeded&gt;&lt;HTML&gt;&lt;![CDATA[&lt;div class="ms-BlogMoreLinks"&gt;&lt;a href="]]&gt;&lt;/HTML&gt;&lt;ListProperty Select="DefaultViewUrl"/&gt;&lt;HTML&gt;&lt;![CDATA[" ID=onetidMoreFavs&gt;
                                        ]]&gt;&lt;/HTML&gt;&lt;HTML&gt;(More Links...)&lt;/HTML&gt;&lt;HTML&gt;&lt;![CDATA[
                                        &lt;/a&gt;&lt;/div&gt;]]&gt;&lt;/HTML&gt;&lt;/RowLimitExceeded&gt;&lt;Query&gt;&lt;OrderBy&gt;&lt;FieldRef Name="Order" Ascending="TRUE"/&gt;&lt;/OrderBy&gt;&lt;/Query&gt;&lt;ViewFields&gt;&lt;FieldRef Name="URL"/&gt;&lt;/ViewFields&gt;&lt;RowLimit&gt;30&lt;/RowLimit&gt;&lt;/View&gt;</ListViewXml>




After doing the modifications, it will now show the list header of the custom list as shown below:







Wednesday, 6 November 2013

Filter SharePoint List Views by Date and Time

By default if you do filtering of views by DateTime field via web, it will only filter the views by date, not including time. In order to include time, you need to modify the view using SharePoint Designer. Here are the steps on how to do it.

  1. Open the site in which the list or document library resides using Microsoft Office SharePoint Designer.
  2. Locate the list or document library and open the .aspx file associated with the view (e.g. “AllItems.aspx”)
  3. Click the Code tab and locate the CAML query associated with the filter (search on the name of your DateTime field, e.g. "StartDateTime"). 
  4. Edit the CAML query to include the IncludeTimeValue attribute (IncludeTimeValue="True"). Please note that you need to include spaces exactly as shown in the sample below: 


            &lt;Gt&gt;
             &lt;FieldRef Name=&quot;StartDateTime&quot;/&gt;
             &lt;Value Type=&quot;DateTime&quot; IncludeTimeValue="True"&gt;
              &lt;Today/&gt;
             &lt;/Value&gt;





Saturday, 2 November 2013

Filter SharePoint List Using URL Parameters

When you filter a list in SharePoint, you will notice that the parameters for filtering are appended automatically to the URL of the page that displays the list. So if you have a requirement to create a custom Search page, you can use the url parameters. For example, using SharePoint designer, you can add the list view web part on the page and then manipulate the url parameters for filtering by using javascript.

Here are the parameters that can be added in the URL to filter the SharePoint list:

  • to filter by one column

               ?FilterField1=<InternalName>&FilterValue1=<Value>

  • to filter by one column with multiple values

              ?FilterName=<InternalName>&FilterMultiValue=<value1>;<value2>
                         ** FilterMultiValue should be semicolon separated

  • to filter by two columns

              ?FilterField1=<InternalName>&FilterValue1=<Value1>&FilterField2=<InternalName>&FilterValue2=<Value2>


Note:
   <InternalName> = the internal name of the column
   <Value> = the value of the column


Examples:

1. To display SharePoint list items where Document Date = '08/16/2011'

http://www.vpc.com/sites/blog/Lists/Posts/AllPosts.aspx?FilterField1=DocumentDate&FilterValue1=08/16/2011

2. To display SharePoint list items where Category = 'Category1' and Document Date = '08/16/2011'.

http://www.vpc.com/sites/blog/Lists/Posts/AllPosts.aspx?FilterField1=PostCategory&FilterValue1=Category1&FilterField2=DocumentDate&FilterValue2=08/16/2011

3. To display SharePoint list items where Title = 'Test' OR Title = 'Sample Title'

http://www.vpc.com/sites/blog/Lists/Posts/AllPosts.aspx?FilterName=Title&FilterMultiValue=test;sample%20title

4. To display SharePoint list items where Title contains 'sample'

http://www.vpc.com/sites/blog/Lists/Posts/AllPosts.aspx?FilterName=Title&FilterMultiValue=*sample*





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");