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

Sunday, June 22, 2014

Programming custom editor part SharePoint 2013

Programming custom editor part SharePoint 2013


This example shows how to create a custom editor part.
In the editor part, a ListBox control is binded to the list of the Lists in the current web and on selecting multiple lists, all the items from all the lists aggregated are shown in the webpart as depicted below.



Below is the code for custom webpart class with properties having the [WebBrowsable(false)]
-------------------------------------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;

namespace DemoEditorParts.DisplayMultipleItems
{
    [ToolboxItemAttribute(false)]
    public class DisplayMultipleItems : WebPart
    {

        private List<string> listIDs;

        [WebBrowsable(false)]
        [WebDescription("Multiple Lists")]
        [Personalizable(PersonalizationScope.Shared)]
        public List<string> ListIDs
        {
            get
            {
                return listIDs;
            }
            set
            {

                listIDs = value;
            }
        }

        Dictionary<string, List<string>> allItemTitles = new Dictionary<string, List<string>>();

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            try
            {

                if (null == ListIDs)
                {
                    return;
                }
                SPWeb currentWeb = SPContext.Current.Web;

                foreach (var listId in ListIDs)
                {
                    SPList list = currentWeb.Lists[new Guid(listId)];
                    if (null == list)
                    {
                        continue;
                    }
                    if (!allItemTitles.ContainsKey(list.Title))
                    {
                        allItemTitles.Add(list.Title, new List<string>());
                    }
                    SPListItemCollection allItems = list.Items;
                    foreach (SPListItem item in allItems)
                    {
                        allItemTitles[list.Title].Add(item.Title);
                    }
                }


            }
            catch (Exception ex)
            {
                this.Controls.Add(new LiteralControl(ex.Message));
            }
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            base.RenderContents(writer);
            foreach (var list in allItemTitles)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Ul);
                writer.Write(list.Key);
                foreach (var title in list.Value)
                {
                    writer.RenderBeginTag(HtmlTextWriterTag.Li);
                    writer.Write(title);
                    writer.RenderEndTag();
                }
                writer.RenderEndTag();
            }
        }

        public override EditorPartCollection CreateEditorParts()
        {
            List<EditorPart> editors = new List<EditorPart>();
            DisplayListsEditorPart editor = new DisplayListsEditorPart();
            editor.ID = this.ID + "_DisplayListsEditorPart";
            editor.Title = "Display Lists EditorPart";
            editors.Add(editor);

            return new EditorPartCollection(base.CreateEditorParts(), editors);
        }

    }
}
----------------------------------------------------------------------------------------
The below is the code for custom editor part
---------------------------------------------------------------------------------------

using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;


namespace DemoEditorParts
{
    public class DisplayListsEditorPart : EditorPart
    {
        private ListBox drpLists;

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            drpLists = new ListBox();
            drpLists.SelectionMode = ListSelectionMode.Multiple;
            drpLists.ToolTip = "All Lists";

            SPWeb currentWeb = SPContext.Current.Web;
            SPListCollection allLists = currentWeb.Lists;

            foreach (SPList list in allLists)
            {
                drpLists.Items.Add(new ListItem()
                {
                    Text = list.Title,
                    Value = list.ID.ToString()
                });
            }
            this.Controls.Add(drpLists);
        }

        public override bool ApplyChanges()
        {
            EnsureChildControls();
            DisplayMultipleItems.DisplayMultipleItems webpart
                = this.WebPartToEdit as DisplayMultipleItems.DisplayMultipleItems;

            ListItemCollection drpItems = drpLists.Items;
            List<string> selectedItems = new List<string>();
            foreach (ListItem item in drpItems)
            {
                if (item.Selected)
                {
                    selectedItems.Add(item.Value);
                }
            }
            webpart.ListIDs = selectedItems;
            return true;
        }
        public override void SyncChanges()
        {
            EnsureChildControls();
            DisplayMultipleItems.DisplayMultipleItems webpart
               = this.WebPartToEdit as DisplayMultipleItems.DisplayMultipleItems;
            List<string> lists = webpart.ListIDs;
            if (null == drpLists)
            {
                return;
            }
            ListItemCollection drpItems = drpLists.Items;
            if (null == lists)
            {
                return;
            }
            foreach (var list in lists)
            {
                ListItem drpItem =
                    drpItems.FindByValue(list);
                if (null == drpItem)
                {
                    continue;
                }
                drpItem.Selected = true;
            }
        }
    }
}

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




