Thursday, 5 May 2016

Hosting a external application as a SharePoint App

There are lots of custom applications in various technologies like .NET,PHP,Mobile Applications. Hosting them in SharePoint would be beneficial for users already using SharePoint. There are many who are embracing SharePoint Online for the powerful features like Search, Storage of documents, Security. I have still not figured out how to get a Provider Hosted App which allows a custom .NET C# code to be written to handle business logic. This article is born because the attempt to deploy Provider Hosted App on NON AZURE ON LOCAL/IIS SERVER has not worked yet[Hopefully this changes...Hurry!!! This has changed.Thanks to code from msdn gallery https://code.msdn.microsoft.com/Working-provider-hosted-8fdf2d95 a provider hosted app could be successfully published to Azure]However, the workaround which was to write the custom logic using Web API and create a simple SharePoint App to point to the custom web URL.This technique can definitely help many external solutions blend with SharePoint easily.
Below are the simple steps [Thanks to a slide from slideshare]

1. Register a new app in SharePoint _layouts/15/appregnew.aspx
ClientID,ClientSecret,Title,URL,


2. Store the data in a notepad

3. Open Visual Studio. Create New Provider Hosted App.Update AppManifest with new StartUrl
and Client ID in "View Code"

4. Publish only the SharePoint App Project[Ignore the Web Portion of the project]

5. Upload the App in "Apps for Testing" section and Launch the App

Sunday, 17 April 2016

SharePoint Online List Creation PowerShell


#Reference http://blogs.technet.com/b/fromthefield/archive/2014/02/18/office365-script-to-create-a-list-add-fields-and-change-the-default-view-using-csom.aspx

#Create List in SharePoint Online

#Specify tenant admin and site URL

$User = "explore@<domain>.onmicrosoft.com"

$SiteURL = "https://<NAME>.sharepoint.com/<SUBSITE>"

$ListTitle = "ListDemo"



#Add references to SharePoint client assemblies and authenticate to Office 365 site - required for CSOM

Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"

Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

$Password = Read-Host -Prompt "Please enter your password" -AsSecureString

$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)



#Bind to site collection

$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)

$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)

$Context.Credentials = $Creds



#Retrieve lists

$Lists = $Context.Web.Lists

$Context.Load($Lists)

$Context.ExecuteQuery()



#Create list with "custom" list template

$ListInfo = New-Object Microsoft.SharePoint.Client.ListCreationInformation

$ListInfo.Title = $ListTitle

$ListInfo.TemplateType = "100"

$List = $Context.Web.Lists.Add($ListInfo)

$List.Description = $ListTitle

$List.Update()

$Context.ExecuteQuery()



#Retrieve site columns (fields)

$SiteColumns = $Context.Web.AvailableFields

$Context.Load($SiteColumns)

$Context.ExecuteQuery()



#Grab city and company fields

$City = $Context.Web.AvailableFields | Where {$_.Title -eq "City"}

$Company = $Context.Web.AvailableFields | Where {$_.Title -eq "Company"}

$Context.Load($City)

$Context.Load($Company)

$Context.ExecuteQuery()



#Add fields to the list

$List.Fields.Add($City)

$List.Fields.Add($Company)

$List.Update()

$Context.ExecuteQuery()



#Add fields to the default view

$DefaultView = $List.DefaultView

$DefaultView.ViewFields.Add("City")

$DefaultView.ViewFields.Add("Company")

$DefaultView.Update()

$Context.ExecuteQuery()



#Adds an item to the list

$ListItemInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation

$Item = $List.AddItem($ListItemInfo)

$Item["Title"] = "New Item1"

$Item["Company"] = "Contoso"

$Item["WorkCity"] = "London"

$Item.Update()

$Context.ExecuteQuery()




Sunday, 10 April 2016

SharePoint Online Coding Cheklist

SharePoint Online Review Checklist

Custom Code

This section defines the checklist for any coding or customizations in SharePoint environment.
This feature or functionality is NOT supported by Out of Box features through Browser
This feature or functionality is NOT supported by no code solutions.
A Developer site is created to host all the custom apps or add ins
The custom code is backed up in a reliable location(s)
Exception Handling is done for custom code.
Is the application scalable to mobile?
Is the app tested as a package on UAT and development server?
Does the code follow best practices to handle large list data

