Search This Blog

Thursday, July 11, 2019

How to open Documents in Browser in SharePoint classic view

In SharePoint, Microsoft provides the below URL format to meet the user's expectation.

The URL format you are looking for is,

<SiteURL>/_layouts/15/WopiFrame.aspx?sourcedoc=<Doc URL>&file=<File Name>&action=default";



<script  type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>    
        
<script  type="text/javascript"> 
    (function () {
        SPClientTemplates.TemplateManager.RegisterTemplateOverrides({  
            Templates: {  
                Fields: {  
                    'LinkFilename': {  
                        'View': function (ctx) {  
                            var currentVal = '';  
                            //from the context get the current item and it's value   
                            if (ctx != null && ctx.CurrentItem != null)  
                                currentVal = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];  
                  
                            if(ctx.CurrentItem.File_x0020_Type == "pptx"||ctx.CurrentItem.File_x0020_Type == "pdf" ||ctx.CurrentItem.File_x0020_Type == "xlsx" ||ctx.CurrentItem.File_x0020_Type == "docx" ||ctx.CurrentItem.File_x0020_Type == "doc"){  
                                el = "<div><a id="+ctx.CurrentItem.UniqueId+" class='ms-listlink ms-draggable' onclick='OpenFileInModal(this);return false;' href='" + ctx.CurrentItem.FileRef + "'>" + ctx.CurrentItem.FileLeafRef + "</a></div>";  
                            }else  
                            {  
                                el = "<div><a id="+ctx.CurrentItem.UniqueId+" class='ms-listlink ms-draggable'  href='" + ctx.CurrentItem.FileRef + "'>" + ctx.CurrentItem.FileLeafRef + "</a></div>";  
                            }  
                            // Render the HTML5 file input in place of the OOTB  
                            return el;  
                        }  
                    }  
                }  
            }  
        });  

    })();

function OpenFileInModal(sender) {  
    var options = SP.UI.$create_DialogOptions();  
    var documentID=$(sender).attr('id');       
    var str=_spPageContextInfo.webAbsoluteUrl +"/_layouts/15/WopiFrame.aspx?sourcedoc=" + documentID + "&file="+sender.text+"&action=default";     
    //Using a generic object.  
    var options = {  
        title: "",  
        width: 1000,  
        height: 1200,  
        url: str  
    };  
  
    SP.UI.ModalDialog.showModalDialog(options);  
}  
</script>  

Tuesday, June 25, 2019

Enable Site Collection App Catalog For Particular Site Collection Level Solution/Features

In this article, we will learn how to enable site collection app catalog. By enabling the site collection level app catalog (not the tenant), we can deploy/install SharePoint AddIn/SPFx solutions at the site collection level. Consider this like sandbox solution, as a component is only deployed and is installed on the site collection and not available for other site collections.



Why do we need a Site Collection App Catalog?


There are times and cases when we, as a developer, have to build a solution which is very much specific to a particular project or application. This solution demands a very determined approach to solving a specific problem which is not required for other site collections of your tenant. Below are some of the reasons why we need a site collection app catalog. 


  • Provide isolated and focused solution/web part for a particular project.
  • Tenant level App/Add-in is visible to all site collection under a tenant. Risk of installing the app in other site collections is nullified for which solution is not required.
  • Provides controls to Site collection admins to manage solutions specific on site collection.
  • No need to provide access to site collection admins to deploy the app on the tenant.
  • Saves times and faster deployment methodology.
  • How to enable site collection app catalog?


Notes

This is a one-time activity to be done by tenant admins.  

open SharePoint Online Management Shell.

Connect to the Tenant.
Connect-SPOService -Url https://wayneenterprise-admin.sharepoint.com -credential bruce@wayneenterprise.com
Connect to the particular site and run Add-SPOSiteCollectionAppCatalog.
# get a reference to the site collection where the  
# site collection app catalog should be created  
$site = Get-SPOSite https://wayneenterprise.sharepoint.com/sites/justiceleague
 # create site collection app catalog  
Add-SPOSiteCollectionAppCatalog -Site $site

Once you go to the site collection, you will see the app for SharePoint library which can be used to deploy the app. 


Source : https://www.c-sharpcorner.com/article/enable-site-collection-app-catalog-for-particular-site-collection-level-solution/

Thursday, April 11, 2019

Comparison (cookies vs cache), (PUT vs POST) && (JSLink vs Script Editor vs Content Editor WebPart)

cookies vs cache

Cookie should be used to store per-user information for the current Web session or persistent information on the client, therefore client has control over the contents of a cookie.

Cache object is shared between users in a single application. Its primary purpose is to cache data from a data store and should not be used as a primary storage. It supports automatic invalidation features.

PUT vs POST

The most commonly used HTTP verbs POST, GET, PUT, DELETE are similar to CRUD (Create, Read, Update and Delete) operations in database. We specify these HTTP verbs in the capital case. So, the below is the comparison between them.

create - POST
read - GET
update - PUT
delete - DELETE
PATCH: Submits a partial modification to a resource. If you only need to update one field for the resource, you may want to use the PATCH method.

JSLink vs Script Editor vs Content Editor WebPart

1. JSlink: you can control rendering of Fields, Items and even Web Parts using a JavaScript File referenced in JS Link property field of a Web Part.

2.  Script Editor Web Part: you could paste your html and JavaScript into Script Editor Web Part. And it is a reusable one.

3. Content Editor Web Part: you could add formatted text, tables, hyperlinks, and images to a Web Part Page by Content Editor Web Part.

Difference between Sandboxed and Farm solution

In this post we will see the difference between Farm solutions and Sandboxed solutions 

Farm solutions, which are hosted in the IIS worker process (W3WP.exe), run code that can affect the whole farm. 

Sandboxed solutions, which are hosted in the SharePoint user code solution worker process (SPUCWorkerProcess.exe), run code that can only affect the site collection of the solution.Farm solutions are installed and deployed. Sandboxed solutions are uploaded and activated.

Embed code and script editor webpart in SharePoint 2013

In this post, we will discuss some difference between the Embed code and Script editor web part in SharePoint 2013.

Both Embed code and Script editor web part are new in SharePoint 2013. You can include JavaScript and HTML contents through the Embed Code which you will get when edit a site page and this is located under Insert Tab in the Ribbon.

Script editor web part also you can use to paste your HTML and JavaScript into the page. But it is a reusable one. The difference between these two is Embed code is not reusable.

Another major difference between these two is Embed code allows you to place the Iframe elements but Script Editor Web Part doesn’t allow. So Youtube, Twitter or LinkedIn or Facebook code you can paste through Embed Code.

Wednesday, April 10, 2019

How To Get All SharePoint List Item Versions Using CSOM For Custom List And Document Library

In CSOM, basically, there is no direct property to get the versions of the items in a List. By using "Lists Web Service"(/_vti_bin/Lists.asmx), however, we can get the information of all the versions and properties of each item inside a Custom List or a Document Library.
To get the above-required functionality, first of all, we have added the "Lists Web Service" in the required project.
In this blog, I am going to share all the codes for getting the version details of list items by using "Lists Web Service". We all know how to add a service to a project.
We are using the below code to achieve the same. The code is self-explanatory because of the comments I have written before each snippet.

Source Code

using System;
using System.Net;
using System.Xml;
using Microsoft.SharePoint.Client;
namespace ConsoleAppTest {
    class Program {
        static void Main(string[] args) {
            ClientContext context = null;
            List list = null;
            ListItemCollection itemCollection = null;
            ListItem item = null;
            string userName = string.Empty;
            string password = string.Empty;
            string dateHistory = string.Empty;
            string commentHistory = string.Empty;
            string editor = string.Empty;
            string loginName = string.Empty;
            try {
                using(context = new ClientContext("https://Testsite.sharepoint.com")) {
                    userName = "UserName";
                    password = "PassWord";
                    // Setting credential for the above site
                    context.Credentials = new SharePointOnlineCredentials(userName, password);
                    context.Load(context.Web);
                    context.ExecuteQuery();
                    // Getting list by Title
                    list = context.Web.Lists.GetByTitle("List Title");
                    context.Load(list, L => L.Id);
                    // Getting all items from selected list using caml query
                    itemCollection = list.GetItems(CamlQuery.CreateAllItemsQuery());
                    //Loading selected list items
                    context.Load(itemCollection, IC => IC.Include(I => I.Id, I => I.DisplayName));
                    context.ExecuteQuery();
                    if (itemCollection != null && itemCollection.Count > 0) {
                        for (int iCount = 0; iCount < itemCollection.Count; iCount++) {
                            try {
                                item = itemCollection[iCount];
                                ListService.Lists listService = new ListService.Lists();
                                listService.Url = context.Url + "/_vti_bin/Lists.asmx";
                                listService.Credentials = context.Credentials;
                                //Getting all item versions from custon list item using List Web Service
                                XmlNode nodeVersions = listService.GetVersionCollection(list.Id.ToString(), item.Id.ToString(), "_UIVersionString");
                                //looping all versions and getting 'Modified' and 'Editor' property of each version
                                foreach(XmlNode xNode in nodeVersions) {
                                    try {
                                        dateHistory = xNode.Attributes["Modified"].Value;
                                        dateHistory = FormatDateFromSP(dateHistory);
                                        commentHistory = xNode.Attributes["_UIVersionString"].Value;
                                        loginName = xNode.Attributes["Editor"].Value;
                                    } catch {}
                                }
                            } catch (Exception ex) {}
                        }
                    }
                }
            } catch (Exception ex) {}
        }

        private static string FormatDateFromSP(string dateHistory) {
            string result;
            result = dateHistory.Replace("T", " ");
            result = result.Replace("Z", "");
            return result;
        }
    }
}   

Tuesday, April 9, 2019

Site Pages and Application Pages in SharePoint 2013

Site Pages
  
                   These Pages are stored in the Content Database and they are parsed when requested by user. A typical web part page is an example of Site Pages. They can be edited, modified by the Power Users and customized according to their needs.

Application Pages

                  They are same as ASP.net Pages and stored on the layouts folder of SharePoint front end web server. When user requests , application pages are compiled and they are much faster than Site Pages. Admin Pages like settings.aspx, accessdenied.aspx are an example of Application Pages. Thus we can say that Application pages are common to all SharePoint Users.

Thursday, November 15, 2018

How to reference css and script in SharePoint Master Page

CSS Reference

<!--SPM:<SharePoint:CssRegistration Name="https://Yugatechnolgy.sharepoint.com/sites/Teamsite/SiteAssets/customstyle.css" runat="server" after="corev15.css"/>-->


Javascript Reference

<!--SPM:<SharePoint:ScriptLink ID="ScriptLink10" language="text/javascript" name="sites/Teamsite/SiteAssets/jquery-2.2.4.min.js" runat="server" />-->


Thursday, August 2, 2018

How to add Custom Action Menu In SharePoint ListItem using Jquery

 The below code is used to add Custom Action Menu in SharePoint ListItem using JSOM.












Add a CEWP/Script Editor webpart in the "/sites/TeamSite/List/EmployeeDetails/AllItems.aspx" Page and paste the below code.

JSOM Code:

<script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
    $(document).ready(function() {
        SP.SOD.executeFunc('sp.js', 'SP.ClientContext', AddCustomUserActionToListItem);
    });

function AddCustomUserActionToListItem() {
    var clientContext = new SP.ClientContext();
    var oWeb = clientContext.get_web();
    var oList = oWeb.get_lists().getByTitle('EmployeeDetails');
    var userCustomActionColl = oList.get_userCustomActions();
    clientContext.load(oList, 'UserCustomActions', 'Title');
    clientContext.executeQueryAsync(function() {
        var customActionEnumerator = userCustomActionColl.getEnumerator();
        var foundAction = 0;
        while (customActionEnumerator.moveNext()) {
            var oUserCustomAction = customActionEnumerator.get_current();
            if (oUserCustomAction.get_title() == 'Custom Edit Page') {
                foundAction = 1;
                break;
            }
        }
        if (foundAction == 0) {
            var oUserCustomAction = userCustomActionColl.add();
            oUserCustomAction.set_location('EditControlBlock');
            oUserCustomAction.set_sequence(100);
            oUserCustomAction.set_title("Custom Edit Page");
            oUserCustomAction.set_url("/sites/TeamSite/Lists/Customer/dispform.aspx?ID={1}&Source=/sites/TeamSite/Lists/EmployeeDetails/AllItems.aspx");
            oUserCustomAction.update();
            clientContext.load(userCustomActionColl);
            clientContext.executeQueryAsync();
        }
    }, function(sender, args) {
        console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    });
}
</script> 

Wednesday, July 25, 2018

How To Migrate SharePoint Search Properties From One Tenant To Another Using CSOM

Create a Search Property:

First, we need to know how to create a search property before migrating it.

  • We should log into the SharePoint Admin Center.
  • Click Search from the left menu.
SharePoint

  • Select “Manage Search Schema”
           
SharePoint

  • Select “New Managed Property”.

     SharePoint

  • Then give the Property Name, Description, Type of the property and select the Searchable, Retrievable checkbox.
  • In the mapping to crawled property section, select “Add a Mapping” to choose the property or column 

  Migrating Search Crawl Property:

     After creating the property, create a windows application and add    “Microsoft.SharePointOnline.CSOM” Nuget package to the solution. We have to perform Export and Import operation to perform the migration. For exporting the search managed property use the below code snippet. 


