Thursday 26 February 2015

SharePoint Modal Pop Up.

If you like the popup SharePoint Uses and wants to implement such in your code here is the code sample that can meet your requirements.

function OpenDocsDialog(url1) {
        var options = {
            url: url1,
            dialogReturnValueCallback: myDialogCallback
        };
        SP.UI.ModalDialog.showModalDialog(options);      
    }

    function myDialogCallback(dialogResult, data) {
        SP.UI.ModalDialog.RefreshPage(dialogResult)
    }

Here is how you can call the function :

function OpenPopup1() {
        OpenDocsDialog("URL");
        return false;
    }


If you want to implement it directly here is the sample code:
SP.UI.ModalDialog.showModalDialog({
    url: dialogUrl,        
    allowMaximize: true,        
    showClose: true,        
    width: 400,        
    height: 200,        
    title: "Pop Up",        
    dialogReturnValueCallback: RefreshOnDialogClose
});

Monday 16 February 2015

Filter Data Table in C#.

In general code data binding , most times we need to bind data through data table. In some case we might require to filter data. There are Three different ways you can filter data in data table.

  1. Using For loop. 
  2. Using Data view.
  3. Using Linq query.

Here we will see the demo for last two options.

A. Using data view.

Code Example:

DataTable  dt = GetDataTable(); //Get data in datatable
DataView dv = dt.DefaultView;
dv.RowFilter ="id=10"; // Filter column = filter value
dv.Sort =  "id"; //sort column (Desc for descending order)


repeater1.datasource = dv;
repeater1.databind();

The problem with data view is if the filter column does not match, it will return you the full table instead of null.

Helpful Blog :

B. Using Linq query

Code Example: 


DataTable dtdata = GetDataTable(); //Get data in datatable
                 
                        var data = (from dt in dtdata.AsEnumerable()
                                    where Convert.ToString(dt["id"]) == "10" 
                                    select dt
                                   ).ToList();
                        if (data.Count > 0)
                        {
                            DataTable dtlevel3 = new DataTable();
                            dtlevel3 = data.CopyToDataTable();
                            repeater1.datasource = dv;
                            repeater1.databind();
                        }

For c# code you will require to add namespace : using  System.Linq; 
For Sharepoint you need to add namespace : using Microsoft.SharePoint.Linq;

"The File is locked for shared use by user in Sharepoint" Error Solution

When we write code in event receiver to add some custom column value on item added or item updated , sometimes we encounter error - "The File is locked for shared use by user". 

Here is the solution for this king of error.

Error code:

public override void ItemAdded(SPItemEventProperties properties)
        {
            try
            {
                base.ItemAdded(properties);
                base.EventFiringEnabled = false;
                SPListItem item = properties.ListItem;                
                item["ColName1"] = "Value";
                item["ColName1"] = "Value";
                item.Update(); // Here it throws error
                      
                base.EventFiringEnabled = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Solution : item.SystemUpdate();

public override void ItemAdded(SPItemEventProperties properties)
        {
            try
            {
                base.ItemAdded(properties);
                base.EventFiringEnabled = false;
                SPListItem item = properties.ListItem;                
                item["ColName1"] = "Value";
                item["ColName1"] = "Value";
                item.SystemUpdate();
                      
                base.EventFiringEnabled = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Wednesday 4 February 2015

Attach Event Receiver to particular list / multiple list on Feature activation sharepoint

Here is code sample for Attaching Event Receiver to particular list / multiple list on Feature activation :


For single list :

public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {

                SPWeb oWeb = properties.Feature.Parent as SPWeb;

                SPList M1list = oWeb.Lists.TryGetList("M1List");
                if (M1list != null)
                {

                    M1list.EventReceivers.Add(SPEventReceiverType.ItemAdding, Assembly.GetExecutingAssembly().FullName, "GlobalSubmit.Intranet.DMParentFolder");
                    M1list.EventReceivers.Add(SPEventReceiverType.ItemUpdating, Assembly.GetExecutingAssembly().FullName, "GlobalSubmit.Intranet.DMParentFolder");
                }
     }
     catch (Exception ex)
            {
                throw ex;
            }
        }

For Multiple list: 
public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {

                SPWeb oWeb = properties.Feature.Parent as SPWeb;

                SPList M1list = oWeb.Lists.TryGetList(Constants.M1List);
                if (M1list != null)
                {

                    M1list.EventReceivers.Add(SPEventReceiverType.ItemAdding, Assembly.GetExecutingAssembly().FullName, "Class path of event receiver");
                    M1list.EventReceivers.Add(SPEventReceiverType.ItemUpdating, Assembly.GetExecutingAssembly().FullName, "Class path of event receiver");
                }

                SPList M2list = oWeb.Lists.TryGetList(Constants.M2List);
                if (M2list != null)
                {

                    M2list.EventReceivers.Add(SPEventReceiverType.ItemAdding, Assembly.GetExecutingAssembly().FullName, "Class path of event receiver");
                    M2list.EventReceivers.Add(SPEventReceiverType.ItemUpdating, Assembly.GetExecutingAssembly().FullName, "Class path of event receiver");
                }
               
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

In this code class path is the only thing you need to worry about. If you pass it wrong then you will not be able to attach event receiver to list\library. Here is an example of class path:

If my solution name is "example.intranet" and my event receiver class name is "demoeventreceiver.cs" then my class path will be-  "example.intranet.demoeventreceiver".



For Deactivation Feature Click Here To See the code.

Remove Attached event receiver on feature deactivation sharepoint

To Remove Attached event receiver on feature deactivation use following example of code:


public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            try
            {
                if (properties != null)
                {
                    SPWeb spWeb = properties.Feature.Parent as SPWeb;
                    if (spWeb != null)
                    {
                        #region M1 List
                        SPList M1List = spWeb.Lists.TryGetList("M1List");

                        if (M1List != null)
                        {
                            SPEventReceiverDefinitionCollection oSPEventReceiverDefinitionCollection = M1List.EventReceivers;

                            System.Collections.Generic.List<SPEventReceiverDefinition> oRecieversToDelete = new System.Collections.Generic.List<SPEventReceiverDefinition>();

                            foreach (SPEventReceiverDefinition oReciever in oSPEventReceiverDefinitionCollection)
                            {
                                if (oReciever != null && oReciever.Assembly.Equals(System.Reflection.Assembly.GetExecutingAssembly().FullName))
                                {
                                    oRecieversToDelete.Add(oReciever);
                                }
                            }
                            foreach (SPEventReceiverDefinition oSPEventReceiverDefinition in oRecieversToDelete)
                            {
                                oSPEventReceiverDefinition.Delete();
                            }
                            M1List.Update();
                        }
                        #endregion

                      }

                }
            }
            catch (Exception ex)
            {
               throw ex;
            }
        }


For Feature Activation Code Sample Click Here

Get List of event receiver attached to List/Library using powershell sharepoint

To get list of event receiver attached to list /Library use followingpowershell script:

Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue
$web=Get-SPWeb "WebURL"
$list=$web.Lists["ListName"]
$list.EventReceivers | Select Name, Assembly, Type

Tuesday 3 February 2015

Save site as a template option for publishing sites sharepoint

Save site as a template option is hidden from the publishing sites.
In order to get around this issue you need to update a single property page value in your SPWeb object for the site you are trying to save as a template
and you are good to go. The property is called SaveSiteAsTemplateEnabled. We need to set that property to true that’s all.

Here is the code sample that shows how to do that using PowerShell:

Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue
$web = Get-SPWeb http://Web URL
$web.AllProperties["SaveSiteAsTemplateEnabled"] = "true"
$web.Update()


OR

Same can be done using SharePoint Designer.
1)Open web in sharepoint designer.
2)on Ribbon,(right hand last button) select Site Options >> Select Parameter Tab >> Select "SaveSiteAsTemplateEnabled".
3)click on modify button and change value from false to true.
4)click ok.

Well, since the Save site as a template option is hidden from the publishing sites settings page we all used the following URL to go there directly:

/_layouts/savetmpl.aspx

Or

/_layouts/15/savetmpl.aspx

Add, Update and Delete List Items Programmatically in Sharepoint

Using Microsoft Sharepoint APIs we can easily Add, Update and Delete list items programmatically. Provided below is a code snippet in C# .Net demonstrating all the three operations..

using (SPSite oSPsite = new SPSite("http://website url/"))
{
using (SPWeb oSPWeb = oSPsite.OpenWeb())
      {
            oSPWeb.AllowUnsafeUpdates = true;

            // Fetch the List
            SPList list = oSPWeb.Lists.TryGetList("MyList");
            if(list !=null && list.Items.Count>0)
{
//Add a new item in the List
SPListItem itemToAdd = list.Items.Add();
itemToAdd["Title"] = "Test Title";
itemToAdd["Description"] = "Test Description";
itemToAdd.Update();

// Get the Item ID
listItemId = itemToAdd.ID;

// Update the List item by ID
SPListItem itemToUpdate = list.GetItemById(listItemId);
itemToUpdate["Description"] = "Changed Description";
itemToUpdate.Update();

// Delete List item
SPListItem itemToDelete = list.GetItemById(listItemId);
itemToDelete.Delete();
}
            oSPWeb.AllowUnsafeUpdates = false;
       }
}