Thursday, May 31, 2018

AngularJS CRUD Operation Using ASP.NET MVC

File->New->Project




Click on Ok Button




Design the database as shown below:



Now, Add a new ADO.NET Data Model, From the Model Folder






Click on Add


Click on Next




Click on New Connection



Click on Test Connection. Once the test connection  is success

Click on Ok Button



Click on Next Button




Click on Next Button, Select the table Name on which you want to do CRUD Operations


Click on Finish Button



Now, we need to Add Angular Js Plugin







Click on Install Button

Once Installed you can see in the script folder


Now, we will Add a EmployeeController and Add the below code

EmployeeController:

public class EmployeeController : Controller
    {
        // GET: Employee
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// This method is used to Get the Details of the Employee
        /// </summary>
        /// <returns>JSONRESULT</returns>
        public JsonResult GetEmployeeDetails()
        {
            using (MYDBEntities Obj = new MYDBEntities())
            {
                List<EMP> Emp = Obj.EMPs.ToList();
                return Json(Emp, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// Insert an Employee
        /// </summary>
        /// <param name="Employe">emp</param>
        /// <returns>String</returns>
        [HttpPost]
        public string InsertEmployee(EMP Employe)
        {
            if (Employe != null)
            {
                using (MYDBEntities Obj = new MYDBEntities())
                {
                    Obj.EMPs.Add(Employe);
                    Obj.SaveChanges();
                    return "Employee Added Successfully";
                }
            }
            else
            {
                return "Employee Not Inserted! Try Again";
            }
        }

        /// <summary>
        /// This method is used to Delete an Employee
        /// </summary>
        /// <param name="Employe">emp</param>
        /// <returns>String</returns>
        public string DeleteEmployee(EMP emp)
        {
            if (emp != null)
            {
                using (MYDBEntities Obj = new MYDBEntities())
                {
                    var Emp_ = Obj.Entry(emp);
                    if (Emp_.State == System.Data.Entity.EntityState.Detached)
                    {
                        Obj.EMPs.Attach(emp);
                        Obj.EMPs.Remove(emp);
                    }
                    Obj.SaveChanges();
                    return "Employee Deleted Successfully";
                }
            }
            else
            {
                return "Employee Not Deleted! Try Again";
            }
        }
        public string UpdateEmployee(EMP Employe)
        {
            if (Employe != null)
            {
                using (MYDBEntities Obj = new MYDBEntities())
                {
                    var Emp_ = Obj.Entry(Employe);
                    EMP EmpObj = Obj.EMPs.Where(x => x.EMPNO == Employe.EMPNO).FirstOrDefault();
                    EmpObj.ENAME = Employe.ENAME;
                    EmpObj.JOB = Employe.JOB;
                    EmpObj.DEPTNO = Employe.DEPTNO;
                    EmpObj.MGR = Employe.MGR;
                    EmpObj.SAL = Employe.SAL;
                    Obj.SaveChanges();
                    return "Employee Updated Successfully";
                }
            }
            else
            {
                return "Employee Not Updated! Try Again";
            }
        }
    }

Javascript Code:


/// <reference path="angular.js" />

var app = angular.module("myApp", []);
app.controller("myController", function ($scope, $http) {

    $scope.InsertData = function () {
        var Action = document.getElementById("btnSave").getAttribute("value");

        if (Action == "Submit") {
            $scope.Employe = {};
            $scope.Employe.EMPNO = $scope.EmpNumber;
            $scope.Employe.ENAME = $scope.EmpName;
            $scope.Employe.JOB = $scope.EmpJob;
            $scope.Employe.MGR = $scope.EmpMgrId;
            $scope.Employe.SAL = $scope.EmpSalary;
            $scope.Employe.DEPTNO = $scope.EmpDept;
            $http({
                method: "post",
                url: "http://localhost:61289/Employee/InsertEmployee",
                datatype: 'json',
                data: JSON.stringify($scope.Employe)
            }).then(function (response) {
                alert(response.data);
                $scope.Employe.EMPNO = "";
                $scope.Employe.ENAME = "";
                $scope.Employe.JOB = "";
                $scope.Employe.MGR = "";
                $scope.Employe.SAL = "";
                $scope.Employe.DEPTNO = "";
                $scope.GetAllData();
            })
        } else {
            debugger;
            $scope.Employe = {};
            $scope.Employe.ENAME = $scope.EmpName;
            $scope.Employe.JOB = $scope.EmpJob;
            $scope.Employe.MGR = $scope.EmpMgrId;
            $scope.Employe.SAL = $scope.EmpSalary;
            $scope.Employe.DEPTNO = $scope.EmpDept;
            $scope.Employe.EMPNO = document.getElementById("EmpNumber_").value;
            $http({
                method: "post",
                url: "http://localhost:61289/Employee/UpdateEmployee",
                datatype: "json",
                data: JSON.stringify($scope.Employe)
            }).then(function (response) {
                alert(response.data);
                $scope.Employe.EMPNO = "";
                $scope.Employe.ENAME = "";
                $scope.Employe.JOB = "";
                $scope.Employe.MGR = "";
                $scope.Employe.SAL = "";
                $scope.Employe.DEPTNO = "";
                $scope.GetAllData();
                document.getElementById("btnSave").setAttribute("value", "Submit");
                document.getElementById("btnSave").style.backgroundColor = "cornflowerblue";
                document.getElementById("spn").innerHTML = "Add New Employee";
            })
        }
    }

    $scope.GetAllData = function () {
        $http({
            method: "post",
            url: "http://localhost:61289/Employee/GetEmployeeDetails"
        }).then(function (response) {
            $scope.employees = response.data;
        }, function () {
            alert("Error Occur");
        })
    };

    $scope.DeleteEmp = function (Emp) {
        $http({
            method: "post",
            url: "http://localhost:61289/Employee/DeleteEmployee",
            datatype: "json",
            data: JSON.stringify(Emp)
        }).then(function (response) {
            alert(response.data);
            $scope.GetAllData();
        })
    };

    $scope.UpdateEmp = function (Emp) {
        document.getElementById("EmpNumber_").value = Emp.EMPNO;
        $scope.EmpName = Emp.ENAME;
        $scope.EmpJob = Emp.JOB;
        $scope.EmpMgrId = Emp.MGR;
        $scope.EmpSalary = Emp.SAL;
        $scope.EmpNumber = Emp.EMPNO;
        $scope.EmpDept = Emp.DEPTNO;
        document.getElementById("btnSave").setAttribute("value", "Update");
        document.getElementById("btnSave").style.backgroundColor = "Yellow";
        document.getElementById("spn").innerHTML = "Update Employee Information";
    }

})


You may get Error in the connection String, please make sure that your connection string is Correct

<connectionStrings>
    <add name="MYDBEntities" connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string=&quot;data source=DESKTOP-HJAK1FL\SQLEXPRESS;initial catalog=MYDB;persist security info=True;user id=sa;Password=1234;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

  </connectionStrings>


Index:


@{
    ViewBag.Title = "Index";
}
<script src="~/scripts/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="~/scripts/CrudOperation.js"></script>
<style>
    .btn-space {
        margin-left: -5%;
        background-color: blue;
        font-size: large;
    }
</style>
<div ng-app="myApp">
    <div ng-controller="myController" ng-init="GetAllData()" class="divList">
        <p class="divHead">Employee Details</p>
        <table cellpadding="12" class="table table-bordered table-hover">
            <tr>
                <td>
                    <b>Employee Number</b>
                </td>
                <td>
                    <b>Emp Name</b>
                </td>
                <td>
                    <b>Job</b>
                </td>
                <td>
                    <b>Salary</b>
                </td>
                <td>
                    <b>Actions</b>
                </td>
            </tr>
            <tr ng-repeat="Emp in employees">
                <td>
                    {{Emp.EMPNO}}
                </td>
                <td>
                    {{Emp.ENAME}}
                </td>
                <td>
                    {{Emp.JOB}}
                </td>
                <td>
                    {{Emp.SAL}}
                </td>
                <td>
                    <input type="button" class="btn btn-warning" value="Update" ng-click="UpdateEmp(Emp)" />
                    <input type="button" class="btn btn-danger" value="Delete" ng-click="DeleteEmp(Emp)" />
                </td>
            </tr>
        </table>
        <div class="form-horizontal" role="form">
            <div class="container">
                <div class="row">
                    <h2>
                        <span id="spn">Add New Employee</span>
                    </h2>
                </div>
                <div class="row">
                    <div class="col-sm-6 col-lg-4">
                        <div class="form-group">
                            <label class="col-md-4 control-label">Emp Number:</label>
                            <div class="col-md-8">
                                <input type="text" class="form-control" id="inputEmpId" placeholder="Employee Number" ng-model="EmpNumber">
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 col-lg-4">
                        <div class="form-group">
                            <label class="col-md-4 control-label">Emp Name:</label>
                            <div class="col-md-8">
                                <input type="text" class="form-control" id="inputEmpName" placeholder="Employee Name" ng-model="EmpName">
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 col-lg-4">
                        <div class="form-group">
                            <label class="col-md-4 control-label">Job:</label>
                            <div class="col-md-8">
                                <input type="text" class="form-control" id="inputJob" placeholder="Employee Designation" ng-model="EmpJob">
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 col-lg-4">
                        <div class="form-group">
                            <label class="col-md-4 control-label">Manager ID:</label>
                            <div class="col-md-8">
                                <input type="text" class="form-control" id="inputMgrId" placeholder="Id of the Manager" ng-model="EmpMgrId">
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 col-lg-4">
                        <div class="form-group">
                            <label class="col-md-4 control-label">Salary :</label>
                            <div class="col-md-8">
                                <input type="text" class="form-control" id="inputSalaryId" placeholder="Salary of the Employoee" ng-model="EmpSalary">
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 col-lg-4">
                        <div class="form-group">
                            <label class="col-md-4 control-label">Dept Number :</label>
                            <div class="col-md-8">
                                <input type="text" class="form-control" id="inputDeptId" placeholder="Department ID of the Employoee" ng-model="EmpDept">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-6 col-lg-4">
                        <input type="button" id="btnSave" class="form-control btn-space" value="Submit" ng-click="InsertData()" />
                    </div>
                </div>
            </div>
        </div>
    </div>
    @Html.Hidden("EmpNumber_")
</div>

Output:




Wednesday, May 30, 2018

Angular JS Part 3

Using ng bind directive:

<html>  
<script src="angular.min.js"></script> 
<body>  
<div ng-app="" ng-init="quantity=23;cost=53">  
<p>Total: <span ng-bind="quantity * cost"></span></p>  
</div>  
</body>  
</html>

output:


Angular JS Arrays:




Same example with ng-bind directive:


Using Angular Js Strings:



using ng-bind directive with strings:

Angular Js Expression vs Javascript Expressions



Angular js
Javascript
It supports Filters
It does not support filters
It can be written inside HTML
It cannot be written inside HTML
It does not support conditional loops
It supports conditional looops


ng-repeat Directive:

It is similar to foreach loop in C Sharp, this  is used to iterative each collection items.


Example:


Javascript Code:


/// <reference path="angular.min.js" />

var myapp = angular.module("myapp", [])
            .controller("mycontroller", function ($scope) {
                var employee = [
                    { FirstName: "Rajakond Uday", LastName: "Kumar", Gender: "Male", Address: "Hyderabad" },
                    { FirstName: "Kittu", LastName: "Kumar", Gender: "Male", Address: "Chennai" },
                    { FirstName: "Ab", LastName: "Kumar", Gender: "FeMale", Address: "Delhi" }
                ];
                $scope.employees = employee;

            });

Default.aspx


<html>

<script src="angular.min.js"></script>
<script src="MyJavascript.js"></script>
<body>
    <div ng-app="myapp" ng-controller="mycontroller">
        <table>
            <thead>
                <tr>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Gender</th>
                    <th>Address</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="employee in employees">
                    <td>{{employee.FirstName}}</td>
                    <td>{{employee.LastName}}</td>
                    <td>{{employee.Gender}}</td>
                    <td>{{employee.Address}}</td>
                </tr>
            </tbody>
        </table>
    </div>
</body>

</html>


Output:



Example:

<html>

<script src="angular.min.js"></script>
<script src="MyJavascript.js"></script>
<body>
    <div ng-app="myapp" ng-init = "states = [
                                {capital:'Hyderabad',name:'Telangana'}, 
                                {capital:'Chennai',name:'TamilNadu'}, 
                                {capital:'Bangalore',name:'Karnataka'}
                                ]">   
        <p>List of Countries with locale:</p>  
   <ol>  
      <li ng-repeat = "st in states">  
         {{ 'Country: ' + st.name + ', StateCapital: ' + st.capital }}  
      </li>  
   </ol>  
    </div>
</body>

</html>

Output:



ng-repeat with Nested Loops:

Javascript Code:


/// <reference path="angular.min.js" />
var myapp = angular.module("myapp", [])
            .controller("mycontroller", function ($scope) {
                var studentDetails = [
                    {
                        Class: 'V Standard',
                        Names:
                            [
                                { StudentName: "Rajakond Uday" },
                                { StudentName: "Kumar" },
                                { StudentName: "ABC" }
                            ]
                    },
                    {
                        Class: 'VI Standard',
                        Names:
                            [
                                { StudentName: "D" },
                                { StudentName: "SD" },
                                { StudentName: "ABC" }
                            ]
                    },
                    {
                        Class: 'VII Standard',
                        Names:
                            [
                                { StudentName: "DSS" },
                                { StudentName: "SS" },
                                { StudentName: "ABDC" }
                            ]
                    }
                ];
                $scope.Students = studentDetails;

            });


Default Page:


<html>
<script src="angular.min.js"></script>
<script src="MyJavascript.js"></script>
<body>
    <div ng-app="myapp" ng-controller="mycontroller">
        <ul>
            <li ng-repeat="cls in Students">
                {{ cls.Class }}
                <ul>
                    <li ng-repeat="student in cls.Names">
                        {{ student.StudentName}}
                    </li>
                </ul>
            </li>
        </ul>
    </div>
</body>

</html>

Output:


Angular Js Part 2

AngularJS Expression:

It is like a JavaScript expression surrounded with braces {{ expression }}. AngularJS evaluates the specified expression and binds the result data to HTML.

AngularJS expression cannot contain comma or void or return keyword.

AngularJS expression cannot declare functions.

It cannot contain conditions, loops, exceptions or regular expressions e.g. if-else, ternary, for loop, while loop etc

It  contains literals of any data type.

Example:





Now, we will Add a complex Object Employee details 


Create a new javascript file, and write the below code

/// <reference path="angular.min.js" />
var myapp = angular.module("myapp", [])

myapp.controller("mycontroller", function ($scope) {
    var empDetails = {
        FirstName: "Rajakonda",
        LastName: "Uday  kumar",
        Address: "Hyderabad"
    };
    $scope.empDetails = empDetails;
});


Page



<html ng-app="myapp">

<head>

    <script src="angular.min.js"></script>

    <script src="MyJavascript.js"></script>

  

</head>
<body>
    <div ng-controller="mycontroller">
        <div>
            FirstName : {{ empDetails.FirstName }}
        </div>
        <div>
            LastName : {{ empDetails.LastName }}
        </div>
        <div>
            Address : {{ empDetails.Address }}
        </div>
    </div>
</body>
</html>


output:




Note: If the controller name is misspelled than we can see the error as  

Argument 'mycontrollername' is not a function,got undefined


What happens , if the name of the controller is misspelled.

We need to go to Developer Tools in the browser window.

The binding expression in the view will not be evaluated. i,e


What happened if the property name in the binding expression is misspelled.
It will return null or undefined.

We can write module, controller in a single line as shown below:



var myapp = angular.module("myapp", [])

            .controller("mycontroller", function ($scope) {

    var empDetails = {

        FirstName: "Rajakonda",

        LastName: "Uday  kumar",

        Address: "Hyderabad"
    };
    $scope.empDetails = empDetails;
});


Expression can be used in arithmetic operations as well.



<html ng-app>

<head>

    <script src="angular.min.js"></script>  

</head>

<body>

    <div>
        {{"Rajakonda" + " Uday Kumar"}}<br />
        {{100 + 100 }}<br />
        {{true + false}}<br />
        {{10.23 + 10.32}}<br />
    </div>
</body>
</html>


Output:



To declare a variable under angular js we  use 

The ng-init directive is used to declare AngularJS application variables of any data type.
The ng-init directive can be used to initialize variables in AngularJS application.



<html>

<head>

    <script src="angular.min.js"></script>  

</head>

<body >

    <div ng-app ng-init="message='Hello World!';amount= 104000;rateOfInterest=10.5;duration=10;myArr=[100, 200]; person={ firstName:'RajakondaUday',lastName :'Kumar'}">
        {{ (amount * rateOfInterest * duration)/100 }}<br />
        {{myArr[1]}} <br />
        {{message}} <br />
        {{person.firstName + " " + person.lastName}}
    </div>
</body>
</html>

Output:


Use of ng-src Directive:

I want to display a image on the page, so in the angular js we have to use this directive.


Note:When using a binding expression in the image src results in the 404 Error.
Example :


<html ng-app="myapp">

<head>
    <script src="angular.min.js"></script>
    <script src="MyJavascript.js"></script>
</head>
<body>
    <div ng-controller="mycontroller">
        <div>
            First Name :  {{ actor.FirstName }}
        </div>
        <div>
            Address :  {{ actor.Address }}
        </div>
        <div>
            <img src="{{ actor.img }} " />
        </div>
    </div>
</body>

</html>

Output:




Now, it is working fine without any Errror 404,But in the developer Tools we can see that.





The reason we are getting this 404 Error is because of Binding Expression which we are using.


As soon as the DOM is parsed a request is issued, at that time angular js binding expressions is not evalued(Which is an invalid path) and it returns 404. As we don't have any image at that point. And the second request is made as soon as the binding expression is evaluated, we get the correct path and the image is loaded correctly. So they are two request made.



To Fix 404 Errror we use ng-src directive.


This means the request is used only after the angular js binding expression is evaluated.



AngularJS Data Binding:

It is very useful and powerful feature used in software development. 
It acts as a bridge between the view and business logic of the application.

Two-Way Data Binding

It keeps the model and view sync all the times. That is change in the model , will update the view, and change in the view will  update the model.

Example:


<html ng-app>

  
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 

<body>  
<div ng-init="firstName='Rajakonda Uday'">  

<p>Input something in the input box:</p>  

<p>Name: <input type="text" ng-model="firstName"></p>  
<p>You wrote: {{ firstName }}</p>  
</div> 
</body>  

</html> 

In the above example,{{ firstName }} expression is an AngularJS data binding expression

ng-init: we have  initialized a variable firstname with the value Rajakonda Uday


{{ firstName }} is bound with ng-model="firstName".



output:






Now, if a i enter anything in the texbox it will display the same value , as shown above.


Example 2:

Two text boxes bound together.


<html ng-app>

  
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
<body>  

<div ng-init="quantity=7;price=264">    

<h2>Cost Calculator</h2>  
Quantity: <input type="number" ng-model="quantity">  
Price: <input type="number" ng-model="price">  
<p><b>Total in rupees:</b> {{quantity * price}}</p>  
</div>   

</body>  


</html>  


ng-init="quantity=7;price=264": These are the initialization of the variables.


quantity is bound with the model==>ng-quantity


price is bound with the  model==>ng-price



Output:




Example :


Write the below java script code in the new file:


/// <reference path="angular.min.js" />

var myapp = angular.module("myapp", [])
            .controller("mycontroller", function ($scope) {
            $scope.message = "Rajakonda Uday Kumar";

});



<html ng-app="myapp">  
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
<script src="MyJavascript.js"></script>  
<body>  
<div ng-controller="mycontroller">  
<input type="text" ng-model="message">   <br /> 
{{message}}
</div>   
</body>  
</html> 


Output:




ng-model directive can  be used in any of the following 


input

select
textarea


We can also have a complex object as shown in below example:

Example:


<html ng-app="myapp">

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="MyJavascript.js"></script>
<body>
    <div ng-controller="mycontroller">
        <table>
            <tr>
                <td>First Name</td>
                <td>
                    <input type="text" ng-model="employee.FirstName"></td>
            </tr>
            <tr>
                <td>Last Name  
                </td>
                <td>
                    <input type="text" ng-model="employee.LastName"></td>
            </tr>
        </table>
        <table>
            <tr>
                <td>First Name</td>
                <td>{{employee.FirstName }} </td>
            </tr>
            <tr>
                <td>Last Name  
                </td>
                <td>{{ employee.LastName }} </td>
            </tr>
        </table>
    </div>
</body>

</html>


Output:


Note:

Expressions should be written inside double braces {{expression}}.They can also be written inside a directive that is ng-bind directive.


It binds the content of an html element to application data.

Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...