Friday, August 10, 2012

SharePoint: Visual Web Part(Any Web Part) with CSOM code on Sandbox Solution.

If you are initializing Web or Site object with URL and target deployment type is Sandbox, You will get below error.

Web Part Error: Unhandled exception was thrown by the sandboxed code wrapper's Execute method in the partial trust app domain: An unexpected error has occurred.

If you want to resolve this issue, change deployment type from Sandbox to Farm.




Tuesday, July 31, 2012

SharePoint: Add Navigation Node using CSOM

Client side object model can update navigation node remotely.  Below is code to add element to top navigation.

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

namespace NavigationCustomAction
{
    class Program
    {
        static void Main(string[] args)
        {
            ClientContext context = new ClientContext("http://goazrapp18:33369");
            Web web = context.Web;
            AddNavigationItem(context, web);


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

        private static void AddNavigationItem(ClientContext context, Web web)
        {
            NavigationNodeCreationInformation navigationNodeCreationInformation = new NavigationNodeCreationInformation();
            navigationNodeCreationInformation.Title = "Custom Node";
            navigationNodeCreationInformation.Url = "http://gooogle.com";
            navigationNodeCreationInformation.IsExternal = true;
            navigationNodeCreationInformation.AsLastNode = true;
            web.Navigation.TopNavigationBar.Add(navigationNodeCreationInformation);
            web.Update();
            context.ExecuteQuery();
            Console.WriteLine("Node created Successfully");
        }
    }
}


If you want to add to Quick Launch bar, you have to update one line as below.

web.Navigation.QuickLaunch.Add(navigationNodeCreationInformation);

This will add element at Quick Launch bar as well.




Monday, July 30, 2012

SharePoint: Client Side Object Model Part - III

List Class defines all list related methods.

Program.cs File

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


namespace ConsoleCSOM
{
    class Program
    {
        static void Main(string[] args)
        {
            ClientContext context = new ClientContext("http://goazrapp18:33369");
            Web web = context.Web;

            //Web Operations
            WebMethods(context, web);

            //List Operations
            //ListMethods(context, web);

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

        private static void ListMethods(ClientContext context, Web web)
        {
            //Get all Lists
            ListOperation.GetLists(context, web);

            //Create List
            ListOperation.CreateList(context, web);


            //Add List Field
            context = new ClientContext("http://goazrapp18:33369");
            web = context.Web;
            ListOperation.AddField(context, web);


            //Add List Item
            context = new ClientContext("http://goazrapp18:33369");
            web = context.Web;
            ListOperation.AddListItem(context, web);

            //Get List Items
            ListOperation.GetListItems(context, web);

            //Update List Item
            ListOperation.ListItemUpdate(context, web);

            //Delete List Item
            ListOperation.DeleteItem(context, web);
        }

        private static void WebMethods(ClientContext context, Web web)
        {
            //Get Title and Description
            WebOperation.GetTitle(context, web);


            //Update Title and Description
            WebOperation.UpdateTitle(context, web);

            //Delete Existing Web
            WebOperation.DeleteWeb(context, web);

            //Create New Web
            WebOperation.CreateWeb(context);
        }
    }
}

ListOperation.cs File

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



namespace ConsoleCSOM
{
    public static class ListOperation
    {
        public static void DeleteItem(ClientContext context, Web web)
        {

            List testList = web.Lists.GetByTitle("Test List");
            ListItem item = testList.GetItemById(1);
            item.DeleteObject();
            context.ExecuteQuery();
            Console.WriteLine("Item Deleted");
        }

        public static void ListItemUpdate(ClientContext context, Web web)
        {
            List testList = web.Lists.GetByTitle("Test List");
            ListItem item = testList.GetItemById(1);
            item["Body"] = "My Body Update on " + DateTime.Now;
            item.Update();
            context.ExecuteQuery();
            Console.WriteLine("Item Updated");
        }

        public static void GetListItems(ClientContext context, Web web)
        {
            List testList = web.Lists.GetByTitle("Test List");
            CamlQuery query = CamlQuery.CreateAllItemsQuery();
            ListItemCollection items = testList.GetItems(query);
            context.Load(items);
            context.ExecuteQuery();

            foreach (ListItem item in items)
                Console.WriteLine("Item Title is " + item["Title"]);
        }

        public static void AddListItem(ClientContext context, Web web)
        {
            List testList = web.Lists.GetByTitle("Test List");
            ListItemCreationInformation listItemCreationInformation = new ListItemCreationInformation();
            ListItem item = testList.AddItem(listItemCreationInformation);
            item["Title"] = "Item Create on " + DateTime.Now;
            item["CustomField"] = 25;
            item.Update();
            context.ExecuteQuery();
            Console.WriteLine("Item Created");
        }

        public static void AddField(ClientContext context, Web web)
        {
            List list = context.Web.Lists.GetByTitle("Test List");
            Field field = list.Fields.AddFieldAsXml("", true, AddFieldOptions.DefaultValue);
            FieldNumber fldNumber = context.CastTo(field);
            fldNumber.MaximumValue = 100;
            fldNumber.MinimumValue = 20;
            fldNumber.Update();
            context.ExecuteQuery();
            Console.WriteLine("List Field Created");

        }

        public static void CreateList(ClientContext context, Web web)
        {
            ListCreationInformation lCreationInfo = new ListCreationInformation();
            lCreationInfo.Title = "Test List";
            lCreationInfo.TemplateType = (int)ListTemplateType.Announcements;
            List wList = web.Lists.Add(lCreationInfo);
            wList.Description = "Test List Description";
            wList.Update();
            context.ExecuteQuery();
            Console.WriteLine("List " + wList.Title + " Created");
        }

