Monday, October 27, 2014

Sharepoint 2013 - App Model

Copyright from: sureshpydi.blogspot.in

App Model is the major and interesting change from SharePoint 2010 to share point 2013. It brings a new set of opportunities from development environment. Before going to app model, we can check few things,

What are development models we have in share point?

  • We have Solution Package model and Client object model and Ecma Script Object model. Solution Packages models are farm solutions and Sand Boxed solutions  Extended in SharePoint 2010) are not deprecated or not going away. There is no change in both of them.
  • App model will not support SharePoint Server side code. there is no chance of access like Sand boxed solutions. All the code must be run in client side (JavaScript) or out of share point (like Azure or other hosting Plat forms), just connect back to share point remotely.
  • Only SharePoint 2013 will support App Model  There is no support for earlier versions of share point yet.
Why App Model?

In SharePoint 2010, with farm solutions, custom code was deployed into server. All the things will deployed to the server means an IT consultant with console access would need to upload the solution package to the server. So that the Access must be required to deploy the solution in farm level. This will only works On Prem environment. It will not suitable for hosted deployment. Both Farm and Sand Boxed solutions developer need to have full understanding on the server and command on sever API.Farm solutions are not suitable for cloud environment. We can use sand boxed solution on cloud environment, but there is lot of limitations put users off from it. For example we cannot call External Web services from sand boxed solutions and we can only access limited set of SharePoint API's.

App model is mainly designed for cloud hosting. It will not use server side code. It will use only client script like java script or jQuery, and will work on top of share point framework. So that it will keep environment light. you can easily migrate the apps and easily add the apps from app store.

App Isolation- 

Apps are isolated. One app cannot talk with other app. When we install app share point will create a sub site in the existing site like as : http://app-APPID1.apps.domain.com/AppName- here apps will run under a separate domain. APPID will generated for share point.

There is no alternative way to call the app with out URL  If you want to try to call the app from parent site (i mean site which app was created or app was installed) it access to URL only. The reason here isolation. Apps will run under a separate domain, If in case apps will run same domain, here apps will use java script to access data. That will cause security issue. So that Microsoft people elected to go for another domain and that will unique for app. So that we can skip cross site attack.

We can present the app in three ways to the customers-

  • Immersive App: Here app will take an entire page and when we click on the app it will redirect to a page. Every App has this functionality because every app app has a start page.
  • Part App: This is app is located in a part of a page, similar as web part  Suppose we have map app..it just provide a widget to show the location.
  • Custom Action App: Here app will be shown in a ribbon control or as menu item. For example we can take print option.
Scope of an App-

There are two choices to build the app scope

  • Web Scoped: Web scoped apps will live only with in the app web.
  • Tenant scoped: we can publish the app to the entire company or to the public scope.
Availability of Apps -

Just like Mobile apps we have a market for share point apps and we can acquire or buy the apps from app market. There is a private market place for employee in corporate company. Microsoft is having market place in cloud. Developers can develop their apps and sell it through Microsoft app market. There is more chances to launch third party market places and sell the apps. This will get more spice to the app market and help boosting the competition.

Types of Apps-

There are three types of app development models are available to build apps.

  • SharePoint Hosted Apps: Here in this option every thing in SharePoint "With in SharePoint Only". When you install the app, a new site will create with in the share point and will keep all the app content in share point  app content will be lists, Pages, Site Columns  Content Types etc. All the process will happen in client browser using client side scripting.
  • Developer Hosted Apps/ External Apps: In this scenario all the logic will be external to share point  Logic may be in any technology like .net , Java, PHP...and on any infrastructure like IIS, Apache ... Here share point will work as a Launching pad. That might do anything. Here the name "Developer/External" comes that developer or external is the responsible for the code.
  • Azure Or Auto Hosted: Here App will be located in cloud. When ever developer download the app from cloud and installs it in site, app will automatically create site and also provisions a new azure website. We can build this type of app and host in cloud. 
What i need to do to develop Apps?

Before developing and deploying apps, we need to do some configurations,

  • Subscription service and App Management service must be running for apps usage.
  • we need to create the DNS domain to create the unique URL's for app.

What we can do with apps?

  1. We can write remote event receivers
  2. Deploy new fields based on existing field types
  3. Can provision lists, Content types  with in app website.
  4. We can have custom application pages to work
  5. Can consume custom web services.

