Search This Blog

Wednesday, August 2, 2017

How to Dynamically load a class and execute a method in .NET

public class DynamicInvoke
{
    // this way of invoking a function
    // is slower when making multiple calls
    // because the assembly is being instantiated each time.
    // But this code is clearer as to what is going on
    public static Object InvokeMethodSlow(string AssemblyName,
           string ClassName, string MethodName, Object[] args)
    {
      // load the assemly
      Assembly assembly = Assembly.LoadFrom(AssemblyName);

      // Walk through each type in the assembly looking for our class
      foreach (Type type in assembly.GetTypes())
      {
        if (type.IsClass == true)
        {
          if (type.FullName.EndsWith("." + ClassName))
          {
            // create an instance of the object
            object ClassObj = Activator.CreateInstance(type);

            // Dynamically Invoke the method
            object Result = type.InvokeMember(MethodName,
              BindingFlags.Default | BindingFlags.InvokeMethod,
                   null,
                   ClassObj,
                   args);
            return (Result);
          }
        }
      }
      throw (new System.Exception("could not invoke method"));
    }

    // ---------------------------------------------
    // now do it the efficient way
    // by holding references to the assembly
    // and class

    // this is an inner class which holds the class instance info
    public class DynamicClassInfo
    {
      public Type type;
      public Object ClassObject;

      public DynamicClassInfo()
      {
      }

      public DynamicClassInfo(Type t, Object c)
      {
        type = t;
        ClassObject = c;
      }
    }


    public static Hashtable AssemblyReferences = new Hashtable();
    public static Hashtable ClassReferences = new Hashtable();

    public static DynamicClassInfo
           GetClassReference(string AssemblyName, string ClassName)
    {
      if (ClassReferences.ContainsKey(AssemblyName) == false)
      {
        Assembly assembly;
        if (AssemblyReferences.ContainsKey(AssemblyName) == false)
        {
          AssemblyReferences.Add(AssemblyName,
                assembly = Assembly.LoadFrom(AssemblyName));
        }
        else
          assembly = (Assembly)AssemblyReferences[AssemblyName];

        // Walk through each type in the assembly
        foreach (Type type in assembly.GetTypes())
        {
          if (type.IsClass == true)
          {
            // doing it this way means that you don't have
            // to specify the full namespace and class (just the class)
            if (type.FullName.EndsWith("." + ClassName))
            {
              DynamicClassInfo ci = new DynamicClassInfo(type,
                                 Activator.CreateInstance(type));
              ClassReferences.Add(AssemblyName, ci);
              return (ci);
            }
          }
        }
        throw (new System.Exception("could not instantiate class"));
      }
      return ((DynamicClassInfo)ClassReferences[AssemblyName]);
    }

    public static Object InvokeMethod(DynamicClassInfo ci,
                         string MethodName, Object[] args)
    {
      // Dynamically Invoke the method
      Object Result = ci.type.InvokeMember(MethodName,
        BindingFlags.Default | BindingFlags.InvokeMethod,
             null,
             ci.ClassObject,
             args);
      return (Result);
    }

    // --- this is the method that you invoke ------------
    public static Object InvokeMethod(string AssemblyName,
           string ClassName, string MethodName, Object[] args)
    {
      DynamicClassInfo ci = GetClassReference(AssemblyName, ClassName);
      return (InvokeMethod(ci, MethodName, args));
    }
  }

// Create an object array consisting of the parameters to the method.
// Make sure you get the types right or the underlying
// InvokeMember will not find the right method
Object [] args = {1, "2", 3.0};
Object Result = DynamicInvoke("Test.dll",
                "ClassName", "MethodName", args);
// cast the result to the type that the method actually returned.


Source :https://www.codeproject.com/Articles/13747/Dynamically-load-a-class-and-execute-a-method-in-N

Sunday, June 18, 2017

How to change list and document library web URL In sharepoint using powershell

I this post we will see how to change the list and document library url using powershell.

            We have some scenarios like have to change the list name for an existing list, we can change the name of the list on the list settings page, Select List name, description, and navigation option under the General settings.but we couldn't able to change the web url using User Interface,but we can achieve this using below powershell script.

For this we need Microsoft Powershell Management shell, open the PMS using run as administrator privileges and use the below powershell script to change the web URL of the list/document library.