        public static void GetLists(ClientContext context, Web web)
        {
            context.Load(web.Lists, lists => lists.Include(list => list.Title, list => list.Id));
            context.ExecuteQuery();
            string temp = string.Empty;
            foreach (List list in web.Lists)
                temp += list.Title + ", ";
            Console.WriteLine("List Name are " + temp);

            //Delete List
            List dList = web.Lists.GetByTitle("Test List");
            dList.DeleteObject();
            context.ExecuteQuery();
            Console.WriteLine("Test List deleted");
        }
    }
}

WebOperation.cs File 

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


namespace ConsoleCSOM
{
    public class WebOperation
    {

        public static void CreateWeb(ClientContext context)
        {
            WebCreationInformation creation = new WebCreationInformation();
            creation.Url = "web1";
            creation.Title = "Web 1";
            creation.Description = " Web 1 Descroption";
            Web newWeb = context.Web.Webs.Add(creation);
            context.ExecuteQuery();
            Console.WriteLine("Web 1 created");
        }

        public static void DeleteWeb(ClientContext context, Web web)
        {
            context.Load(web.Webs, webs => webs.Include(tWeb => tWeb.Title));
            context.ExecuteQuery();
            foreach (Web tWeb in web.Webs)
                if (tWeb.Title == "Web 1")
                {
                    tWeb.DeleteObject();
                    context.ExecuteQuery();
                    Console.WriteLine("Web 1 deleted");
                }
        }

        public static void UpdateTitle(ClientContext context, Web web)
        {
            web.Title = "New Team Site " + DateTime.Now;
            web.Description = "Team Site Description " + DateTime.Now;
            web.Update();
            context.ExecuteQuery();
            Console.WriteLine(web.Title);
            Console.WriteLine(web.Description);
        }

        public static void GetTitle(ClientContext context, Web web)
        {
            context.Load(web, w => w.Title, w => w.Description);
            context.ExecuteQuery();
            Console.WriteLine(web.Title);
            Console.WriteLine(web.Description);
        }
    }
}




Saturday, July 7, 2012

SharePoint: Client Side Object Model Part - II

Let's start with Modules. Web Class defines all web related methods.

Program.cs file

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

namespace ConsoleCSOM
{
    class Program
    {
        static void Main(string[] args)
        {
            ClientContext context = new ClientContext("http://goazrapp18:33369");
            Web web = context.Web;

            //Web Operations
            WebMethods(context, web);

            //List Operations
            ListMethods(context, web);

            Console.WriteLine("Please press any key to exit");
            Console.ReadLine();
        }
 private static void WebMethods(ClientContext context, Web web)
        {
            //Get Title and Description
            WebOperation.GetTitle(context, web);


            //Update Title and Description
            WebOperation.UpdateTitle(context, web);

            //Delete Existing Web
            WebOperation.DeleteWeb(context, web);

            //Create New Web
            WebOperation.CreateWeb(context);
        }
    }
}

WebOperation.cs File


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


namespace ConsoleCSOM
{
    public class WebOperation
    {

        public static void CreateWeb(ClientContext context)
        {
            WebCreationInformation creation = new WebCreationInformation();
            creation.Url = "web1";
            creation.Title = "Web 1";
            creation.Description = " Web 1 Descroption";
            Web newWeb = context.Web.Webs.Add(creation);
            context.ExecuteQuery();
            Console.WriteLine("Web 1 created");
        }

        public static void DeleteWeb(ClientContext context, Web web)
        {
            context.Load(web.Webs, webs => webs.Include(tWeb => tWeb.Title));
            context.ExecuteQuery();
            foreach (Web tWeb in web.Webs)
                if (tWeb.Title == "Web 1")
                {
                    tWeb.DeleteObject();
                    context.ExecuteQuery();
                    Console.WriteLine("Web 1 deleted");
                }
        }

        public static void UpdateTitle(ClientContext context, Web web)
        {
            web.Title = "New Team Site " + DateTime.Now;
            web.Description = "Team Site Description " + DateTime.Now;
            web.Update();
            context.ExecuteQuery();
            Console.WriteLine(web.Title);
            Console.WriteLine(web.Description);
        }

        public static void GetTitle(ClientContext context, Web web)
        {
            context.Load(web, w => w.Title, w => w.Description);
            context.ExecuteQuery();
            Console.WriteLine(web.Title);
            Console.WriteLine(web.Description);
        }
    }
}


Output :


Friday, June 29, 2012

SharePoint: Client Side Object Model Part - I

This example will explain you about very general operation using CSOM

            ClientContext context = new ClientContext("http://goazrapp18:33369");
         
            //Get Title and Description
            Web web = context.Web;
            context.Load(web, w => w.Title, w=>w.Description);
            context.ExecuteQuery();
            Console.WriteLine(web.Title);
            Console.WriteLine(web.Description);
         
            //Update Title and Description
            web.Title = "New Team Site "+ DateTime.Now;
            web.Description = "Team Site Description " + DateTime.Now;
            web.Update();
            context.ExecuteQuery();
            Console.WriteLine(web.Title);
            Console.WriteLine(web.Description);

            //Delete Existing Web
            context.Load(web.Webs, webs => webs.Include(tWeb => tWeb.Title));
            context.ExecuteQuery();
            foreach (Web tWeb in web.Webs)
                if (tWeb.Title == "Web 1")
                {
                    tWeb.DeleteObject();
                    context.ExecuteQuery();
                    Console.WriteLine("Web 1 deleted");
                }

            //Create New Web
            WebCreationInformation creation = new WebCreationInformation();
            creation.Url = "web1";
            creation.Title = "Web 1";
            creation.Description = " Web 1 Descroption";
            Web newWeb = context.Web.Webs.Add(creation);
            context.ExecuteQuery();
            Console.WriteLine("Web 1 created");

