Sunday, January 31, 2016

AngularJS : Create a web site using Angular JS, ASP.net MVC, web api - PART 3 : Coding Server side


PLAN

Introduction

now we will define our  services which acts as intermediary between Client and DataBase.

Using the code

I) Exchange between client and server

the different requests that can be sent from client to server, can be described as follow :
1) userExist : verify if  login and password passed as parameters belong an existing user in EC_User table or not.



  • Input parameters : 


loginUser : is a string data that contains the user name.
mp : is a string data that contains password.

  • Output parameters :
status : is boolean data that return true if user exists, else false.
2) disconnect : kill the current session.
3) insertUser : add a new user into EC_User table.

  • Input parameters : 
loginUser : is a string data that contains the user name.
mp : is a string data that contains password.

  • Output parameters :
status : is a boolean data, return true if the insertion operation is successfully done, else will return false.

4) ProductsList : get a list of available product from EC_Product table.
  • Input parameters :  void.
  • Output parameters :  return list of available product.  
5) deleteProduct : delete a specific product from EC_Product table.
  • Input parameters :
id : is an integer data that refer to product identifier.
  • Output parameters : void
6) updateProduct : update the details of a specific product .
  • Input parameters :
id :  is an integer data that refers to product identifier.
  • Output parameters :
status :  return true, if the update operation is successfully done, else will return false.

7) insertProduct : insert a new row into EC_Product table.
  • Input parameters :
Productfile : is a binary image file, which contains the product image file.
ProductName : is a string data, which contains the product name.
ProductDescription : is a string data, which contains the product description.
ProductPrice : is an integer data, that contains the unit price of a new product.
  • Output parameters :
status :  return true, if the insertion operation is successfully done, else will return false.

8) updateCommand : update status of specific command.
  • Input parameters :
commandId : is an integer data, that refers to the identifier of current command.
commandStatus : is a string data, that contains the new state of current command.
  • Output parameters :
status :  return true if the updating operation is successfully done, else will return false.

9) CommandsList : get a list of command from EC_Command table, related to a connected user.
  • Input parameters :
loginUser : is the user name, that used to filter commands before sending them to client side.
  • Output parameters :
list : is a list of commands related to the logged user. if loginUser variable is empty all commands will be returned.

10) insertCommand : add user transaction to EC_Command table. the initial state of command is always 'Received'
  • Input parameters :
shoppingCart : is a list of couple ProductIdentifier-productCout tuple.
  • Output parameters :
status :  return true, if the insertion operation is successfully done, else will return false.

II) Implementation of Services

