Sunday, November 9, 2014

Dynamically Loading Controllers and Views with AngularJS/$controllerProvider and RequireJS

Copyright from: weblogs.asp.net/dwahlin

A complete sample application that uses the techniques shown in this post can be found athttps://github.com/DanWahlin/CustomerManager.
AngularJS provides a simple way to associate a view with a controller and load everything at runtime using the$routeProvider object. Routing code is typically put in a module’s config() function and looks similar to the following:
$routeProvider
     .when('/customers',
        {
            controller: 'CustomersController',
            templateUrl: '/app/views/customers.html'
        })
    .when('/customerorders/:customerID',
        {
            controller: 'CustomerOrdersController',
            templateUrl: '/app/views/customerOrders.html'
        })
    .when('/orders',
        {
            controller: 'OrdersController',
            templateUrl: '/app/views/orders.html'
        })
    .otherwise({ redirectTo: '/customers' });

While this type of code works great for defining routes it requires controller scripts to be loaded upfront in the main shell page by default. That works fine in some scenarios but what if you have a lot of controller scripts and views in a given application and want to dynamically load them on-the-fly at runtime? One way of dealing with that scenario is to define a resolve property on each route and assign it a function that returns a promise. The function can handle dynamically loading the script containing the target controller and resolve the promise once the load is complete. An example of using the resolve property is shown next:

$routeProvider
    .when('/customers',
        {
            templateUrl: '/app/views/customers.html',
            resolve: resolveController('/app/controllers/customersController.js')
        });

This approach works well in cases where you don’t want all of your controller scripts loaded upfront, but it still doesn’t feel quite right – at least to me. I personally don’t like having to define two paths especially if you’ll be working with a lot of routes. If you’ve ever worked with a framework that uses convention over configuration then you’ll know that we can clean up this code by coming up with a standard convention for naming views and controllers. Coming up with a convention can help simplify routes and maintenance of the application over time. The approach that I’ll demonstrate in this post uses the following routing code to define the path, view and controller: 

$routeProvider
    .when('/customers', route.resolve('Customers'))
    .when('/customerorders/:customerID', route.resolve('CustomerOrders'))
    .when('/orders', route.resolve('Orders'))
    .otherwise({ redirectTo: '/customers' });


Notice that a single value is passed into the route.resolve() function. Behind the scenes the function will automatically create the path to the view and the path to the controller based on some simple conventions and then load the appropriate files dynamically. You can access a sample (work in progress) project athttps://github.com/DanWahlin/CustomerManager. Let’s take a look at how it works. 

Dynamically Loading Controllers

The following diagram shows the different players involved in simplifying routes and dynamically loading controllers. RequireJS is used to dynamically load controller JavaScript files and make an application’s main module available to the controllers so that they’re registered properly after they’re loaded. 
image

Here’s how it works:
  1. A file named main.js defines custom scripts that will be loaded using RequireJS. I originally defined 3rd party libraries such as AngularJS in main.js as well but decided there simply wasn’t enough benefit over loading them at the bottom of the initial page using a

Tuesday, November 4, 2014

Impersonation in ASP.NET causes [COMException (0x80072020): An operations error occurred. ]

Copyright from: sharepoint-tweaking.blogspot.com

When you run code that uses DirectorySearcher, DirectoryEntry or other classes that communicates with network resources from a webpart in a Sharepoint site, you recieve a: [COMException (0x80072020): An operations error occurred. ]
This is caused by the fact that when a user is authenticated against a sharepoint server using NTLM or Kerberos, a "secondary token" is sent to the server that it uses to authenticate the user. This token cannot be used to authenticate the current user against another server (e.g. a domain controller).
This can be circumvented by reverting the impersonation to the application pool account used by IIS (if this account has access to Active Directory) with the following code (this is equal to running with impersonation set to false in web.config):

using System.Web.Hosting;
...
...
// Code here runs as the logged on user
using (HostingEnvironment.Impersonate()) {// This code runs as the application pool user
     DirectorySearcher searcher ...
}

// Code here runs as logged on user again

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!