            //Get all Lists
            context.Load(web.Lists, lists => lists.Include(list => list.Title, list => list.Id));
            context.ExecuteQuery();
            string temp = string.Empty;
            foreach (List list in web.Lists)
                temp += list.Title +", ";
            Console.WriteLine("List Name are " + temp);

            //Delete List
            List dList = web.Lists.GetByTitle("Test List");
            dList.DeleteObject();
            context.ExecuteQuery();
            Console.WriteLine("Test List deleted");

            //Create List
            ListCreationInformation lCreationInfo = new ListCreationInformation();
            lCreationInfo.Title = "Test List";
            lCreationInfo.TemplateType = (int)ListTemplateType.Announcements;
            List wList = web.Lists.Add(lCreationInfo);
            wList.Description = "Test List Description";
            wList.Update();
            context.ExecuteQuery();
            Console.WriteLine("List " + wList.Title + " Created");
         
            Console.WriteLine("Please press any key to exit");
            Console.ReadLine();


Output:



Wednesday, June 27, 2012

SharePoint Client Object Model with Lambda Expressions - Part III

You will learn how to use IEnumerable with LoadQuery in Lambda Expressions.


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


namespace ClientSideConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var context = new ClientContext(@"http://localhost:22266");
            var web = context.Web;
            var lists = web.Lists;
            IEnumerable genericLists = context.LoadQuery(lists.Where
                        (list => list.BaseType == BaseType.GenericList));
             
            context.ExecuteQuery();
            foreach (var list in genericLists)
            {
                Console.WriteLine(list.Title);
            }
            Console.ReadLine();
        }
    }
}

Saturday, June 23, 2012

SharePoint Client Object Model with Lambda Expressions - Part II

In Part - II, You will learn how to filter query in Lambda Expressions.



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


namespace ClientSideConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var context = new ClientContext(@"http://localhost:22266");
            var web = context.Web;
            var lists = web.Lists;
            context.Load(lists,
                lx => lx.Include
                    (list => list.Title).Where
                        (list => list.BaseType == BaseType.GenericList));
             
            context.ExecuteQuery();
            foreach (var list in lists)
            {
                Console.WriteLine(list.Title);
            }
            Console.ReadLine();


        }
    }
}

Friday, June 22, 2012

SharePoint Client Object Model with Lambda Expressions - Part I

How to use Client Object Model with Lambda Expressions.

First we have to add given references to project.

Microsoft.SharePoint.Client
Microsoft.SharePoint.Client.Runtime




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


namespace ClientSideConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var context = new ClientContext(@"http://localhost:22266");
            var web = context.Web;
            context.Load(web, x => x.Title, x => x.Description);
            context.ExecuteQuery();
            Console.WriteLine(web.Title);
            Console.WriteLine(web.Description);

            Console.ReadLine();


        }
    }
}


Above code loads only title and description for given web.

Sunday, June 17, 2012

SharePoint Feature Activation/Deactivation Tool

You can activate/deactivate feature for whole web application. Feature can be Site or Web level. Here is the configuration settings for that tool

Console Application Code : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.SharePoint;
using System.Configuration;
using Microsoft.SharePoint.Administration;

namespace FeatureActivation
{
    class Program
    {
        private static StreamWriter logWriter;
        private static Guid FeatureGUID;

