Month: November 2012

Disable List Deletion sharepoint 2010

If you don’t want users to be able to delete a specific SharePoint 2010 list, you can disable list deletion using Windows PowerShell. The example below demonstrates how to disable deletion of the tasks list on a Web site:

PS > $spWeb = Get-SPWeb
PS > $spList = $spWeb.Lists[“Tasks”]
PS > $spList.AllowDeletion = $false
PS > $spList.Update()
PS > $spWeb.Dispose()

Versioning of Visual Studio SharePoint Workflow

This article is copy of
Phil Wicklund’sbook of SharePoint Workflow

Thanks to him for solving biggest problem of Sharepoint State Machine Workflow.

You built this compelling Visual Studio workflow and deployed it into production.
But, after a few months, the business requests a small change to the workflow. You go
back into the workflow code, add a few activities to fulfill the request, and redeploy
the workflow into production. To your shock, all the workflows start breaking! You’re
frantic because you’re certain you adequately unit-tested the changes and can’t figure
out what might be going wrong. You didn’t version your workflow.
Workflow versioning is an important technique. When a workflow goes idle, the
state of the workflow is saved into the database. This saving of a workflow’s state is
called hydration. When the workflow resumes, the state is dehydrated out of the database,
and the workflow starts processing again. Versioning is important because, if you
change the assembly while the workflow is hydrated (saved in the database), there’s
no guarantee that, when the workflow is dehydrated, it will match the construct of the
new assembly. If it doesn’t match the construct upon deserialization, the workflow will
break. Changes like adding or removing activities and changing property values may
necessitate a new workflow version. The best practice is to create a new version every
time rather than deploying the assembly and crossing your fingers.
Think of a new workflow version as a new workflow. The basic technique is to
make your assembly increment the version number with each build (rather than leaving
it at forever). Then, for each upgrade, you create a new feature for that
version of the workflow, pointing to the new assembly. You add the new assembly into
the global assembly cache (GAC) alongside the old assembly. Last, you specify that
the old version cannot start new instances of the workflow and then you add the new
workflow onto the list. This way, the old version of the assembly never changes, so
there’s no risk of hydrated workflows breaking when they are dehydrated. You deploy
another version of the assembly and add the new workflow to the list and disable previous
versions. You don’t want to remove the previous versions because that will
orphan those running instances. For the full set of procedures, follow the steps in
table below to create a new version for an existing workflow.

Old version overwritten
If you don’t create a new version and merely upgrade the solution, all running instances
of the workflow will be deleted. The old version of the workflow will be removed,
and the new version will be added with zero running instances. Don’t
upgrade without creating a new version unless you’re entirely sure you don’t need
to retain the running instances.

Create version in your
workflow’s elements
1 In the Elements.xml file of your workflow, replace $assemblyname$
in CodeBesideAssembly with the following:
[assembly name], Version=,
Culture=neutral, PublicKeyToken=[token]
2 Replace [assembly name] with your assembly name.
3 Replace [token] with your public key token. You can do this by finding
your assembly in the GAC (c:\windows\assembly) and rightclicking
it, choosing Properties, and copying the token.
4 Change the name of the workflow in the Elements file to reference
the new version.
NOTE: This ensures that the user working with the workflow knows
what version it is. It has no technical implications. For example
5 Add a copy of version to solution package by double-clicking
on the Package and, under the Advanced tab, add an existing
assembly and browse to your assembly version:
NOTE: Notice how the Location and Source of the assembly are in a
path under Version When the package is created, the version is put in its own path. It cannot be in the same path
as the current version because they both have the same name.
Your workflow’s feature
is now specifically referencing
the version
of your assembly
With version established,
you can
now simulate the
need to create
Change the version
of the
1 Under the Properties folder in the solution, open the Assembly-
Info.cs file.
2 Scroll to the bottom of the file and change the two versions to
The current version of
the workflow’s assembly
is now
Update the workflow’s
xml file to
reference both
the version workflow
and now the new version.
1 Under the workflow, open the Elements.xml file.
2 Copy the Workflow element in its entirety and paste it directly
after the tag.
3 Change the name and the version (in the CodeBesideAssembly) of
the second workflow to reference version
4 Change the ID in the version to a new GUID. You can create
a new GUID by using the Create GUID tool under the tools menu.
5 Build and deploy the solution.
The workflow’s feature
now enables two workflows.
The main difference
is that one is
referencing the
assembly, and the
other is referencing the assembly.

