In Focus

Using Angular.js in Visual Studio LightSwitch : Part 3

In this article we will see how to use Angular.js in a LightSwitch application.

Introduction
 
In this article we will see how to use Angular.js in a LightSwitch application. Please check the previous articles on LightSwitch by visiting the following links.
 
 
Please have a look at the previus articles since this is the continuation of them.
  • Step 1: Right-click on the Server project and select Add then New Folder. Name the folder Model and then add a class named AngularProduct.cs to it as shown below.

 Server project and select Add then New Folder
 
 Add the following properties to the class:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace LightSwitchApplication.Model  
  7. {  
  8.     public class AngularProduct  
  9.     {  
  10.   
  11.         public int Id { getset; }  
  12.         public string ProductName { getset; }  
  13.         public string ProductManufacturer { getset; }  
  14.         public string Manfacturerdate { getset; }  
  15.          
  16.     }  
  17. }  
  • Step 2: Create WebAPI2 Controller class as shown below:
Create WebAPI2 Controller class
 
Name 
 
Name the controller AngularProductController and add the following Implementation.
 
Here we have used the following methods:
  • GetStore(): gets all the Products from the store.
  • GetProduct: gets the single product based on id.
  • PutProduct: updates the product.
  • PostProduct: inserts a new product.
  • DeleteProduct: deletes the product.
The ServerApplicationContext API is a new feature in LightSwitch, available with Visual Studio 2012 Update 2 or later, that allows you to create entirely new ways to call custom business logic on the LightSwitch Server.
  1. using LightSwitchApplication.Model;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Net;  
  6. using System.Net.Http;  
  7. using System.Text;  
  8. using System.Web.Http;  
  9. namespace LightSwitchApplication.Controllers  
  10. {  
  11.     public class AngularPersonController : ApiController  
  12.     {  
  13.         // GET api/AngularProduct  
  14.         public IEnumerable<AngularProduct> GetStore() // Get All Products  
  15.         {  
  16.             using (var serverContext = GetServerContext())  
  17.             {  
  18.                 var ProductSet = from objProduct in serverContext.DataWorkspace  
  19.                                     .ApplicationData.Store.GetQuery().Execute()  
  20.                                 select new AngularProduct  
  21.                                 {  
  22.                                     Id = objProduct.Id,  
  23.                                     ProductName = objProduct.ProductName,  
  24.                                     ProductManufacturer = objProduct.ProductManufacturer,  
  25.                                     Manfacturerdate=objProduct.ManfacturerDate.ToShortDateString()  
  26.                                       
  27.                                 };  
  28.                 return ProductSet.AsEnumerable();  
  29.             }  
  30.         }  
  31.         // GET api/AngularProduct/  
  32.         public AngularProduct GetProduct(int id) // get one Product  
  33.         {  
  34.             using (var serverContext = GetServerContext())  
  35.             {  
  36.                 var objAngularProduct = (from objProduct in serverContext.DataWorkspace  
  37.                                             .ApplicationData.Store.GetQuery().Execute()  
  38.                                          where objProduct.Id == id  
  39.                                         select new AngularProduct  
  40.                                         {  
  41.                                             Id = objProduct.Id,  
  42.                                             ProductName = objProduct.ProductName,  
  43.                                             ProductManufacturer = objProduct.ProductManufacturer,  
  44.                                             Manfacturerdate = objProduct.ManfacturerDate.ToShortDateString()  
  45.                                         }).FirstOrDefault();  
  46.                 return objAngularProduct;  
  47.             }  
  48.         }  
  49.         // PUT api/AngularProduct/  
  50.         public HttpResponseMessage PutProduct(int id, AngularProduct product) // An Update  
  51.         {  
  52.             if (!ModelState.IsValid)  
  53.             {  
  54.                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);  
  55.             }  
  56.             try  
  57.             {  
  58.                 using (var serverContext = GetServerContext())  
  59.                 {  
  60.                     var objLightSwitchProduct = (from LightSwitchProduct in serverContext.DataWorkspace  
  61.                                                     .ApplicationData.Store.GetQuery().Execute()  
  62.                                                  where LightSwitchProduct.Id == product.Id  
  63.                                                  select LightSwitchProduct).FirstOrDefault();  
  64.                     if (objLightSwitchProduct == null)  
  65.                     {  
  66.                         return Request.CreateErrorResponse(HttpStatusCode.NotFound, "not found");  
  67.                     }  
  68.                     else  
  69.                     {  
  70.                         objLightSwitchProduct.ProductName = product.ProductName;  
  71.                         objLightSwitchProduct.ProductManufacturer = product.ProductManufacturer;  
  72.                         objLightSwitchProduct.ManfacturerDate = Convert.ToDateTime(product.Manfacturerdate);  
  73.                         serverContext.DataWorkspace.ApplicationData.SaveChanges();  
  74.                     }  
  75.                 }  
  76.                 return Request.CreateResponse(HttpStatusCode.OK);  
  77.             }  
  78.             catch (Exception ex)  
  79.             {  
  80.                 // Throw the exception so it will be caught by 'notificationFactory'  
  81.                 throw new Exception(GetLightSwitchError(ex));  
  82.             }  
  83.         }  
  84.         // POST api/AngularProduct  
  85.         public HttpResponseMessage PostProduct(AngularProduct product) // An Insert  
  86.         {  
  87.             if (ModelState.IsValid)  
  88.             {  
  89.                 using (var serverContext = GetServerContext())  
  90.                 {  
  91.                     try  
  92.                     {  
  93.                         var objLightSwitchProduct = serverContext.DataWorkspace  
  94.                             .ApplicationData.Store.AddNew();  
  95.                         objLightSwitchProduct.ProductName = product.ProductName;  
  96.                         objLightSwitchProduct.ProductManufacturer = product.ProductManufacturer;  
  97.                         objLightSwitchProduct.ManfacturerDate = Convert.ToDateTime(product.Manfacturerdate);  
  98.                         serverContext.DataWorkspace.ApplicationData.SaveChanges();  
  99.                         // Set the Id so it can be returned  
  100.                         product.Id = objLightSwitchProduct.Id;  
  101.                         HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, product);  
  102.                         response.Headers.Location = new Uri(Url.Link("DefaultApi"new { id = product.Id }));  
  103.                         return response;  
  104.                     }  
  105.                     catch (Exception ex)  
  106.                     {  
  107.                         // Throw the exception so it will be caught by 'notificationFactory'  
  108.                         throw new Exception(GetLightSwitchError(ex));  
  109.                     }  
  110.                 }  
  111.             }  
  112.             else  
  113.             {  
  114.                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);  
  115.             }  
  116.         }  
  117.         // DELETE api/AngularProduct/5  
  118.         public HttpResponseMessage DeleteProduct(int id) // Delete Product  
  119.         {  
  120.             AngularProduct objProduct = GetProduct(id);  
  121.             if (objProduct == null)  
  122.             {  
  123.                 return Request.CreateResponse(HttpStatusCode.NotFound);  
  124.             }  
  125.             using (var serverContext = ServerApplicationContext.CreateContext())  
  126.             {  
  127.                 try  
  128.                 {  
  129.                     var objLightSwitchProduct = (from LightSwitchProduct in serverContext.DataWorkspace  
  130.                                                     .ApplicationData.Store.GetQuery().Execute()  
  131.                                                  where LightSwitchProduct.Id == id  
  132.                                                  select LightSwitchProduct).FirstOrDefault();  
  133.                     if (objLightSwitchProduct == null)  
  134.                     {  
  135.                         return Request.CreateResponse(HttpStatusCode.NotFound);  
  136.                     }  
  137.                     else  
  138.                     {  
  139.                         objLightSwitchProduct.Delete();  
  140.                         serverContext.DataWorkspace.ApplicationData.SaveChanges();  
  141.                         return Request.CreateResponse(HttpStatusCode.OK, objProduct);  
  142.                     }  
  143.                 }  
  144.                 catch (Exception ex)  
  145.                 {  
  146.                     // Throw the exception so it will be caught by 'notificationFactory'  
  147.                     throw new Exception(GetLightSwitchError(ex));  
  148.                 }  
  149.             }  
  150.         }  
  151.         // Utility  
  152.         private static ServerApplicationContext GetServerContext()  
  153.         {  
  154.             ServerApplicationContext serverContext =  
  155.                 (LightSwitchApplication.ServerApplicationContext)ServerApplicationContext.Current;  
  156.             if (serverContext == null)  
  157.             {  
  158.                 serverContext =  
  159.                     (LightSwitchApplication.ServerApplicationContext)ServerApplicationContext.CreateContext();  
  160.             }  
  161.             return serverContext;  
  162.         }  
  163.         private string GetLightSwitchError(Exception ex)  
  164.         {  
  165.             string strError = "";  
  166.             Microsoft.LightSwitch.ValidationException ValidationErrors =  
  167.                     ex as Microsoft.LightSwitch.ValidationException;  
  168.             if (ValidationErrors != null)  
  169.             {  
  170.                 StringBuilder sbErrorMessage = new StringBuilder();  
  171.                 foreach (var error in ValidationErrors.ValidationResults)  
  172.                 {  
  173.                     sbErrorMessage.Append(string.Format("<p>{0}</p>", error.Message));  
  174.                 }  
  175.                 strError = sbErrorMessage.ToString();  
  176.             }  
  177.             else  
  178.             {  
  179.                 if (ex.InnerException != null)  
  180.                 {  
  181.                     strError = ex.InnerException.InnerException.Message;  
  182.                 }  
  183.                 else  
  184.                 {  
  185.                     // This is a simple error -- just show Message  
  186.                     strError = ex.Message;  
  187.                 }  
  188.             }  
  189.             return strError;  
  190.         }  
  191.     }  
  192. }  
Step 3: Now let's add the Angular Grid control.

 
Insert the folders and files into the Scripts folder as shown below.

Note, we need to create the folders and import each file into each folder one by one using Add, then Existing Item.
 
 folder
 
Angular Grid Control

Replace the contents of Index.cshtml (in the Views/Home folder) with the following:
  1. <!doctype html>  
  2. <html ng-app="app">  
  3. <head>  
  4.     <title>AngularJS-WebApi-EF</title>  
  5.     @Styles.Render("~/content/bootstrap/base")  
  6.     @Styles.Render("~/content/toastr")  
  7.     @Styles.Render("~/content/css")  
  8.     @Styles.Render("~/content/angular")  
  9. </head>  
  10. <body>  
  11.     <h1>Products</h1>  
  12.     <div crud-grid table='AngularProduct'  
  13.          columns='[  
  14.                     {"name":"Id", "class":"col-md-1", "autoincrement": "true"},  
  15.                     {"name":"ProductName"},  
  16.                     {"name":"ProductManufacturer"},  
  17.                     {"name":"ManufacturerDate"}  
  18.             ]'></div>  
  19.     @Scripts.Render("~/bundles/jquery")  
  20.     @Scripts.Render("~/bundles/angular")  
  21.     @Scripts.Render("~/bundles/toastr")  
  22.     @Scripts.Render("~/bundles/bootstrap")  
  23. </body>  
  24. </html>  
Control BundleConfigcs
 
Update the file called BundleConfig.cs (in the App_Start directory) and add the following implementation:
  1. using System.Web;  
  2. using System.Web.Optimization;  
  3. namespace LightSwitchApplication  
  4. {  
  5.     public class BundleConfig  
  6.     {  
  7.         // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725  
  8.         public static void RegisterBundles(BundleCollection bundles)  
  9.         {  
  10.             bundles.Add(new ScriptBundle("~/bundles/jquery").Include(  
  11.                         "~/Scripts/jquery-{version}.js"));  
  12.             bundles.Add(new ScriptBundle("~/bundles/angular").Include(  
  13.                         "~/Scripts/angular.js""~/Scripts/angular-resource.js",  
  14.                         "~/Scripts/App/app.js",  
  15.                         "~/Scripts/App/Services/*.js",  
  16.                         "~/Scripts/App/Directives/*.js""~/Scripts/App/Directives/Services/*.js"));  
  17.             bundles.Add(new ScriptBundle("~/bundles/toastr").Include(  
  18.                         "~/Scripts/toastr.js"));  
  19.             bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(  
  20.                         "~/Scripts/jquery-ui-{version}.js"));  
  21.             bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(  
  22.                         "~/Scripts/jquery.unobtrusive*",  
  23.                         "~/Scripts/jquery.validate*"));  
  24.             // Use the development version of Modernizr to develop with and learn from. Then, when you're  
  25.             // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.  
  26.             bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(  
  27.                         "~/Scripts/modernizr-*"));  
  28.             bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));  
  29.             bundles.Add(new StyleBundle("~/Content/angular").Include("~/Scripts/App/Directives/Content/*.css"));  
  30.             bundles.Add(new StyleBundle("~/Content/toastr").Include("~/Content/toastr.css"));  
  31.             bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(  
  32.                         "~/Content/themes/base/jquery.ui.core.css",  
  33.                         "~/Content/themes/base/jquery.ui.resizable.css",  
  34.                         "~/Content/themes/base/jquery.ui.selectable.css",  
  35.                         "~/Content/themes/base/jquery.ui.accordion.css",  
  36.                         "~/Content/themes/base/jquery.ui.autocomplete.css",  
  37.                         "~/Content/themes/base/jquery.ui.button.css",  
  38.                         "~/Content/themes/base/jquery.ui.dialog.css",  
  39.                         "~/Content/themes/base/jquery.ui.slider.css",  
  40.                         "~/Content/themes/base/jquery.ui.tabs.css",  
  41.                         "~/Content/themes/base/jquery.ui.datepicker.css",  
  42.                         "~/Content/themes/base/jquery.ui.progressbar.css",  
  43.                         "~/Content/themes/base/jquery.ui.theme.css"));  
  44.         }  
  45.     }  
  46. }  
Run the application and navigate to the Home directory.
 
Note: Here I didn't define a home screen in Lightswitch.
 
You will find the following output:
 
output
Summary

In this article we learned how to use Angular.js in a Lightswitch application.