Search This Blog

Saturday, December 24, 2016

How to install an App in SharePoint 2013 programmatically using c#

The below method is used to install the app in the sharepoint site programmatically using C#

InstallAppPart("http://sharepoint2013/site/","d:\\SampleApp\TestApp.app")

public void InstallAppPart(string WebURL, string AppFullPath)
{
   Guid appId = Guid.Empty;

    using(site = new SPSite(WebURL))
   {
       using(web = site.OpenWeb())
       {
            Stream package = null;
            try
           {
              //This code is used to start installing the app
              package = File.OpenRead(AppFullPath);
              SPAppInstance appInstance = web.LoadAndInstallApp(package);
              if (appInstance != null && appInstance.Status == SPAppInstanceStatus.Initialized)
             {
                //Your App is started installing now
                 appId = appInstance.Id;
             }
 
           //This code is used to check the app completeley installed in the sharepoint site
          SPAppInstance newAppInstance = null;
          int maxTry = 150;
          int count = 0;
          do
          {
              Thread.Sleep(1000);
              newAppInstance = web.GetAppInstanceById(appId);
              count++;
          }
          while (newAppInstance != null && newAppInstance.Status != SPAppInstanceStatus.Installed             && count  < maxTry);

         if(newAppInstance != null && newAppInstance .Status == SPAppInstanceStatus.Installed)
         {
                  Console.WriteLine("App installation complete. App URL:" +                localInstance.AppWebFullUrl.ToString());
         }
     }
     finally
     {
        if (package != null)
           package.Close();
     }
   }
 }
}

Sunday, December 11, 2016

Create Promoted Links/My Report Library/Asset Library list in SharePoint 2013 using Client Object Model C#

using Microsoft.SharePoint.Client;

//use one of the templateName that suits your purpose
string templateName = "Promoted Links";
string templateName = "Report Library";
string templateName = "Asset Library";
string templateName = "Custom List";

ClientContext ctx = new ClientContext(weburl);
ctx.Credentials = new SharePointOnlineCredentials(userName, passWord);

Web web = ctx.Web;

// Get the list template by name
ListTemplate listTemplate = web.ListTemplates.GetByName(templateName);

ctx.Load(listTemplate);
ctx.ExecuteQuery();

// Create a new object for ListCreationInformation class - used to specify the // properties of the new list
ListCreationInformation creationInfo = new ListCreationInformation();

// Specify the title of your List
creationInfo.Title = "My Custom List";

// Specify the list description, if any
creationInfo.Description = "Description";

// Set a value that specifies the feature identifier of the feature 
// that contains the list schema for the new list.
creationInfo.TemplateFeatureId = listTemplate.FeatureId;

// Set a value that specifies the list server template of the new list
creationInfo.TemplateType = listTemplate.ListTemplateTypeKind;

web.Lists.Add(creationInfo);
ctx.ExecuteQuery();

Attach Event Receiver to SharePoint List using CSOM (Client Side Object Model)

using Microsoft.SharePoint.Client;
using System;
using System.Net;
 
private static void AttachEventReceiver()
{
            var userName = "<<UserNameWithoutDomainName>>";
            var password = "<<Password>>";
            string domain = "<<DomainName>>";
            string webUrl = "<<WebUrl>>";
 
            using (var context = new ClientContext(webUrl))
            {
                context.Credentials = new NetworkCredential(userName, password, domain);
                var list = context.Web.Lists.GetByTitle("<<ListName>>");
                var eventReceivers = list.EventReceivers;
                context.Load(eventReceivers);
                context.ExecuteQuery();
 
                EventReceiverType eventType = EventReceiverType.ItemUpdated;    //event type (ItemAdded / ItemUpdated)
                string receiverAssembly = "<<FullyQualifiedAssemblyName>>";     //Example: <<AssemblyName>>, Version=<<AssemblyVersion>>, Culture=neutral, PublicKeyToken=<<PublicKeyToken>>
                string receiverClass = "<<ReceiverClassNameStartingWithNamespaceName>>";    //Example: <<NamespaceName>>.<<ClassName>>
                string receiverName = "<<ReceiverName>>";       //you can give any name
 
                bool isEventReceiverAlreadyAssociated = false;
                foreach (var eventReceiver in eventReceivers)
                {
                    if (eventReceiver.EventType == eventType
                            && string.Compare(eventReceiver.ReceiverAssembly, receiverAssembly, StringComparison.OrdinalIgnoreCase) == 0
                            && string.Compare(eventReceiver.ReceiverClass, receiverClass, StringComparison.OrdinalIgnoreCase) == 0
                            && string.Compare(eventReceiver.ReceiverName, receiverName, StringComparison.OrdinalIgnoreCase) == 0
                        )
                    {
                        isEventReceiverAlreadyAssociated = true;
                    }
                }
 
                if (!isEventReceiverAlreadyAssociated)
                {
                    EventReceiverDefinitionCreationInformation eventReceiver
                                       = new EventReceiverDefinitionCreationInformation
                                         {
                                               EventType = eventType,
                                               ReceiverAssembly = receiverAssembly,
                                               ReceiverClass = receiverClass,
                                               ReceiverName = receiverName,
                                          };
 
                    list.EventReceivers.Add(eventReceiver);
                    context.ExecuteQuery();
                }
            }
 }  

Adding Remote Event Receivers To An Exisiting List In Office 365

// This Below method is used to build creation information for the event receiver.

public static EventReceiverDefinitionCreationInformation CreateGenericEventRecieverWithoutEventType()
{
string remoteAppurl = HttpContext.Current.Request["RemoteAppUrl"];
string remoteEventEndPointUrl = String.Format("{0}/ServiceName.svc", remoteAppurl);
EventReceiverDefinitionCreationInformation eventReceiver = new EventReceiverDefinitionCreationInformation();
eventReceiver.ReceiverName = "Give Your Receiver Name";
eventReceiver.ReceiverUrl = remoteEventEndPointUrl;
eventReceiver.SequenceNumber = 5000;
eventReceiver.ReceiverClass = "Fully qualified Path To RER Assembly";
eventReceiver.ReceiverAssembly = Assembly.GetExecutingAssembly().FullName;
return eventReceiver;
}

// The below method is used to check whether the event receiver is already exists in the lists or not