        static void Main(string[] args)
        {
            logWriter = new StreamWriter("FeatureActivationLog.txt");
            string strWebApplicationName = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["WebApplicationName"]);
            FeatureGUID = new Guid(Convert.ToString(ConfigurationManager.AppSettings["FeatureID"]));
            string strDeploymentType = Convert.ToString(ConfigurationManager.AppSettings["DeploymentType"]);
            string strFeatureType = Convert.ToString(ConfigurationManager.AppSettings["FeatureType"]);
            int siteCollectionCount = 0;
            int siteCount = 0;
            int webCount = 0;
            DateTime startTime;
            DateTime endTime;
            if (string.IsNullOrEmpty(strWebApplicationName))
            {
                Console.WriteLine("Configuration Error");
                Console.WriteLine("Press enter to continue...");
                Console.ReadLine();
            }
            else
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {

                    if (strDeploymentType.ToLower() == "deploy")
                    {
                        if (!IsFeatureInstall())
                        {
                            Console.WriteLine("Feature is not installed");
                            logWriter.WriteLine("Feature is not installed");
                            logWriter.WriteLine("==========================================================================");
                            return;
                        }
                    }
                    if (strFeatureType.ToLower() == "site")
                    {
                        using (SPSite objSite = new SPSite(strWebApplicationName))
                        {
                            SPSiteCollection objSiteCollection = objSite.WebApplication.Sites;
                            if (objSiteCollection != null && objSiteCollection.Count > 0)
                            {
                                startTime = DateTime.Now;
                                foreach (SPSite objTempSite in objSiteCollection)
                                {
                                    siteCollectionCount++;
                                    try
                                    {
                                        if (strDeploymentType.ToLower() == "deploy")
                                        {
                                            
                                                ActivateSiteFeature(objTempSite);
                                                Console.WriteLine("Activate feature for " + objTempSite.Url);
                                                logWriter.WriteLine("Activate feature for " + objTempSite.Url);
                                                logWriter.WriteLine("==========================================================================");
                                            
                                        }
                                        else if (strDeploymentType.ToLower() == "rollback")
                                        {
                                            

                                                DeactivateSiteFeature(objTempSite);
                                                Console.WriteLine("Deactivate feature for " + objTempSite.Url);
                                                logWriter.WriteLine("Deactivate feature for " + objTempSite.Url);
                                                logWriter.WriteLine("==========================================================================");


                                            
                                        }
                                        else
                                        {
                                            logWriter.WriteLine("Unknown Deployment Type");
                                            logWriter.WriteLine("==========================================================================");
                                            Console.WriteLine("Unknown Deployment Type");
                                        }

                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine("Error : Resetting feature for " + objTempSite.Url);
                                        logWriter.WriteLine("Error : Resetting feature for " + objTempSite.Url + " Error Message is " + ex.StackTrace, ex.Message, ex.InnerException, ex.Source);
                                        logWriter.WriteLine("==========================================================================");

                                    }


                                    objTempSite.Close();
                                }
                                endTime = DateTime.Now;
                                logWriter.WriteLine("**********************SUMMARY*****************************");
                                Console.WriteLine("Total Number Of SiteCollection for " + strWebApplicationName + " is " + siteCollectionCount);
                                logWriter.WriteLine("Total Number Of SiteCollection for " + strWebApplicationName + " is " + siteCollectionCount);

                                Console.WriteLine("Start Time Of " + strWebApplicationName + " is " + startTime.ToString());
                                logWriter.WriteLine("Start Time Of " + strWebApplicationName + " is " + startTime.ToString());

                                Console.WriteLine("End Time Of " + strWebApplicationName + " is " + endTime.ToString());
                                logWriter.WriteLine("End Time Of " + strWebApplicationName + " is " + endTime.ToString());
                                logWriter.Close();
                            }
                        }
                    }
                    else if (strFeatureType.ToLower() == "web")
                    {
                        using (SPSite objSite = new SPSite(strWebApplicationName))
                        {
                            SPSiteCollection objSiteCollection = objSite.WebApplication.Sites;
                            if (objSiteCollection != null && objSiteCollection.Count > 0)
                            {
                                startTime = DateTime.Now;
                                foreach (SPSite objTempSite in objSiteCollection)
                                {
                                    siteCollectionCount++;
                                    foreach (SPWeb objTempWeb in objTempSite.AllWebs)
                                    {
                                        webCount++;
                                        try
                                        {
                                            if (strDeploymentType.ToLower() == "deploy")
                                            {
                                                    ActivateWebFeature(objTempWeb);
                                                    Console.WriteLine("Activate feature for " + objTempWeb.Url);
                                                    logWriter.WriteLine("Activate feature for " + objTempWeb.Url);
                                                    logWriter.WriteLine("==========================================================================");
                                            }
                                            else if (strDeploymentType.ToLower() == "rollback")
                                            {
                                                    DeactivateWebFeature(objTempWeb);
                                                    Console.WriteLine("Deactivate feature for " + objTempWeb.Url);
                                                    logWriter.WriteLine("Deactivate feature for " + objTempWeb.Url);
                                                    logWriter.WriteLine("==========================================================================");

                                            }
                                            else
                                            {
                                                logWriter.WriteLine("Unknown Deployment Type");
                                                logWriter.WriteLine("==========================================================================");
                                                Console.WriteLine("Unknown Deployment Type");
                                            }

                                        }

                                        catch (Exception ex)
                                        {
                                            Console.WriteLine("Error : Resetting feature for " + objTempWeb.Url);
                                            logWriter.WriteLine("Error : Resetting feature for " + objTempWeb.Url + " Error Message is " + ex.StackTrace, ex.Message, ex.InnerException, ex.Source);
                                            logWriter.WriteLine("==========================================================================");

                                        }
                                        objTempWeb.Close();
                                    }

                                    objTempSite.Close();
                                }
                                endTime = DateTime.Now;

                                logWriter.WriteLine("**********************SUMMARY*****************************");
                                Console.WriteLine("Total Number Of SiteCollection for " + strWebApplicationName + " is " + siteCollectionCount);
                                logWriter.WriteLine("Total Number Of SiteCollection for " + strWebApplicationName + " is " + siteCollectionCount);

                                Console.WriteLine("Total Number Of Web for " + strWebApplicationName + " is " + webCount);
                                logWriter.WriteLine("Total Number Of Web for " + strWebApplicationName + " is " + webCount);

                                Console.WriteLine("Start Time Of " + strWebApplicationName + " is " + startTime.ToString());
                                logWriter.WriteLine("Start Time Of " + strWebApplicationName + " is " + startTime.ToString());

                                Console.WriteLine("End Time Of " + strWebApplicationName + " is " + endTime.ToString());
                                logWriter.WriteLine("End Time Of " + strWebApplicationName + " is " + endTime.ToString());
                                logWriter.Close();
                            }
                        }
                    }
                    else
                    {
                        logWriter.WriteLine("Unknown Feature Type");
                        logWriter.WriteLine("==========================================================================");
                        Console.WriteLine("Unknown Feature Type");
                    }
                });
                Console.WriteLine("Press enter to continue...");
                Console.ReadLine();
            }
        }

        private static bool IsFeatureInstall()
        {
            bool bFound = false;
            //Finds the feature definition.
            foreach (SPFeatureDefinition featureDef in SPFarm.Local.FeatureDefinitions)
            {
                try
                {
                    if (featureDef.Id.Equals(FeatureGUID))
                    {
                        bFound = true;
                        break;
                    }
                }
                catch (Exception ex)
                {
                    //This is failing if feature is installed and feature file is not there
                    //we have to ignore this exception
                }
            }
            return bFound;
        }

        private static void ActivateSiteFeature(SPSite objSite)
        {
            bool bActive = false;
            //Checks whether the user is activated already.
            foreach (SPFeature feature in objSite.Features)
            {
                if (feature.DefinitionId.Equals(FeatureGUID))
                {
                    bActive = true;
                    break;
                }
            }

            if (!bActive)
            {
                objSite.Features.Add(FeatureGUID);
            }
        }
        private static void DeactivateSiteFeature(SPSite objSite)
        {
            bool bActive = false;
            //Checks whether the user is activated already.
            foreach (SPFeature feature in objSite.Features)
            {
                if (feature.DefinitionId.Equals(FeatureGUID))
                {
                    bActive = true;
                    break;
                }
            }

            if (bActive)
            {
                objSite.Features.Remove(FeatureGUID);
            }
        }
        private static void ActivateWebFeature(SPWeb objWeb)
        {
            bool bActive = false;
            //Checks whether the user is activated already.
            foreach (SPFeature feature in objWeb.Features)
            {
                if (feature.DefinitionId.Equals(FeatureGUID))
                {
                    bActive = true;
                    break;
                }
            }

            if (!bActive)
            {
                objWeb.Features.Add(FeatureGUID);
            }
        }
        private static void DeactivateWebFeature(SPWeb objWeb)
        {
            bool bActive = false;
            //Checks whether the user is activated already.
            foreach (SPFeature feature in objWeb.Features)
            {
                if (feature.DefinitionId.Equals(FeatureGUID))
                {
                    bActive = true;
                    break;
                }
            }

            if (bActive)
            {
                objWeb.Features.Remove(FeatureGUID);
            }
        }

    }
}