Add-PSSnapin Microsoft.SharePoint.Powershell
#Paste the site or subsite url
#If you are using site collection url using Get-Spsite instead of Get-Spweb
$Web = Get-SPWeb "http://Test:8080/sites/TestSite/SubSite/"
#Mention the name of the to which the web url should change
$List = $Web.Lists["TestList"]
#Paste the new url which we prefer to change 
$List.RootFolder.MoveTo("/sites/TestSite/SubSite/Lists/test") 

Saturday, June 17, 2017

How to backup the deployed wsp using powershell

The below powershell code is used to get the backup of deployed wsp solution

$farm = Get-SPFarm
$file = $farm.Solutions.Item("MySolution.wsp").SolutionFile
$file.SaveAs("c:\MySolution.wsp")  

Export webpart from sharepoint page

In this post we will see how to export webpart from the sharepoint page.

First we have to find the webpart id of the webpart which we are going to export,For that  press f12 in you webbrowser and inspect the webpart and find the webpart Id.

In SharePoint there is a hidden application page that exports web parts: /_vti_bin/exportwp.aspx. This page takes two query parameters:

pageurl. The absolute url of the page where the web part resides that you want to export
guidstring. The guid that is called webpartid in the markup on the page

So, suppose, you have this site: https://parthasarathybalan.sharepoint.com and a web part (id: 66509661-e83d-4e18-9f74-07c04c8e5a79') on a page https://intranet.contoso.com/Pages/Home.aspx

This will be the resulting URL to export your webpart:

https://parthasarathybalan.sharepoint.com/sites/Testsite/_vti_bin/exportwp.aspx?pageurl=https://parthasarathybalan.sharepoint.com/sites/Testsite/SitePages/Home.aspx&guidstring='66509661-e83d-4e18-9f74-07c04c8e5a79'

How to get value from multilinetext field using csom

//The below code is used to retrieve value from multiline text field using csom

static void Main(string[] args)
{
 string siteUrl = "http://domainname/sites/TestSite";
 using(ClientContext clientContext = new ClientContext(siteUrl))
 {
    var web = clientContext.Web;
    var list = web.Lists.GetByTitle("Test List");
    var listFields = list.Fields;
    clientContext.Load(listFields);
    var listItem = list.GetItemById("1");
    var itemFieldValues = listItem.FieldValuesAsText;
    clientContext.Load(itemFieldValues);
    clientContext.ExecuteQuery();
    string multitextValue = Convert.ToString(itemFieldValues["MultiLineTextField"]);
 }
}

Saturday, June 10, 2017

How to resolve time zone in sharepoint 2013

The below method is used to resolve time zone in sharepoint 2013

public static DateTime ResolveTimeZone(ClientContext oParentContext, DateTime dtDate)
{
   //DateTime dtStartDate = DateTime.UtcNow;
  try
  {
    var spTimeZone = oParentContext.Web.RegionalSettings.TimeZone;
    oParentContext.Load(spTimeZone);
    oParentContext.ExecuteQuery();
    var fixedTimeZoneName = spTimeZone.Description.Replace("and", "&");
    var timeZoneInfo = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(tz => tz.DisplayName == fixedTimeZoneName); //"(UTC-08:00) Pacific Time (US and Canada)"
    TraceUtil.TraceMessage("UTC= " + dtDate);
    TraceUtil.TraceMessage("TZ= " + timeZoneInfo);
    dtDate = TimeZoneInfo.ConvertTimeFromUtc(dtDate.Date.ToUniversalTime(), timeZoneInfo);
    dtDate = dtDate.Date + ts;
  }
  catch (Exception ex)
  {
     throw ex;
  }

  return dtDate;
}

How to Disable Event Firing on List Item Update in SharePoint 2013 Programmatically

public classEventFiring : SPItemEventReceiver
{
  public void DisableHandleEventFiring()
  {
     this.EventFiringEnabled =false;
  }

  public void EnableHandleEventFiring()
  {
     this.EventFiringEnabled =true;
  }
}


class Program
{
  static void Main(string[] args)
  {
    using (SPSite site = new SPSite("https://serverName/sites/testsite/"))
    {
      using (SPWeb web = site.OpenWeb())
      {
        SPList list = web.Lists.TryGetList("Test List");
        SPListItem item = list.GetItemById(1);
        item["Title"] ="Updated Successfully";
        EventFiring eventFiring = newEventFiring();
        eventFiring.DisableHandleEventFiring();
        item.Update();
        eventFiring.EnableHandleEventFiring();
        Console.WriteLine("Updated Successfully");
        Console.ReadLine();
     }
   }
  }
}

