Sunday, 27 September 2015

JavaScriptObjectModel in SharePoint(JSOM)

Hi All,

We have JSOM is SharePoint. Lets see with different examples.

All these example can be placed in Content Editor webpart to test.

Example 1: Modify the Title of specific list item based on ID

<script type="text/javascript">
var clientContext = null;
var web = null;

function Initialize()
{
clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
this.list = web.get_lists().getByTitle('Genericlist');
this.oListItem = list.getItemById(1);
oListItem.set_item('Title', 'NewTitle updated');
oListItem.update();
clientContext.executeQueryAsync(Function.createDelegate(this, this.onUpdateListItemSuccess), Function.createDelegate(this, this.onQueryFailed));
}
function onUpdateListItemSuccess(sender, args) {
alert("list item updated");
}
function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}</script>​​​
<button onclick="Initialize()">Insert</button>​​

Example 2: How to get the Created date and Last Modified date of a Site?

<div id="display"></div>  
<!-- Script Content -->  
<script type='text/javascript'>  
var oWeb;  
function getwebdetails()  
{  
    var clientContext = SP.ClientContext.get_current(); // equivalent to SPContext.Current  
    oWeb = clientContext.get_web(); //Gets the current Web Object    
    clientContext.load(oWeb,'Title', 'Created', 'LastItemModifiedDate');  
    clientContext.executeQueryAsync(onSucceeded,onFailed);  
}  
function onSucceeded()  
{  
    var strmsg = "";
    strmsg += "<b>Web Title:</b> " + oWeb.get_title() +"<br/>";
    strmsg += "Created Date: "+ oWeb.get_created()+"<br/>";
    strmsg += "Last Modified Date: "+ oWeb.get_lastItemModifiedDate();  
    document.getElementById("display").innerHTML = strmsg;
}  
function onFailed(sender, args)  
{  
    try  
    {  
        console.log('Error: ' + args.get_message());  
    }  
    catch (err)  
    {  
    }  
}  
ExecuteOrDelayUntilScriptLoaded(getwebdetails, "sp.js");  
</script>

Example 3: Get current loggedin user,id and usertitle

<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(init,'sp.js');
var currentUser;
function init(){
    this.clientContext = new SP.ClientContext.get_current();
    this.oWeb = clientContext.get_web();
    currentUser = this.oWeb.get_currentUser();
    this.clientContext.load(currentUser);
    this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));
}

function onQuerySucceeded() {
    document.getElementById('userLoginName').innerHTML = currentUser.get_loginName();
    document.getElementById('userId').innerHTML = currentUser.get_id();
    document.getElementById('userTitle').innerHTML = currentUser.get_title();  
}

function onQueryFailed(sender, args) {
    alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
</script>
<div>Current Logged User:
    <span id="userLoginName"></span>
    <span id="userId"></span>
    <span id="userTitle"></span>  
</div>

Get ItemsCount in a sharepoint list:

<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>

<script type="text/ecmascript">
    var customlist ;
    function GetListInformation() {
        var clientContext = new SP.ClientContext.get_current();
        var oWebsite = clientContext.get_web();
        customlist = oWebsite.get_lists();
        clientContext.load(customlist);
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
    }      

    function onQuerySucceeded() {    
alert("Success");
         alert("Item Count : " + this.customlist.get_itemCount());
    }

    function onQueryFailed(sender, args) {
        alert(" Failed");
    }      
</script>

<button type="button" onclick="GetListInformation()">Click Me!</button>

Hope this helps!!!

SharePoint Client Side Object Model(CSOM)

We have different object models in SharePoint. CSOM is one of the model.
To use this, we need an asssembly i.e. Microsoft.SharePoint.Cleint.dll.

Below are few exercises to get familiar.

All these examples are tested in Windows Application.
Example 1: Get List of Tasks from SharePoint Tasks list and bind those to GridView.

   ClientContext context = new ClientContext(webUrl);
            List list = context.Web.Lists.GetByTitle("Tasks");
            CamlQuery query = new CamlQuery();
            query.ViewXml = "<View/>";
            ListItemCollection items = list.GetItems(query);
            context.Load(list);
            context.Load(items);
            context.ExecuteQuery();
            DataTable table = new DataTable();
            table.Columns.Add("Id");
            table.Columns.Add("Title");
            foreach (ListItem item in items)
                table.Rows.Add(item.Id, item["Title"]);
            displayGrid.DataSource = table;

Example 2: Modify the Title of Task List Items

    ClientContext context = new ClientContext(webUrl);
            List list = context.Web.Lists.GetByTitle("Tasks");
            CamlQuery query = new CamlQuery();
            query.ViewXml = "<View/>";
            ListItemCollection items = list.GetItems(query);
            context.Load(items);
            context.ExecuteQuery();
            foreach (ListItem item in items)
            {
                item["Title"] = "**";
                item.Update();
            }
            context.ExecuteQuery();
            MessageBox.Show("Updated Successfully");

Example 3: Get only two items from the Tasks list and bind those to Grid.

     ClientContext context = new ClientContext(webUrl);
            Web web = context.Web;
            List list = web.Lists.GetByTitle("Tasks");
            CamlQuery query = new CamlQuery();
            query.ViewXml = "<View><RowLimit>2</RowLimit></View>";
            ListItemCollection listItems = list.GetItems(query);
            context.Load(listItems);
            context.ExecuteQuery();
            DataTable table = new DataTable();
            table.Columns.Add("Id");
            table.Columns.Add("Title");
            foreach (ListItem item in listItems)
                table.Rows.Add(item.Id, item["Title"]);
            displayGrid.DataSource = table;

Note: Load() and ExecuteQuery() methods are crucial in CSOM.

Saturday, 26 September 2015

Converting DOC,PPT,XLS to DOCX,PPTX and XLSX extensions in SharePoint Library

Hi,

I would like demonstrate how to convert extensions of files in a SharePoint Library.

Here we go:

using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    SPFolder destnationLibrary= web.Folders[libraryName];
                    SPFileCollection fileColl = destnationLibrary.Files;
                    ChangeFileNames(siteUrl, libraryName, destnationLibrary, fileColl);
                    web.AllowUnsafeUpdates = false;
                    MessageBox.Show("Extensions are Successfully Changed", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
=======================================================================
  public static void ChangeFileNames(string siteUrl, string docLibraryName, SPFolder mylibrary, SPFileCollection actualfileColl)
        {
            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPFolder doclibrary = web.Folders[docLibraryName];

                    foreach (SPFile file in actualfileColl)
                    {
                        SPFileCollection fileColl = doclibrary.Files;
                        string eXtension = Path.GetExtension(file.Name);
                        if (eXtension != "")
                        {
                            switch (eXtension)
                            {
                                case ".doc":                                  
                                    string wordAutomationServiceName = "Word Automation Services";
                                    ConversionJob job = new ConversionJob(wordAutomationServiceName);
                                    job.Settings.UpdateFields = true;
                                    job.AddFile(siteUrl + "/Shared%20Documents/sample.doc", siteUrl + "/Shared%20Documents/sample.docx");
                                    job.Start(); // ConversionJob to check file is converting or not
                                    fileColl.Add(file.Name + "x", file.OpenBinary());
                                    fileColl.Delete(file.Url);
                                    break;
                                case ".ppt":
                                    fileColl.Add(file.Name + "x", file.OpenBinary());
                                    fileColl.Delete(file.Url);
                                    break;
                                case ".xls":
                                    fileColl.Add(file.Name + "x", file.OpenBinary());
                                    fileColl.Delete(file.Url);
                                    break;
                            }
                        }
                    }
                }
            }
        }
=======================================================================

Hope this helps!!!

Working on Interfaces

