Wednesday, May 30, 2012

Property bags in SharePoint


Property bag in SharePoint exist in MOSS version and even continued to be a part of 2010 version. Property bag is nothing but a key value pair stored as hash table that we can retrieve in object model.

We can add, edit or remove properties from property bag from SharePoint Designer or through object model.

So let’s go ahead and check that out in Designer. Connect with the site.

Check out site options and click on it.

Here you can see parameters; these are the properties for this site. Here we can add, edit and remove. Let’s go ahead and add three properties and values.

Click on Add give name and value.



In the same way create two more properties.

Before we dive into coding part, I would like to bring in some more details.

We can define properties for several levels in SharePoint. At highest level we can have it for SPFarm, then SPWebApplication, then for SPSite, for SPWeb and for SPList.

Let’s us start by adding and retrieving properties that we just defined at web level.

  protected void btnPropertyBag_Click(Object sender, EventArgs e)
        {
            SPWeb objWeb = SPContext.Current.Web;
            objWeb.Properties.Add("CustomKey4AddedFromCode", "CustomValue4AddedFromCode");  
            objWeb.Properties.Update();  

            string strProp =  objWeb.AllProperties["CustomKey1"].ToString();
            strProp = objWeb.AllProperties["CustomKey2"].ToString();
            strProp = objWeb.AllProperties["CustomKey3"].ToString();
           
        }  



Sometime you can have Properties and not AllProperties like for SPlist, , SP web application and SP farm.

You can also remove property that we’ve added.

  objWeb.Properties.Remove("CustomKey4AddedFromCode");


If you want to check if the key exist, use containskey

if(objWeb.Properties.ContainsKey(""))


If you want to add it to the list or library, then you won’t find properties collection directly. You need to take rootfolder object and store it there. Like shown below.

SPWeb objWeb = SPContext.Current.Web;

SPList lstCalendar = objWeb.Lists.TryGetList("Calendar");

lstCalendar.RootFolder.Properties.Add("CustomCalendarKey", "CustomCalendarValue");

For SPSite there is no as such property bag available, but if you want to store, then use rootweb for SPSite and then assign properties. Like shown below.

SPWeb objWeb = SPContext.Current.Web;

SPSite objSite = objWeb.Site;

objSite.RootWeb.Properties.Add("SiteLevelKey", "SiteLevelValue");

For Web Application you can use this

SPWeb objWeb = SPContext.Current.Web;

             Microsoft.SharePoint.Administration.SPWebApplication objWebApp = objWeb.Site.WebApplication;

             objWebApp.Properties.Add("WebAppLevelKey", "WebAppLevelValue");

 Hope this will help to understand property bag.

Thursday, May 24, 2012

Connectable web parts in MOSS / SharePoint 2010


Well I thought for a while and saw that we have still not covered a basic topic that is how to connect two different custom web parts with custom properties.

So here we are explaining you how to connect two web parts.

In web part connection we have two types of web part. One is the provider web part and the other is consumer web part.

Provider web part sends a property which is received by the consumer web part and then processed in a code.

Create new empty project give it a name connectabewebpart.



Add as a farm solution and then click on add item. Point to an Interface.

We need to add interface as this interface will be implemented by provider web part. We have to define all the properties in this interface which we want provider web part to be able to send to consumer web part.

I am going to have one single property called OrderNumber just for demonstration purpose.



Define an interface like this. We are declaring one property called OrderNumber.



Now we are going to add new item to the project and select type web part and call it OrderNumberProviderWebPart.

Now this web part class must implement interface that we defined. So let’s implement this interface in provider class.

Now because we implemented interface, we need to define property which is declared in the interface.

So we have defined local variable and public property with the same name. Plus we have decorated that property with several attribute so that we can set the property with editor pane when we edit the web part. The property is set to have shared behavior.

Then we have defined one very important method which returns the interface and able to pass on this property which we defined as connection provider attribute of the method.

So here is a complete code for connection provider web part.



Now we are going to add consumer web part. So add new item, add web part. Call it OrderNumberConsumerWebPart. Now this web part will not implement interface. We need to declare a local variable which will receive the order number from provider.

So we’ve added a local variable called providedordernumber.

We need to define a method which has connectionconsumer attribute with property name that is defined in an interface. Parameter will be an interface which has that property that can be set to a local variable.

And then in create child control method we are showing the provided order number. Here is a code.



We are done with creating both web parts. It’s time to deploy them and check how they work.
I have deployed both web parts and I am on a page where I want to add them. Click to add web part. 