APPS
Is this Intranet, Extranet or Internet App?
Does the installer have Site Owner rights to install apps?
Has the App catalog been configured to install Apps?
The app domain is not a subdomain. Not apps.contoso.com[contosoapps.com]
The app domain should be in the Internet or Restricted sites security zone in Internet Explorer.
Prefixes must be less than 48 characters and cannot contain special characters or dashes
Is the app tested as a package on UAT and development server or site collection?


Reference
https://technet.microsoft.com/en-us/library/fp161237(v=office.15).aspx

Thursday, 17 March 2016

SharePoint Lists Creation using CSOM

SharePoint Lists are the building blocks of SharePoint. There are many ways to create SharePoint lists. The easiest through clicks is Site Setting-> Add an app -> Choose the type -> Type Name..Done. What if you want to do this across multiple site collections. That is when the Powerful tool named PowerShell comes to your aid. This has helped me to create dummy lists needed for fulfilling certain SharePoint requirement to create custom views on a list using CSOM. I would not want to go and create a list from UI each time to do the testing. The script makes the developers life also easier.
Steps:
1. Decide the Name and Properties of the list. There are various templates in SharePoint to choose from. The most commonly used templates are
100 - Generic List
101 - Document Library
In our example, we are using a "Fruits" list of Type "GenericList" which is a Custom List.
2. Get the URL of the list where the list will be placed.
For example. http://w15-sp
3. Open the PowerShell as Administrator and write the code shown below. Please change the url and list properties as per the requirement.

#Reference to the site
$spWeb = Get-SpWEb -SIte "http://w15-sp"
#Get lists
$spLists = $spWeb.Lists
#$spLists
#List Title
$listTitle = "Fruits"
#List Description
$listDesc = "This list stores all fruits"
#List Template
#View All List Templates
#[System.Enum]::GetValues("Microsoft.SharePoint.SPListTemplateType")
$listTemplateType = [Microsoft.SharePoint.SPListTemplateType]::GenericList
$guid=$spLists.Add($listTitle,$listDesc,$listTemplateType)
"A list with GUID $guid created successfully"

Video: http://youtu.be/-iHKRQ490G4?hd=1

JavaScript CSOM to create LIst
'use strict';
var context = SP.ClientContext.get_current(); //gets the current context
var web = context.get_web(); //gets the web object
var list = web.get_lists(); //gets the collection of lists

(function () {
    // This code runs when the DOM is ready and creates a context object which is
    // needed to use the SharePoint object model
    $(document).ready(function () {
        createItem();
    });
    function createItem() {
        // Retrieve the list and add an item to it.
        var targetList = list.getByTitle("Fruits");
        //create a new item object
        var listItemCreation = new SP.ListItemCreationInformation();
        //add the item to the list using addItem method
        var newItem = targetList.addItem(listItemCreation);
        var listItemTitle = document.getElementById("txtTitle").value;
        alert(listItemTitle);
        //var listItemCustom = document.getElementById("txtCustom").value;
        //alert(listItemCustom);
        //using set_item method u can set the values to the item fields
        newItem.set_item('Title', listItemTitle);
        //newItem.set_item('MyCustomField', listItemCustom);
        newItem.update();
        context.load(newItem);
        context.executeQueryAsync(ItemCreationSuccess, ItemCreationFail);
    }
    // This function is executed if the above call is successful
    // It replaces the contents of the 'message' element with the user name
    function ItemCreationSuccess() {
        $('#message').text('Item created successfully ');
    }
    // This function is executed if the above call fails
    function ItemCreationFail(sender, args) {
        alert('Failed to create Item' + args.get_message());
    }
})();

Wednesday, 16 March 2016

SharePoint Views using CSOM