public static bool DoesEventReceiverDefintionExistBasedOnCreationInfo(EventReceiverDefinitionCreationInformation info, List list)
{
bool exists = false;
list.Context.Load(list, x => x.EventReceivers);
list.Context.ExecuteQuery();
foreach (EventReceiverDefinition eventReceiverDefinition in list.EventReceivers)
{
string innerDefId = eventReceiverDefinition.ReceiverClass;
string outerDefId = info.ReceiverClass;
if (innerDefId.Equals(outerDefId, StringComparison.InvariantCultureIgnoreCase))
{
exists = true;
break;
}
}
return exists;
}

// Since the receivers were built without a specific event type, you can specify as many receiver capture behaviors as you want, as demonstrated in the below example.

public static void AttachEventReceiver(ClientContext context, List list)
{
EventReceiverDefinitionCreationInformation eventReceiver =CreateGenericEventRecieverWithoutEventType();
eventReceiver.EventType = EventReceiverType.ItemAdded;
if (!DoesEventReceiverDefintionExistBasedOnCreationInfo(eventReceiver, list))
{
list.EventReceivers.Add(eventReceiver);
}
eventReceiver = CreateGenericEventRecieverWithoutEventType();
eventReceiver.EventType = EventReceiverType.ItemUpdated;
if (!DoesEventReceiverDefintionExistBasedOnCreationInfo(eventReceiver, list))
{
list.EventReceivers.Add(eventReceiver);
}
eventReceiver = CreateGenericEventRecieverWithoutEventType();
eventReceiver.EventType = EventReceiverType.ItemDeleted;
if (!DoesEventReceiverDefintionExistBasedOnCreationInfo(eventReceiver, list))
{
list.EventReceivers.Add(eventReceiver);
}
eventReceiver = CreateGenericEventRecieverWithoutEventType();
eventReceiver.EventType = EventReceiverType.ItemFileMoved;
if (!DoesEventReceiverDefintionExistBasedOnCreationInfo(eventReceiver, list))
{
list.EventReceivers.Add(eventReceiver);
}
context.ExecuteQuery();
}

//The below method is used to delete event receivers in the list 

public static void DeleteEventReceiver(ClientContext context, List list)
{
EventReceiverDefinitionCollection eventReceiverDefinitionCollection = list.EventReceivers;
context.Load(eventReceiverDefinitionCollection);
context.ExecuteQuery();
List<Guid> ids = eventReceiverDefinitionCollection.Select(eventReceiverDefinition => eventReceiverDefinition.ReceiverId).ToList();
foreach (EventReceiverDefinition definition in ids.Select(eventReceiverDefinitionCollection.GetById))
{
definition.DeleteObject();
context.ExecuteQuery();
}
}

Thursday, November 10, 2016

How to check event receivers for web using Powershell

Add-PSSnapin microsoft.sharepoint.powershell
$web = Get-SPWeb "*subsiteurl*"
$web.EventReceivers | sort Type | ft Class, Type

Click Here to check How to attach web event receivers using powershell

Attach Web Event Receivers using Powershell



# Defintion of function to attach web event receivers
# if they are not already added
Function AddWebEventReceivers($webER)
{
  $assembly = "*fully_qualified_assembly_name*"
  $class = "*class_name_including_namespace*"
  # To Check fully qualified assembly name Click Here
  # Only attach receivers if there aren't already added
  # You can make the check more specific by checking the Type
  # property as well if required
  $existingER = $webER.EventReceivers | Where { $_.Class -eq $class }
  if($existingER -eq $null -or $existingER.length -eq 0)
  {
    $webER.EventReceivers.Add("WebDeleting", $assembly, $class)
  }
}

# Iterate all webs and attach the web event receivers to
$web = Get-SPWeb "*SubsiteUrl*"
$subwebs = $web.GetSubwebsForCurrentUser()
foreach($web in $subwebs)
{
  try
  {
    AddWebEventReceivers($web)
    Write-Host "Event Receiver attached to web: $web"
  }
  catch [System.Exception]
  {
    $errorMessage = $Error[0]
    Write-Host "Failed: $errorMessage" -NoNewline -F Red
  }
  finally
  {
    $web.Dispose()
  }
}
$web.Dispose()

Saturday, October 22, 2016

Sharepoint 2013 Vs Sharepoint 2010

SharePoint 2013SharePoint 2010
What is SharePoint 2013 (Preview) –
A new version of Microsoft famous Collaboration portal called SharePoint. The version adds few new exciting features such as Social Feed,SharePoint Apps and cross-site publishing.
What is SharePoint 2010 – It is a previous or I should say current version of SharePoint that was released in year 2010.
Development Changes –
  • In SharePoint 2013 Microsoft Introduced a new Cloud App Model for designing Apps for SharePoint. Apps for SharePoint are self-contained pieces of functionality that extend the capabilities of a SharePoint website. You can use HTML, CSS, JavaScript and protocols like the Open Data protocol (OData), and OAuth to communicate with SharePoint using Apps.
  • Tools – SharePoint 2013 has Introduced new Tools for App development. Visual Studio 2012 now lets you develop apps for SharePoint and apps for Office. In addition a new web-based tools called “Napa” Office 365 Development Tools were introduced for developing apps.
  • No more Sandbox solutions. SharePoint 2013 sandboxed solutions are deprecated. So all we got is the New App model and the Old SharePoint Farm solutions. check outSharePoint 2013 – Apps Vs Farm solutions
Development Changes –
  • SharePoint 2010 Introduced Sandbox solutions to help developers deploy code that did not effect the whole farm.
  • In SharePoint 2010 you could use Server Object model and Client Object model (.Net Managed, ECMASCRIPT and silverlight) to extract data from SharePoint.
  • In SharePoint 2010 developers were also developing Farm solutions as they did with the previous SharePoint 2007 version.
Social and Collaboration features – 
Microsoft in SharePoint 2013 Introduced new Social capabilities for better collaboration in the company.New Features added are –
  • Interactive feed
  • Community Site
  • Follow people
  • Follow Sites
Social and Collaboration features –SharePoint 2010 had very few social capabilities.
  • My sites
  • Tags and Tag profile pages
  • Notes
Search – SharePoint 2013 includes several enhancements, custom content processing with the Content Enrichment web service, and a new framework for presenting search result types. Some of the features added are –
  • Consolidated Search Results
  • Rich Results Framework
  • keyword query language (KQL) enhancements