Friday, June 20, 2014

SharePoint FAQs - Part1 - Append your answers here

1)      What is SharePoint?
2)      What is List?
3)      What is Content type?
4)      What is ListItem?
5)      Difference between listitem and content type
6)      Difference between list and library
7)      Pros and Cons of storing data in table vs list
8)      Item.update() vs item.SystemUpdate()
9)      SPSecurity.RunWithElewatedPriveleges(); code block runs with user account
10)   When do you dispose objects for SPSite? Or new SPSite() vs SPContext.Current.Site
11)   What are the different types of Event receivers?
12)   What are features and their scopes?
13)   What are master pages, page layouts?
14)   Difference between Site pages and Application pages
15)   What is Event bubbling?
16)   How to redirect to error page from Event receiver?
17)   Differences in execution of Synchronous and Asynchronous events
18)   How to cancel and event in event receiver?
19)   In which process does timer jobs execute?
20)   How to enable debugging in web.config? How to debug farm solutions?
21)   What is worker process? How to know worker process corresponding to SharePoint Web application?
22)   What are service applications?
23)   What are Custom actions in SharePoint?
24)   What are Sandboxed solutions and how to debug them?
25)   What are full trust proxies or Hybrid solutions and how to debug them?
26)   Differences between farm solutions and sandboxed solutions?
27)   What is Claims authentication?
28)   What is Forms Based Authentication? What is the difference between MOSS 2007 and SP 2010 in configuring FBA?
29)   What is the difference between classic mode and claims mode authentication?
30)   Difference between NTLM and Kerberos authentication?
31)   Can we send email in Sandboxed solutions? Limitations of Sandboxed solutions.
32)   What is client object model and its types?
33)   Difference between Load and LoadQuery in Client object model?
34)   Explain the Information Architecture?

35)   How do you deploy the SharePoint solutions?

Thursday, June 19, 2014

Developer DashBoard SharePoint 2010 and SharePoint 2013

There are three Modes for developer dashboard (DD)
On: Means the dashboard starts collecting the statistics and the same is displayed at the bottom of the page(for SharePoint 2010)
Off (default): No statistics are collected
OnDemand: An icon is displayed at the top right corner of the page. On clicking the icon, the statistics are shown at the bottom of the page (for SharePoint 2010) or in a new window(for SharePoint 2013)

Different ways you can configure the DD

Powershell
$dd = [Microsoft.SharePoint.Administration.SPWebService]::ContentService.DeveloperDashboardSettings
$
dd.DisplayLevel = 'OnDemand'
$
dd.TraceEnabled = $true
$
dd.Update()
Stsadm
stsadm -o setproperty -pn developer-dashboard -pv On
Object Model

SPPerformanceMonitor pm = SPFarm.Local.PerformanceMonitor;
pm.DeveloperDashboardLevel = SPPerformanceMonitoringLevel.Off;
pm.Update()

Saturday, June 14, 2014

Client object model operations in SharePoint 2013

Client object model operations in SharePoint 2013

The below console application example shows common Client object model operations in SharePoint 2013