Authenticating .NET Client Object Model in Office 365 using shareepoint online

The below code is used to authenticating sharepoint online site

using (ClientContext clientContext = new ClientContext("https://yoursite.sharepoint.com/"))
{
    SecureString passWord = new SecureString();

    foreach (char c in "yourpassword".ToCharArray()) passWord.AppendChar(c);

    clientContext.Credentials = new SharePointOnlineCredentials("admin@yoursite.onmicrosoft.com", passWord);

    Web web = clientContext.Web;

    clientContext.Load(web);

    clientContext.ExecuteQuery();

    Console.WriteLine(web.Title);

    Console.ReadLine();
}

Method to get timestamp in c#

 public static string GetTimeStamp()
 {
     return DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fff");
 }

How to read listitem attachments using sharepoint client object model

The below method is used to get the files which is attached in the listitem in the custom list

public static FileCollection GetListItemAttachments( string sitePath, string listName, string itemID)
{
   try
   {
      FileCollection oFileCollection=null;
      Folder attachmentsFolder = null;
      ClientContext clientContext = new ClientContext(sitePath);
      Web web = clientContext.Web;
      clientContext.Load(web);
      clientContext.ExecuteQuery();

      attachmentsFolder = web.GetFolderByServerRelativeUrl(sitePath + "/Lists/" + listName + "/attachments/" + itemID);
      clientContext.Load(attachmentsFolder);
      oFileCollection = attachmentsFolder.Files;
      clientContext.Load(oFileCollection);
      clientContext.ExecuteQuery();
   
      return oFileCollection;
   }
   catch (Exception ex)
   {
     throw ex;
   }
 }

How to remove registered app from sharepoint online

In this post i will explain how to remove registered app from sharepoint online.

For this please install Azure PD Powershell before going through this post.

Open the  Installed  Azure PD Powershell with run as Administrator permission.and run the following sript to remove the app from sharepoint online.

Connect-MsolService
$appPrincipal = Get-MsolServicePrincipal -ServicePrincipalName 'Paste your app client id here'
Remove-MsolServicePrincipal -ObjectId $appPrincipal.ObjectId

After executing the above script please register your app again in 
"SiteUrl/_layouts/15/appregnew.aspx"






Monday, April 24, 2017

How to check Lookup Field is a single or multi select programmatically using CSOM?