Search – SharePoint 2010 had Introduced Integrated FAST search as an Enterprise search. In addition to this build-in SharePoint search is still widely used in companies.
Enterprise Content Management (ECM) –
SharePoint 2013 added some of the best capabilities of an ECM software. The newly added stuff is
  • Design Manager
  • Managed Navigation
  • Cross-site Publishing
  • EDiscovery
Enterprise Content Management (ECM) –SharePoint 2010 on the other hand had Introduced Managed metadata and taxonomy as a part of new ECM benefits for SP 2010. This version did not had Managed Navigation and Cross-site Publishing. SharePoint designer was a primary tool to modify Master pages instead of the new Design Manager.

Thursday, October 20, 2016

Export SPGridView to Excel spreadsheet in Sharepoint 2013

using System;
using System.IO;
using System.Web;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Web.UI.WebControls;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace ExportGridtoExcel
{
    [Guid("2fa65763-1ef1-4173-8a77-685e840f0196")]
    public class ExportGridtoExcel : System.Web.UI.WebControls.WebParts.WebPart
    {
        SPGridView myGridView;
        SPDataSource myDataSource = new SPDataSource();
        Button oBtn_Export;

        protected override void CreateChildControls()
        {
            oBtn_Export = new Button();
            oBtn_Export.Text = "Export to Excel";
            oBtn_Export.CssClass = "ButtonHeightWidth";
            oBtn_Export.Click += new EventHandler(oBtn_Export_Click);
            this.Controls.Add(oBtn_Export);

            myGridView = new SPGridView();
            myGridView.Enabled = true;
            myGridView.AutoGenerateColumns = false;                    

            SPBoundField colTitle = new SPBoundField();
            colTitle.DataField = "Country";
            colTitle.HeaderText = "Country";
            this.myGridView.Columns.Add(colTitle);

            SPBoundField colMission = new SPBoundField();
            colMission.DataField = "State";
            colMission.HeaderText = "State";
            this.myGridView.Columns.Add(colMission);

            this.Controls.Add(myGridView);
        }

        void oBtn_Export_Click(object sender, EventArgs e)
        {
            ExportToExcel("CountryState.xls", myGridView);
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            SPSite mySite = SPContext.Current.Site;
            SPWeb myWeb = SPContext.Current.Web;
            SPList list = myWeb.Lists["Countries"];
            myDataSource.List = list;
            myGridView.DataSource = myDataSource;
            myGridView.DataBind();
        }

        public static void ExportToExcel(string strFileName, SPGridView gv)
        {
            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    //  Create a form to contain the grid
                    Table table = new Table();

                    //  add the header row to the table
                    if (gv.HeaderRow != null)
                    {
                        PrepareControlForExport(gv.HeaderRow);
                        table.Rows.Add(gv.HeaderRow);
                    }

                    //  add each of the data rows to the table
                    foreach (GridViewRow row in gv.Rows)
                    {
                        PrepareControlForExport(row);
                        table.Rows.Add(row);
                    }

                    //  add the footer row to the table
                    if (gv.FooterRow != null)
                    {
                        PrepareControlForExport(gv.FooterRow);
                        table.Rows.Add(gv.FooterRow);
                    }

                    //  render the table into the htmlwriter
                    table.RenderControl(htw);

                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.AddHeader("content-disposition",
                   string.Format("attachment; filename={0}", strFileName));
                    HttpContext.Current.Response.ContentType = "application/ms-excel";
                    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    //render the htmlwriter into the response
                    HttpContext.Current.Response.Write(sw.ToString());
                    HttpContext.Current.Response.End();
                }
            }
        }

        private static void PrepareControlForExport(Control control)
        {
            for (int i = 0; i < control.Controls.Count; i++)
            {
                Control current = control.Controls[i];
                if (current is LinkButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
                }
                else if (current is ImageButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
                }
                else if (current is HyperLink)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
                }
                else if (current is DropDownList)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
                }
                else if (current is CheckBox)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
                }

                if (current.HasControls())
                {
                    PrepareControlForExport(current);
                }
            }
        }
    }
}

A Quick Guide to Getting and Setting the various SPField types using C#

Introduction

This article demonstrates how to set and get the various SPField types for a SharePoint list using C#.

The examples demonstrated set and get fields from an item that belongs to a custom list. The custom list contains a number of fields, and all the fields are named based on the type of field they are. For example, there is a Text field, which has been named, textfield. This is depicted in the following picture:





Applies To

The examples demonstrated below are tested with and apply to the following versions of SharePoint:
SharePoint 2010
SharePoint 2013

Get the List, and the first SPListItem

This is the basic code for getting an item. If the list has at least one item, the first item is retrieved, otherwise a new item is created.

var web = SPContext.Current.Site.RootWeb;
var list = web.Lists.TryGetList("fieldslist");
if (list == null) return;
//Get Item 1, or add a new item if the list doesn't contain any items
SPListItem item;
item = list.ItemCount > 0 ? list.Items[0] : list.Items.Add();

Create Variables used in the Examples

//Date of current update
var t = DateTime.Now.ToLongTimeString();
//StringBuilder for output
var s = new StringBuilder();
//Variable for storing temporary values
String value;

Set and Get the Title

Set the title

//Set the Title

item["Title"] = String.Format("Title updated at {0}",t);

Get the title

value = item["Title"].ToString();
s.AppendLine(String.Format("<span>Title Field: {0}</span></br>", value));

Set and Get a Text Field

Set a text field

item["textfield"] = String.Format("At {0} dogs still can't write poems", t);
item.Update();

Get a text field

value = item["textfield"].ToString();
s.AppendLine(String.Format("<span>Text Field: {0}</span></br>", value));

Set and Get a Note (or RichText) Field

Set a note field

item["notefield"] = String.Format("At {0} dogs still can't write poems. \r\nBut then, neither can I!", t);
item.Update();

Get a note field

value = item["notefield"].ToString();
s.AppendLine(String.Format("<span>Note Field: {0}</span></br>", value));

Set and Get a Yes/No Field (Boolean)

Set a yes/no field

item["yesnofield"] = false;
item.Update();

Get a yes/no field

value = item["yesnofield"].ToString();
s.AppendLine(String.Format("<span>Yes/No Field: {0}</span></br>", value));


Set and Get a Number Field

The type of a Number field is a Double. When you get the number from the field, you can use standard numeric format specifies to format the number for display. See Double.ToString for more information.

Set a number field

item["numberfield"] = 35;
//Or
item["numberfield"] = Double.Parse("354.67");
item.Update();

Get a number field

