LinkedIn

Friday, July 14, 2017

Programatically accessing SharePoint List using REST API in CSOM

using Newtonsoft.Json.Linq; //JSON.Net

static void Main(string[] args)
        {

var webUri = new Uri("https://Your SharePoint Server/sites/IA/");
            const string userName = "username";
            const string password = "password";
            var securePassword = new SecureString();
            foreach (var c in password)
            {
                securePassword.AppendChar(c);
            }
            var credentials = new SharePointOnlineCredentials(userName, securePassword);

            var list = GetList( credentials);
            //print List title
            Console.WriteLine(list["Title"]);
}




public static JToken GetList(ICredentials credentials)
        {
            using (var client = new WebClient())
            {
                client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
                client.Credentials = credentials;
                client.Headers.Add(HttpRequestHeader.ContentType, "application/json;odata=verbose");
                client.Headers.Add(HttpRequestHeader.Accept, "application/json;odata=verbose");
                                var result = client.DownloadString("https://Your Server name/sites/IA/_api/web/lists/getbytitle('Listname')");
                var t = JToken.Parse(result);
                return t["d"];
            }
        }

Sunday, November 6, 2016

Microsoft Virtual Academy on SharePoint


https://mva.microsoft.com/en-US/training-courses/sharepoint-at-microsoft-14475?l=xsEThVUmB_3805193246

New Features of SharePoint 2016

New Features of SharePoint 2016:

1) Emphasis on Hybrid possibilities with On-Prem SP 2016 & O365
One Drive Re-Direction: You can redirect your My Sites to your Office 365 subscription’s OneDrive for Business host Sites you follow in one place – On-Prem + O365 – Sown under Sites in App Launcher.
Hybrid Cloud Search – Unified Search Experience-  the Office 365 Search will take your On-Premises SharePoint Search Index so that it can give you results from both for the same query.

** Delve helps you discover the information that's likely to be most interesting to you right now - across Office 365

2) App Launcher & UI Changes
SharePoint 2016 introduces the App Launcher, as well as changes to the UI, to help it match the Office 365 experience.
3) Server Roles (Min Role) - You can now install just the role that you want on particular SharePoint 2016 servers. WFE/ App/ Distributed cache/Search/ Custom
4) Zero Downtime Patching - They’ve also removed the downtime previously required to update SharePoint servers.
5) Removed 5,000 View Threshold – sort of: Instead of removing this unpopular threshold, they automated the creation of Indexed Columns.
6) Increased File Size for uploads – 2 GB to 10 GB
7) Fast Site Creation - Site Collections in 1 second from 40 seconds previously
8) New Compliance Center in SharePoint 2016 - In-Place Policy Hold Center and the Compliance Center – Help you to define your own compliance polices
9) New Collaboration Experience – Touch friendly interface
10) Link Durability: Links that are shared to documents on SharePoint 2016 can still work even if the filename is changed or if it moves to a different site collection.

Office 365 Video Feature

Videos is new feature in Office 365 offering which has state of the art video streaming capabilities and in this feature videos are stored in Azure Media services which will give better end user experience for people who are viewing the videos.


 

Office 365 Planner - Microsoft's Answer to Kanban Cards

Planner , recently introduced in Office 365, is useful tool for simple task management.This tool is great for managing internal projects that have a team working on them. You can assign tasks, add due dates and have comments on the tasks to allow easy communication and collaboration within the team.

Microsoft Teams - The new chat-based workspace in Office 365

Solved Remote Event Receiver on updated will be firing multiple times in SharePoint 2013/16

 Most of you who are working on Remote Event Receivers must have encountered this issue of "Updated event getting fired multiple times". The following code should fix the issue:

Use the adding or updating events. And then update the title within the "ProcessEvent" as follows:

public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties)
    {
        SPRemoteEventResult result = new SPRemoteEventResult();

            result.ChangedItemProperties.Add("Title", "NEW Title");
            result.Status = SPRemoteEventServiceStatus.Continue;
        return result;
    }