What we can't do?

  1. Custom Site Definitions
  2. Delegate Controls
  3. Custom Themes
  4. Custom Action groups and Custom Hidings
  5. Custom User Controls
  6. Timer Jobs
  7. Workflows


Thanks for Salman Blog and Andrew Connel to providing very useful posts on App model. 

Wednesday, October 22, 2014

A Unified Approach to Client-Side Storage

Copyright from: John Papa

This simple API can give you a leg up on local storage in your Web apps.
Web apps, generally, have sets of data that either don't change a whole lot, or that represent state -- the configuration, content and attributes -- which must be maintained between page calls. HTTP offers a variety of great features, but state has to be reset between page calls because it's stateless. So where do you store that data in Web applications? The concept of local storage addresses this challenge quite nicely.
Why Use Storage? 
Local storage in HTML5 refers specifically to the localStorage object. I recommend using it if you're building an app for an HTML5-compliant browser that implements localStorage. (You can check the popular site, caniuse.com, to see if your browsers support localStorage and other features.) Historically, browsers have used a variety of techniques to store local data, including localStorage, sessionStorage (which differs from localStorage in that its data goes away when the browser closes), globalStorage, cookies and userData.
You can use cookies, but there are some limitations, which Christian Heilmann explains in his article, "Local Storage and How to Use It on Web Sites". It's worth noting that while you can store a lot of data in local storage, you should use this feature judiciously -- it's not a database, after all. Local storage is ideal for retaining data that either doesn't change often (you can set expiration dates), or to help maintain state across pages, tabs and browser sessions.
Say you're building a Web app that supports multiple versions of different browsers. You want to use localStorage where available, but also fall back and provide graceful degradation in older browsers. What do you do? Certainly not a lot of conditional logic -- bleh!
Unified API with Amplify.store 
This is the sweet spot for AmplifyJS, a library of jQuery components built by the folks at appendTo LLC. It includes three main features: AJAX requests, pub/sub messaging and storage. The amplify.store object provides a unified way to persist data from a variety of Web browsers. It offers a single API across multiple browsers, which implement storage quite differently. The amplify.store library hides the complexity and logic, so you can focus on storing and retrieving data -- and not on how to handle it in different browsers. You can find a complete list of the amplify.store default storage mechanisms based on browser support here.

Note: If your browser doesn't support JSON2, you must include JSON2.js as well. This is required in Internet Explorer 7 and earlier versions to use the JSON.stringify and JSON.parse methods.
Local storage stores a key value pair, where the key and the value are both strings. What this means is that if you want to store arrays and objects, you should serialize them first, using JSON.stringify (and de-serialize them with JSON.parse). However, if you use amplify.store, it will serialize and de-serialize the data to and from JSON for you.
The following sample code defines an array of people objects:
var testKey = 'people'; 
var testVal = [
  { name: 'John', age: 34, pets: [{name: 'Fido', type: 'dog'},
    {name: 'Tink', type: 'cat'}]},
  { name: 'Landon', age: 14, pets: [{name: 'Iron Man', type: 'dog'}, 
    {name: 'McQueen', type: 'dog'}]}];
You can store these objects using amplify.store by passing a key value, followed by the textVal object. Amplify.store will serialize the data in testVal, do a check for localStorage support (and fallback, if necessary), then store the data.The data can be retrieved using the same store method, by only passing a key value. You can also clear the storage by passing a null in for the value.
Examining Local Storage
You can examine what's currently in local storage by calling amplify.store and passing no parameters. If you want to know which key values are being stored, you could also run a script. You can clear a data value from local storage immediately by calling amplify.store(key, null) or setting an expiration on the data when you store it. Simply pass an optional parameter to the store method following the data value. The parameter is an object containing an expiration value in milliseconds.
The simplicity of the API, its support for the localStorage object and its graceful degradation make this one of my favorite APIs for this space. All of the sample code can be found in this fiddle, which uses toastr to display the values and log the storage and retrieval.
About the Author
John Papa is a Microsoft Regional Director and former Microsoft technical evangelist. Author of 100-plus articles and 10 books, he specializes in professional application development with Windows, HTML5, JavaScript, CSS, Silverlight, Windows Presentation Foundation, C#, .NET and SQL Server. Check out his online training with Pluralsight; find him at johnpapa.net and on Twitter at twitter.com/john_papa. 

