Friday, June 13, 2014

SharePoint 2013 App: Handling App Install, Un-Install retry mechanism

Building SharePoint provider hosted apps we often come across scenario which require to provision SharePoint artefacts to host web and clean up once app is un-installed, obvious choice is to go with App events. I'm not going to bore your with how to create it there are tons of documentation available out there. Before we talk about "retry mechanism" let's do a quick re-cap so that we all are on same page.

App Event Receivers are implemented as WCF service deployed to remote web-application (ASP.NET MVC/Forms) which are called by SharePoint when app is installed/un-installed/upgraded. Imagine you have to provision quite a lot of artefacts perform certain validations this is quite a bit of task, and remember we are communicating back to SharePoint Host Web using Managed Client Object Model which is again a REST call under the hood, so all operations are happening asynchronously.

You implement all the logic and configure required permissions for App to create artefacts on Host Web while debugging App Installation you notice that App Install event is called repeatedly and it again attempts to create the same artefact you already created, don't think that you forgot to configure you app properly or your app install event is behaving in weird fashion, its actually by design (read: Installing apps for SharePoint : Notes Section)

Note

Sometimes a temporary loss of a network connection can block installation. If installation fails for any reason, the installation infrastructure will retry three times. If it does not succeed, an indication of the failure appears in the UI. Users can retry the installation later.


 

Cool, now that you know the reason behind "retry" let's discuss the probable solutions to handle this. The obvious way would be to keep a track of installation/un-install progress is to make use of persisted store and check the next time the "Installation Infrastructure retries". Let's explore the options for persisted store.

  1. App Web Property Bag
  2. List
  3. Cache
  4. SQL Store
  5. File System

App Web property bag is a decent store, since during install event you have access to App Web Property bag (note: you cannot make changes to host web property bag (Tried With SiteCollection Manged rights)), this is still decent but not optimal as you have to make additional REST call to App Web which to perform CRUD operation on Web Property bag. This technique works fine when you work with Install Event, but as you apply the same technique to Un-Install event your code will *break* because by design when the app is removed it deletes the associated App Web and hence you don't have the App Web Property Bag to store the un-install progress information.

So what next, SharePoint List is again a decent option but it has to be on Host Web and will not be fast and high performing.

As we talk about performance "Caching" comes to our mind, but before you start using your favourite search engine, please read (Caching Support for WCF Web HTTP Services). I attempted to configure the Basic Web Http Service Caching and I was not able to deploy my App. So I had to rule out this option and had to fall back on App Web Property Bag, but was a partial implementation.

Later I thought of configuring external Caching and utilize Azure Managed Cache Service this gives a flexibility to come around the situation to Configure my WCF service for Caching and utilize external store. By this mechanism I was able to properly keep track progress of Install/Un-Install events.

Azure Managed Cache Service is great, but I wanted something really simple coz I don't need a full blown distributed caching service just to keep progress!!!!

This is great but my quest for making it lighter and configuration free made me to look out for another optimized cache store, and finally my search ended at "ObjectCache and MemoryCache" these master pieces resides in "System.Runtime.Caching.dll" a quick note below (taken from links)


 

Note

The MemoryCache class is similar to the ASP.NET Cache class. The MemoryCache class has many properties and methods for accessing the cache that will be familiar to you if you have used the ASP.NET Cache class. The main differences between the Cache and MemoryCache classes are that the MemoryCache class has been changed to make it usable by .NET Framework applications that are not ASP.NET applications. For example, the MemoryCacheclass has no dependencies on the System.Web assembly. Another difference is that you can create multiple instances of the MemoryCache class for use in the same application and in the same AppDomain instance.


 

System.Runtime.Caching.dll allows you to cache across all .Net apps, not just the IIS worker process.The highlighted point gave me a hint and I thought of trying it out and guess what it worked flawlessly it was eureka moment for me trust me.I did bit more study as I didn't new much about it and found it is quite performing (StackOverflow: here, here).

So the ultimate winner is "MemoryCache".

Stay tuned, I'll shortly post the link to a sample code, but its cake walk just use your favourite search engine and you should be good to go.

A quick one: http://www.allinsight.de/caching-objects-in-net-with-memorycache/

I didn't get any post talking about the retry mechanism so thought of putting it up. This is one of the problem to solve during SharePoint App Development.

Thanks for being so patience as it was quite a theoretical article.

If you have any comment, reach me at @AkhileshN

Thanks

/a/


 

Thursday, April 24, 2014

SharePoint 2013: Require JS + SharePoint Hosted Apps


During my early days I was bit scared writing JavaScript applications since I was so use to C# that I always try to find similar feature or offerings in JavaScript, I must say it took me sometime to really grasp the concepts because there are different ways to do a single task e.g. creating an object. I wanted to apply the basic principles of SOLID and found myself nowhere near to adhering to it.

SOLID:

Single responsibility (SRP)

Open Close (OCP)

Liskov substitution principle (LSP)

Interface segregation principle (ISP)

Dependency inversion principle (DIP)


 

Well I'm too young in JavaScript still to apply all the principles but have at-least I now able to partially apply SRP, DIP up to a certain extent.
Mostly I've seen in SharePoint Hosted apps developers writing a big fat JavaScript file which contains all the business logic and it becomes hard to read and debug (really I mean it).
Modular programming helps a lot here but to achieve one must need to understand modules (class) and how they can be defined in JavaScript, splitting your logic in modules certainly helps you to achieve SRP but that still doesn't solves the root problem as you are still loading the entire module at once which doesn't gives you much benefit in terms of performance. Well loading individual modules can be loaded but you need a solution, and the answer to that is Require.JS, it's an AMD (Asynchronous Module Definition implementation)
Well if you are SharePoint developer then you'll argue that why we need another framework for loading individual module which is already provided by SharePoint via SP.SOD (Script on Demand).
A quick comparison between both approaches
Require JSSOD (Script On Demand)
Highly ConfigurableNo Configurations
Support to External LibrariesNo Exports for External Libraries
Inject, Exports, ShimNo exports or injection support (natively loads the plugin)
Cleaner Dependency construct and resolutionComplex construct to write dependencies within external libraries

 