value = item["numberfield"].ToString();
s.AppendLine(String.Format("<span>Number Field: {0}</span></br>", value));
value = Double.Parse(item["numberfield"].ToString()).ToString("F1");
s.AppendLine(String.Format("<span>Number Field (one decimal place): {0}</span></br>", value));
value = Double.Parse(item["numberfield"].ToString()).ToString("F0");
s.AppendLine(String.Format("<span>Number Field (two decimal places): {0}</span></br>", value));

Set and Get a Currency (Number) Field

A currency field uses the same SharePoint field type as Number (SPFieldNumber). The type of a Number field is a Double. When you get the number from the field, you can use standard numeric format specifies to format the number for display, specifically, formatting it as a currency. See Double.ToString for more information.

Set a currency field

item["currencyfield"] = Double.Parse("354.67");
item.Update();

Get a currency field

value = item["currencyfield"].ToString();
s.AppendLine(String.Format("<span>Currency Field: {0}</span></br>", value));
value = Double.Parse(item["currencyfield"].ToString()).ToString("C2");
s.AppendLine(String.Format("<span>Currency Field (formatted as a currency): {0}</span></br>", value));
value = (Double.Parse(item["numberfield"].ToString()) + 123).ToString("C2");
s.AppendLine(String.Format("<span>Currency Field (addition): {0}</span></br>", value));

Set and Get a Percent (Number) Field

A percentage field uses the same SharePoint field type as Number (SPFieldNumber). The type of a Number field is a Double. When you get the number from the field, you can use standard numeric format specifies to format the number for display, specifically, formatting it as a percentage. See Double.ToString for more information.

Set a percent field

item["percentfield"] = Double.Parse("0.8735");
item.Update();

Get a percent field

value = item["percentfield"].ToString();
s.AppendLine(String.Format("<span>Percent Field: {0}</span></br>", value));
value = Double.Parse(item["percentfield"].ToString()).ToString("P0");
s.AppendLine(String.Format("<span>Percent Field (formatted as a percent, and as a whole number): {0}</span></br>", value));
value = Double.Parse(item["percentfield"].ToString()).ToString("P2");
s.AppendLine(String.Format("<span>Percent Field (formatted as a percent, with two decimal places): {0}</span></br>", value));

Set and Get a Date Field

To set a date field, use a System.DateTime object to create a date, then assign the DateTime object to the list item's field. When you retrieve the value of a DateTime field, you can use standard date format specifiers to format the output of the value. See DateTime.ToString for more information.

Set a date field

item["datefield"] = DateTime.Now;
//Or, set the date to Now + two days
item["datefield"] = DateTime.Now.AddDays(2);
item.Update();

Get a date field

value = item["datefield"].ToString();
s.AppendLine(String.Format("<span>Date Field: {0}</span></br>", value));
value = DateTime.Parse(item["datefield"].ToString()).ToString("d");
s.AppendLine(String.Format("<span>Date Field (using the \"6/15/2008\" format): {0}</span></br>", value));
value = DateTime.Parse(item["datefield"].ToString()).ToString("D");
s.AppendLine(String.Format("<span>Date Field (using the \"Sunday, June 15, 2008\" format): {0}</span></br>", value));
value = DateTime.Parse(item["datefield"].ToString()).ToString("R");
s.AppendLine(String.Format("<span>Date Field (using the \"Sun, 15 Jun 2008 21:15:07 GMT\" format): {0}</span></br>", value));
var dateValue = DateTime.Parse(item["datefield"].ToString());
value = dateValue.AddDays(13).ToString("dd-MMM-yy");
s.AppendLine(String.Format("<span>Date Field (using a custom display format): {0}</span></br>", value));

Set and Get a Choice Field

Set a choice field

item["choicefield"] = list.Fields["choicefield"].GetFieldValue("Green");
item.Update();
//Or, to add a new value
var choiceField = list.Fields["choicefield"] as SPFieldChoice;
if (!choiceField.Choices.Contains("Aquamarine"))
{
    choiceField.AddChoice("Aquamarine");
    choiceField.Update();
}
item["choicefield"] = list.Fields["choicefield"].GetFieldValue("Aquamarine");
item.Update();

Get a choice field

value = item["choicefield"].ToString();
s.AppendLine(String.Format("<span>Choice Field: {0}</span></br>", value));

Set and Get a Multi-Choice Field

Set a multi-choice field

var choicevalues = new SPFieldMultiChoiceValue();
choicevalues.Add("Green");
choicevalues.Add("Blue");
item["multiplechoicefield"] = choicevalues;
item.Update();

Get a multi-choice field

list.Fields["multiplechoicefield"].ParseAndSetValue(item, choicevalues.ToString());
var multipleChoiceValues = new SPFieldMultiChoiceValue(item["multiplechoicefield"].ToString());
s.AppendLine(String.Format("<span>Multiple Choice Field: {0}</span></br>", multipleChoiceValues));
for (int i = 0; i <= multipleChoiceValues.Count - 1; i++)
{
    s.AppendLine(String.Format("<span>Multiple Choice Field, value {0}: {1}</span></br>", i, multipleChoiceValues[i]));
}

Set and Get a Person Field

Set a person field

item["personfield"] = web.EnsureUser("contoso\\fred");
//or
item["personfield"] = web.EnsureUser("fred@contoso.com");
item.Update();

Get a person field

value = item["personfield"].ToString();
s.AppendLine(String.Format("<span>Person Field: {0}</span></br>", value));
var userFieldValue = new SPFieldUserValue(web, item["personfield"].ToString());
s.AppendLine(String.Format("<span>Person Field: Name = {0}, Email = {1}</span></br>", userFieldValue.User.Name, userFieldValue.User.Email));

Set and Get a Multi-Person Field

Set a multi-person field

var lotsofpeople = new SPFieldUserValueCollection(web, item["lotsofpeoplefield"].ToString());
var personA = web.EnsureUser("contoso\\fred");
var personAValue = new SPFieldUserValue(web, personA.ID, personA.LoginName);
var personB = web.EnsureUser("contoso\\barnie");
var personBValue = new SPFieldUserValue(web, personB.ID, personB.LoginName);
lotsofpeople.Add(personAValue);
lotsofpeople.Add(personBValue);
item["lotsofpeoplefield"] = lotsofpeople;
item.Update();

Get a multi-person field