Go to custom tab and you’ll find both web parts there. Add them wherever you want on a page.



Now we have something like this.



Edit the provider web part and set order number in editor part.





Now we need to send this order number to consumer web part. Either you can send from provider to consumer or you can receive from provider in consumer. Both way works.





Once you set that you are done with connecting two web parts.


Thursday, May 17, 2012

Set default field value using SharePoint Designer


We can set a default field value in SharePoint. But if we want to pass a field value with parameter and then set field value then we have several option. One of them if use jQuery and set the field.


The other one is the one that I am going to show you in this post and that is through SharePoint Designer.

I have one dummy list just to show you how this work. This list has two dates. One start date and the other end date. We are going to pass two dates as parameters and then set those dates with the values. Both are date time fields.

The idea is those two dates should be disabled and cannot be edited by the end user plus they should have default value set passed by query string.

Now open SharePoint Designer 2010 and connect with the site. Note that this can also be done using Designer 2007 for MOSS 2007 / WSS 3.0 sites.


We are going to create a new form and have that new form as default new form. We will not make any changes to the actual new form.

Click on New



Configure properties like this



Now we have set the new item form for us and we have made it default form for new item instead of built in newform.aspx



Now click on that new item form that we’ve just created.

Page opens in HTML and design view. Now the idea is we need to remove the entire web part and to remove it. Select the entire web part and click delete that web part.



You will have something like this



Place cursor where highlighted and then click on Insert tab, custom list form.



Select Default Value Check list and new form and then click on ok. We are adding custom list new form now on this page instead of the default new page.

Now you’ll get this



Select start date and change it to a text box, do that same for end date.



You will observe a change in HTML code. Both have turned in to textboxes now.



Select both textboxes and check properties and select enabled to false for start date and end date.



We are yet not done with this. We now have to create parameters first. First save the form.
Click on options and the parameters from the ribbon



We need to create two parameters one for start date and the other for end date.



Configure it like this





Now we need to set these parameters with start date and end date fields on the form. Locate the start date text box in HTML and check out the text property.



Change it to this. This is the name of the query string and not the query string variable. Query string variable needs to be passed in URL.



Do the same for end date.

Save the form now.

And now go back to actual form via browser and pass on Start and End as parameters and you are done.


Tuesday, May 15, 2012

How Modify MasterPage or Pagelayout programmatically? (Especially when it is in use)


Most of the time we are using SharePoint Designer for master page and page layout deployment, which is fine for first time going live because for the first time we mostly used backup restore or other stuff.

But problem occurs when you want to update master page or page layout in subsequent release. We can do that easily with SharePoint designer but some unlucky fellow like us who do not have access to production will have to find some workaround for that. And if master page and Page Layout  being used then it will not allow to delete and add it again.

Here are simple steps what we had done

  • Add physical copy of master page/page layout in your project (or put it in 14 hive)
  • Create a feature receiver which will read that file added in 14 hive, read as binary stream.
  • Find master page in master page gallery (_catalog folder)
  • If (not found) then add new master page/layout (will be used for first time deployment)
  • If (found) then open/read master page/layout from library
  1. Check out
  2. Open as binary form and copy binary object from physical copy
  3. Commit transection, so new version will be added for master page/layout.
  4. Check in
  5. Publish
This way if master page is currently used in site or page layout has been used any of the page you can easily update it from code.

 It will not require access to production. You can add feature receiver in WSP and activate it on deployment; and you are done.

We will provide code snippet for this soon :)

Monday, May 14, 2012

Workflow Event handlers in SharePoint 2010


In SharePoint 2010, we now have new receivers and one of them is workflow event receivers. We can handle different events with respect to the workflows that triggers in SharePoint.

You can handle multiple events with regards to the workflow. These are:

1)    When workflow is starting
2)    When workflow is started
3)    When workflow is completed
4)    When workflow is postponed

As name suggests you can trap different events of the workflow. 

These come handy if you have requirement to start series of workflow based on completion criteria from one workflow to another. If one workflow completes and then you want to start another workflow in chain, that can be done now by trapping these events.

This is only for list or library workflows and not for the site workflow.

Here is an example with code.