Saturday, June 16, 2012

How to Override click event using jQuery


If let's say control has click event attached and you don't have code to change or override click event, here is the solution for that

OOB Code Snippet:

onclick="javascript:SelectUserImage()
;return false;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$PlaceHolderMain$ctl12", "", true, "", "", false, true))" type="button" value="Choose Picture"/>
Now if you want to override click event, use given code to achieve it.




It will only call our function (alert message only).

Wednesday, June 13, 2012

How to restrict photo size in My Site Edit Profile page



Here is the technical approach to achieve this functionality.

My Site’s Edit Profile page uploads photos to Picture Library under user’s My Site. Event Receiver will be developed and attached to that library. That Event Receiver will check configuration value from web configuration file and validate with picture’s size which user will upload. It will throw an exception if condition doesn’t match.

One Feature will be developed to attach event receiver for Picture Library and it will be activated when user creates My Site. One console application will developed to activate that feature for all existing My Sites.

JS code will be added to SelectPicture2.aspx page to convert SharePoint generic error with configured error message. This message will be configured in web configuration file. Select Picture page calls by Edit profile page to upload picture. 

Tuesday, June 5, 2012

SharePoint 2010 - Linq

If you want to use Linq in SharePoint, you have to generate class using SPMetal utility.
You have to provide some parameters to generate class file like web, namespace, class etc.



This command will generate class file for you and you have to attach to you project file.

You have to add reference from 14/ISAPI folder for Sharepoint.Linq dll.

Here is the simple code snippet to get List items.


using System.Linq;
using Microsoft.SharePoint.Linq;
using SP2010.Demo;


