building .net client tools for sharepoint online
TRANSCRIPT
Building .NET Client Tools for SharePoint Online
A guided tour following the steps to build our SharePoint Find & Replace tool
KWizCom Corporation
• Founded in 2005
• Headquartered in Toronto
• Global vendor of SharePoint Add-Ons
• 5000+ customers worldwide
Shai Petel
Director of Research and Development at KWizCom
MCPD, MVP: SharePoint
[email protected] | @shaibs | http://kwizcom.blogspot.com
What are SharePoint Apps?
Extend the capabilities of SharePoint.
Do not execute code on SharePoint
Are not installed on SharePoint
What are SharePoint Apps?
Provide UI, UX, Logic & State Browser: via scripts, html
Server side code: azure or your server
Client: run on your device (PC, mobile or tablet)
Requires no SharePoint development skills at all!
What are SharePoint Apps?
Communicates with SharePoint using CSOM– REST: direct calls, added in SharePoint 2013– JavaScript: via JavaScript OM within SharePoint hosted app only– .NET: via OM libraries (available for Silverlight and mobile as
well)
Share the similar limits and restrictions (3 level throttling)
Going through the same tunnel– SharePoint 2010: /_vti_bin/client.svc– SharePoint 2013: /_api (alias)
Context – SharePoint Hosted Apps
SharePoint hosted apps can use the app web or host web using JavaScript OM and the query string parameter: SPHostUrl automatically added to the app URL by SharePoint.
//current app webvar ctx_appWeb = SP.ClientContext.get_current();//host web url – from query stringvar spHostUrl = GetQueryStringParameterByName('SPHostUrl');//host web context, supports CORSvar ctx_hostWeb = new SP.AppContextSite(ctx_appWeb, spHostUrl);
Context – Provider Hosted Apps
Provider hosted apps can create a client context using the query string parameter that is automatically added to the Url when a user visiting the app from his SharePoint site: SPHostUrl
//Get SharePoint site URLvar sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);//Get client context of the site, using an OAuth access tokenClientContext clientContext =
TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
Context – Client Apps
In client apps, it is up to the developer to provide the SharePoint site Url, either by having the user type it, having it in the app configuration file or by hard coding it.
With ClickOnce this can be
sent as a parameter to the
app (see example later).
Authentication
You will need to authenticate to the SharePoint site before you can use any of the SharePoint APIs.
Authentication – SharePoint Hosted Apps
Since the SharePoint JavaScript API is running in the browser, after the user has successfully logged in, the authentication part is transparent to the developer and no special actions are needed.
Authentication – Provider Hosted Apps
When building a provider hosted apps, you will have to get an OAuth token before you can make any requests to the server.
Use access token with REST:
Use access token with .NET client OM, using the TokenHelper class:
request.Headers.Add("Authorization", "Bearer " + accessToken);
TokenHelper.GetClientContextWithAccessToken
Authentication – Client Apps
With client apps, you have a few options to authenticate to SharePoint:
Use default credentials
Create network credentials
Use SP special login class for SP Online
OAuth
ClientContext.Credentials = CredentialCache.DefaultCredentials;//CSOMWebClient.UseDefaultCredentials = true;//REST
Authentication – Client Apps
With client apps, you have a few options to authenticate to SharePoint:
Use default credentials
Create network credentials
Use SP special login class for SP Online
OAuth
ClientContext.Credentials = new System.Net.NetworkCredential(username, password); //CSOM
Authentication – Client Apps
With client apps, you have a few options to authenticate to SharePoint:
Use default credentials
Create network credentials
Use SP special login class for SP Online
OAuth
SecureString passWord = new SecureString();foreach (char c in password.ToCharArray()) passWord.AppendChar(c);ClientContext.Credentials = new sp.SharePointOnlineCredentials(username, passWord);
Authentication – Client Apps
With client apps, you have a few options to authenticate to SharePoint:
Use default credentials
Create network credentials
Use SP special login class for SP Online
OAuth
TokenHelper.GetAccessTokenTokenHelper.GetClientContextWithAccessToken
Rule of thumb questionsClient App
• Is your app being used by a specificgroup of users on various sites and lists?
• Does your app require very rich user experience?
• Should the app support large, lengthy, operations?
Web App
• Does you app “belong” to the content?
• Is any user working on the list or site need to use your app?
Common
• What will feel more natural to your target audience?
• What platforms should you app be available?
Experience
Client apps– Rich UI native to device
– Best experience for specific device input (keyboard, touch, pen, etc.)
– Integrate with other devices / features (camera, printer, office client, GPS etc.)
Web apps– Rely on browser (Mandatory: IE9+, Chrome & FireFox)
– Built mostly on JavaScript, CSS, HTML
– Flash, Java and Silverlight may provide richer experience, but not cross platform
Experience
CSOM 3 level throttling– Break your requests into smaller requests
– Keep the state of large operations in your app
Client apps are much better at keeping track of large state operations
Web apps tend to be more vulnerable to browser crash, close or navigate by accident (how many times did you hit backspace out of a textbox and browser went back losing your state?)
Experience – avoid list throttle
sp.ListItemCollectionPosition pos = null;do {sp.CamlQuery query = new sp.CamlQuery();//get 500 items at a time, appease the angry throttling godsquery.ViewXml = "<View><ViewFields>" + ViewFields + "</ViewFields><RowLimit>500</RowLimit></View>";if (pos != null) query.ListItemCollectionPosition = pos;var items = currentList.GetItems(query);CurrentGlobalDataContext.Progress.ClientContext.Load(items);CurrentGlobalDataContext.Progress.ClientContext.ExecuteQuery();//set position to next batch. Last batch will return nullpos = items.ListItemCollectionPosition;//add batch to all itemsforeach (var item in items) CurrentGlobalDataContext.AllItemsInList.Add(item);} while (pos != null);
Experience - Updates
Web apps, Mobile & Tablet:
– Store files on your own server (apps.kwizcom.com)
– Some changes require publishing a new app to the store
Desktop apps:
– Using ClickOnce easily push updates to clients
– Supports optional or mandatory updates
– Online only option: require users to launch it from your site
Development machine
Windows 7 SP1 and up, Server 2008 R2 and up
Install Visual Studio 2012/2013
Install SharePoint Client Components SDK
No need to build on SharePoint server
ClickOnce
In project properties->Publish set up click once application
Publish directly to FTP/Web server, optionally wrap in a WSP to host in SharePoint
Support multiple publish locations
Auto update, force update
ClickOnce
It is highly recommended you digitally sign your application, with a valid code signing certificate, to avoid nasty prompts for users when launching your application. Do that in project propertyes -> signing, as well as in your project csproj file:
<Target Name="SignOutput" AfterTargets="CoreCompile"><Exec Command=""C:\Program Files (x86)\Windows Kits\8.0\bin\x86\signtool"
sign /f "$(ProjectDir)xCodeSigningCertificate.pfx" /p "[password]" "$(ProjectDir)obj\$(ConfigurationName)\$(TargetName)$(TargetExt)"" />
</Target>
ClickOnce
To pass parameters to your application visit project properties -> publish -> options, and check “Allow URL parameter to be passed to application” box.
In IE only, parameters can be sent to the application installer URL:
http://my.srv/myapp/myapp.application?product=KSCP
Note: these parameters are not saved when launching the application from the desktop in the future! You have the option to save it in IsolatedStorage.
ClickOnce
To send parameters to non IE browsers, if you have a set possible values, you can create specific setup files and point the users to them:
copy setup.exe setup-petelab.exesetup.exe -url="http://my.server/myapp.application?SPHostUrl=https://petelab.sharepoint.com" /dest=setup-petelb.exe
ClickOnce
To read parameters in your app, run this code:
Note: if you allow the application to be used from the desktop, you must save the parameters in IsolatedStorage
if (ApplicationDeployment.IsNetworkDeployed) {string queryString = ApplicationDeployment.CurrentDeployment.ActivationUri.Query;if (!string.IsNullOrEmpty(queryString))Parameters = System.Web.HttpUtility.ParseQueryString(queryString);}
ClickOnce
When it is time to update your application, you simply publish a new version to your server.
You can force users to update before they can use your app.
Samples
Live demo:
KWizCom Find & Replace
– Login
– Get client context
KWizCom Web Installer
– Publish via WSP
– Get query string parameters
Samples
Keep login info + parameters in IsolatedStorage where only the user and your app can access
//get the user store for your appIsolatedStorageFile iSt = IsolatedStorageFile.GetUserStoreForAssembly();//create a writerStreamWriter sw = new StreamWriter(new IsolatedStorageFileStream(“appinfo", FileMode.Create, iSt));//write to the isolated storagesw.WriteLine(Encrypt(UserName));sw.WriteLine(Encrypt(Password));sw.Flush();sw.Close();
Samples
Retrieve them later when application loaded:
//get the user store for your appIsolatedStorageFile iSt = IsolatedStorageFile.GetUserStoreForAssembly();//create a readerStreamReader sr = new StreamReader(new IsolatedStorageFileStream(“appinfo", FileMode.OpenOrCreate, iSt));if (sr == null) return;//read datastring user = Decrypt(sr.ReadLine());string password = Decrypt(sr.ReadLine());//close readersr.Close();
Shai Petel
Director of Research and Development at KWizCom
MCPD, MVP: SharePoint
[email protected] | @shaibs | http://kwizcom.blogspot.com
Additional links
Understanding and Using the SharePoint 2013 REST Interface
Authorization and authentication of apps for SharePoint 2013
How to: Complete basic operations using SharePoint 2013 REST endpoints
Authentication Code OAuth flow for apps in SharePoint 2013
How to: Create a basic provider-hosted app for SharePoint