using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoClientObjModelSol
{
    class Program
    {
        static void Main(string[] args)
        {
            //DisplayListItems();
            //AddList();
            //AddFields();
            AddSubSite();
            Console.ReadLine();
        }
        private static void DisplayListItems()
        {
            try
            {
                using (ClientContext ctx = new ClientContext(@"<<siteUrl>>"))
                {
                    ctx.AuthenticationMode = ClientAuthenticationMode.Default;
                    //ctx.Credentials = System.Net.CredentialCache.DefaultCredentials;
                    //ctx.Credentials = new System.Net.NetworkCredential()
                    Web web = ctx.Web;
                    ctx.Load(web);

                    ctx.ExecuteQuery();

                    Console.WriteLine(web.Title + " URL: " + web.Url);

                    List empList = web.Lists.GetByTitle("DemoCustomList");

                    ListItemCreationInformation itemInfo = new ListItemCreationInformation();
                    ListItem newItem = empList.AddItem(itemInfo);
                    newItem["Title"] = "sample123";
                    newItem["DemoSiteCol1"] = "sampleDemoSiteCol1123412";
                    newItem["DemoSiteCol2"] = "DemoSiteCol2Choice4";
                    newItem.Update();
                    ctx.ExecuteQuery();


                    ListItemCollection itemColl = empList.GetItems(new CamlQuery()
                    {
                        ViewXml = "<View></View>"
                    });

                    ctx.Load(itemColl);
                    ctx.ExecuteQuery();

                    if (null == itemColl)
                    {
                        return;
                    }
                    foreach (ListItem item in itemColl)
                    {
                        Console.WriteLine(item["Title"]);
                    }

                }

            }
            catch (ClientRequestException spe)
            {
                Console.WriteLine(spe.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        private static void AddList()
        {

            try
            {
                using (ClientContext ctx = new ClientContext(@"<<siteUrl>>"))
                {
                    ctx.AuthenticationMode = ClientAuthenticationMode.Default;
                    //ctx.Credentials = System.Net.CredentialCache.DefaultCredentials;
                    //ctx.Credentials = new System.Net.NetworkCredential()
                    Web web = ctx.Web;
                    ctx.Load(web);

                    ctx.ExecuteQuery();

                    ListCreationInformation listInfo = new ListCreationInformation();
                    listInfo.Title = "DemoClientList";
                    listInfo.TemplateType = (int)ListTemplateType.GenericList;
                    List custList = web.Lists.Add(listInfo);
                    custList.EnableVersioning = true;
                    custList.Update();
                    ctx.ExecuteQuery();



                }
            }
            catch (ClientRequestException ce)
            {

                Console.WriteLine(ce.Message);
            }
        }
        private static void AddFields()
        {
            try
            {
                using (ClientContext ctx = new ClientContext(@"<<siteUrl>>"))
                {
                    ctx.AuthenticationMode = ClientAuthenticationMode.Default;
                    //ctx.Credentials = System.Net.CredentialCache.De;
                    //ctx.Credentials = new System.Net.NetworkCredential()
                    Web web = ctx.Web;
                    ctx.Load(web);

                    ctx.ExecuteQuery();

                    List empList = web.Lists.GetByTitle("DemoCustomList");
                    Field demoField = empList.Fields.AddFieldAsXml(@"<Field DisplayName='DemoSiteCol123' Type='Text'
Required='FALSE'
Name='DemoSiteCol1' />", true, AddFieldOptions.AddToAllContentTypes);

                    ctx.ExecuteQuery();


                }
            }
            catch (ClientRequestException ce)
            {

                Console.WriteLine(ce.Message);
            }
        }

        private static void AddSubSite()
        {
            try
            {
                using (ClientContext ctx = new ClientContext(@"<<siteUrl>>"))
                {
                    ctx.AuthenticationMode = ClientAuthenticationMode.Default;
                    //ctx.Credentials = System.Net.CredentialCache.De;
                    //ctx.Credentials = new System.Net.NetworkCredential()
                    Web web = ctx.Web;
                    WebCreationInformation webInfo = new WebCreationInformation();
                    webInfo.Title = "DemoSubSite";
                    webInfo.WebTemplate = "STS#1";
                    webInfo.Url = "DemoSubSite";

                    Web newWeb = web.Webs.Add(webInfo);
                    ctx.ExecuteQuery();
                }
            }
            catch (ClientRequestException ce)
            {

                Console.WriteLine(ce.Message);
            }
        }
    }
}

Using Server object model SharePoint 2013

The below console application shows the common operations using the SharePoint 2013 Server object model.


using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            //DisplayListItems();
            //DisplayItemById(1);
            //QueryList();
            //CreateList();
            //DisplayPagesLib();
            //AddListFields();
            //AddSiteContentType();
            //AddView();
            AddListItem();
            Console.ReadLine();
        }
        private static void DisplayListItems()
        {
            try
            {
                using (SPSite site = new SPSite(@"<<siteUrl>>"))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList empList = web.GetList("/Lists/EmpInfo");
                        SPListItemCollection items = empList.Items;
                        if (null == items)
                        {
                            return;
                        }
                        foreach (SPListItem item in items)
                        {
                            Console.WriteLine(item.Title);
                        }

                    }
                }

            }
            catch (SPException spe)
            {
                Console.WriteLine(spe.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        private static void DisplayItemById(int id)
        {
            try
            {
                using (SPSite site = new SPSite(@"<<siteUrl>>"))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList empList = web.GetList("/Lists/EmpInfo");
                        SPListItem item = empList.GetItemById(id);
                        if (null == item)
                        {
                            Console.WriteLine("Item with this id: {0} doesn't exists", id);
                            return;
                        }
                        Console.WriteLine(item.Title);
                        Console.WriteLine(item["EmpFirstName"]);
                        Console.WriteLine(item.ID);
                        Console.WriteLine(item["EmpLastName"]);
                    }
                }

            }
            catch (SPException spe)
            {
                Console.WriteLine(spe.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        private static void QueryList()
        {
            try
            {
                using (SPSite site = new SPSite(@"<<siteUrl>>"))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList empList = web.GetList("/Lists/EmpInfo");
                        SPQuery query = new SPQuery();
                        query.RowLimit = 100;
                        query.Query = "<Where><Or><Eq><FieldRef Name='ID' /><Value Type='Counter'>1</Value></Eq><Eq><FieldRef Name='ID' /><Value Type='Counter'>2</Value></Eq></Or></Where>";
                        SPListItemCollection items = empList.GetItems(query);
                        foreach (SPListItem item in items)
                        {
                            Console.WriteLine("item : " + item.ID);
                            Console.WriteLine(item.Title);
                            Console.WriteLine(item["EmpFirstName"]);
                            Console.WriteLine(item["EmpLastName"]);
                        }

                    }
                }

            }
            catch (SPException spe)
            {
                Console.WriteLine(spe.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        private static void CreateList()
        {
            try
            {
                using (SPSite site = new SPSite(@"<<siteUrl>>"))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        Guid listId = web.Lists.Add("DemoCustomList", "DemoCustomList", SPListTemplateType.GenericList);
                        SPList list = web.Lists[listId];
                        list.ContentTypesEnabled = true;

                        list.EnableAttachments = false;
                        list.EnableVersioning = true;
                        list.Update();


                    }
                }
            }
            catch (Exception ex) { }
        }
        private static void AddListFields()
        {
            try
            {
                using (SPSite site = new SPSite(@"<<siteUrl>>"))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList demoList = web.GetList("/Lists/DemoCustomList");
                        //demoList.Fields.Add("DemoCol", SPFieldType.Text, false);
                        //demoList.Fields.Add("DemoChoice", SPFieldType.Choice, false);
                        //SPFieldChoice choiceField = demoList.Fields["DemoChoice"] as SPFieldChoice;
                        //choiceField.AddChoice("DemoChoice1");
                        //choiceField.AddChoice("DemoChoice2");
                        //choiceField.AddChoice("DemoChoice3");
                        //choiceField.AddChoice("DemoChoice4");
                        //choiceField.Update();
                        Guid empInfoListId = web.GetList("/Lists/Empinfo").ID;
                        demoList.Fields.AddLookup("DemoLkpCol", empInfoListId, false);

                        SPFieldLookup lkpDemoLookup = demoList.Fields["DemoLkpCol"] as SPFieldLookup;
                        lkpDemoLookup.LookupField = "Title";
                        lkpDemoLookup.Update();


                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }
        private static void DisplayPagesLib()
        {
            try
            {
                using (SPSite site = new SPSite(@"<<siteUrl>>"))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPDocumentLibrary pagesLib = web.GetList("/Pages") as SPDocumentLibrary;
                        SPListItemCollection pagesColl = pagesLib.Items;
                        foreach (SPListItem item in pagesColl)
                        {
                            Console.WriteLine("Title: " + item.Title + "           Url: " + SPUrlUtility.CombineUrl(web.Url, item.Url));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private static void AddSiteContentType()
        {
            try
            {
                using (SPSite site = new SPSite(@"<<siteUrl>>"))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        //web.Fields.Add("DemoSiteCol1", SPFieldType.Text, false);
                        //StringCollection choiceColl = new StringCollection();
                        //choiceColl.Add("DemoSiteCol2Choice1");
                        //choiceColl.Add("DemoSiteCol2Choice2");
                        //choiceColl.Add("DemoSiteCol2Choice3");
                        //choiceColl.Add("DemoSiteCol2Choice4");
                        //web.Fields.Add("DemoSiteCol2", SPFieldType.Choice, false, false, choiceColl);

                        //SPField demoCol1 = web.Fields["DemoSiteCol1"];
                        //SPField demoCol2 = web.Fields["DemoSiteCol2"];
                        //SPContentType itemCT = web.ContentTypes["Item"];
                        //SPContentType demoCt = new SPContentType(itemCT, web.ContentTypes, "DemoCT1");
                        //web.ContentTypes.Add(demoCt);


                        //SPField field1 = web.Fields["DemoSiteCol1"];
                        //SPField field2 = web.Fields["DemoSiteCol2"];

                        //SPFieldLink link1 = new SPFieldLink(field1);
                        //SPFieldLink link2 = new SPFieldLink(field2);

                        //SPContentType demoCT1 = web.ContentTypes["DemoCT1"];
                        //demoCT1.FieldLinks.Add(link1);
                        //demoCT1.FieldLinks.Add(link2);
                        //demoCT1.Update();


                        SPContentType demoSiteCT = web.ContentTypes["DemoCT1"];

                        SPList demoList = web.GetList("/Lists/DemoCustomList");
                        demoList.ContentTypes.Add(demoSiteCT);
                        demoList.Update();

                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        private static void AddView()
        {
            try
            {

                using (SPSite site = new SPSite(@"<<siteUrl>>"))
                {
                    using (SPWeb web = site.OpenWeb())
                    {


                        SPList demoList = web.GetList("/Lists/DemoCustomList");
                        //StringCollection viewFields = new StringCollection();
                        //viewFields.Add("DemoSiteCol1");
                        //viewFields.Add("DemoSiteCol2");
                        //viewFields.Add("Title");
                        //viewFields.Add("ID");
                        //SPView view = demoList.Views.Add("Demoview", viewFields, "", 30, true, true);

                        SPView demoView = demoList.Views["Demoview"];
                        demoView.Query = "<OrderBy><FieldRef Name='DemoSiteCol1' /></OrderBy>";
                        demoView.Update();

                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private static void AddListItem()
        {
            try
            {

                using (SPSite site = new SPSite(@"<<siteUrl>>"))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList demoList = web.GetList("/Lists/DemoCustomList");
                    SPListItem item= demoList.Items.Add();
                    item["Title"] = "demo123";
                    item["DemoSiteCol1"] = "DemoSiteCol1123412";
                    item["DemoSiteCol2"] = "DemoSiteCol2Choice4";
                    item.Update();

                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}