Add Custom button to SharePoint ribbon with server side code to execute

To add custom button to ribbon we will need to do below things:-

1.       Create SharePoint Empty Project.

2.       Add new “Empty Element”.

3.        Map Layout folder.

4.       Add One JS file to Layout folder.

5.       Add Application Page to same folder.

6.       Crete 2 logo images

Look at below solution Structure:-



Custom button will be enabled only when item is selected:-

1.       Element.XML

<?xml version=1.0 encoding=utf-8?>

  <CustomAction Id=CustomRibbonSolution Location=CommandUI.Ribbon>



        <CommandUIDefinition Location=Ribbon.Documents.Copies.Controls._children>

          <Button Id=Ribbon.Documents.Copies.ExportFilteredView





                  LabelText=Export Filtered View

                  Description=Export Filtered view to XSL












  <CustomAction Id=Ribbon.Library.Actions.Scripts


                ScriptSrc=/_layouts/CustomRibbonSolution/CustomRibbonJsFile.js />


2.       CustomRibbonJsFile.js

function enable() {

    var items = SP.ListOperation.Selection.getSelectedItems();

    var itemCount = CountDictionary(items);

    return (itemCount > 0);


function ExportFilteredView() {


    var context = SP.ClientContext.get_current(); = context.get_site();

    this.web = context.get_web();




        Function.createDelegate(this, this.onQuerySucceeded),

        Function.createDelegate(this, this.onQueryFailed)



function onQuerySucceeded() {

    var items = SP.ListOperation.Selection.getSelectedItems();

    var itemCount = CountDictionary(items);

    if (itemCount == 0) return;

    var ids = “”;

    for (var i = 0; i < itemCount; i++) {

        ids += items[i].id + “;”;


    //send a request to the zip aspx page.

    var form = document.createElement(“form”);

    form.setAttribute(“method”, “post”);

    form.setAttribute(“action”, + this.web.get_serverRelativeUrl() + “/_layouts/CustomRibbonSolution/ExpoerViewToXSL.aspx”);

    var hfSourceUrl = document.createElement(“input”);

    hfSourceUrl.setAttribute(“type”, “hidden”);

    hfSourceUrl.setAttribute(“name”, “sourceUrl”);

    hfSourceUrl.setAttribute(“value”, location.href);


    var hfItemIds = document.createElement(“input”)

    hfItemIds.setAttribute(“type”, “hidden”);

    hfItemIds.setAttribute(“name”, “itemIDs”);

    hfItemIds.setAttribute(“value”, ids);





function onQueryFailed(sender, args) {

    this.statusID = SP.UI.Status.addStatus(“Export to XSL:”,

        “Exporting Failed: “ + args.get_message() + Close.”, true);

    SP.UI.Status.setStatusPriColor(this.statusID, “red”);


function closeStatus() {



3.       ExportViewToXSL.aspx.cs






    public partial class ExpoerViewToXSL : LayoutsPageBase


        protectedvoid Page_Load(objectsender, EventArgs e)


            //string fullDocLibSourceUrl = Request.Params[“sourceUrl”];

            //if (string.IsNullOrEmpty(fullDocLibSourceUrl)) return;

            //string docLibUrl = fullDocLibSourceUrl.Replace(SPContext.Current.Site.Url, “”);

            //SPList list = SPContext.Current.Web.GetList(docLibUrl);

            //if (!list.IsDocumentLibrary()) return;

            //string pItemIds = Request.Params[“itemIDs”];

            //if (string.IsNullOrEmpty(pItemIds)) return;

            //SPDocumentLibrary library = (SPDocumentLibrary)list;

            //string[] sItemIds = pItemIds.Split(new char[] { ‘;’ }, StringSplitOptions.RemoveEmptyEntries);

            //int[] itemsIDs = new int[sItemIds.Length];

            //for (int i = 0; i < sItemIds.Length; i++)


            //    itemsIDs[i] = Convert.ToInt32(sItemIds[i]);


            //foreach (int id in itemsIDs)


            //Write Export logic here






Customize SharePoint Content Editor Web Part in VS 2012 classic webpart

1. Paste below code in cs file of classic web part(Not visual web Part)

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
namespace POC2012CEWP.MyClassicCEWP
    public class MyClassicCEWP : Microsoft.SharePoint.WebPartPages.WebPart
        private string _content;
        private HtmlGenericControl editableRegion = new HtmlGenericControl();
        private HtmlGenericControl emptyPanel = new HtmlGenericControl();
        private bool IsInEditMode
                SPWebPartManager currentWebPartManager = (SPWebPartManager)WebPartManager.GetCurrentWebPartManager(this.Page);
                return (((currentWebPartManager != null) && !base.IsStandalone) && currentWebPartManager.GetDisplayMode().AllowPageDesign);
        protected override void OnInit(EventArgs e)
            if (this.IsInEditMode)
                SPRibbon current = SPRibbon.GetCurrent(this.Page);
                if (current != null)
                    if (!(this.Page is WikiEditPage))

        protected override void CreateChildControls()
           // base.OnLoad();
            // Prevent default display of webpart chrome in standard view mode
            this.ChromeType = PartChromeType.None;
            this.Page.Header.Controls.Add(new LiteralControl(“”));
            System.Web.UI.HtmlControls.HtmlGenericControl divEventCalendar = new System.Web.UI.HtmlControls.HtmlGenericControl(“DIV”);
            divEventCalendar.ID = “divEventCalendar”;
            System.Web.UI.HtmlControls.HtmlGenericControl divEventCalendarWebpart = new System.Web.UI.HtmlControls.HtmlGenericControl(“DIV”);
            divEventCalendarWebpart.ID = “divEventCalendarWebpart”;
            divEventCalendarWebpart.Attributes.Add(“class”, “divEventCalendarWebpart”);
            System.Web.UI.HtmlControls.HtmlGenericControl divEventCalendarWebpartTitle = new System.Web.UI.HtmlControls.HtmlGenericControl(“DIV”);
            divEventCalendarWebpartTitle.ID = “divEventCalendarWebpartTitle”;
            divEventCalendarWebpartTitle.Attributes.Add(“class”, “divEventCalendarWebpartTitle shadow”);
            Label labelTitle = new Label();
            labelTitle.Text = “CEWP 2012”;
            divEventCalendarWebpartTitle.Attributes.Add(“style”, “background:#840f08”);
            System.Web.UI.HtmlControls.HtmlGenericControl DCContentBlock = new System.Web.UI.HtmlControls.HtmlGenericControl(“DIV”);
            DCContentBlock.ID = “DCContentBlock”;
            DCContentBlock.Attributes.Add(“class”, “DCContentBlock”);
            System.Web.UI.HtmlControls.HtmlGenericControl DCContent = new System.Web.UI.HtmlControls.HtmlGenericControl(“DIV”);
            DCContent.ID = “DCContent”;
            DCContent.Attributes.Add(“class”, “DCContent”);
            Panel plhContentEdit = new Panel();
            plhContentEdit.ID = “plhContentEdit”;
            Panel plhContentDisplay = new Panel();
            plhContentEdit.ID = “plhContentDisplay”;
            Panel plhNoContent = new Panel();
            plhContentEdit.ID = “plhNoContent”;

            plhContentDisplay.Controls.Add(new LiteralControl(this.Content));
            string strUpdatedContent = this.Page.Request.Form[this.ClientID + “content”];
            if ((strUpdatedContent != null) && (this.Content != strUpdatedContent))
                this.Content = strUpdatedContent;
                    SPWebPartManager currentWebPartManager = (SPWebPartManager)WebPartManager.GetCurrentWebPartManager(this.Page);
                    Guid storageKey = currentWebPartManager.GetStorageKey(this);
                catch (Exception exception)
                    Label child = new Label();
                    child.Text = exception.Message;
            if (this.IsInEditMode)
                this.Page.ClientScript.RegisterHiddenField(this.ClientID + “content”, this.Content);
                plhContentDisplay.Visible = false;
                this.emptyPanel.TagName = “DIV”;
                this.emptyPanel.Style.Add(HtmlTextWriterStyle.Cursor, “hand”);
                this.emptyPanel.Controls.Add(new LiteralControl(“Click here to Edit”));
                this.emptyPanel.Style.Add(HtmlTextWriterStyle.TextAlign, “center”);
                base.Attributes[“RteRedirect”] = this.editableRegion.ClientID;
                ScriptLink.RegisterScriptAfterUI(this.Page, “SP.UI.Rte.js”, false);
                ScriptLink.RegisterScriptAfterUI(this.Page, “SP.js”, false);
                ScriptLink.RegisterScriptAfterUI(this.Page, “SP.Runtime.js”, false);
                this.editableRegion.TagName = “DIV”;
                this.editableRegion.InnerHtml = this.Content;
                this.editableRegion.Attributes[“class”] = “ms-rtestate-write ms-rtestate-field”;
                this.editableRegion.Attributes[“contentEditable”] = “true”;
                this.editableRegion.Attributes[“InputFieldId”] = this.ClientID + “content”;
                this.editableRegion.Attributes[“EmptyPanelId”] = this.emptyPanel.ClientID;
                this.editableRegion.Attributes[“ContentEditor”] = “True”;
                this.editableRegion.Attributes[“AllowScripts”] = “True”;
                this.editableRegion.Attributes[“AllowWebParts”] = “False”;
                string script = “RTE.RichTextEditor.transferContentsToInputField(‘” + SPHttpUtility.EcmaScriptStringLiteralEncode(this.editableRegion.ClientID) + “‘);”;
                this.Page.ClientScript.RegisterOnSubmitStatement(base.GetType(), “transfer” + this.editableRegion.ClientID, script);
        // Properties
        public string Content
                return this._content;
                _content = value;

2. use Below CSS to add custom styles

  /* Common styles*/
 .divEventCalendarWebpart{font-family:Arial;width: 342px;position: relative;border: 1px solid #e6e7e7 !important;float:left;padding:50px 20px 5px 20px;}
.divEventCalendarWebpartTitle{font-family: Georgia;font-size: 16px;font-weight: bold;padding: 12px 20px;color: #FFFFFF;position: absolute;top: -15px;left: -15px;box-shadow:5px 5px 5px #CCCCCC;width:155px !important;}
 .shadow {-moz-box-shadow: 5px 5px 5px #999999;-webkit-box-shadow: 5px 5px 5px #999999;box-shadow: 5px 5px 5px #999999;-ms-filter: “progid:DXImageTransform.Microsoft.Shadow(Strength=6, Direction=135, Color=’#999999′)”;filter: progid:DXImageTransform.Microsoft.Shadow(Strength=6, Direction=135, Color=’#999999′);}{-ms-name: “My Header”;font-family: Georgia;font-size: 14px;font-weight: bold;padding:0 0 0 0;color: #840f08 !important;}{-ms-name:”My Separator”;border-bottom:1px solid #e6e7e7;height:1px;padding:10px 0;}{-ms-name: “My LeftParagraph”;width:250px;float:left;font-size: 11px;color: #666666;font-family:Arial;}{-ms-name: “My RightImage”;width:100px;float:right;}