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;
       }
}

Tuesday, 13 January 2015

Seperate comma seperated value and store in temp data table

If you want to seperate values by comma or something here is the solution.


DECLARE @data NVARCHAR(MAX),
@delimiter NVARCHAR(5)
SELECT @data = 'abc-abc-abc'
set @delimiter = '-'
DECLARE @textXML XML;
SELECT @textXML = CAST('<d>' + REPLACE(@data, @delimiter, '</d><d>') + '</d>' AS XML);

declare @temp table (num nvarchar(max))
insert into @temp
SELECT T.split.value('.', 'nvarchar(max)') AS data
FROM @textXML.nodes('/d') T (split)

select * from @temp

Wednesday, 7 January 2015

different ways of extracting different parts of URL

Here is the sample how you can have different ways of extracting different parts of URL

EXAMPLE (Sample URL)

http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QuerrString2=2

CODE

Response.Write("<br/> " + HttpContext.Current.Request.Url.Host);
Response.Write("<br/> " + HttpContext.Current.Request.Url.Authority);
Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsolutePath);
Response.Write("<br/> " + HttpContext.Current.Request.ApplicationPath);
Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsoluteUri);
Response.Write("<br/> " + HttpContext.Current.Request.Url.PathAndQuery);
OUTPUT

localhost
localhost:60527
/WebSite1test/Default2.aspx
/WebSite1test
http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QuerrString2=2
/WebSite1test/Default2.aspx?QueryString1=1&QuerrString2=2


If you have something like this:

"http://localhost:1234/Default.aspx?un=asdf&somethingelse=fdsa"
or like this:

"https://www.something.com/index.html?a=123&b=4567"
and you only want the part that a user would type in then this will work:

String strPathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
String strUrl = HttpContext.Current.Request.Url.AbsoluteUri.Replace(strPathAndQuery, "/");
which would result in these:

"http://localhost:1234/"
"https://www.something.com/"

Wednesday, 31 December 2014

Add Custom Webppart to MySite Sharepoint -I

Recently I have requirement to modify the About Me page in My Site.I have create a site feature and in its event receiver added some code. Here is the solution if you have same requirement :


If you want to add Content Editor web part :

string Username = SPContext.Current.Web.CurrentUser.Name;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPWeb web = siteCollection.OpenWeb())
                    {
                        if (web.WebTemplate == "SPSMSITEHOST")
                        {
                            //About Me Webpart
                            ContentEditorWebPart contentEditor = new ContentEditorWebPart();

                            XmlDocument xmlDoc = new XmlDocument();
                            XmlElement xmlElement = xmlDoc.CreateElement("HtmlContent");
                            xmlElement.InnerText = "<strong>About " + Username + "</strong>";
                            contentEditor.Content = xmlElement;
                            contentEditor.ChromeType = PartChromeType.None;
                            using (SPLimitedWebPartManager manager =
                              web.GetLimitedWebPartManager("Person.aspx", PersonalizationScope.Shared))
                            {
                                manager.AddWebPart(contentEditor, "TopZone", 2);
                            }                          
                        }
                    }
                });

If you want to add custom web part to page:
Add-custom-webppart-to-mysite

Add Custom Webppart to MySite Sharepoint -II

If you want to modify MySite with custom web part, here is the solution.


SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPWeb web = siteCollection.OpenWeb())
{
if (web.WebTemplate == "SPSMSITEHOST")
{
//User Info Webpart
AddWebPartToPage(web, "Person.aspx", "UserInformation", "TopZone", 1);                          
}
}
});

Support Methods:

/// <summary>
/// Method to Get the custom web part
/// </summary>
/// <param name="web">web Url</param>
/// <param name="pageUrl">Page Name</param>
/// <param name="webPartName">Webpart name</param>
/// <param name="zoneID">Zone where you want to deploy webpart</param>
/// <param name="zoneIndex">Zone index</param>
/// <returns></returns>
public static string AddWebPartToPage(SPWeb web, string pageUrl, string webPartName, string zoneID, int zoneIndex)
{
using (SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared))
{
IList<System.Web.UI.WebControls.WebParts.WebPart> _listFormWebParts = (from _wp in manager.WebParts.Cast<System.Web.UI.WebControls.WebParts.WebPart>()
  where string.Compare(_wp.Title, webPartName, true) == 0
  select _wp).ToList();

//Check if there are any web parts found
if (_listFormWebParts == null || _listFormWebParts.Count == 0)
{
using (System.Web.UI.WebControls.WebParts.WebPart webPart = CreateWebPart(web, webPartName, manager))
{
if (webPart != null)
{
manager.AddWebPart(webPart, zoneID, zoneIndex);
return webPart.ID;
}
else
return "Web part not found";
}
}
else
return "exists";
}
}

/// <summary>
/// Create webpart from webpart template
/// </summary>
/// <param name="web">Web Url</param>
/// <param name="webPartName">webpart template name</param>
/// <param name="manager">SPLimitedWebPartManager object</param>
/// <returns></returns>
public static System.Web.UI.WebControls.WebParts.WebPart CreateWebPart(SPWeb web, string webPartName, SPLimitedWebPartManager manager)
{
SPQuery query = new SPQuery();
//query.Query = String.Format(CultureInfo.CurrentCulture, "&lt;Where&gt;&lt;Eq&gt;&lt;FieldRef Name='FileLeafRef'/&gt;&lt;Value Type='File'&gt;{0}&lt;/Value&gt;&lt;/Eq&gt;&lt;/Where&gt;", webPartName);

query.Query = String.Concat("<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + webPartName + "</Value></Eq></Where>");
SPList webPartGallery = null;
if (null == web.ParentWeb)
{
webPartGallery = web.GetCatalog(SPListTemplateType.WebPartCatalog);
}
else
{
webPartGallery = web.Site.RootWeb.GetCatalog(SPListTemplateType.WebPartCatalog);
}          

SPListItemCollection webParts = webPartGallery.GetItems(query);
if (webParts == null)
{
return null;
}
XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());
string errorMessage;
System.Web.UI.WebControls.WebParts.WebPart webPart = manager.ImportWebPart(xmlReader, out errorMessage);
webPart.ChromeType = PartChromeType.None;
return webPart;
}

Tuesday, 30 December 2014

Error : "Thread was being aborted" - Resolution

sometimes when we try to create sub site using site template or we might have some code that takes longer time to debug, it will time out and the error will show that "Thread was being aborted".

In my case I follow following steps and get rid from it.

1.    In a basic text editor such as Notepad, open the web.config file
2.    Press CTRL + F to open the Find dialog box.
3.    Find the following tag:
 <httpRuntime maxRequestLength="51200" />
4.    Replace it with this tag:
 <httpRuntime executionTimeout="6000" maxRequestLength="51200" />


Original Post: thread-was-being-aborted-error.

SharePoint Classic Site Retirement: Your Plan to Avoid Last-Minute Chaos

Classic SharePoint has been on borrowed time for years. Microsoft has now put dates on the remaining pieces. Microsoft will disable creation...