1) Configuration :
First we must add web Api class to our ASP.net Project, so we must follow these steps :



 
 

 
 

 
 
 
2) Code c# :
  • userExist :

 string res = "false";  
       try  
       {  
         //get current Http Request  
         HttpRequest request = HttpContext.Current.Request;  
         //get parameters seneded by client  
         var loginUser = request.Params["loginUser"];  
         var mp = request.Params["mp"];  
         //fetch into EC_User table, if that exists user that have  
         //the same loginUser and password  
         var _user = dataContext.EC_User.Where(x => x.loginUser ==  
         loginUser && x.mpUser == mp).First();  
         if (_user != null) {  
           //create a new session by saving current user login into session variable  
           if (System.Web.HttpContext.Current.Session["login"] == null)  
           {  
             System.Web.HttpContext.Current.Session["login"] =  
             loginUser.ToString();  
           }  
           return _user.C_Type;  
         }  
       }  
       catch (Exception e)  
       {  
         ;  
       }  
       return res;  
   }  

  • disconnect :

 [HttpGet]  
    public void disconnect()  
    {  
      //destroy session  
      System.Web.HttpContext.Current.Session["login"] = null;  
    }  

  • insertUser :

 [HttpGet]  
    public Boolean insertUser()  
    {  
      Boolean res = true;  
      try  
      {  
        //get current Http Request  
        HttpRequest request = HttpContext.Current.Request;  
        //get parameters seneded by client  
        var loginUser = request.Params["loginUser"];  
        var mpUser = request.Params["mpUser"];  
        //As default the new member is simple user of application  
        var _Type = "U";  
        //save a new user into EC_User table  
        var _user = new Models.EC_User();  
        _user.loginUser = loginUser;  
        _user.mpUser = mpUser;  
        _user.C_Type = _Type;  
        dataContext.EC_User.Add(_user);  
        dataContext.SaveChanges();  
      }  
      catch (Exception e)  
      {  
        res = false;  
      }  
      return res;  
    }  

  • ProductsList :

 [HttpGet]  
  public IEnumerable<ProducTRecord> ProductsList()  
  {  
    //get all available product in EC_Product table  
    var list = dataContext.EC_Product.Select(t => new ProducTRecord { idProduct = t.idProduct, imageProduct = t.imageProduct, descriptionProduct = t.descriptionProduct, nameProduct = t.nameProduct, price = t.price })  
      .ToList();  
    return list;  
  }  

  • deleteProduct :

 [HttpGet]  
    public Boolean deleteProduct()  
    {  
      //http://localhost:56034/api/Services/deleteProduct/?id=1  
      Boolean res = true;  
      try  
      {  
        //get current Http Request  
        HttpRequest request = HttpContext.Current.Request;  
        //get parameters seneded by client  
        int id = int.Parse(request.Params["id"]);  
        //delete a specific product identified by idProduct from EC_Product table  
        var product = new WebApplication1.Models.EC_Product { idProduct = id };  
        dataContext.EC_Product.Attach(product);  
        dataContext.EC_Product.Remove(product);  
        dataContext.SaveChanges();  
      }  
      catch (Exception e)  
      {  
        res = false;  
      }  
      return res;  
    }  

  • updateProduct :

 [HttpPost]  
     public Boolean updateProduct()  
     {  
       Boolean res = true;  
       try  
       {  
         //get current Http Request  
         HttpRequest request = HttpContext.Current.Request;  
         //get parameters seneded by client  
         HttpPostedFile Productfile = (request.Files.Count > 0) ? request.Files[0] : null;  
         var productKey = int.Parse(request.Params["productKey"]);  
         var ProductName = request.Params["ProductName"];  
         var ProductDescription = request.Params["ProductDescription"];  
         int ProductPrice = int.Parse(request.Params["ProductPrice"]);  
         //find specific product by using productKey as identifier for search  
         var product = dataContext.EC_Product.Where( x => x.idProduct == productKey ).First();  
         if (product != null)  
         {  
           product.nameProduct = ProductName;  
           product.descriptionProduct = ProductDescription;  
           product.price = ProductPrice;  
           //saving product image  
           if (Productfile != null )  
           {  
             var imageServerPath = HttpContext.Current.Server.MapPath("~/Content/Images");  
             //creating a unique name  
             imageServerPath = System.IO.Path.Combine(imageServerPath, System.IO.Path.GetRandomFileName().Replace('.', ' ') + System.IO.Path.GetExtension(Productfile.FileName));  
             Productfile.SaveAs(imageServerPath);  
             try  
             {  
               if (product.imageProduct != null) {  
                 var filePath = HttpContext.Current.Server.MapPath("~/Content/Images");  
                 var imagePath = System.IO.Path.Combine(filePath, product.imageProduct);  
                 System.IO.File.Delete(imagePath);  
               }  
             }  
             catch (Exception e)  
             {  
               ;  
             }  
             product.imageProduct = System.IO.Path.GetFileName(imageServerPath);  
           }  
           dataContext.SaveChanges();  
         }  
       }  
       catch (Exception e)  
       {  
         res = false;  
       }  
       return res;  
     }  

  • insertProduct :

 [HttpPost]  
     public Boolean insertProduct()  
     {  
       Boolean res = true;  
       try  
       {  
         //get current Http Request  
         HttpRequest request = HttpContext.Current.Request;  
         //get parameters seneded by client  
         HttpPostedFile Productfile = (request.Files.Count > 0) ? request.Files[0] : null;  
         var ProductName = request.Params["ProductName"];  
         var ProductDescription = request.Params["ProductDescription"];  
         int ProductPrice = int.Parse(request.Params["ProductPrice"]);  
         //build our delete query  
         var product = new WebApplication1.Models.EC_Product();  
         //ajout d'image.  
         product.nameProduct = ProductName;  
         product.descriptionProduct = ProductDescription;  
         product.price = ProductPrice;  
         //saving a new image product  
         if (Productfile != null)  
         {  
           var imageServerPath = HttpContext.Current.Server.MapPath("~/Content/Images");  
           imageServerPath = System.IO.Path.Combine(imageServerPath, System.IO.Path.GetRandomFileName().Replace('.', ' ') + System.IO.Path.GetExtension(Productfile.FileName));  
           Productfile.SaveAs(imageServerPath);  
           product.imageProduct = System.IO.Path.GetFileName(imageServerPath);  
         }  
         dataContext.EC_Product.Add(product);  
         dataContext.SaveChanges();  
       }  
       catch (Exception e)  
       {  
         res = false;  
       }  
       return res;  
     }  

  • updateCommand :

 [HttpGet]  
     public Boolean updateCommand()  
     {  
       Boolean res = true;  
       try  
       {  
         //get current Http Request  
         HttpRequest request = HttpContext.Current.Request;  
         //get parameters seneded by client  
         var commandId = int.Parse(request.Params["commandId"]);  
         var status = request.Params["status"];  
         //find a command by using unique identifier (commandID)  
         var command = dataContext.EC_Command.Where(x=> x.C_id == commandId ).First();  
         command.C_status = status;  
         dataContext.SaveChanges();  
       }  
       catch (Exception e)  
       {  
         res = false;  
       }  
       return res;  
     }  

  • CommandsList :

 [HttpGet]  
    public IEnumerable<CommandRecord> CommandsList()  
    {  
      IEnumerable<CommandRecord> List = null;  
      try  
      {  
        //get current Http Request  
        HttpRequest request = HttpContext.Current.Request;  
        //get parameters seneded by client  
        var login = request.Params["loginUser"];  
        if (login != null && login != "")  
        {  
          //get current loginUser from login session variable  
          login = System.Web.HttpContext.Current.Session["login"].ToString();  
          //return the list of commands sent by current user  
          List = dataContext.EC_Command.Where(x => x.loginUser == login).Select(x => new CommandRecord { CommandId = x.C_id, loginUser = x.loginUser, CMDDate = x.CommandDate, ProductName = x.EC_Product.nameProduct, Status = x.C_status }).ToList().AsEnumerable();  
        }  
        else  
        {  
          List = dataContext.EC_Command.Select(x => new CommandRecord { CommandId = x.C_id, CMDDate = x.CommandDate, loginUser = x.loginUser, ProductName = x.EC_Product.nameProduct, Status = x.C_status }).ToList();  
        }  
      }  
      catch (Exception e)  
      {  
        ;  
       }  
      return List;  
    }  

  • insertCommand :

 [HttpGet]  
    public Boolean insertCommand()  
    {  
      Boolean res = true;  
      try  
      {  
        //get current Http Request  
        HttpRequest request = HttpContext.Current.Request;  
        //var status = '0';//int.Parse(request.Params["statu"]);  
        dynamic shoppingcart =  
        JsonConvert.DeserializeObject(request.Params["shoppingcart"]);  
        //save all command into EC_Command  
        foreach (var elem in shoppingcart)  
        {  
          var command = new Models.EC_Command();  
          command.loginUser =  
          System.Web.HttpContext.Current.Session["login"].ToString();  
          command.idProduct = int.Parse(elem.Name);  
          command.C_status = "Received";  
          command.CommandDate = DateTime.Now;  
          // command.C_status = status;  
          dataContext.EC_Command.Add(command);  
          dataContext.SaveChanges();  
        }  
      }  
      catch (Exception e)  
      {  
        res = false;  
      }  
      return res;  
    }  

Conclusion

Now we finished the implmentation of Server side by definining our dataBase and Restful services.
Next we will start the coding of Client side.

No comments:

Post a Comment