Tuesday, October 21, 2014

JSLink and Display Templates Part 5 – Creating custom List Views

Copyright from: www.martinhatch.com

This post will look at a slightly different scenario – List Views. The general principles are the same (we write some JavaScript which tells SharePoint to override the rendering of various elements) but because we are now dealing with a whole view instead of just a single field there are some new elements to play with.
This is actually one of the more simple examples so I’ll start with all of the JavaScript in one block
var mjhViews = mjhViews || {};
mjhViews.itemHtml = function (ctx) {
  var returnHtml = 

 + ctx.CurrentItem.Title + 
;
  if (ctx.CurrentItem.MyCustomField) {
    returnHtml += “” + ctx.CurrentItem.MyCustomField + 
;
  }  
  return returnHtml;
};
(function () {
  var mjhOverrides = {};
  mjhOverrides.Templates = {};
  mjhOverrides.Templates.Header = 
;
  mjhOverrides.Templates.Item = mjhViews.itemHtml;
  mjhOverrides.Templates.Footer = 
;
  
  mjhOverrides.ListTemplateType = 104;
  mjhOverrides.BaseViewID = 1;
  
  SPClientTemplates.TemplateManager.RegisterTemplateOverrides(mjhOverrides);
})();


So we start off as good JavaScript developers and create ourselves a namespace (mjhViews) for our function (so we don’t pollute the global namespace). This contains a single function (mjhViews.itemHtml) which accepts the same render context object we’ve been using throughout this series.
The itemHtml method simply returns some basic HTML consisting of the item Title in an H2 element followed by the “MyCustomField” (if it exists, this field was used in Parts 3 and 4). Of course there are different methods for retrieving the values of the current item but the render context will automatically provide properties for the basic data types (some field types, external data fields in particular, don’t work like this and you might need to get creative with AJAX REST calls but be careful about performance!).
Finally we have our anonymous function which actually registers this override with SharePoint, and this is where things get interesting.
The main thing you might notice here is that we aren’t controlling any specific fields but instead override the “Header” and “Footer” with plain old HTML. For the “Item” we reference our rendering method and this will be executed for every item present in the view.
We then have two more properties (both of which are optional by the way).
The ListTemplateType and the BaseViewID both define which specific list types and views this rendering should be used for. If you don’t specify values for these then when this rendering override is registered it will override EVERY list and view on the page.
Finally we use the same old RegisterTemplateOverrides to tell SharePoint to process our object and do its thing!
Now before I apply this view it looks like this (which should be a pretty familiar SharePoint view):
Standard SharePoint list view
Once I apply my custom view rendering it looks like this:
A custom (if slightly boring) list view done with JavaScript
So .. quite easy huh? But the bright among you might have wondered .. where the hell has the toolbar and paging gone? Ahh .. yes .. that is all handled by the header and footer.
The header and footer contain important List View elements
This isn’t the only setback, if you try to use the view I defined above in “Quick Edit” mode then you also get the following error message:
TypeError: Unable to get property ‘style’ of undefined or null reference
The problem is that if you don’t override the Header you get some slightly funky behaviour because the headers injects a table object and it expects your content to be rendered inside that HTML table as rows. So by default I end up with the following (note the headers are at the bottom!)
Custom rendering with the header intact, but column headers are appearing AFTER the other content
So if you really want to play ball with the list views (and want the headers to be available) then you need to use TR and TD elements for your render HTML. For example:
mjhViews.itemHtml = function (ctx) {
  // start with a and a
  var returnHtml = “ ” ;
  returnHtml += 

 + ctx.CurrentItem.Title + 
;
  if (ctx.CurrentItem.MyCustomField) {
    returnHtml += “” + ctx.CurrentItem.MyCustomField + 
;
  }  // close off our and elements
  returnHtml += ;
  return returnHtml;
};
Once we put this in place, our headers are back in the right place.
Custom rendering with column headers in the right place
Making your views use the correct Display Template
In order to make sure the Display Templates are used in the correct places you have a number of options.
  1. In your schema.xml of a custom list definition you can define the JSLink property allowing you to override specific views. This allows you to build List Templates which have completely bespoke views when required (especially useful for use with list view web parts)
  2. You can define the JSLink property on the List View Web Part .. and this works either for defined views in the List or for List View Web Parts which you have dropped onto other web part pages or publishing pages.
  3. You can use Code / PowerShell to modify the JSLink property of the SPView object programmatically
  4. You can of course just drop in your JavaScript file using a Script Editor or custom Master Page and use the ListTemplateType and BaseViewID properties I told you about at the beginning on this post :)
  5. or you can use a funky new method which allows users to create their own views using your custom templates … but more about that in Part 6 :)
