Saturday 21 November 2015

Error: App Management Shared Service Proxy is Not Installed

Introduction

I created a SharePoint 2013 workflow using Designer and when I tried to publish the workflow I was getting the following error:
Error Message

Errors were found when compiling the workflow. The workflow files were saved but cannot be run.

Microsoft.SharePoint.SPException: App Management Shared Service Proxy is not installed.

Reason

This is because the App Management Service application is not created or the App Management Service is not running or the App Management Service Proxy is not added to the default proxy group.

Solution
  1. Open "Central Administration".
  2. Click on "Application Management" in the quick launch bar.
  3. Click on "Manage Service Applications" available under the Service Applications section.
  4. Check whether the App Management Service application is created, if not then create the App Management Service application.
  5. Click on "Application Management" in the quick launch bar.
  6. Click on "Configure service application associations" available under the Service Applications section.
  7. Check whether the App Management Service proxy is added to the default proxy group, if not then add it to the default proxy group.
  8. Click on "Application Management" in the quick launch bar.
  9. Click on "Manage services on server" available under the Service Applications section.
  10. Check whether the App Management Service is started, if not then start the service.
Below article helps me to resolve the issue:
http://www.c-sharpcorner.com/UploadFile/anavijai/error-app-management-shared-service-proxy-is-not-installed/

Thanks

Sunday 27 September 2015

Trying to use an SPWeb object that has been closed or disposed and is no longer valid


You get above error if the code is trying to access the SPSite or SPweb object which was disposed.

Trying to use an SPWeb object that has been closed or disposed and is no longer valid.

If you have code with SPContext, do not dispose the SPWeb or SPSite objects. You can’t dispose the SPcontext objects

i.e.  we cant dispose the object SPContext.current.Web or SPContext.Current.Site directly

when you say SPWeb spWeb= SPContext.Current.Web we are not creating a new instance of spweb, we are referring to the existing instance of the web object which is already there in SPContext. if you use using (SPWeb spWeb= SPContext.Current.Web), using will dispose the spWeb object after control goes out of its scope. here catch is, you are disposing an object which is not created by you.


using (SPSite mySiteCollection = SPContext.Current.Site)
{
using (SPWeb mySite = mySiteCollection.OpenWeb())
{

}
}
Above code gives you exception

so you can rewrite as

using (SPSite mySiteCollection = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb mySite = mySiteCollection.OpenWeb())
{

}
}
or don’t use using when you use SPContext.

Hope this helps!!!

List All SharePoint PowerShell Commands


Hi All,

Here is the simple way to list all Power shell commands.

1. To know the total count:
    Get Count: (Get-Command -PSSnapin Microsoft.SharePoint.PowerShell).count

2. List of all commands : 
    Get-Command –PSSnapin “Microsoft.SharePoint.PowerShell” | select name, definition | fl > C:\PowerShell_Commands.txt

Above command gives the text file which will have all the powershell commands.

Cheers

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