/// <summary>
    /// List Workflow Events
    /// </summary>
    public class EventReceiver1 : SPWorkflowEventReceiver
    {
       /// <summary>
       /// A workflow is starting.
       /// </summary>
       public override void WorkflowStarting(SPWorkflowEventProperties properties)
       {
           SPWeb Web = properties.ActivationProperties.List.ParentWeb;
           
           SPList lstTracking = Web.Lists["Track Different Events"];                 

           SPListItem item = lstTracking.Items.Add();

           item["Title"] = "Starting the workflow";

           item.Update();          

       }

       /// <summary>
       /// A workflow was started.
       /// </summary>
       public override void WorkflowStarted(SPWorkflowEventProperties properties)
       {
           using (SPSite site = new SPSite(properties.WebUrl))
           {
               using (SPWeb Web = site.OpenWeb())
               {

                   SPList lstTracking = Web.Lists["Track Different Events"];                

                   SPListItem item = lstTracking.Items.Add();

                   item["Title"] = "workflow has been started";

                   item.Update();
               }
           }
           
       }

       /// <summary>
       /// A workflow was completed.
       /// </summary>
       public override void WorkflowCompleted(SPWorkflowEventProperties properties)
       {
            using (SPSite site = new SPSite(properties.WebUrl))
            {
                using (SPWeb Web = site.OpenWeb())
                {
                    SPList lstTracking = Web.Lists["Track Different Events"];                   

                    SPListItem item = lstTracking.Items.Add();

                    item["Title"] = "workflow has been completed";

                    item.Update();
                   
                }
            }              

       }
    }

You can also handle several completion type enumerations in WorkflowCompleted method that helps you to execute certain code based on the completion criteria.


You can also check completion type enumerations in WorkflowCompleted method.





Thursday, May 10, 2012

Site Workflow in SharePoint 2010


In SharePoint 2010 we now have a new workflow which is site workflow. Just like how we can set a workflow on list, library and content type, now we can associate a workflow with the site.

Site workflow is different than list or library level workflow as it has advantages over them.

It can run on different libraries, different lists, and different items at the same time. We can check in, check out a document in one library, create an item in list, capture version of document set all in one workflow.

Other advantage is those site workflows are always triggered manually through site workflow link from view all site content page. The link to start the individual site workflow can be placed on any page as it does not involve any dynamic parameter.

If your site workflow has a requirement of interacting with user, then the form will be in InfoPath. Hence we can always go ahead and make changes to InfoPath form that workflow creates.

There are certain limitations of site workflow though. It cannot be created in Visio. Some actions related to current item are not available while creating site workflow

We would be diving into creating a site workflow and then test it how it works. I am taking a very simple example of creating orders with few fields. Real business scenario can simple be anything.

I’ve got a list called orders.

         
 
Now we are going to go and open our SharePoint Designer 2010. Connect with your site. click on workflows and then click on site workflows from ribbon.


Click on create list item in workflow designer.



Now before starting on this, we need certain parameters to start with. The form will have these parameters so that user can enter values in them and then those get inserted to the orders list.
Click on Initiate parameters from the ribbon.



Enter names of the parameters. These will be similar to our fields in the list.





In this way, define all four parameters.

So at the end, you should have something like this.



Now click on create list link and that will open up a dialog which allows us to select the list 

where we want to create an item and then bind parameters to the fields from that list.



In this way associate all parameters to its respective fields.



At the end you should have something like this



Save and publish the workflow. Open the site and click on view all site content.

Click on site workflow.



You will find our workflow that we’ve just created.



Click on the order enter workflow and you’ll be presented with the form. You can copy and use this URL wherever you want as it is a static URL to this workflow form.



Enter the values and you’ll see that workflow starts and then ends and at the end it creates an entry in orders list.



Now you must be wondering this form does not look good. If you observe the workflow settings page in designer, you can see one xsn InfoPath form has been created for us by Designer.

Click on that form to open in InfoPath to modify.



I’ve modified the form in this. Now save and publish back to the same location.



Try to start the site workflow now and you will see modified form this time.



I hope this will help to create site workflow. Do let us know if you have any questions or face any issues.



Share your SharePoint Experiences with us...
As good as the SharePointKings is, we want to make it even better. One of our most valuable sources of input for our Blog Posts comes from ever enthusiastic Visitors/Readers. We welcome every Visitor/Reader to contribute their experiences with SharePoint. It may be in the form of a code stub, snippet, any tips and trick or any crazy thing you have tried with SharePoint.
Send your Articles to sharepointkings@gmail.com with your Profile Summary. We will Post them. The idea is to act as a bridge between you Readers!!!

If anyone would like to have their advertisement posted on this blog, please send us the requirement details to sharepointkings@gmail.com