var fieldUserValueCollection = new SPFieldUserValueCollection(web, item["lotsofpeoplefield"].ToString());
s.AppendLine(String.Format("<span>MultiPerson Field: {0}</span></br>", fieldUserValueCollection));
var userCount = 1;
foreach (SPFieldUserValue v in fieldUserValueCollection)
{
    s.AppendLine(String.Format("<span>MultiPerson Field, value {0}: {1}</span></br>", userCount, v.User.Name));
    userCount++;
}

Set and Get a Lookup Field

Set a lookup field

var lookupField = list.Fields["lookupfield"] as SPFieldLookup;
var lookupList = web.Lists[new Guid(lookupField.LookupList)];
var lookupitem = lookupList.Items[0];
//-or-
//lookupitem = lookupList.GetItemByUniqueId(new Guid("fc71b84c-74d4-4f7c-9eed-fb7a5fbe24a6"));
//-or-
//lookupitem = lookupList.GetItemById(1);
var lookupValue = new SPFieldLookupValue(lookupitem.ID, lookupitem.ID.ToString());
item["lookupfield"] = lookupValue;
item.Update();

Get a lookup field

var lookupItemValue = new SPFieldLookupValue(item["lookupfield"].ToString());
value = lookupItemValue.LookupValue;
s.AppendLine(String.Format("<span>Lookup Field: {0}</span></br>", value));

Setting and Getting a HyperLink Field

Set a hyperlink field

var hyperlinkField = list.Fields["hyperlinkfield"] as SPFieldUrl;
var urlFieldValue = new SPFieldUrlValue();
urlFieldValue.Description = "Microsoft";
urlFieldValue.Url = "http://www.microsoft.com";
//SharePoint 2013 Only
hyperlinkField.ValidateParseAndSetValue(item, urlFieldValue.ToString());
//SharePoint 2010 and SharePoint 2013
hyperlinkField.ParseAndSetValue(item, urlFieldValue.ToString());
item.Update();

Get a hyperlink field

var hyperlinkFieldValue = new SPFieldUrlValue(item["hyperlinkfield"].ToString());
value = String.Format("<a href=\"{1}\" alt=\"{0}\">{0}</a>", hyperlinkFieldValue.Description, hyperlinkFieldValue.Url);
s.AppendLine(String.Format("<span>Hyperlink Field: {0}</span></br>", value));

Setting and Getting a Managed Metadata Field

Set a Managed Metadata field

var managedMetaDataField = list.Fields["managedmetadatafield"] as TaxonomyField;
var termsetId = managedMetaDataField.TermSetId;
var termstoreId = managedMetaDataField.SspId;
var taxonomySession = new TaxonomySession(web.Site);
var termstore = taxonomySession.TermStores[termstoreId];
var termset = termstore.GetTermSet(termsetId);
var termname = "Rubbish Tip";
var terms = termset.GetTerms(termname, false);
Term term;
if (terms.Count == 0)
{
    term = termset.CreateTerm(termname, termstore.Languages[0]);
    termstore.CommitAll();
}
else
{
    term = terms[0];
}
managedMetaDataField.SetFieldValue(item, term);
item.Update();

Get a Managed Metadata field

var taxonomyFieldValue = item["managedmetadatafield"] as TaxonomyFieldValue;
s.AppendLine(String.Format("<span>Taxonomy Field: {0} ({1})</span></br>", taxonomyFieldValue.Label, taxonomyFieldValue.TermGuid));

Setting and Getting a Multiple Valued Managed Metadata Field

Set a Multiple Valued Managed Metadata field

var managedMetaDataField = list.Fields["managedmetadatafield"] as TaxonomyField;
var termsetId = managedMetaDataField.TermSetId;
var termstoreId = managedMetaDataField.SspId;
var taxonomySession = new TaxonomySession(web.Site);
var termstore = taxonomySession.TermStores[termstoreId];
var termset = termstore.GetTermSet(termsetId);
var multipleManagedMetaDataField = list.Fields["multiplemanagedmetadatafield"] as TaxonomyField;
var termCollection = new TaxonomyFieldValueCollection(multipleManagedMetaDataField);
var taxonomyLabels = new[] {"Frog Catcher", "Giraffe Stealer", "Moon Dog"};
Term term;
foreach (var label in taxonomyLabels)
{
    var terms = termset.GetTerms(label, false);
    term = null;
    if (terms.Count == 0)
    {
        term = termset.CreateTerm(label, termstore.Languages[0]);
        termstore.CommitAll();
    }
    else
    {
        term = terms[0];
    }
    var termValue = new TaxonomyFieldValue(multipleManagedMetaDataField);
    termValue.TermGuid = term.Id.ToString();
    termValue.Label = term.Name;
    termCollection.Add(termValue);
}
multipleManagedMetaDataField.SetFieldValue(item, termCollection);
item.Update();

Get a Multiple Valued Managed Metadata field

var taxonomyFieldValueCollection = item["multiplemanagedmetadatafield"] as TaxonomyFieldValueCollection;
value = String.Empty;
foreach (var taxonomyValue in taxonomyFieldValueCollection)
{
    value = String.IsNullOrEmpty(value)
                ? String.Format("{0} ({1})", taxonomyValue.Label, taxonomyValue.TermGuid)
                : String.Format("{0}, {1} ({2})", value, taxonomyValue.Label, taxonomyValue.TermGuid);
    //Or, to use get the term
    var currentTerm = termstore.GetTerm(new Guid(taxonomyValue.TermGuid));
    //do something with the term
}
s.AppendLine(String.Format("<span>Multiple Taxonomy Field Values: {0})</span></br>", value));

Setting and Getting a Calculated Field

Calculated fields work in a different manner to that of normal fields. A formula is set on the list field, and when a list item is added or updated, the value of the column for that list item is calculated based on the formula.

Get a Calculated Field value 

Get a reference to the calculated field. Then get a reference to the list item. Finally, call the GetFieldValueAsText method, passing in the value of the item objects calculated field.

var calculatedfield = list.Fields["calculatedfield"] as SPFieldCalculated;
value = calculatedfield.GetFieldValueAsText(item["calculatedfield"]);
s.AppendLine(String.Format("<span>Calculated Field: {0}</span></br>", value));

Set the Properties of a Calculated Field 

The value of a calculated field is calculated at the time a list item is created or updated. It is not possible to directly set this value. You can use the following methods to set the formula though, which is used to calculate the fields value. Before looking at these methods, there are four main properties that can be set on a calculated field; Formula, OutputType, DisplayFormat and DateFormat. Which properties you need to set, depends on the value of the calculation.
Formula: The formula used to calculate the value.
OutputType: The type of the value that results from the calculation. Supported types are, Text, Number, Integer, Currency, Boolean and DateTime.
DisplayFormat: Used with number, integer and currency to specify the number of decimal places
DateFormat: Used with DateTime to specify Date, or Date and Time.
In the following example, we perform the following tasks:
View the current formula
View the current display format
Change the display format from two decimal places to four decimal places
Change the output type from currency to integer
Change the formula, output type and set the date format

//Configuring the calculated field

s.AppendLine(String.Format("<span>Calculated Field Formula: {0}</span></br>", calculatedfield.Formula));
s.AppendLine(String.Format("<span>Calculated Display Format: {0}</span></br>", calculatedfield.DisplayFormat));
s.AppendLine(String.Format("<span>Calculated Output Type: {0}</span></br>", calculatedfield.OutputType));
calculatedfield.DisplayFormat = SPNumberFormatTypes.FourDecimals;
calculatedfield.Update();
item.Update();
s.AppendLine(String.Format("<span>Calculated Field (Display Format 4 decimals): {0}</span></br>", calculatedfield.GetFieldValueAsText(item["calculatedfield"])));
calculatedfield.OutputType = SPFieldType.Integer;
calculatedfield.Update();
item.Update();
s.AppendLine(String.Format("<span>Calculated Field (Output Type Integer): {0}</span></br>", calculatedfield.GetFieldValueAsText(item["calculatedfield"])));
calculatedfield.Formula = "=[datefield]+90";
calculatedfield.DateFormat = SPDateTimeFieldFormatType.DateOnly;
calculatedfield.OutputType = SPFieldType.DateTime;
calculatedfield.Update();
item.Update();
s.AppendLine(String.Format("<span>Calculated Field (Updated Formula, Date Format and Output Type): {0}</span></br>", calculatedfield.GetFieldValueAsText(item["calculatedfield"])));

Friday, August 12, 2016

RESTful web service body format

Assume that you have some contract with XML request/response and some simple data contract:

[ServiceContract]
public interface IService
{
    ...
    [OperationContract]
    [WebInvoke(Method = "POST",
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped)]
    Entity DoWork(Entity entity);
    ...
}

[DataContract]
public class Entity
{
    [DataMember]
    public string Name;

    [DataMember]
    public string Value;
}

Depending on the combination of BodyStyle, RequestFormat and ResponseFormat you will have different formats but in general:

JSON and WebMessageBodyStyle.Bare request and response will be:

Request:

{"Name":"name","Value":"value"}
Response:

{"Name":"ResultName:name","Value":"ResultValue:value"}
JSON and WebMessageBodyStyle.Wrapped request and response will be:

Request:

{"entity":{"Name":"name","Value":"value"}}

Response:

{"DoWorkResult":{"Name":"name","Value":"value"}}
Note: you can change default DoWorkResult name to you own:

[return: MessageParameter(Name = "MyResult")]
Entity DoWork(Entity entity);`
so from now this will be:

{"MyResult":{"Name":"name","Value":"value"}}
XML and WebMessageBodyStyle.Bare request and response will be:

Request:

<Entity xmlns="http://schemas.datacontract.org/2004/07/WcfService" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
   <Name>name</Name>
   <Value>value</Value>
</Entity>

Response:

<Entity xmlns="http://schemas.datacontract.org/2004/07/WcfService" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
   <Name>name</Name>
   <Value>value</Value>
</Entity>
XML and WebMessageBodyStyle.Wrapped request and response will be:

Request:

 <DoWork xmlns="http://tempuri.org/">
   <entity>
      <Name>name</Name>
      <Value>value</Value>
   </entity>
 </DoWork>

Response:

 <DoWorkResponse xmlns="http://tempuri.org/">
   <DoWorkResult xmlns:a="http://schemas.datacontract.org/2004/07/WcfService" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
      <a:Name>name</a:Name>
      <a:Value>value</a:Value>
   </DoWorkResult>
 </DoWorkResponse>
Note: you can also change default DoWorkResult name with the return: MessageParameter

To answer to your question, which WebMessageBodyStyle you should use depends on your needs and there is no golden rule here. For interoperability, one or another format can be sometimes required. But keep in mind about one limitation of bare body style: as there is only one root in XML format and one object in JSON format, only one parameter can be passed to a method. In fact, if you changed a service contract to something like:

[OperationContract]
[WebInvoke(Method = "POST",
    ResponseFormat = WebMessageFormat.Json,
    RequestFormat = WebMessageFormat.Json,
    BodyStyle = WebMessageBodyStyle.Bare)]
Entity DoWork(string id, Entity entity);
a service would throw a exception:

Operation '' of contract '' specifies multiple request body parameters to be serialized without any wrapper elements. At most one body parameter can be serialized without wrapper elements. Either remove the extra body parameters or set the BodyStyle property on the WebGetAttribute/WebInvokeAttribute to Wrapped.

Sources : http://stackoverflow.com/questions/20206069/restful-web-service-body-format

How to find latitude and longitude values from google maps using c#

 public static DataTable GetGeoLocation(string Address)
 {
            DataTable dtCoordinates = new DataTable();
            string url = "http://maps.google.com/maps/api/geocode/xml?address=" + Address + "&sensor=false";
            WebRequest request = WebRequest.Create(url);
            using (WebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    DataSet dsResult = new DataSet();
                    dsResult.ReadXml(reader);

                    dtCoordinates.Columns.AddRange(new DataColumn[4]
                    { new DataColumn("Id", typeof(int)),
                    new DataColumn("Address", typeof(string)),
                    new DataColumn("Latitude",typeof(string)),
                    new DataColumn("Longitude",typeof(string)) });
                    foreach (DataRow row in dsResult.Tables["result"].Rows)
                    {
                        string geometry_id = dsResult.Tables["geometry"].Select("result_id = " + row["result_id"].ToString())[0]["geometry_id"].ToString();
                        DataRow location = dsResult.Tables["location"].Select("geometry_id = " + geometry_id)[0];
                        dtCoordinates.Rows.Add(row["result_id"], row["formatted_address"], location["lat"], location["lng"]);
                    }
                }
                return dtCoordinates;
            }
}

Thursday, July 21, 2016

Selecting first 10 records, then next 10, paging using Linq

var total = dtDetails.Rows.Count;
var pageSize = 10; // set your page size, which is number of records per page

var page = 1; // set current page number, must be >= 1

var skip = pageSize * (page-1);

var canPage = skip < total;

if (canPage) // do what you wish if you can page no further
   return;

DataTable dtFilteredData= dtDetails.AsEnumerable().Skip(skip).Take(pageSize).CopyToDataTable();

How to create C# variables dynamically?

In some cases we have scenario like have to create variables dynamically.To achieve this we have to use dictionary.I have shown some sample example with this post.

Sample variables
String strvar_1=null;
String strvar_2=null;
String strvar_3=null;

strvar_1="DynamicValue_1";
strvar_2="DynamicValue_2";
strvar_3="DynamicValue_3";

//below is the code to dynamically create above variable and assigning the values 

//Create dictionary to create variable names
//In this first string would be the variable name and second string would be the value for that variable we are assigning null initially
Dictionary<String, String> dynstr = new Dictionary<String, String>();
for(int i = 1; i < 4; i++) {
  dynstr .Add("strvar_" + i, null);
  }

//we are assigning value to those variables
  for(int i = 1; i < 4; i++) {
    dogs["strvar_" + i] = "DynamicValue_" + i;
  }

Saturday, July 2, 2016

Create Retrieve Update and Delete SharePoint List Item using REST API and JQuery

In this article, it is showed you how to  utilizing SharePoint REST API and JQuery to Create, Retrieve, Update and Delete SharePoint list item.

Pre-Requisite

Reference to latest jquery.min.js
For this example purposes, create custom List called “MyList” with default “Title” column.
Create

// occurs when a user clicks the create button

function CreateNew() {
    var listName = "MyList";
    var newItemTitle = "New Title Item";
    CreateListItemWithDetails(listName, _spPageContextInfo.webAbsoluteUrl, newItemTitle, function () {
        alert("New Item has been created successfully.");
 }, function () {
     alert("Ooops, an error occured. Please try again.");
 });
}

CREATE Operation

// listName: The name of the list you want to get items from
// weburl: The url of the web that the list is in. 
// newItemTitle: New Item title.
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails

function CreateListItemWithDetails(listName, webUrl, newItemTitle, success, failure) {
    var itemType = GetItemTypeForListName(listName);
    var item = {
        "__metadata": { "type": itemType },
        "Title": newItemTitle
    };

    $.ajax({
        url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            failure(data);
        }
    });
}

Get List Item Type metadata

function GetItemTypeForListName(name) {
    return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}

Retrieve Item

 READ SPECIFIC ITEM operation

// itemId: The id of the item to get
// listName: The name of the list you want to get items from
// siteurl: The url of the site that the list is in. 
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails

function getListItemWithId(itemId, listName, siteurl, success, failure) {
    var url = siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items?$filter=Id eq " + itemId;
    $.ajax({
        url: url,
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            if (data.d.results.length == 1) {
                success(data.d.results[0]);
            }
            else {
                failure("Multiple results obtained for the specified Id value");
            }
        },
        error: function (data) {
            failure(data);
        }
    });
}


Retrieve All Items

// occurs when a user clicks the read button

function Read() {
    var listName = "MyList";
    var url = _spPageContextInfo.webAbsoluteUrl;

    getListItems(listName, url, function (data) {
        var items = data.d.results;

        // Add all the new items
        for (var i = 0; i < items.length; i++) {
            alert(items[i].Title + ":" + items[i].Id);
        }
    }, function (data) {
        alert("Ooops, an error occured. Please try again");
    });
}

 READ operation

// listName: The name of the list you want to get items from
// siteurl: The url of the site that the list is in. 
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails

function getListItems(listName, siteurl, success, failure) {
    $.ajax({
        url: siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            failure(data);
        }
    });
}

Update

// occurs when a user clicks the update button

function Update() {
    var listName = "MyList";
    var url = _spPageContextInfo.webAbsoluteUrl;
    var itemId = "1"; // Update Item Id here
    var title = "New Updated Title";
    updateListItem(itemId, listName, url, title, function () {
        alert("Item updated, refreshing avilable items");
    }, function () {
        alert("Ooops, an error occured. Please try again");
    });
}

Update Operation

/ listName: The name of the list you want to get items from
// siteurl: The url of the site that the list is in. // title: The value of the title field for the new item
// itemId: the id of the item to update
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails

function updateListItem(itemId, listName, siteUrl, title, success, failure) {
    var itemType = GetItemTypeForListName(listName);

    var item = {
        "__metadata": { "type": itemType },
        "Title": title
    };

    getListItemWithId(itemId, listName, siteUrl, function (data) {
        $.ajax({
            url: data.__metadata.uri,
            type: "POST",
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(item),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "X-HTTP-Method": "MERGE",
                "If-Match": data.__metadata.etag
            },
            success: function (data) {
                success(data);
            },
            error: function (data) {
                failure(data);
            }
        });
    }, function (data) {
        failure(data);
    });
}


Delete

// occurs when a user clicks the delete button

function Delete() {
    var listName = "MyList";
    var url = _spPageContextInfo.webAbsoluteUrl;
    var itemId = "1"; // Update Item ID here
    deleteListItem(itemId, listName, url, function () {
        alert("Item deleted successfully");
    }, function () {
        alert("Ooops, an error occured. Please try again");
    });
}

// Delete Operation
// itemId: the id of the item to delete
// listName: The name of the list you want to delete the item from
// siteurl: The url of the site that the list is in.
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails
function deleteListItem(itemId, listName, siteUrl, success, failure) {
    getListItemWithId(itemId, listName, siteUrl, function (data) {
        $.ajax({
            url: data.__metadata.uri,
            type: "POST",
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-Http-Method": "DELETE",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "If-Match": data.__metadata.etag
            },
            success: function (data) {
                success(data);
            },
            error: function (data) {
                failure(data);
            }
        });
    },
   function (data) {
       failure(data);
   });
}


Source url : https://tjendarta.wordpress.com/2014/02/20/create-retrieve-update-and-delete-sharepoint-list-item-using-rest-api-and-jquery/ 

Wednesday, June 22, 2016

How to add Items in sharepoint list using CSOM

public void AddNewItemToList(string Title,string Subject)
{
   using(ClientContext objCtx = new ClientContext("http://Sharepoint.com"))
   {
       List oList = ctx.Web.Lists.GetByTitle("TestList");
       ListItemCreationInformation objItemCreateInfo = new ListItemCreationInformation();
       ListItemnewItem = oList.AddItem(objItemCreateInfo);
       newItem["Title"] = Title;
       newItem["Subject"] = Subject;
       newItem.Update();
       context.ExecuteQuery();
    }
}

Wednesday, June 8, 2016

How to access the files in bin/debug within the project folder in Visual studio 2012?

string executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string xslLocation = Path.Combine(executableLocation, "doc.xml");

Retrieve Author of SPListItem as SPUser in SharePoint; programmatically (C#)

  public string GetListItemAuthorNameSPBuiltInFieldId(SPListItem spListItem)
      {
          string loginName = string.Empty;
          SPWeb spWeb = SPContext.Current.Web;

          var fullUserName = spListItem[SPBuiltInFieldId.Author] as string;
          var userName = fullUserName.Split('#')[1];//This is only to get the user name. My fullUserName was 1;#Setup Admin.
          SPUser spUser = spWeb.EnsureUser(userName);//You can get SPUser from here
          loginName = spUser.LoginName;
          return loginName;

      }

      public string GetListItemAuthorName(SPListItem spListItem)
      {
         string loginName = string.Empty;
         var spFieldUser = spListItem.Fields.GetFieldByInternalName("Author") as SPFieldUser;
   
         if (spFieldUser != null && spListItem["Author"] != null)
         {
            var fieldValue = spFieldUser.GetFieldValue(spListItem["Author"].ToString()) as SPFieldUserValue;
            if (fieldValue != null)
            {
               var spUser = fieldValue.User;//Get the SPUser
               loginName = spUser.LoginName;//Get the login name from SPUser
            }
         }
      return loginName;
      }

How to clear People Editor control value in sharepoint 2013 programmatically

<SharePoint:PeopleEditor id="spPPlEdtr" MultiSelect="true" 
  ValidatorEnabled="true" SelectionSet="User,SPGroup" runat="server"/>

Client Side:

<script type="text/javascript">

    // this registers clearPicker to run every time the page reloads

    _spBodyOnLoadFunctionNames.push("clearPicker");

     // this is the function that clears the picker and helper variables

    function clearPicker() {
        var control;
        var arr = document.getElementsByTagName("div");
        for (var i = 0; i < arr.length; i++) 
        {
            if (arr[i].id.indexOf("upLevelDiv") > 0)
            { control = arr[i]; }
        }
        control.innerHTML = '';
        arr = document.getElementsByTagName("input");
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].name.indexOf("hiddenSpanData") > 0)
            { control = arr[i]; }
        }
        control.value = '';
    }
</script>


Server Side:

PeopleEditor picker = spPPlEdtr; 
picker.Accounts.Clear(); 
picker.Entities.Clear(); 
picker.ResolvedEntities.Clear(); 

How to find strong name of an assembly using powershell

[System.Reflection.AssemblyName]::GetAssemblyName("dllpath").FullName

Wednesday, May 18, 2016

Cross Site List Query using SPSiteDataQuery in SharePoint 2013

SPSiteDataQuery can be used to perform cross-site and cross-list queries. In order to use it, you must call SPWeb.GetSiteData method on the appropriate web and provide a SPSiteDataquery object.

We can use this class to retrieve data from selected lists or from all the lists in the current site  collection. We have to set the following before we start.

  • Specify the scope of the query by setting the Webs property (Site collection, site etc). 
  • Specify the lists to participate in the query by setting the Lists property 
  • Specify the fields to return by setting the View Fields property. 
  • We have to Control data selection and order by setting the Query property.


SPSiteDataQuery and SPQuery differ SPSiteDataQueries ability to search more than a single site or single list. SPSiteDataQuery can be configured to search in all lists of a particular list type or list base type located in either

1) The complete site collection

2) a particular site and sub-sites

Using SPSiteDataQuery.Webs property you can specify where the data will be retrieved from. This property can have one of the following values:

“” (or string.Empty) – default value : will search only the SPWeb on which you run GetSiteData

“<Webs Scope=’SiteCollection’ />” : will search on all webs in the site collection

“<Webs Scope=’Recursive’ />” : will search the SPWeb on which you run GetSiteData and all subwebs

You can restrict the search using Lists and Query properties. In the following example we query all contacts lists in the site collection for items containing John in the Last Name field:SPSiteDataQuery query = new SPSiteDataQuery();

//query contacts list.

query.Lists = “<Lists ServerTemplate=’105′ />”;

query.ViewFields = “<FieldRef Name=’Title’ />”;

query.Query = “<Where><Contains>” +

“<FieldRef Name=’Title’ /><Value Type=’text’>John</Value>”+

“</Contains></Where>”;

query.Webs = “<Webs Scope=’SiteCollection’ />”;

DataTable dt = SPContext.Current.Web.GetSiteData(query);

For the Lists property you can use constructs like:

<Lists ServerTemplate=’10001′ /> – query lists with template 10001

<Lists BaseType=’5′ /> – Issues lists

<Lists><List ID=”960BF6F6-F264-4305-B3CB-BDB9BF8F67DF” /></Lists> – query a specific list

Wednesday, May 4, 2016

How to remove the webpart in the site pages of sharepoint 2013 progrmmatically

Here i have given a sample code to remove the webpart in the pages of sharepoint 2013 programmatically


 RemoveWebPart(oSPWeb, "http://TestServer/sites/Test/Sitepages/Home.aspx","Test details");

///<summary> /// Remove a web part based on its title
        /// </summary>
        ///Web site to remove the web part from
        ///Web page to remove the web part within
        ///Title of the web part(s) to remove
        public static void RemoveWebPart(SPWeb web, string page, string webPartTitle)
        {
            try
            {
                using (SPLimitedWebPartManager webPartManager = web.GetLimitedWebPartManager(web.Url + page, PersonalizationScope.Shared))
                {
                    IEnumerable webPartList = from System.Web.UI.WebControls.WebParts.WebPart webPart in webPartManager.WebParts
                                              where webPart.Title == webPartTitle
                                              select webPart;

                    foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in webPartList)
                    {
                        Console.WriteLine("Removing Webpart" + webPartTitle + " in " + web.Url + page + " Please wait...");
                        webPartManager.DeleteWebPart(webPart);
                        break;
                    }

                    web.Update();
                }

            }
            catch (Exception ex)
            {
                     Console.WriteLine("Exception =" + ex.ToString() );
            }
        }