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.
Using Angular.js in Visual Studio LightSwitch Part 1
Using Angular.js in Visual Studio LightSwitch Part 2
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. namespace LightSwitchApplication.Model
  6. {
  7. public class AngularProduct
  8. {
  9. public int Id { get; set; }
  10. public string ProductName { get; set; }
  11. public string ProductManufacturer { get; set; }
  12. public string Manfacturerdate { get; set; }
  13. }
  14. }
  • 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. return ProductSet.AsEnumerable();
  28. }
  29. }
  30. // GET api/AngularProduct/
  31. public AngularProduct GetProduct(int id) // get one Product
  32. {
  33. using (var serverContext = GetServerContext())
  34. {
  35. var objAngularProduct = (from objProduct in serverContext.DataWorkspace
  36. .ApplicationData.Store.GetQuery().Execute()
  37. where objProduct.Id == id
  38. select new AngularProduct
  39. {
  40. Id = objProduct.Id,
  41. ProductName = objProduct.ProductName,
  42. ProductManufacturer = objProduct.ProductManufacturer,
  43. Manfacturerdate = objProduct.ManfacturerDate.ToShortDateString()
  44. }).FirstOrDefault();
  45. return objAngularProduct;
  46. }
  47. }
  48. // PUT api/AngularProduct/
  49. public HttpResponseMessage PutProduct(int id, AngularProduct product) // An Update
  50. {
  51. if (!ModelState.IsValid)
  52. {
  53. return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
  54. }
  55. try
  56. {
  57. using (var serverContext = GetServerContext())
  58. {
  59. var objLightSwitchProduct = (from LightSwitchProduct in serverContext.DataWorkspace
  60. .ApplicationData.Store.GetQuery().Execute()
  61. where LightSwitchProduct.Id == product.Id
  62. select LightSwitchProduct).FirstOrDefault();
  63. if (objLightSwitchProduct == null)
  64. {
  65. return Request.CreateErrorResponse(HttpStatusCode.NotFound, "not found");
  66. }
  67. else
  68. {
  69. objLightSwitchProduct.ProductName = product.ProductName;
  70. objLightSwitchProduct.ProductManufacturer = product.ProductManufacturer;
  71. objLightSwitchProduct.ManfacturerDate = Convert.ToDateTime(product.Manfacturerdate);
  72. serverContext.DataWorkspace.ApplicationData.SaveChanges();
  73. }
  74. }
  75. return Request.CreateResponse(HttpStatusCode.OK);
  76. }
  77. catch (Exception ex)
  78. {
  79. // Throw the exception so it will be caught by 'notificationFactory'
  80. throw new Exception(GetLightSwitchError(ex));
  81. }
  82. }
  83. // POST api/AngularProduct
  84. public HttpResponseMessage PostProduct(AngularProduct product) // An Insert
  85. {
  86. if (ModelState.IsValid)
  87. {
  88. using (var serverContext = GetServerContext())
  89. {
  90. try
  91. {
  92. var objLightSwitchProduct = serverContext.DataWorkspace
  93. .ApplicationData.Store.AddNew();
  94. objLightSwitchProduct.ProductName = product.ProductName;
  95. objLightSwitchProduct.ProductManufacturer = product.ProductManufacturer;
  96. objLightSwitchProduct.ManfacturerDate = Convert.ToDateTime(product.Manfacturerdate);
  97. serverContext.DataWorkspace.ApplicationData.SaveChanges();
  98. // Set the Id so it can be returned
  99. product.Id = objLightSwitchProduct.Id;
  100. HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, product);
  101. response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = product.Id }));
  102. return response;
  103. }
  104. catch (Exception ex)
  105. {
  106. // Throw the exception so it will be caught by 'notificationFactory'
  107. throw new Exception(GetLightSwitchError(ex));
  108. }
  109. }
  110. }
  111. else
  112. {
  113. return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
  114. }
  115. }
  116. // DELETE api/AngularProduct/5
  117. public HttpResponseMessage DeleteProduct(int id) // Delete Product
  118. {
  119. AngularProduct objProduct = GetProduct(id);
  120. if (objProduct == null)
  121. {
  122. return Request.CreateResponse(HttpStatusCode.NotFound);
  123. }
  124. using (var serverContext = ServerApplicationContext.CreateContext())
  125. {
  126. try
  127. {
  128. var objLightSwitchProduct = (from LightSwitchProduct in serverContext.DataWorkspace
  129. .ApplicationData.Store.GetQuery().Execute()
  130. where LightSwitchProduct.Id == id
  131. select LightSwitchProduct).FirstOrDefault();
  132. if (objLightSwitchProduct == null)
  133. {
  134. return Request.CreateResponse(HttpStatusCode.NotFound);
  135. }
  136. else
  137. {
  138. objLightSwitchProduct.Delete();
  139. serverContext.DataWorkspace.ApplicationData.SaveChanges();
  140. return Request.CreateResponse(HttpStatusCode.OK, objProduct);
  141. }
  142. }
  143. catch (Exception ex)
  144. {
  145. // Throw the exception so it will be caught by 'notificationFactory'
  146. throw new Exception(GetLightSwitchError(ex));
  147. }
  148. }
  149. }
  150. // Utility
  151. private static ServerApplicationContext GetServerContext()
  152. {
  153. ServerApplicationContext serverContext =
  154. (LightSwitchApplication.ServerApplicationContext)ServerApplicationContext.Current;
  155. if (serverContext == null)
  156. {
  157. serverContext =
  158. (LightSwitchApplication.ServerApplicationContext)ServerApplicationContext.CreateContext();
  159. }
  160. return serverContext;
  161. }
  162. private string GetLightSwitchError(Exception ex)
  163. {
  164. string strError = "";
  165. Microsoft.LightSwitch.ValidationException ValidationErrors =
  166. ex as Microsoft.LightSwitch.ValidationException;
  167. if (ValidationErrors != null)
  168. {
  169. StringBuilder sbErrorMessage = new StringBuilder();
  170. foreach (var error in ValidationErrors.ValidationResults)
  171. {
  172. sbErrorMessage.Append(string.Format("<p>{0}</p>", error.Message));
  173. }
  174. strError = sbErrorMessage.ToString();
  175. }
  176. else
  177. {
  178. if (ex.InnerException != null)
  179. {
  180. strError = ex.InnerException.InnerException.Message;
  181. }
  182. else
  183. {
  184. // This is a simple error -- just show Message
  185. strError = ex.Message;
  186. }
  187. }
  188. return strError;
  189. }
  190. }
  191. }
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.