I won't go in detail of how to setup require.js the documentation is itself self-explanatory trust me It took me a while to get this up but now it's a piece of cake !!!
I'll talk about some important part of the configuration which is required so that a SharePoint developer can leverage functionality and get benefitted from best of both worlds
The key aspect in require.js is configuration which is very powerful important attribute

 



 

Above is my simple configuration for require.js 

Please focus on deps and paths property

#1 Paths : The SharePoint JSOM runtime and main js to be loaded.
#2 Deps : Deps setting causes the runtime and sp.js file to be loaded before any module is loaded, thus making required core and necessary classes available for developer to program.

 

The Module

I've created two module which fetches the current user display name from web and user profile

// Module for Web



 


 

// Module for User Profile

User Profile Code : http://www.vrdmn.com/2013/02/sharepoint-2013-working-with-user.html @vrdmn

 



 


 

The Start-up Module




SP.SOD.loadMultiple(['sp.js''userprofile'], ShowUserName);

#1 The responsibility of ensuring that sp.js and sp.userprofile.js has been loaded is delegated to native SharePoint SOD module, the trick is to use SP.SOD.loadMultiple() which loads multiple modules and triggers the final function to be loaded.
Note: Here you can see the difference in the way require.js works and SOD works, require.js injects the dependencies as a parameters and SOD doesn't which gives more clear understanding of what to expect.


I've already published the sample at github: https://github.com/akhileshnirapure/sp_hosted_app_requirejs

Feel free to fork and if you have any question the reach me at Twitter: @AkhileshN
Thanks
Akhilesh Nirapure


Saturday, February 1, 2014

SharePoint 2013 Client Side People Picker + SharePoint Hosted Apps + Knockout

It’s been quite a while playing with knockout, and trust me a great learning, every framework especially JavaScript has a stiff learning curve so as with knockout. Working on SharePoint Hosted App came across a valid use case of having a people picker to be part of application, integrating it using jQuery and as per Microsoft’s guideline it’s a cake walk (here). Well as I mentioned using with knockout was a bit of challenge, dealing with some really simple requirement can be scary sometime. So let’s look at it.

Requirement: User should be able to lookup user and also the control should be pre-populated initially if data exists.

Well I’m not going to go in details every bits of the code, I assume you already have some idea about how knockout works if not then a good starting point knockoutjs.com.

Okay enough talk, in a nut shell what you need is a custom binding handler to work with.

Before we get started, just a quick note, there is no one-size which fits all so the code which I’m going to show you will not suffice all the requirement, so my suggestion get inspiration and tweak as you need J

ko.bindingHandlers.kopeoplepicker = {
init: function (element, valueAccessor, allBindingsAccessor) {

var schema = {};
schema['PrincipalAccountType'] = 'User';
schema['SearchPrincipalSource'] = 15;
schema['ShowUserPresence'] = true;
schema['ResolvePrincipalSource'] = 15;
schema['AllowEmailAddresses'] = true;
schema['AllowMultipleValues'] = false;
schema['MaximumEntitySuggestions'] = 50;
schema['Width'] = '280px';
schema["OnUserResolvedClientScript"] = function (elemId, userKeys) {
// get reference of People Picker Control
var pickerElement = SPClientPeoplePicker.SPClientPeoplePickerDict[elemId];
var observable = valueAccessor();
observable(pickerElement.GetControlValueAsJSObject()[0]);
console.log(JSON.stringify(pickerElement.GetControlValueAsJSObject()[0]));
};


// TODO: You can provide schema settings as options
var mergedOptions = allBindingsAccessor().options || schema;

// Initialize the Control, MS enforces to pass the Element ID hence we need to provide
// ID to our element, no other options
this.SPClientPeoplePicker_InitStandaloneControlWrapper(element.id, null, mergedOptions);

// Force to Ensure User
var userValue = ko.utils.unwrapObservable(valueAccessor());
var pickerControl = SPClientPeoplePicker.SPClientPeoplePickerDict[element.id + "_TopSpan"];
var editId = "#" + pickerControl.EditorElementId;
jQuery(editId).val(userValue);

// Resolve the User
pickerControl.AddUnresolvedUserFromEditor(true);


}
};



Microsoft’s Client Side People picker relies heavily on ID of element for the implementation of its controls (editor, hidden fields, etc.) so we have to work with it in our custom binding handler I wanted to highlight this point because most of the examples you see with KO is able to work with the element property itself)


#1 here we are initializing the People Picker Control.


 


#2 here we are looking for People Picker control using a special suffix which helps us in grabbing the control and then finding out the Editor element id (which actually has the value) and then making use of AddUnresolvedUserFromEditor(true) to resolve the user passed in a value. E.g. akhilesh.nirapure@zevenseas.com.


 


#3 here I’m providing my own implementation of what to do when we have a resolved user (from server) by using “OnUserResolvedClientScript” event. Again we here need to make use of People Picker control (we have to again find out by its id) and make use of GetControlValueAsJSObject() method which gets us the result as JSON.


 


Well the above implementation is not full blown code with exceptional handling it can be used as a reference point of how we can work with various event.


 


I’ve uploaded my sample code on GitHub (https://github.com/akhileshnirapure/sp13peoplepickerko) please feel free to fork it and extend it as you want.


 


Akhilesh Nirapure (@AkhileshN)