So that pretty much covers off how list views can be rendered using bespoke code. Hope you’ve been enjoying the series but we’re not done yet!

JSLink and Display Templates Part 4 – Validating user input

Copyright from: www.martinhatch.com

In the previous posts we have looked at JSLink and how we can use it, we have looked at overriding the rendering of individual fields both for display and also for editing. Now we are going to look at Validatorsand how we can validate user input before their changes are saved.
In order for a validator to work you need three moving parts:
  • Validation method (to tell SharePoint if the field input is valid or not)
  • OnError method (to handle any errors which are raised)
  • Registration code to do the plumbing
Validation Method
We’ll base this sample on the Custom Editing interface we built in Part 3 and first off we will build ourselves a validation method.
This is technically going to be an object with a Validate method (to which SharePoint will pass a value). The code for this method is as follows:
mjh.MyCustomFieldValidator = function () {
  mjh.MyCustomFieldValidator.prototype.Validate = function (value) {
    var isError = false;
    var errorMessage = “”;
    if (value == “Item 2″) {
      isError = true;
      errorMessage = “You cannot select ‘Item 2′”;
    }
    returnnew SPClientForms.ClientValidation.ValidationResult(isError, errorMessage);
  };
};
The code above contains a very simple if statement to check the items value (in my example saying that an error message will be displayed if the item value is set to “Item 2″ .. one of the drop-down choices from Part 3 of this series).
Finally we call the SPClientForms.ClientValidation.ValidationResult method passing in our “isError” (a true/false boolean) and the error message (a text string).
OnError Method
We then need a final method which tells SharePoint basically what to do when an error actually occurs. This is a fairly simple method in which you can basically do whatever you want (pop-up alerts, add HTML to the page, change CSS, whatever you need).
Now we could just use an Alert(error.message) function if we wanted a particularly crude error message but it would be much better to have some formatted error message just like SharePoint does out of the box .. and for that to work we first need to have ourselves a recognisable element that we can manipulate using jQuery, so we add the following code to our rendering method for the edit interface:
// add the error span
returnHtml += ;
Once we have this we can manipulate it in our “onError” function (which as you can see is very simple).
mjh.onError = function (error) {
  $(“#MyCustomFieldError”)
  .html( + error.errorMessage + );
};
So all we are really doing is grabbing the span using the ID we gave it, then injecting our error message.
Now for the plumbing …
So the only thing missing is making this all hang together from inside our render method: 
var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);

// register the field validators

var fieldValidators = new SPClientForms.ClientValidation.ValidatorSet();
if (formCtx.fieldSchema.Required) {
  fieldValidators.RegisterValidator(
    new SPClientForms.ClientValidation.RequiredValidator()
  );
} fieldValidators.RegisterValidator(new mjh.MyCustomFieldValidator());
formCtx.registerValidationErrorCallback(formCtx.fieldName, mjh.onError);
formCtx.registerClientValidator(formCtx.fieldName, fieldValidators);
So lets walk through what we are doing in the code above.
First off we create ourselves a new ValidatorSet which will contain the validators that we need for the field. We then do a simple check to see if it is a required (mandatory) field and if it is we add the standard SharePoing “RequiredValidator” to our ValidatorSet.
Then we add our own new “MyCustomFieldValidator” object to the validator set.
Finally we have two register methods. The first one registerValidationErrorCallback is basically telling SharePoint that if our field fails validation that it should call the mjh.onError method to deal will letting the user know what has gone wrong.
The second one registerClientValidator actually registers our validators with SharePoint for the chosen field.
Note – it is perfectly possible to register your client validator without providing a validation error callback. If you do this then the validator will stop the form from being saved but the user won’t be told why (they’ll just get a frustrating form which won’t post back).
So ..  assuming all of the above has worked correctly you would see something like this if you tried to selected “Item 2″:
Validation message being shown in SharePoint
So that should be what you need to start putting together your own custom validation. You can of course use this technique on any number of fields.
For the complete code-sample to date (including Parts 2 and 3) please download the Visual Studio solution here: