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 http://SP01.powershell.nu
PS > $spList = $spWeb.Lists[“Tasks”]
PS > $spList.AllowDeletion = $false
PS > $spList.Update()
PS > $spWeb.Dispose()
source:-secretsofsharepoint.com

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 1.0.0.0 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.

Action
Steps
Result
Create version
1.0.0.0 in your
workflow’s elements
file.
1 In the Elements.xml file of your workflow, replace $assemblyname$
in CodeBesideAssembly with the following:
[assembly name], Version=1.0.0.0,
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 1.0.0.0 to solution package by double-clicking
on the Package and, under the Advanced tab, add an existing
assembly and browse to your 1.0.0.0 assembly version:
NOTE: Notice how the Location and Source of the assembly are in a
path under Version 1.0.0.0. When the package is created, the
1.0.0.0 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 1.0.0.0 version
of your assembly
With version
1.0.0.0 established,
you can
now simulate the
need to create
version 2.0.0.0.
Change the version
of the
assembly
to 2.0.0.0.
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
2.0.0.0.
The current version of
the workflow’s assembly
is now 2.0.0.0.
Update the workflow’s
Elements.
xml file to
reference both
the version
1.0.0.0 workflow
and now the new
2.0.0.0 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 2.0.0.0.
4 Change the ID in the 2.0.0.0 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 1.0.0.0
assembly, and the
other is referencing the
2.0.0.0 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:-

 

Output:-

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




1.       Element.XML

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

  <CustomAction Id=CustomRibbonSolution Location=CommandUI.Ribbon>

    <CommandUIExtension>

      <CommandUIDefinitions>

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

          <Button Id=Ribbon.Documents.Copies.ExportFilteredView

                  Command=ExportFilteredView

                  Sequence=20

                  Image16by16=/_layouts/images/CustomRibbonSolution/zip_16x16.png

                  Image32by32=/_layouts/images/CustomRibbonSolution/zip_32x32.png

                  LabelText=Export Filtered View

                  Description=Export Filtered view to XSL

                  TemplateAlias=o1/>

        </CommandUIDefinition>

      </CommandUIDefinitions>

      <CommandUIHandlers>

        <CommandUIHandler

          Command=ExportFilteredView

          CommandAction=javascript:ExportFilteredView();

          EnabledScript=javascript:enable();/>

      </CommandUIHandlers>

    </CommandUIExtension>

  </CustomAction>

  <CustomAction Id=Ribbon.Library.Actions.Scripts

                Location=ScriptLink

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

</Elements>

2.       CustomRibbonJsFile.js

function enable() {

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

    var itemCount = CountDictionary(items);

    return (itemCount > 0);

}

function ExportFilteredView() {

    //alert(‘hi’);

    var context = SP.ClientContext.get_current();

    this.site = context.get_site();

    this.web = context.get_web();

    context.load(this.site);

    context.load(this.web);

    context.executeQueryAsync(

        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.site.get_url() + 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);

    form.appendChild(hfSourceUrl);

    var hfItemIds = document.createElement(“input”)

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

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

    hfItemIds.setAttribute(“value”, ids);

    form.appendChild(hfItemIds);

    document.body.appendChild(form);

    form.submit();

}

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() {

    SP.UI.Status.removeStatus(this.statusID);

}

3.       ExportViewToXSL.aspx.cs

usingSystem;

usingMicrosoft.SharePoint;

usingMicrosoft.SharePoint.WebControls;

namespaceCustomRibbonSolution.Layouts

{

    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

            //}

            Response.Redirect(http://www.google.com&#8221;);

        }

    }

}

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
{
    [ToolboxItemAttribute(false)]
    public class MyClassicCEWP : Microsoft.SharePoint.WebPartPages.WebPart
    {
        private string _content;
        private HtmlGenericControl editableRegion = new HtmlGenericControl();
        private HtmlGenericControl emptyPanel = new HtmlGenericControl();
        private bool IsInEditMode
        {
            get
            {
                SPWebPartManager currentWebPartManager = (SPWebPartManager)WebPartManager.GetCurrentWebPartManager(this.Page);
                return (((currentWebPartManager != null) && !base.IsStandalone) && currentWebPartManager.GetDisplayMode().AllowPageDesign);
            }
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (this.IsInEditMode)
            {
                SPRibbon current = SPRibbon.GetCurrent(this.Page);
                if (current != null)
                {
                    current.MakeTabAvailable(“Ribbon.EditingTools.CPEditTab”);
                    current.MakeTabAvailable(“Ribbon.Image.Image”);
                    current.MakeTabAvailable(“Ribbon.EditingTools.CPInsert”);
                    current.MakeTabAvailable(“Ribbon.Link.Link”);
                    current.MakeTabAvailable(“Ribbon.Table.Layout”);
                    current.MakeTabAvailable(“Ribbon.Table.Design”);
                    if (!(this.Page is WikiEditPage))
                    {
                        current.TrimById(“Ribbon.EditingTools.CPEditTab.Layout”);
                        current.TrimById(“Ribbon.EditingTools.CPEditTab.EditAndCheckout”);
                    }
                }
            }
        }

        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”);
            divEventCalendar.Controls.Add(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”);
            divEventCalendarWebpartTitle.Controls.Add(labelTitle);
            divEventCalendarWebpart.Controls.Add(divEventCalendarWebpartTitle);
            System.Web.UI.HtmlControls.HtmlGenericControl DCContentBlock = new System.Web.UI.HtmlControls.HtmlGenericControl(“DIV”);
            DCContentBlock.ID = “DCContentBlock”;
            DCContentBlock.Attributes.Add(“class”, “DCContentBlock”);
            divEventCalendarWebpart.Controls.Add(DCContentBlock);
            System.Web.UI.HtmlControls.HtmlGenericControl DCContent = new System.Web.UI.HtmlControls.HtmlGenericControl(“DIV”);
            DCContent.ID = “DCContent”;
            DCContent.Attributes.Add(“class”, “DCContent”);
            DCContentBlock.Controls.Add(DCContent);
            Panel plhContentEdit = new Panel();
            plhContentEdit.ID = “plhContentEdit”;
            Panel plhContentDisplay = new Panel();
            plhContentEdit.ID = “plhContentDisplay”;
            Panel plhNoContent = new Panel();
            plhContentEdit.ID = “plhNoContent”;
            DCContentBlock.Controls.Add(plhContentEdit);
            DCContentBlock.Controls.Add(plhContentDisplay);
            DCContentBlock.Controls.Add(plhNoContent);
            this.Controls.Add(divEventCalendar);

            plhContentDisplay.Controls.Add(new LiteralControl(this.Content));
            plhContentEdit.Controls.Add(this.editableRegion);
            plhNoContent.Controls.Add(this.emptyPanel);
            string strUpdatedContent = this.Page.Request.Form[this.ClientID + “content”];
            if ((strUpdatedContent != null) && (this.Content != strUpdatedContent))
            {
                this.Content = strUpdatedContent;
                try
                {
                    SPWebPartManager currentWebPartManager = (SPWebPartManager)WebPartManager.GetCurrentWebPartManager(this.Page);
                    Guid storageKey = currentWebPartManager.GetStorageKey(this);
                    currentWebPartManager.SaveChanges(storageKey);
                }
                catch (Exception exception)
                {
                    Label child = new Label();
                    child.Text = exception.Message;
                    this.Controls.Add(child);
                }
            }
            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
        [WebPartStorage(Storage.Shared)]
        public string Content
        {
            get
            {
                return this._content;
            }
            set
            {
                _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′);}

 DIV.ms-rteElement-mkg-Header{-ms-name: “My Header”;font-family: Georgia;font-size: 14px;font-weight: bold;padding:0 0 0 0;color: #840f08 !important;}
DIV.ms-rteElement-mkg-Separator{-ms-name:”My Separator”;border-bottom:1px solid #e6e7e7;height:1px;padding:10px 0;}
DIV.ms-rteElement-mkg-LeftParagraph{-ms-name: “My LeftParagraph”;width:250px;float:left;font-size: 11px;color: #666666;font-family:Arial;}
DIV.ms-rteElement-mkg-RightImage{-ms-name: “My RightImage”;width:100px;float:right;}