or



   public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties)
        {
            SPRemoteEventResult result = new SPRemoteEventResult();
            if (properties.EventType == SPRemoteEventType.ItemAdding ||
                properties.EventType == SPRemoteEventType.ItemUpdating)
            {
                // Generate Image Search for Flower
                result.ChangedItemProperties.Add("Title", 
                    "My New Title");
                result.Status = SPRemoteEventServiceStatus.Continue;
            }
            return result;

        }


Reference:

http://code.msdn.microsoft.com/office/SharePoint-2013-Add-list-2c6e71e0

Wednesday, October 26, 2016

Infopath Alternative StratusForms Form Builder

StratusForms Form Builder  is a free tool which will  help you get started creating new StratusForms forms for SharePoint. It does not contain all the possible functionality for StratusForms.
http://www.stratusforms.com/formbuilder.html

For more information on StratusForms including information on creating PeoplePickers, Encrypted fields, and other functionality please visit http://www.stratusforms.com or join the discussion on our IT Unity channel at https://www.itunity.com/community/stratusforms.

Thursday, October 20, 2016

Rest, OAuth and OData in SharePoint

Representational State Transfer Application Program Interface (REST API)  is an architectural style (Communication Protocol) which help in communicate over HTTP, using  verbs such as GET, POST, PUT and DELETE.
In Simple words, REST is an communication protocol which uses HTTP for communication between Clients(Browsers) & Servers.

Developers can now interact remotely with SharePoint data by using any technology that supports REST web requests. This means that developers can perform Create, Read, Update, and Delete (CRUD) operations from their SharePoint Add-ins, solutions, and client applications, using REST web technologies and standard Open Data Protocol (OData) syntax.

OData is a Standard protocol or a set of rules for creating RESTful calls. You can use OData system query options to control the result.
OData defines an abstract data model and a protocol that let any client access information exposed by SharePoint. The OData protocol is based on REST which define how HTTP verbs are used.

REST - design pattern / Architecture Style (It is an architecture of how to send messages over HTTP)
OData - enabling technology (It is a specific implementation of REST, really defines the content of the messages in different formats)


OAuth is not the protocol for authenticating users to access SharePoint. It would still be done by Claims Authentication. The OAuth comes into picture when we want to authenticate and authorize SharePoint 2013 Apps. OAuth is the internet protocol for creating and managing app identity. It is also a cross-platform mechanism for authentication and authorizing apps. The OAuth is also the emerging internet standard which is used by Facebook, Twitter and Google.
OData is a Standard protocol or a set of rules for creating RESTful calls. You can use OData system query options to control the result. OData defines an abstract data model and a protocol (HTTP) that let any client access information exposed by any data source.
OData's answer is the Entity Data Model. In many ways a modern take on the familiar entity-relationship model, the EDM models data as entities and associations among those entities. This general approach lets the EDM -- and thus OData -- work with pretty much any kind of data.
The client.svc web service in SharePoint handles this HTTP request and returns the response in JSON format. A client application handling this request can parse the response.

OData which was set to become THE reference API for access to data for applications based on HTTP requests (for communication with the server)
 OData uses the REST concepts for operations ie using HTTP verbs:
·         GET => Reading
·         POST => Insert
·         PATCH => Modification
·         DELETE => Delete
An OData query is composed of 3 major parts:
The service URL
The URL of the desired resource
Possible settings (filter, sort ...)
·      Now about SharePoint including the 2010 version was introduced via OData client.svc service to access the data. SharePoint 2013 extends the functionalities of client.svc especially now implements OData in accordance with the standards of this protocol. SharePoint 2013 also offers a client-side API (MSOC) that can be used in .NET or JavaScript which is partly based on OData. client.svc still exists but an alias created (_api) to simplify calls to SharePoint to retrieve data (eg http: // server / sites / TeamSite / _api / lists )
OAuth is not the protocol for authenticating users to access SharePoint. It would still be done by Claims Authentication. The OAuth comes into picture when we want to authenticate and authorize SharePoint 2013 Apps. OAuth is the internet protocol for creating and managing app identity. It is also a cross-platform mechanism for authentication and authorizing apps. The OAuth is also the emerging internet standard which is used by Facebook, Twitter and Google.
Step 1 –> The user accesses the SharePoint 2013 portal and SharePoint 2013 authenticates the user using Claims Authentication
Step 2 –>  SharePoint 2013 requests for the Context Token for the user, from Windows Azure ACS (Access Control Services)
Step 3 –> ACS returns Context Token
Step 4 –> SharePoint 2013 passes the Context Token to the user
Step 5 –> User accesses App using Context Token
Step 6 –> Client App pulls Refresh Token from the Context Token and requests ACS for oAuthToken
Step 7 –> ACS server returns OAuth token to the client app
Step 8 –> Client App makes CSOM/REST calls to SharePoint site by passing OAuth Token
Step 9 –> SharePoint 2013 returns site content to App based on the App Permission Manifests
Step 10 –> Client App returns the App Content to the user.


Rest, OAuth and OData in SharePoint

Representational State Transfer Application Program Interface (REST API)  is an architectural style (Communication Protocol) which help in communicate over HTTP, using  verbs such as GET, POST, PUT and DELETE.
In Simple words, REST is an communication protocol which uses HTTP for communication between Clients(Browsers) & Servers.

Developers can now interact remotely with SharePoint data by using any technology that supports REST web requests. This means that developers can perform Create, Read, Update, and Delete (CRUD) operations from their SharePoint Add-ins, solutions, and client applications, using REST web technologies and standard Open Data Protocol (OData) syntax.

OData is a Standard protocol or a set of rules for creating RESTful calls. You can use OData system query options to control the result.
OAuth is not the protocol for authenticating users to access SharePoint. It would still be done by Claims Authentication. The OAuth comes into picture when we want to authenticate and authorize SharePoint 2013 Apps. OAuth is the internet protocol for creating and managing app identity. It is also a cross-platform mechanism for authentication and authorizing apps. The OAuth is also the emerging internet standard which is used by Facebook, Twitter and Google.
OData is a Standard protocol or a set of rules for creating RESTful calls. You can use OData system query options to control the result. OData defines an abstract data model and a protocol (HTTP) that let any client access information exposed by any data source.
OData's answer is the Entity Data Model. In many ways a modern take on the familiar entity-relationship model, the EDM models data as entities and associations among those entities. This general approach lets the EDM -- and thus OData -- work with pretty much any kind of data.
The client.svc web service in SharePoint handles this HTTP request and returns the response in JSON format. A client application handling this request can parse the response.

OData which was set to become THE reference API for access to data for applications based on HTTP requests (for communication with the server)
 OData uses the REST concepts for operations ie using HTTP verbs:
·         GET => Reading
·         POST => Insert
·         PATCH => Modification
·         DELETE => Delete
An OData query is composed of 3 major parts:
The service URL
The URL of the desired resource
Possible settings (filter, sort ...)
·      Now about SharePoint including the 2010 version was introduced via OData client.svc service to access the data. SharePoint 2013 extends the functionalities of client.svc especially now implements OData in accordance with the standards of this protocol. SharePoint 2013 also offers a client-side API (MSOC) that can be used in .NET or JavaScript which is partly based on OData. client.svc still exists but an alias created (_api) to simplify calls to SharePoint to retrieve data (eg http: // server / sites / TeamSite / _api / lists )
OAuth is not the protocol for authenticating users to access SharePoint. It would still be done by Claims Authentication. The OAuth comes into picture when we want to authenticate and authorize SharePoint 2013 Apps. OAuth is the internet protocol for creating and managing app identity. It is also a cross-platform mechanism for authentication and authorizing apps. The OAuth is also the emerging internet standard which is used by Facebook, Twitter and Google.
Step 1 –> The user accesses the SharePoint 2013 portal and SharePoint 2013 authenticates the user using Claims Authentication
Step 2 –>  SharePoint 2013 requests for the Context Token for the user, from Windows Azure ACS (Access Control Services)
Step 3 –> ACS returns Context Token
Step 4 –> SharePoint 2013 passes the Context Token to the user
Step 5 –> User accesses App using Context Token
Step 6 –> Client App pulls Refresh Token from the Context Token and requests ACS for oAuthToken
Step 7 –> ACS server returns OAuth token to the client app
Step 8 –> Client App makes CSOM/REST calls to SharePoint site by passing OAuth Token
Step 9 –> SharePoint 2013 returns site content to App based on the App Permission Manifests
Step 10 –> Client App returns the App Content to the user.


SharePoint 2016 New Improvements


SharePoint 2016 New Improvements


1)    Emphasis on Hybrid possibilities with On-Prem SP 2016 & O365

One Drive Re-Direction: You can redirect your My Sites to your Office 365 subscription’s OneDrive for Business host

Sites you follow in one place – On-Prem + O365 – Sown under Sites in App Launcher

Hybrid Cloud Search – Unified Search Experience-  the Office 365 Search will take your On-Premises SharePoint Search Index so that it can give you results from both for the same query.



** Delve helps you discover the information that's likely to be most interesting to you right now - across Office 365



2)    App Launcher & UI Changes

SharePoint 2016 introduces the App Launcher, as well as changes to the UI, to help it match the Office 365 experience.

3)    Server Roles - You can now install just the role that you want on particular SharePoint 2016 servers. WFE/ App/ Distributed cache/Search/ Custom

4)    Zero Downtime Patching - They’ve also removed the downtime previously required to update SharePoint servers.

5)    Removed 5,000 View Threshold – sort of: Instead of removing this unpopular threshold, they automated the creation of Indexed Columns.

6)    Increased File Size for uploads – 2 GB to 10 GB

7)    Fast Site Creation - Site Collections in 1 second from 40 seconds previously

8)    New Compliance Center in SharePoint 2016 - In-Place Policy Hold Center and the Compliance Center – Help you to define your own compliance polices

9)    New Collaboration Experience – Touch friendly interface

10) Link Durability: Links that are shared to documents on SharePoint 2016 can still work even if the filename is changed or if it moves to a different site collection.

SharePoint Hosted App & Provider Hosted App

SharePoint Hosted Apps

With SharePoint Hosted Apps, everything including the app files are stored within SharePoint. When an app is installed to a site from the app catalog, a sub- site (sub-web) is created that stores the files that make up the app. This is usually referred to as an appweb. Things like pages, java script, etc… When a user leverages the app within SharePoint, the client will automatically fetch the app contents from the sub-web and client processing occurs to render whatever the app does. In this case, it’s not possible to run servers side code and app processing occurs client side.

Why use Provider Hosted Apps and not SharePoint Hosted Apps?
There are two answers to this question.
  1. The first is you need to run some server side code which is not possible with a SharePoint hosted app.
  2. The second is if SAML Claims authentication provider is setup with ADFS 2.0. This isn’t compatible with SharePoint hosted apps so you must use Provider Hosted Apps.
Note: If customer is using ADFS 3.0, they can leverage and use SharePoint Hosted Apps.

Provider Hosted Apps

Provider Hosted App is one where the app is hosted outside of SharePoint. For Example, a server hosting IIS can host the app contents in a site. This is referred to as a remoteweb. This is more of a hybrid in that it can run a mix of both client and server side code.

Progrmatically set Lookup Field Value in a SharePoint List using CSOM

Programmatically set Lookup Field Value in a SharePoint List using CSOM



 List> data = new List>();
                                    data = GetLookupIDFromList(clientContext, "Account", "AccountID", "Some Value");

ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                                    ListItem newItem = oList.AddItem(itemCreateInfo);
                                    newItem["Title"] = row.Field(0);
                                    newItem["OpportunityName"] = row.Field(1);
                                    if (data != null)
                                    {
                                        FieldLookupValue fld = new FieldLookupValue() { LookupId = int.Parse(data[0].Key) };
                                        if (int.Parse(data[0].Key) > 0)
                                        {
                                            newItem["AccountID"] = fld.LookupId;
                                            newItem["AccountName"] = fld.LookupId;
                                        }
                                    }




   public static List> GetLookupIDFromList(ClientContext context, string listname, string strLookupColumnName, string strLookupValue)
        {
            try
            {
                List> data = new List>();
                List list = context.Web.Lists.GetByTitle(listname);
                //string strCAMLQuery = "" + strLookupValue + "";
                string strCAMLQuery = "" +
                                   "" +
                                      "" +
                                         "" +
                                         "" + strLookupValue + "" +
                                      "
" +
                                   "
" +
                                "
";
                //If you are developing console application, use 
                // System.Web.HttpUtility.HtmlEncode(strLookupValue) instead of
                //System.Web.HttpContext.Current.Server.HtmlEncode(strLookupValue)

                CamlQuery query = new CamlQuery();
                query.ViewXml = @"" + strCAMLQuery + "";
                ListItemCollection items = list.GetItems(query);
                context.Load(items);
                context.ExecuteQuery();
                if (items.Count > 0)
                {
                    // int iRet = items[0].Id;

                    data.Add(new KeyValuePair(items[0].Id.ToString(), items[0].FieldValues["AccountName"].ToString()));
                    return data;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

Creating Client Context in SharePoint 2013 CSOM

Creating Client Context in SharePoint 2013 CSOM


 private static ClientContext spAuthentication(string path,string username, string pwd)
        {
            ClientContext ctx = new ClientContext(path);
            SecureString secStr = new SecureString();

            if (pwd.Length > 0)
            {
                foreach (var c in pwd.ToCharArray())
                {
                    secStr.AppendChar(c);
                }
            }
            ctx.Credentials = new SharePointOnlineCredentials(username, secStr);
            return ctx;
        }

How to get all the fields in a list in Sharepoint client object model

// return all rows and (selected) fields of a list--fields are included dynamically private Dictionary<string,Dictionary<string,object>> getListData( ClientContext ctx ) { Log.LogMessage( "Fetching {0}{1}", ctx.Url, ListName ); var list = ctx.Web.Lists.GetByTitle( ListName ); // fetch the fields from this list FieldCollection fields = list.Fields; ctx.Load( fields ); ctx.ExecuteQuery(); // dynamically build a list of fields to get from this list var columns = new List { "ID" }; // always include the ID field foreach( var f in fields ) { // Log.LogMessage( "\t\t{0}: {1} of type {2}", f.Title, f.InternalName, f.FieldTypeKind ); if( f.InternalName.StartsWith( "_" ) || f.InternalName.StartsWith( "ows" ) ) continue; // skip these if( f.FieldTypeKind == FieldType.Text ) // get Text fields only... but you can get other types too by uncommenting below // || f.FieldTypeKind == FieldType.Counter // || f.FieldTypeKind == FieldType.User // || f.FieldTypeKind == FieldType.Integer // || f.FieldTypeKind == FieldType.Number // || f.FieldTypeKind == FieldType.DateTime // || f.FieldTypeKind == FieldType.Lookup // || f.FieldTypeKind == FieldType.Computed // || f.FieldTypeKind == FieldType.Boolean ) { columns.Add( f.InternalName ); } } // build the include expression of which fields to fetch List<Expression<Func<ListItemCollection, object>>> allIncludes = new List<Expression<Func<ListItemCollection, object>>>(); foreach( var c in columns ) { // Log.LogMessage( "Fetching column {0}", c ); allIncludes.Add( items => items.Include( item => item[ c ] ) ); } // get all the items in the list with the fields ListItemCollection listItems = list.GetItems( CamlQuery.CreateAllItemsQuery() ); ctx.Load( listItems, allIncludes.ToArray() ); ctx.ExecuteQuery(); var sd = listItems.ToDictionary( k => k["Title"] as string, v => v.FieldValues ); // FieldValues is a Dictionary // show the fields foreach( var i in sd.Keys ) { Log.LogMessage( "\tItem: {0}", i ); foreach( var c in columns ) { Log.LogMessage( "\t\t{0}: {1}", c, sd[ i ][ c ] ); } } return sd; }

You Can also try:

// Get your ClientContext for your site  in 'clientContext'

SP.List oList = clientContext.Web.Lists.GetByTitle("List Title Here"); 
SP.FieldCollection fieldColl = oList.Fields;
clientContext.Load(fieldColl);
clientContext.ExecuteQuery();

foreach (SP.Field fieldTemp in fieldColl)
{
    MessageBox.Show(fieldTemp.InternalName.ToString()); //I used MessageBox to show, but you can do whatever you like with it here.
}