//The below Method is used to find the lookup field is a single or multi select

 public static bool AllowMultipleValues(ClientContext clientContext, List oList, string columnInternalName)
        {
            bool IsMultipleValues = false;
            try
            {
                if (oList != null)
                {
                    Field oField = oList.Fields.GetByInternalNameOrTitle(columnInternalName);
                    if (oField != null)
                    {
                        var lookupField = clientContext.CastTo<FieldLookup>(oField);
                        clientContext.Load(lookupField, x => x.AllowMultipleValues);
                        clientContext.ExecuteQuery();
                        IsMultipleValues = lookupField.AllowMultipleValues;
                        return IsMultipleValues;
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLogger.LogException(ex);
            }
            return IsMultipleValues;
        }

How to check Person or Group Field is a single user or multi user programmatically using CSOM

This Below method is used to check the user field is a single user or multi user. 

public static bool AllowUserMultipleValues(ClientContext clientContext, List oList, string columnInternalName)
        {
            bool IsMultipleValues = false;
            try
            {
                if (oList != null)
                {
                    Field oField = oList.Fields.GetByInternalNameOrTitle(columnInternalName);
                    if (oField != null)
                    {
                        var lookupField = clientContext.CastTo<FieldUser>(oField);
                        clientContext.Load(lookupField, x => x.AllowMultipleValues);
                        clientContext.ExecuteQuery();
                        IsMultipleValues = lookupField.AllowMultipleValues;
                        return IsMultipleValues;
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLogger.LogException(ex);
            }
            return IsMultipleValues;
        }

Sunday, March 26, 2017

Add Users to Sharepoint Group in SharePoint 2013 using CSOM

 using(ClientContext clientContext = new ClientContext("http://Test.sharepoint.com/sites/TestSite/"))
 {
            GroupCollection Groups = context.Web.SiteGroups;
            //Get the group by its name 
            Group ownersGroup = Groups.GetByName("GroupName");
            // Create the new user info  
            UserCreationInformation userCreationInfo = new UserCreationInformation();
            userCreationInfo.Email = "Parthasarathy@sharepoint.com";
            userCreationInfo.LoginName = "sharepoint\\Parthasarathy";
            userCreationInfo.Title = "User";  
            // Add the user to the group  
            User newUser = ownersGroup.Users.Add(userCreationInfo);
            context.ExecuteQuery();
 }  

Wednesday, March 22, 2017

How to assign permission to the Sharepoint group using CSOM C#


AddPermissionToGroup(clientContext, web, "Group Name", "Read");

public static void AddPermissionToGroup(ClientContext clientContext, Web web, string groupName, string Permission)
{
  try
  {
    using (clientContext)
    {
      //Get group by its name
       var group = clientContext.Web.SiteGroups.GetByName(groupName);
      //Get role by its name
       var roletypes = clientContext.Web.RoleDefinitions.GetByName(Permission);
       clientContext.ExecuteQuery();
       web.BreakRoleInheritance(true, false);
       RoleDefinitionBindingCollection collRoleDefinitionBinding = new       RoleDefinitionBindingCollection(clientContext);
       collRoleDefinitionBinding.Add(roletypes);
       web.RoleAssignments.Add(group, collRoleDefinitionBinding);
       web.Update();
       clientContext.ExecuteQuery();
    }
  }
  catch (Exception ex)
  {
     ErrorLogger.LogException(ex);
  }
}

Saturday, March 18, 2017

How to retrieve associated list name from a FieldLookupValue Sharepoint 2013 CSOM

The following example demonstrates how to retrieve associated List for Predecessors field from Tasks list:

using (var oClientContext = new ClientContext("http://Testserver/sites/Test"))
{
     var list = oClientContext.Web.Lists.GetByTitle("Tasks");
     var field = list.Fields.GetByInternalNameOrTitle("Predecessors");
     var lookupField = oClientContext.CastTo<FieldLookup>(field);
     oClientContext.Load(lookupField);
     oClientContext.ExecuteQuery();
     var lookupListId = new Guid(lookupField.LookupList); //returns associated list id
     //Retrieve associated List
     var lookupList = oClientContext.Web.Lists.GetById(lookupListId);
     oClientContext.Load(lookupList);
     oClientContext.ExecuteQuery();
}

How to determine the value entered is a User or Group via CSOM

public static string GetUserFieldType(ClientContext clientContext,FieldUserValue value)
{
    var userInfoList = clientContext.Site.RootWeb.SiteUserInfoList;
    var userInfo = userInfoList.GetItemById(value.LookupId);
    clientContext.Load(userInfo,i => i.ContentType);
    clientContext.ExecuteQuery();
    return userInfo.ContentType.Name;
}

If  the return value is Person it is a User, if it is SharePointGroup it is a Group

How to update the JSLink value of a Web Part Programmatically via CSOM in Office365

    //The below Code is used to update the JSLink property value of a webpart  programmatically using csom

    using (ClientContext oClientContext = new ClientContext(siteUrl))
    {
      //Connect to the SharePoint Online site
       oClientContext.AuthenticationMode = ClientAuthenticationMode.Default;
       oClientContext.Credentials = credentials;
       oClientContext.Load(clientContext.Web);
       oClientContext.ExecuteQuery();

      //Get the list
       List olist = oClientContext.Web.Lists.GetByTitle(“Test List”);
       oClientContext.Load(olist);
       oClientContext.Load(olist.Forms);
       oClientContext.ExecuteQuery();

      //Get all the forms
       foreach (var spForm in olist.Forms)
       {
        //Get the New form
        if (spForm.ServerRelativeUrl.Contains(“NewForm.aspx”))
        {
           File oFile = oClientContext.Web.GetFileByServerRelativeUrl(spForm.ServerRelativeUrl);
           LimitedWebPartManager wpm = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared);
           oClientContext.Load(wpm.WebParts,wps => wps.Include(wp => wp.WebPart.Title));
           oClientContext.ExecuteQuery();

          //Set the properties for all web parts
          foreach (WebPartDefinition wpd in wpm.WebParts)
          {
            WebPart wp = wpd.WebPart;
            wp.Properties[“JSLink”] = “~/sitecollection/Style%20Library/CustomScript.js”;
            wpd.SaveWebPartChanges();
            oClientContext.ExecuteQuery();
          }
        }

      }

    }

         

How to retrieve Lookup Field via CSOM Javascript in Sharepoint 2013


The below code is used to get lookup values from lookup field

//Get LookupField value
var oLookupField = item.get_item('FieldName');
var oLookupValue = oLookupField.get_lookupValue();
var oLookupID = oLookupField.get_lookupId();


The below code is used to get lookup values from multi lookup field

//Get Multiple Lookup Field value
var oLookupField = item.get_item('FieldName');
for(var i = 0; i < oLookupField.length; i++) {
   var oLookUpColumn = oLookupField[i];
   var oLookupValue = oLookUpColumn.get_lookupValue();
   var oLookupID = oLookUpColumn.get_lookupId();
}

How to add a value for column in Item adding event in Remote event receivers using csom



public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties)
{
SPRemoteEventResult result = new SPRemoteEventResult();
if (properties.EventType == SPRemoteEventType.ItemAdding)
{
result.ChangedItemProperties.Add("Title", "After adding");
result.Status = SPRemoteEventServiceStatus.Continue;
}
return result;
}

Monday, February 27, 2017

Add, Update and Delete list items using ECMAScript


Introduction
In this post we will see how to Add, Update and Delete SharePoint list items with ECMAScript (aka javascript client object model)
  •     Add item to SharePoint list
  •     Update item of SharePoint list
  •     Delete item from SharePoint list
Add item to SharePoint list

     To add an item to the list, use the ListItemCreationInformation object,set the properties using set_item, call the update and ExecuteQueryAsync methods.
function AddListItem(){
    var ListName = "Test List";
    var context = new SP.ClientContext.get_current(); // the current context is taken by default here        //you can also create a particular site context as follows
    //var context = new SP.ClientContext('/Sites/site1');
    var lstObject = context.get_web().get_lists().getByTitle(ListName);
    var listItemCreationInfo = new SP.ListItemCreationInformation();
    var newItem = lstObject.addItem(listItemCreationInfo);
    newItem.set_item('Title', 'This is new item');
    // set values to other columns of the list here
    newItem.update();
    context.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
        Function.createDelegate(this, this.onFailure));
     function onSuccess() {
        alert('Item created: ' + newItem.get_id());
    }
    function onFailure(sender, args) {
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
}
Update Item of SharePoint list   

function UpdateListItem()
{
var ListName = "Test List";
var context = new SP.ClientContext.get_current();
// the current context is taken by default here
//you can also create a particular site context as follows
//var context = new SP.ClientContext('/Sites/site1');
var lstObject = context.get_web().get_lists().getByTitle(ListName);
this.lstObjectItem = lstObject.getItemById(1);
lstObjectItem.set_item('Title', 'This is updated item');
lstObjectItem.update();
lstObject.set_description("Updated description using ECMAScript");
lstObject.update();
context.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
Function.createDelegate(this, this.onFailure));
}
function onSuccess() {
alert('Item udated');
}
function onFailure(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}


Delete Item from SharePoint list

function DeleteListItem()
{
var ListName = "Test List";
var context = new SP.ClientContext.get_current();
// the current context is taken by default here
//you can also create a particular site context as follows
//var context = new SP.ClientContext('/Sites/site1');
var lstObject = context.get_web().get_lists().getByTitle(ListName);
this.lstObjectItem = lstObject.getItemById(1);
lstObjectItem.deleteObject();
context.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
Function.createDelegate(this, this.onFailure));
}
function onSuccess() {
alert('Item Deleted');
}
function onFailure(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Remarks

Reference to ‘sp.js’ file should be there in the page where you are using ECMAScript.

Friday, February 10, 2017

How to add values in multi select lookup field in sharepoint using CSOM


Create a List of FieldLookupValue's
List<FieldLookupValue> oLookupValues = new List<FieldLookupValue>();

Add a new FieldLookupValue for each file id
oLookupValues.Add(new FieldLookupValue() { LookupId = Convert.ToInt32(lookupID) });

When finished set the listitem to the List
listItem["FieldName"] = oLookupValues ;
listItem.Update();