private static string exportSearchSettings(ClientContext clientContext) {  
    SearchConfigurationPortability searchConfiguration = null;  
    SearchObjectOwner searchObjectOwner = null;  
    ClientResult < string > configResults = null;  
    string stringresult = string.Empty;  
    try {  
        searchConfiguration = new SearchConfigurationPortability(clientContext);  
        searchObjectOwner = new SearchObjectOwner(clientContext, SearchObjectLevel.SPSiteSubscription);  
        configResults = searchConfiguration.ExportSearchConfiguration(searchObjectOwner);  
        clientContext.ExecuteQuery();  
        if (configResults.Value != null) stringresult = configResults.Value;  
    } catch (Exception) {  
        throw;  
    }  
    return stringresult;  
}  

From the above code, we will be getting an xml string which can be imported to another site. After the above code execution, make sure that you’re storing the content somewhere to reuse it. I am saving the document as a file inside the application as “searchConfiguration.xml”
After storing it, use the below code to migrate the configurations to a new tenant.

private static void importSearchSettings(ClientContext clientContext) {  
    SearchConfigurationPortability searchConfiguration = null;  
    SearchObjectOwner searchObjectOwner = null;  
    string location = string.Empty, directory = string.Empty;  
    try {  
        location = Assembly.GetExecutingAssembly().Location;  
        directory = Path.GetDirectoryName(location);  
        searchConfigurationString = System.IO.File.ReadAllText(directory + "/searchConfiguration.xml");  
        searchConfiguration = new SearchConfigurationPortability(clientContext);  
        searchObjectOwner = new SearchObjectOwner(clientContext, SearchObjectLevel.SPSiteSubscription);  
        searchConfiguration.ImportSearchConfiguration(searchObjectOwner, searchConfigurationString);  
        clientContext.ExecuteQuery();  
    } catch (Exception) {  
        throw;  
    }  

Source:

Wednesday, May 9, 2018

How to retrieve items using SPSiteDataQuery in SharePoint 2013

In this post we will see how to retrieve the items from multiple lists using SPSiteDataQuery in SharePoint 2013.

SPSiteDataQuery:
                It is used to retrieve data from list or from all list in the site collection (i.e. used for cross-site and cross-list queries).

SPSiteDataQuery.Webs:
                This property will be used to specify from where the data will be retrieved.

SPWeb.GetSiteData:
                It is used to retrieve the data.

Sample Code to retreive the Items from the Tasks list

string siteUrl = SPContext.Current.Web.Url;
string username=string.Empty;

using (SPSite site = new SPSite(siteUrl ))
{
   using (SPWeb web = site.RootWeb)
   {
      SPUser user = web.CurrentUser;
      username = user.LoginName;
      SPSiteDataQuery dataQuery = new SPSiteDataQuery();
    //if it is set to SiteCollection, the query considers all Web sites that are in the       same site collection as the current Web site. 
     dataQuery.Webs = "<Webs Scope=\"SiteCollection\">";
//if it set to Recursive the query considers only the current Web site and all       subsites of the current Web site. 
   //dataQuery.Webs = "<Webs Scope=\"Recursive\">";
   //107 Maps to the tasks list
     dataQuery.Lists = "<Lists ServerTemplate=\"107\" />";
     dataQuery.ViewFields = "<FieldRef Name=\"Title\" />" + "<FieldRef           Name=\"AssignedTo\" />" + "<FieldRef Name=\"DueDate\" />";
     string spQuery = "<Where><Eq><FieldRef Name=\"AssignedTo\"/><Value   Type='User'>" + username + "</Value></Eq></Where>";
     dataQuery.Query = spQuery;
     DataTable dt = web.GetSiteData(dataQuery);
     DataView dv = new DataView(dt);
     gvResult.DataSource = dv;
     gvResult.DataBind();
              
    }

}

Tuesday, March 20, 2018

Some of the media queries for all devices

I have mentioned some of the media queries below

/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
/* Styles */
}
/**********
iPad 3
**********/
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen  and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen  and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

/* iPhone 5 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* iPhone 6 ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* iPhone 6+ ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* Samsung Galaxy S3 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* Samsung Galaxy S4 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

/* Samsung Galaxy S5 ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

How to merge more dll's into single dll (ILMerge tool)

We can merge multiple dll's into a single dll using the tool ILMerge.

Prerequisites:
                  Have to install this ILMerge before using the below  ILMerge-GUI tool.

ILMerge Link
https://www.microsoft.com/en-in/download/details.aspx?id=17630

You can download ILMerge-GUI tool in the below link

ILMerge-GUI Link
http://www.softpedia.com/get/Programming/Other-Programming-Files/ILMerge-GUI.shtml

How to use?
                   Add all the assemblies which we want to merge and select the primary assembly which we want to merge with other assemblies and select the Output path of the assembly in Output assembly and click merge after few minutes you will get a message box with message "Assemblies Merged"


   


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