This post is regarding a recent SharePoint requirement related to creating views using CSOM.
Once upon a time, I used to play with the Content Editor Web in MOSS 2007 and could happily satisfy the customer requirements without the need to do server side coding , and also not lose out on the joy of coding. A web part page was created and Content Editor Web Part was dropped on the page which contained the code mostly using jQuery. Things have improved soo much in SharePoint 2013 version. I got a requirement to create views from SharePoint page using CSOM. I started off trying to create the view from SharePoint User Interface.Then, with the help of PowerShell, I got the Query needed for the CSOM. I almost got stuck with the part where the view needed to be updated with Scope=Recursive. Initially, I tried through SPViewInformation and this did not support much properties.I tried though CAML query <QueryOptions><ViewAttributes Scope='Recursive'></QueryOptions> which was not working in SharePoint 2013.Later, thankfully, like magic, I was taken to a msdn site which indicated the SP.ViewScope property.The page with the code will be updated soon for a more generic example to Create Views for a simple Document Library and a Custom List  in SharePoint.


References:
https://msdn.microsoft.com/en-us/library/office/ee548053(v=office.14).aspx

Thursday, 7 January 2016

Updating a SharePoint LookUp column of List Item.

Updating a SharePoint List Item.


This post started after trying to solve an issue for a SharePoint Developer regarding Lookup columns for SharePoint. I started to test the same code in the Microsoft Virtual Labs and trying to solve the issue turned out to be a useful learning experience for me. Updating a list item seemed much simpler. I first created the "Sample1" Parent list containing the values
1. Approved
2. Pending
Then I created a second list "Sample2" list and added the custom Lookup column from the "Sample1" list.
Then, while testing in Powershell, the new columns are not appearing. Magically after sometime, the new columns are showing up. I believe this may be due to longer time for updated list to appear in Powershell. I realised my mistake.
The following script in Powershell does not show the expected new columns immediately.
(Get-SpWEb -identity "http://w15-sp").Lists["Sample2"].Items[1] |select Title,Status --WRONG
Get-SpWEb -identity "http://w15-sp").Lists["Sample2"].Items[1]["Status"]
The custom  fields are stored in the "XML" COLUMNS and cannot be viewed as you see in the Browser of a SharePoint site.
Below is a code to update lookup column in SharePoint site

Add-PSSnapin "Microsoft.SharePoint.Powershell"
$wpSite = Get-SPWeb "http://w15-sp"
$secondListItem = $wpSite.Lists["Sample2"].Items[1]
$secondListItem["Status"] = "1;#Approved"
$secondListItem.Update();
$secondListItem["Status"]



I tested the same updation using C#

using (SPSite wpSite = new SPSite("http://w15-sp"))
            {
                SPWeb wpWeb = wpSite.OpenWeb();
                //Get list "Sample1" with LookUp values 1:Approved;2:Rejected
                SPList lstSample1 = wpWeb.Lists["Sample1"];
                //Actual list to be updated
                SPList lstSample2 = wpWeb.Lists["Sample2"];
                SPListItem secondItem = lstSample2.Items[1];
                Console.WriteLine("Old values {0} {1}", secondItem["Title"], secondItem["Status"]);
                SPFieldLookupValue newValue = new SPFieldLookupValue(2, "Rejected");
                secondItem["Status"] = newValue;
                secondItem.Update();
                //After Update
                Console.WriteLine("New values {0} {1}", secondItem["Title"], secondItem["Status"]);
               
                Console.ReadLine();
            }





Tuesday, 5 January 2016

SharePoint Development Basics Part 1

The goal of this series is to create very basic projects for SharePoint in Visual Studio. Many times, we have starting trouble. If you are new to SharePoint, this tutorial can lay foundation for excellence in the existing SharePoint work you. You may already be developing or maintaining codes without understanding. After this series, hopefully, what seems complex is actually simple. The same code to retrieve a SharePoint object property would be done from simple Console to complex Solutions.

My favourite is C# Console Application and was actually first struggling to get the code running. On third day, magically the code ran after testing the SPSite against GUID instead of actual Url. In case you get errors like "The Web Application cannot be found..", check the following:
1. Run Visual Studio as Administrator
2. Set target platform to x64
3. .NET framework 4.5
4. Test the code against ID instead of string parameters which might have type error.

Generic steps for a SharePoint Development Project:
1.Open Visual Studio
2.Create New Project(x64)
3.Add SharePoint dll (from hive) [C:\ProgramFiles\Common Files\Microsoft shared\web server extentions\15\ISAPI]
4.Add using directive [Microsoft.SharePoint]
5.Write code
6.Debug

Below is the video illustrating the detailed steps for a simple Console Application reading the Site Collection properties: