Using Angular.js in Visual Studio LightSwitch Part 4

Rama Sagar
Posted by in LightSwitch category on for Beginner level | Points: 250 | Views : 2252 red flag

AngularJS is a JavaScript framework that embraces extending HTML into a more expressive and readable format.
It decreases emphasis on directly handling DOM manipulation from the application logic, allowing for easier
testing. It employs efficient two-way data binding and sensible MVC implementation, reducing the server load
of applications. It features directives, which are incredibly robust tools that are significant contributors
to Angular’s ubiquity.

Introduction


In this article we will see creation of model,and controller............

Please check previous articles on Light switch by visiting following links.


Using Angular.js in Visual studio Light switch Part1
Using Angular.js in Visual studio Light switch Part2


Objective


The  objective of the article is to explain how to use Angular.js in Lightswitch Applications.


  • 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





          

AngularProduct.cs


Add the following properties to the class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace LightSwitchApplication.Model
{
    public class AngularProduct
    {

        public int Id { get; set; }
        public string ProductName { get; set; }
        public string ProductManufacturer { get; set; }
        public string Manfacturerdate { get; set; }
       
    }
}

  • Step 2: Create WebAPI2 Controller class as shown below

   






Name the controller AngularProductController and add the following Implementation:

Here we have used the following methods

GetStore() : Which gets all the Products from the store 

GetProduct: will get the single product based on id

PutProduct: will update the product

PostProduct :which inserts new product

DeleteProduct: which deletes the product

The ServerApplicationContext API is a new feature in LightSwitch, available with Visual Studio 2012 Update 2 or later, which allows you to create entirely new ways to call custom business logic on the LightSwitch Server.


using LightSwitchApplication.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
namespace LightSwitchApplication.Controllers
{
    public class AngularPersonController : ApiController
    {
        // GET api/AngularProduct
        public IEnumerable<AngularProduct> GetStore() // Get All Products
        {
            using (var serverContext = GetServerContext())
            {
                var ProductSet = from objProduct in serverContext.DataWorkspace
                                    .ApplicationData.Store.GetQuery().Execute()
                                select new AngularProduct
                                {
                                    Id = objProduct.Id,
                                    ProductName = objProduct.ProductName,
                                    ProductManufacturer = objProduct.ProductManufacturer,
                                    Manfacturerdate=objProduct.ManfacturerDate.ToShortDateString()
                                    
                                };
                return ProductSet.AsEnumerable();
            }
        }
        // GET api/AngularProduct/
        public AngularProduct GetProduct(int id) // get one Product
        {
            using (var serverContext = GetServerContext())
            {
                var objAngularProduct = (from objProduct in serverContext.DataWorkspace
                                            .ApplicationData.Store.GetQuery().Execute()
                                         where objProduct.Id == id
                                        select new AngularProduct
                                        {
                                            Id = objProduct.Id,
                                            ProductName = objProduct.ProductName,
                                            ProductManufacturer = objProduct.ProductManufacturer,
                                            Manfacturerdate = objProduct.ManfacturerDate.ToShortDateString()
                                        }).FirstOrDefault();
                return objAngularProduct;
            }
        }
        // PUT api/AngularProduct/
        public HttpResponseMessage PutProduct(int id, AngularProduct product) // An Update
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            try
            {
                using (var serverContext = GetServerContext())
                {
                    var objLightSwitchProduct = (from LightSwitchProduct in serverContext.DataWorkspace
                                                    .ApplicationData.Store.GetQuery().Execute()
                                                 where LightSwitchProduct.Id == product.Id
                                                 select LightSwitchProduct).FirstOrDefault();
                    if (objLightSwitchProduct == null)
                    {
                        return Request.CreateErrorResponse(HttpStatusCode.NotFound, "not found");
                    }
                    else
                    {
                        objLightSwitchProduct.ProductName = product.ProductName;
                        objLightSwitchProduct.ProductManufacturer = product.ProductManufacturer;
                        objLightSwitchProduct.ManfacturerDate = Convert.ToDateTime(product.Manfacturerdate);
                        serverContext.DataWorkspace.ApplicationData.SaveChanges();
                    }
                }
                return Request.CreateResponse(HttpStatusCode.OK);
            }
            catch (Exception ex)
            {
                // Throw the exception so it will be caught by 'notificationFactory'
                throw new Exception(GetLightSwitchError(ex));
            }
        }
        // POST api/AngularProduct
        public HttpResponseMessage PostProduct(AngularProduct product) // An Insert
        {
            if (ModelState.IsValid)
            {
                using (var serverContext = GetServerContext())
                {
                    try
                    {
                        var objLightSwitchProduct = serverContext.DataWorkspace
                            .ApplicationData.Store.AddNew();
                        objLightSwitchProduct.ProductName = product.ProductName;
                        objLightSwitchProduct.ProductManufacturer = product.ProductManufacturer;
                        objLightSwitchProduct.ManfacturerDate = Convert.ToDateTime(product.Manfacturerdate);
                        serverContext.DataWorkspace.ApplicationData.SaveChanges();
                        // Set the Id so it can be returned
                        product.Id = objLightSwitchProduct.Id;
                        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, product);
                        response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = product.Id }));
                        return response;
                    }
                    catch (Exception ex)
                    {
                        // Throw the exception so it will be caught by 'notificationFactory'
                        throw new Exception(GetLightSwitchError(ex));
                    }
                }
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }
        // DELETE api/AngularProduct/5
        public HttpResponseMessage DeleteProduct(int id) // Delete Product
        {
            AngularProduct objProduct = GetProduct(id);
            if (objProduct == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }
            using (var serverContext = ServerApplicationContext.CreateContext())
            {
                try
                {
                    var objLightSwitchProduct = (from LightSwitchProduct in serverContext.DataWorkspace
                                                    .ApplicationData.Store.GetQuery().Execute()
                                                 where LightSwitchProduct.Id == id
                                                 select LightSwitchProduct).FirstOrDefault();
                    if (objLightSwitchProduct == null)
                    {
                        return Request.CreateResponse(HttpStatusCode.NotFound);
                    }
                    else
                    {
                        objLightSwitchProduct.Delete();
                        serverContext.DataWorkspace.ApplicationData.SaveChanges();
                        return Request.CreateResponse(HttpStatusCode.OK, objProduct);
                    }
                }
                catch (Exception ex)
                {
                    // Throw the exception so it will be caught by 'notificationFactory'
                    throw new Exception(GetLightSwitchError(ex));
                }
            }
        }
        // Utility
        private static ServerApplicationContext GetServerContext()
        {
            ServerApplicationContext serverContext =
                (LightSwitchApplication.ServerApplicationContext)ServerApplicationContext.Current;
            if (serverContext == null)
            {
                serverContext =
                    (LightSwitchApplication.ServerApplicationContext)ServerApplicationContext.CreateContext();
            }
            return serverContext;
        }
        private string GetLightSwitchError(Exception ex)
        {
            string strError = "";
            Microsoft.LightSwitch.ValidationException ValidationErrors =
                    ex as Microsoft.LightSwitch.ValidationException;
            if (ValidationErrors != null)
            {
                StringBuilder sbErrorMessage = new StringBuilder();
                foreach (var error in ValidationErrors.ValidationResults)
                {
                    sbErrorMessage.Append(string.Format("<p>{0}</p>", error.Message));
                }
                strError = sbErrorMessage.ToString();
            }
            else
            {
                if (ex.InnerException != null)
                {
                    strError = ex.InnerException.InnerException.Message;
                }
                else
                {
                    // This is a simple error -- just show Message
                    strError = ex.Message;
                }
            }
            return strError;
        }
    }
}


Conclusion

In this article we have seen the CRUD operations in WEB API controller in Light switch...In next part we will see how to add the angular grid control and perform the CRUD operations

Reference

http://angularjs.org/
http://msdn.microsoft.com/en-us/library/ff852065.aspx


Page copy protected against web site content infringement by Copyscape

About the Author

Rama Sagar
Full Name: RamaSagar Pulidindi
Member Level: Silver
Member Status: Member,MVP
Member Since: 12/30/2012 1:51:40 AM
Country: India
ramasagar
http://www.ramasagar.com
A Software Profesional working in Microsoft .NET technologies since year 2008, and I work for Dake ACE. I am passionate about .NET technology and love to contribute to the .NET community at Dot Net Funda

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)