Archive

Archive for the ‘SharePoint 2010’ Category

SharePoint – Retrieve SharePoint Timer Job Schedule

Here is a utility function which can give you the Job Schedule

string GetTimerJobStatus(string timerJobName) 
{
    string schedule = string.Empty;

    SPSecurity.RunWithElevatedPrivileges(() => 
    { 
        SPWebApplication webApp = SPContext.Current.CurrentWeb.WebApplication;
        foreach (SPJobDefinition job in webApp.JobDefinitions)
        {
            if (job.Name.Equals(timerJobName))
            {
                schedule = job.Schedule.GetType().FullName;
                break;
            }
        }
    });

    return schedule;
}

SharePoint – Updating External Lookup Field

November 21, 2014 Leave a comment

Updating an external look up is a bit different compared to updating other look up fields.

Below is a small snippet which can help you with this task

SPBusinessDataField dataField = item.Fields["Field Display Name"] as SPBusinessDataField;
item[dataField.RelatedField] = EntityInstanceIdEncoder.EncodeEntityInstanceId(new object[] { NEWVALUE }); ;
item["Field_x0020_Internal_x0020_Name"] = newCRMNumber;

For getting SPBusinessDataField you need to get the fields from item which is the listitem we are trying to modify.

item.Fields["Field Display Name"] – This require you to pass the Field Display name

SharePoint – Programatically Starting a Workflow

Here is a code snippet I recently developed for starting a sharepoint workflow from code behind.

public void StartWorkFlow(string listName, int itemID, string workflowName)
{
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
        using (SPSite oSite = new SPSite(SPContext.Current.Site.Url))
        {
            using (SPWeb oWeb = oSite.OpenWeb())
            {
                oWeb.AllowUnsafeUpdates = true;
                SPList oList = oWeb.Lists[listName];
                SPListItem oItem = list.GetItemById(itemID);
                SPWorkflowManager wfManager = oSite.WorkflowManager;

                foreach (SPWorkflowAssociation association in oList.WorkflowAssociations)
                {
                    if (association.Name == workflowName)
                    {
                        string associationData = association.AssociationData;
                        wfManager.StartWorkflow(oItem, association, associationData);                                
                        break;
                    }
                }
                oWeb.AllowUnsafeUpdates = false;
            }
        }
    });
}
Categories: SharePoint, SharePoint 2010 Tags:

SharePoint – Timer Job Executing Multiple Times

March 13, 2014 1 comment

Custom timer jobs are created by inheriting SPJobDefinition class. This class is available under Microsoft.SharePoint.Administration namespace.

Recently I was working on a timer job which was scheduled to run every 5 minutes. After deployment I found the job is invoked multiple times during each 5 minute cycle. In my case this was executing 10 times. This happened because I have 10 content database. To avoid this we should make use of the SPJobLockType enumeration.

public MyCustomTimerJob(string jobName, SPWebApplication webapp) : 
base(jobName, webapp, null, SPJobLockType.Job) {
	this.Title = "My Custom Timer Job";
}

Hope this helps!

SharePoint 2013 – List Validation

November 26, 2013 2 comments

One of my friend recently asked me how to apply list validation in SharePoint 2013. I explained him and thought of documenting it so others can use it for reference.

To start with I am trying to enforce the following requirement

There is a list with 3 choice columns “A”, “B”, and “C”. In any of these columns a value = “None” is not allowed.

Solution

Open list setting

ListValidation1

Click on Validation Settings

ListValidation2

Now you can apply formula and a message which will appear if validation fails

ListValidation3

Formula uses the IF condition for validation. The general syntax is IF(condition, true case, false case).
First we will check if column “A” is not equal to “None”, then only go and validate “B”. The same logic is applied for validating “B” and then “C”

ListValidation4

OleDBConnection – Unspecified error

August 5, 2013 1 comment

On top of SharePoint 2010, I was trying to create an excel parser where I hit with this strange “Unspecified error”. The exception is getting generated from “OleDBConnection.Open” method

There was no inner exceptions or stack traces, which made it difficult to find the root cause. After trying out different steps like uninstalling office, restarting iis etc. eventually I resolved it by the below 3 steps

  1. Download latest Access Databas Engine http://www.microsoft.com/en-in/download/details.aspx?id=13255. Ensure to select the correct platform 32 vs 64
  2. Connection string = “Provider=Microsoft.ACE.OLEDB.12.0;Data Source=fileLocation;Extended Properties=”Excel 12.0 Xml;HDR=Yes;IMEX=1”
  3. In the web configuration file turn off Impersonation¬†<identity impersonate=”false” />

In the connection string I am using HDR=Yes, this mean the first row in the excel file is a header row. IMEX=1 will force the excel cells to be treated as Text rather than the Excel General type which converts the data (The feature I hate most)

SharePoint Survey List – EventReceiver

SharePoint Survey list behaves differently compared to others. A survey can have many questions, that can be on different pages. There must be scenarios where we need to do calculations once a Survey response is completed. For doing this the best option is event receiver customization. In this case we need to handle both ItemAdded and ItemUpdated events.

When a user respond’s to a survey the value in field Completed will be 255. Once the user clicks on the finish button the value changes to 1. Hence in the receiver we need to take action only once the value equals 1.

Below is a template you can use

using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace Survey
{    
    /// <summary>
    /// List Item Events
    /// </summary>
    public class SurveyListReceiver : SPItemEventReceiver
    {
       /// <summary>
       /// An item was added.
       /// </summary>
       public override void ItemAdded(SPItemEventProperties properties)
       {
           try
           {
               if (properties.ListItem["Completed"] != null && properties.ListItem["Completed"].ToString() == "1")
               {
                   //Survey is complete. Do The Action
               }
           }
           catch
           {
           }
           base.ItemAdded(properties);
       }

       /// <summary>
       /// An item was updated.
       /// </summary>
       public override void ItemUpdated(SPItemEventProperties properties)
       {
           try
           {
               if (properties.ListItem["Completed"] != null && properties.ListItem["Completed"].ToString() == "1")
               {
                   //Survey is complete. Do The Action
               }
           }
           catch
           {
           }
           base.ItemUpdated(properties);
       }
    }
}