I would like to give some brief idea about interfaces.
Example 1:
using System.IO;
using System;

class Program
{
    static void Main()
    {
        sampleclass sample = new sampleclass();
        sample.operation();
        phase1 ph = (phase1)sample;
        ph.operation();
phase2 ph2 = (phase2)sample;
ph2.operation();
    }
}
interface phase1
{
void operation();
}
interface phase2
{
void operation();
}
class sampleclass:phase1,phase2
{
  public void operation()
  {
      Console.WriteLine("Here is the operation");
  }
}

Output:
Here is the operation
Here is the operation
Here is the operation

Description: In the above code we are implementing interfaces methods in sampleclass. As we can not create the instance of interface, we are making use of sampleclass object.
Here operation() method implementation is common for phase1,phase2 interfaces.
If we have different implementations for both interfaces, lets see below example2:
=====================================================================
Example 2:

using System.IO;
using System;

class Program
{
    static void Main()
    {
        sampleclass sample = new sampleclass();
        phase1 ph1 = (phase1)sample;
        phase2 ph2 = (phase2)sample;
        ph1.operation();
        ph2.operation();
     
    }
}
interface phase1
{
void operation();
}
interface phase2
{
void operation();
}
class sampleclass:phase1,phase2
{
  void phase1.operation()
  {
      Console.WriteLine("Here is the Phase1 method");
  }
  void phase2.operation()
  {
      Console.WriteLine("Here is the Phase2 method");
  }
}

Output:
Here is the Phase1 method
Here is the Phase2 method

Description: Here we are implementing same method in different ways. For that we are using interface name then period(.) and method name.

Hope this gives little idea regarding interfaces :)

Monday, 9 February 2015

Upload file into sharepoint document library

Here is the code:

String documentLibraryName = "Documents";
            using (SPSite oSite = new SPSite(SPContext.Current.Site.Url))  
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    if (!FileUpload1.HasFile)//Check file is selected or not
                        throw new FileNotFoundException("File not found.", FileUpload1.FileName);
                    SPFolder myLibrary = oWeb.Folders[documentLibraryName];//Access the document library
                    // Prepare to upload
                    bool replaceExistingFiles = true;
                    String fileName = System.IO.Path.GetFileName(FileUpload1.FileName);//get Filename
                    Stream fileStream = FileUpload1.PostedFile.InputStream;//Get filesstream from uploadcontrol
                    SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);// Upload document
                    myLibrary.Update();// Commit
                }
            }

Friday, 30 August 2013

Could not load file or assembly "" or one of its dependencies. The system cannot find the file specified

I got the above exception while deploying the code.So I quickly checked the following things.

1.Public Key of the assembly and it is correct.
2.Version of the assembly and it is updated one.But still I got the same error.

So I followed below steps and it worked.

1.Copy the dll and paste it any where in the server.
2.Open Start->Microsoft Visual Studio 2010->Visual Studio Tools->Visual Studio Command Prompt(2010)

Run the command below:

gacutil /i "Path of the assembly where it is located"

It will install the assembly into Global Assembly Cache.

3.Add it to the respective application bin folder.(Some times it is not needed)
4.Drag and Drop the dll file into "C:\Windows\assembly" folder(Optional)

Above steps resolved my problem.

Sunday, 11 August 2013

Backup and Restore SiteCollections using PowerShell

Backup the SiteCollection:

1.Open SharePoint Management Shell from SharePoint Products
2.Create a folder named as "SharePointBackups" in D: drive.
3.Run the below command
   Backup-SPSite -Identity https://sharepoint.com -Path D:\SharePointBackups\mysite.bak -Force
 
   It will create a mysite.bak file in SharePointbackups folder.

Restore the SiteCollection:

Run the below command:
   Restore-SPSite -Identity "Target Site Url" -Path "D:\SharePointBackups\mysite.bak" -Force

It will restore the site collection in target site.