namespace SP2010.Demo.LinqWebPart
{
    [ToolboxItemAttribute(false)]
    public class LinqWebPart : WebPart
    {
        protected override void CreateChildControls()
        {
            using (var ctx = new LinqDemoDataContext(SPContext.Current.Web.Url))
            {
                var parentList = from pl in ctx.ParentList
                                 select new {pl.CustomerID,pl.Name };
                foreach(var p in parentList)
                {
                    Controls.Add(new LiteralControl(string.Format("{0},{1}
",p.CustomerID,p.Name)));
                }

            }
        }
    }
}






Friday, June 1, 2012

How to add Heading Sub Heading for SharePoint Navigation


SharePoint doesn't allow to add Sub Heading under Heading. Here is the code to achieve it.

SPNavigationNode oNewNode = new SPNavigationNode("Heading", "");
oWeb.Navigation.TopNavigationBar.AddAsLast(oNewNode);
oNewNode.Properties.Add("NodeType", "Heading");
oNewNode.Update();


SPNavigationNode oChild1 = new SPNavigationNode("SubHead1", "");
oNewNode.Children.AddAsFirst(oChild1);
oChild1.Properties.Add("NodeType", "Heading");
oChild1.Update();

SPNavigationNode oChild2 = new SPNavigationNode("SubHead2", "");
oNewNode.Children.Add(oChild2, oChild1);
oChild2.Properties.Add("NodeType", "Heading");
oChild2.Update();

SPNavigationNode oChild3 = new SPNavigationNode("SubHead3", "");
oNewNode.Children.Add(oChild3, oChild2);
oChild3.Properties.Add("NodeType", "Heading");
oChild3.Update();

Tuesday, May 8, 2012

SharePoint : How to edit DispForm.aspx

Here is how you enable it:


  1. Navigate to the page you want to add a web part to, e.g. a Content Editor Web part. 
  2. Remove everything on the URL after “?ID=#“
  3. Append the following to the end:  
           &PageView=Shared&ToolPaneView=2


That is it.

Wednesday, March 28, 2012

Percentage Complete Progress Bar

Percentage Complete Progress Bar can be done by various way. Below is more flexible interface for progress bar. It's web control which you can add it in master page or any page.

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Tittle
{
public class PercentageComplete : WebControl, INamingContainer
{
private string borderColor = "#547095";
private string borderType = "solid";
private string borderWidth = "1";
private string bgColor = "white";
private string controlWidth = "95%";
private string cellpadding = "0";
private string cellspacing = "0";
private string controlAlignment = "center";
private string fillColor = "#FF7979";
private string startColor = "#E5E5E5";
private string endColor = "#FF7979";
private bool gradientVertical = false;
private string textFontSize = "1";
private string textFontFamily = "verdana";
private string textFontColor = "#3D526D";
private bool textBold = false;
private decimal count = 0;
private string text = "";
private bool displayText = true;
private bool gradient = true;
private string remainingColor = "";

/// < summary>
/// Integer or decimal value, mandatory, which tells how much percentage is completed.
/// < /summary>
public decimal Count { set { count = value; } get { return count; } }
/// < summary>
/// You can override default percentage text with this.. e.g. if 19% is completed, then
/// it will show "19%" text in middle, but you change text to "2 of 10" something like this.
/// < /summary>
public string Text { set { text = value; } get { return text; } }
/// < summary>
/// By default it is true, set to false, and no text will be displayed in middle.
/// < /summary>
public bool DisplayText { set { displayText = value; } get { return displayText; } }
/// < summary>
/// Box Border Color, this can be overwritten by Remaining Color.
/// < /summary>
public string BgColor { set { bgColor = value; } get { return bgColor; } }
/// < summary>
/// Box Width (default 100%)
/// < /summary>
public string ControlWidth { set { controlWidth = value; } get { return controlWidth; } }
/// < summary>
/// Cellpadding of Table. default 0.
/// < /summary>
public string Cellpadding { set { cellpadding = value; } get { return cellpadding; } }
/// < summary>
/// Cellspacing of Table. default 0.
/// < /summary>
public string Cellspacing { set { cellspacing = value; } get { return cellspacing; } }
/// < summary>
/// Box Alignment in the container, by default center
/// < /summary>
public string ControlAlignment { set { controlAlignment = value; } get { return controlAlignment; } }
/// < summary>
/// Box Border Color (E.g. red,#c0c0c0)
/// < /summary>
public string BoxBorderColor { set { borderColor = value; } get { return borderColor; } }
/// < summary>
/// Box Border Type i.e. (solid, dashed, dotted, ridge, inset, outset)
/// < /summary>
public string BorderType { set { borderType = value; } get { return borderType; } }
/// < summary>
/// Box Border Width i.e. (0, 1, 2.. )
/// < /summary>
public string BoxBorderWidth { set { borderWidth = value; } get { return borderWidth; } }
/// < summary>
/// Percentage Completed Color.
/// < /summary>
public string FillColor { set { fillColor = value; } get { return fillColor; } }
/// < summary>
/// If percentage complete is 60%, then remaining 40% will have this color in background, no gradient supported for remaining color.
/// < /summary>
public string RemainingColor { set { remainingColor = value; } get { return remainingColor; } }
/// < summary>
/// By default gradient effect is true, set this to false, and fill color will take preference over startcolor and endcolor
/// < /summary>
public bool Gradient { set { gradient = value; } get { return gradient; } }
/// < summary>
/// By default gradient effect, and this is start color of gradient effect.
/// < /summary>
public string StartColor { set { startColor = value; } get { return startColor; } }
/// < summary>
/// By default gradient effect, and this is end color of gradient effect.
/// < /summary>
public string EndColor { set { endColor = value; } get { return endColor; } }
/// < summary>
/// By default gradient horizontal is true, you can set to to vertical instead of horizontal (default is false)
/// < /summary>
public bool GradientVertical { set { gradientVertical = value; } get { return gradientVertical; } }
/// < summary>
/// Font Size of Text displayed in middle.
/// < /summary>
public string TextFontSize { set { textFontSize = value; } get { return textFontSize; } }
/// < summary>
/// Font family/face of text displayed in middle.
/// < /summary>
public string TextFontFamily { set { textFontFamily = value; } get { return textFontFamily; } }
/// < summary>
/// Font color of text displayed in middle.
/// < /summary>
public string TextFontColor { set { textFontColor = value; } get { return textFontColor; } }
/// < summary>
/// Whether displayed text in middle should be bold or not. (default false)
/// < /summary>
public bool TextBold { set { textBold = value; } get { return textBold; } }


public PercentageComplete() : base()
{

}

protected override void Render(HtmlTextWriter output)
{
base.Render(output);
string s = " ";
s += "< table cellspacing='" + cellspacing + "' cellpadding='" + cellpadding + "' style='border:" + borderWidth + " " + borderType + " " + borderColor + ";background-color:" + bgColor +"' width='" + controlWidth + "' align='" + controlAlignment + "' >";
s += " < tr >";
s += " < td width='100%' style='background-color:"+remainingColor+"' >";
s += " < div style='position:absolute;background-color:" + fillColor + ";width:" + count + "%;";
if ( gradient == true )
{
s += " filter:progid:DXImageTransform.Microsoft.Gradient(GradientType=" + (gradientVertical==true?"1":"0") + ",StartColorStr=" + startColor + ", EndColorStr=" + endColor + ")";
}
s += " ;' align='center'>< font size='" + TextFontSize + "'> < /font>< /div> ";
string textPart=" ";
if ( displayText == true )
{
if ( text == "" )
textPart = count.ToString() + "%";
else
textPart = text;
}

s += " < div style='position:relative;width:100%' align='center' >< font " + (textBold==true?"style='font-weight:bold'":"") + " size='" + textFontSize + "' color='" + textFontColor + "' face='" + textFontFamily + "' >" + textPart + "< /font>< /div>";
s += " < /td>";
s += "< /tr>";
s += "< /table>";
output.Write(s);
}
}
}





how to use


< Controls:PercentageComplete id="PercentageComplete2" runat="server" Count="65" FillColor="#0099FF" Gradient="false" cellspacing="2" TextFontColor="#FF6600" TextBold="true" TextFontSize="2" RemainingColor="#ABD0BC" />
< Controls:PercentageComplete id="PercentageComplete1" runat="server" Count="79" Text="79% occupied" />
< Controls:PercentageComplete id="Percentagecomplete4" runat="server" Count="80" Text="8 of 10" StartColor="#6868B9" EndColor="#ABD0BC" BoxBorderColor="#FF6600" CellSpacing="0" TextFontFamily="Times New Roman" TextFontColor="White" TextFontSize="3" BorderType="double" BoxBorderWidth="3" />
< Controls:PercentageComplete id="Percentagecomplete3" runat="server" Count="55" StartColor="#B7B748" EndColor="#E5E5E5" BoxBorderColor="green" BgColor="#E5E5E5" BorderType="dotted" />
< Controls:PercentageComplete id="Percentagecomplete5" runat="server" Count="90" StartColor="#FF6600" EndColor="#0099FF" BoxBorderColor="Red" CellPadding="3" cellspacing="1" TextFontFamily="Verdana" TextBold="True" TextFontColor="#FF9999" TextFontSize="3" BorderType="inset" GradientVertical="True" BoxBorderWidth="1" />
< Controls:PercentageComplete id="Percentagecomplete6" runat="server" Count="45" StartColor="#99FF00" EndColor="#6600FF" BoxBorderColor="Red" CellPadding="4" BgColor="#E8E8FF" BorderType="dashed" TextFontFamily="Tahoma" TextFontColor="red" TextFontSize="2" />

Saturday, March 10, 2012

SharePoint - Feature Activation Tool

Here is sample code which will activate/deactivate site/web feature for whole web application

Configuration:


    < add key="WebApplicationName" value="{Web Application URL}" />
    < add key="DeploymentType" value="Deploy {or Rollback}" />
    < add key="FeatureID" value="{Feature Id}" />
    < add key="FeatureType" value="web{or Site}" />


Code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.SharePoint;
using System.Configuration;
using Microsoft.SharePoint.Administration;

namespace FeatureActivation
{
    class Program
    {
        private static StreamWriter logWriter;
        private static Guid FeatureGUID;

        static void Main(string[] args)
        {
            logWriter = new StreamWriter("FeatureActivationLog.txt");
            string strWebApplicationName = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["WebApplicationName"]);
            FeatureGUID = new Guid(Convert.ToString(ConfigurationManager.AppSettings["FeatureID"]));
            string strDeploymentType = Convert.ToString(ConfigurationManager.AppSettings["DeploymentType"]);
            string strFeatureType = Convert.ToString(ConfigurationManager.AppSettings["FeatureType"]);
            int siteCollectionCount = 0;
            int siteCount = 0;
            int webCount = 0;
            DateTime startTime;
            DateTime endTime;
            if (string.IsNullOrEmpty(strWebApplicationName))
            {
                Console.WriteLine("Configuration Error");
                Console.WriteLine("Press enter to continue...");
                Console.ReadLine();
            }
            else
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {

                    if (strDeploymentType.ToLower() == "deploy")
                    {
                        if (!IsFeatureInstall())
                        {
                            Console.WriteLine("Feature is not installed");
                            logWriter.WriteLine("Feature is not installed");
                            logWriter.WriteLine("==========================================================================");
                            return;
                        }
                    }
                    if (strFeatureType.ToLower() == "site")
                    {
                        using (SPSite objSite = new SPSite(strWebApplicationName))
                        {
                            SPSiteCollection objSiteCollection = objSite.WebApplication.Sites;
                            if (objSiteCollection != null && objSiteCollection.Count > 0)
                            {
                                startTime = DateTime.Now;
                                foreach (SPSite objTempSite in objSiteCollection)
                                {
                                    siteCollectionCount++;
                                    try
                                    {
                                        if (strDeploymentType.ToLower() == "deploy")
                                        {
                                           
                                                ActivateSiteFeature(objTempSite);
                                                Console.WriteLine("Activate feature for " + objTempSite.Url);
                                                logWriter.WriteLine("Activate feature for " + objTempSite.Url);
                                                logWriter.WriteLine("==========================================================================");
                                           
                                        }
                                        else if (strDeploymentType.ToLower() == "rollback")
                                        {
                                           

                                                DeactivateSiteFeature(objTempSite);
                                                Console.WriteLine("Deactivate feature for " + objTempSite.Url);
                                                logWriter.WriteLine("Deactivate feature for " + objTempSite.Url);
                                                logWriter.WriteLine("==========================================================================");


                                           
                                        }
                                        else
                                        {
                                            logWriter.WriteLine("Unknown Deployment Type");
                                            logWriter.WriteLine("==========================================================================");
                                            Console.WriteLine("Unknown Deployment Type");
                                        }

                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine("Orphaned site or could be any other reason. Please check log for more detail: " + ex.Message + ex.StackTrace); ;
                                        logWriter.WriteLine("Orphaned site or could be any other reason. Please check log for more detail: " + ex.Message + ex.StackTrace);
                                        logWriter.WriteLine("==========================================================================");
                                        continue;
                                    }


                                    objTempSite.Close();
                                }
                                endTime = DateTime.Now;
                                logWriter.WriteLine("**********************SUMMARY*****************************");
                                Console.WriteLine("Total Number Of SiteCollection for " + strWebApplicationName + " is " + siteCollectionCount);
                                logWriter.WriteLine("Total Number Of SiteCollection for " + strWebApplicationName + " is " + siteCollectionCount);

                                Console.WriteLine("Start Time Of " + strWebApplicationName + " is " + startTime.ToString());
                                logWriter.WriteLine("Start Time Of " + strWebApplicationName + " is " + startTime.ToString());

                                Console.WriteLine("End Time Of " + strWebApplicationName + " is " + endTime.ToString());
                                logWriter.WriteLine("End Time Of " + strWebApplicationName + " is " + endTime.ToString());
                                logWriter.Close();
                            }
                        }
                    }
                    else if (strFeatureType.ToLower() == "web")
                    {
                        using (SPSite objSite = new SPSite(strWebApplicationName))
                        {
                            SPSiteCollection objSiteCollection = objSite.WebApplication.Sites;
                            if (objSiteCollection != null && objSiteCollection.Count > 0)
                            {
                                startTime = DateTime.Now;
                                foreach (SPSite objTempSite in objSiteCollection)
                                {
                                    try
                                    {
                                        siteCollectionCount++;
                                        foreach (SPWeb objTempWeb in objTempSite.AllWebs)
                                        {
                                            webCount++;
                                            try
                                            {
                                                if (strDeploymentType.ToLower() == "deploy")
                                                {
                                                    ActivateWebFeature(objTempWeb);
                                                    Console.WriteLine("Activate feature for " + objTempWeb.Url);
                                                    logWriter.WriteLine("Activate feature for " + objTempWeb.Url);
                                                    logWriter.WriteLine("==========================================================================");
                                                }
                                                else if (strDeploymentType.ToLower() == "rollback")
                                                {
                                                    DeactivateWebFeature(objTempWeb);
                                                    Console.WriteLine("Deactivate feature for " + objTempWeb.Url);
                                                    logWriter.WriteLine("Deactivate feature for " + objTempWeb.Url);
                                                    logWriter.WriteLine("==========================================================================");

                                                }
                                                else
                                                {
                                                    logWriter.WriteLine("Unknown Deployment Type");
                                                    logWriter.WriteLine("==========================================================================");
                                                    Console.WriteLine("Unknown Deployment Type");
                                                }

                                            }

                                            catch (Exception ex)
                                            {
                                                // for sub sites.
                                                Console.WriteLine("Orphaned site or could be any other reason. Please check log for more detail: " + ex.Message + ex.StackTrace);
                                                logWriter.WriteLine("Orphaned site or could be any other reason. Please check log for more detail: " + ex.Message + ex.StackTrace);
                                                logWriter.WriteLine("==========================================================================");
                                                continue;
                                            }
                                            objTempWeb.Close();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        // for site collection.
                                        Console.WriteLine("Orphaned site or could be any other reason. Please check log for more detail: " + ex.Message + ex.StackTrace);
                                        logWriter.WriteLine("Orphaned site or could be any other reason. Please check log for more detail: " + ex.Message + ex.StackTrace);
                                        logWriter.WriteLine("==========================================================================");
                                        continue;
                                    }

                                    objTempSite.Close();
                                }
                                endTime = DateTime.Now;

                                logWriter.WriteLine("**********************SUMMARY*****************************");
                                Console.WriteLine("Total Number Of SiteCollection for " + strWebApplicationName + " is " + siteCollectionCount);
                                logWriter.WriteLine("Total Number Of SiteCollection for " + strWebApplicationName + " is " + siteCollectionCount);

                                Console.WriteLine("Total Number Of Web for " + strWebApplicationName + " is " + webCount);
                                logWriter.WriteLine("Total Number Of Web for " + strWebApplicationName + " is " + webCount);

                                Console.WriteLine("Start Time Of " + strWebApplicationName + " is " + startTime.ToString());
                                logWriter.WriteLine("Start Time Of " + strWebApplicationName + " is " + startTime.ToString());

                                Console.WriteLine("End Time Of " + strWebApplicationName + " is " + endTime.ToString());
                                logWriter.WriteLine("End Time Of " + strWebApplicationName + " is " + endTime.ToString());
                                logWriter.Close();
                            }
                        }
                    }
                    else
                    {
                        logWriter.WriteLine("Unknown Feature Type");
                        logWriter.WriteLine("==========================================================================");
                        Console.WriteLine("Unknown Feature Type");
                    }
                });
                Console.WriteLine("Press enter to continue...");
                Console.ReadLine();
            }
        }

        private static bool IsFeatureInstall()
        {
            bool bFound = false;
            //Finds the feature definition.
            foreach (SPFeatureDefinition featureDef in SPFarm.Local.FeatureDefinitions)
            {
                try
                {
                    if (featureDef.Id.Equals(FeatureGUID))
                    {
                        bFound = true;
                        break;
                    }
                }
                catch (Exception ex)
                {
                    //This is failing if feature is installed and feature file is not there
                    //we have to ignore this exception
                }
            }
            return bFound;
        }

        private static void ActivateSiteFeature(SPSite objSite)
        {
            bool bActive = false;
            //Checks whether the user is activated already.
            foreach (SPFeature feature in objSite.Features)
            {
                if (feature.DefinitionId.Equals(FeatureGUID))
                {
                    bActive = true;
                    break;
                }
            }

            if (!bActive)
            {
                objSite.Features.Add(FeatureGUID);
            }
        }
        private static void DeactivateSiteFeature(SPSite objSite)
        {
            bool bActive = false;
            //Checks whether the user is activated already.
            foreach (SPFeature feature in objSite.Features)
            {
                if (feature.DefinitionId.Equals(FeatureGUID))
                {
                    bActive = true;
                    break;
                }
            }

            if (bActive)
            {
                objSite.Features.Remove(FeatureGUID);
            }
        }
        private static void ActivateWebFeature(SPWeb objWeb)
        {
            bool bActive = false;
            //Checks whether the user is activated already.
            foreach (SPFeature feature in objWeb.Features)
            {
                if (feature.DefinitionId.Equals(FeatureGUID))
                {
                    bActive = true;
                    break;
                }
            }

            if (!bActive)
            {
                objWeb.Features.Add(FeatureGUID);
            }
        }
        private static void DeactivateWebFeature(SPWeb objWeb)
        {
            bool bActive = false;
            //Checks whether the user is activated already.
            foreach (SPFeature feature in objWeb.Features)
            {
                if (feature.DefinitionId.Equals(FeatureGUID))
                {
                    bActive = true;
                    break;
                }
            }

            if (bActive)
            {
                objWeb.Features.Remove(FeatureGUID);
            }
        }

    }
}