Tuesday, March 1, 2016

CURD operation using MVC with AgularJS and Entity Framework

       


Here we will create a simple MVC application using AgularJS and Entity Framework to perform CURD operations.

  1. Create a new MVC Application by Opening Visual Studio 2013 --> ASP.NET Web Application ---> MVC template
  2. Add AgularJS from Nuget Package, Right click on project--> select manage Nuget package and search for AgularJS install.
  3. Add a script file in script folder and write your AgularJS code from here.
var myapp = angular.module("myapp", []);
  1. angular.module is the starting point for AgularJS.

ng-app="myapp"> Add this in your cshtml file
  1. Now add Entity Framework to the Project. For this, you need to first right click on the project and click on "Add new item".
  2. Select Data and select ADO.Net Entity Data Model. From here you can add whatever tables you want. For this Application I added a table called 'Tbl_StudentInfo'. Then build your solution.
  3. Retrieve
    Create an object for your entities in controller.
AngularJSDBEntities entity = new AngularJSDBEntities();
Using entity oject we can access the database tables.
Example: var data = entity.Tbl_StudentInfo.ToList();

  1. Go to your js file and write below code.
myapp.factory('StudentService', ['$http', function ($http) {
var StudentService = {};
StudentService.getStudents = function () {
return $http.get('/Student/GetStudents');
};
return StudentService;
}]);



  1. Here we are using a factory service, these methods will interact with the controller.cs.
  2. Write a controller method which will call the StudentService getStudents() method.
myapp.controller("studentInfo", function ($scope, StudentService) {
var Student = {
Id: "",
FristName: "",
LastName: "",
RllNo: "",
ClassName: ""
}
StudentService.getStudents().success(function (res) {
$scope.studentresult = res;
$scope.Action = "Save";
})
});
  1. Go to .html file and write the below script.
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></scr ipt>
<script src="~/Scripts/Student.js"></script>
<div ng-app="myapp">
<div ng-controller="studentInfo">
<table>
<tr>
<td><b>ID</b></td>
<td><b>Frist Name</b></td>
<td><b>Last Name</b></td>
<td><b>Roll No</b></td>
<td><b>Class Name</b></td>
</tr>
<tr ng-repeat="student in studentresult">
<td>
{{student.Id}}
</td>
<td>
{{student.FristName}}
</td>
<td>
{{student.LastName}}
</td>
<td>
{{student.RllNo}}
</td>
<td>
{{student.ClassName}}
</td>
<td>
<span ng-click="GetStudentById(student)">Edit</span>
<span ng-click="Delete(student)">Delete</span>
</td>
</tr>
</table>
  1. Here we are using ng-repeat in order to show the data into a tabular format.
  2. In Controller class and add below code.
AngularJSDBEntities4 entity = new AngularJSDBEntities4();
public JsonResult GetStudents()
{
var data = entity.Tbl_StudentInfo.ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
Output:
ID
Frist Name
Last Name
Roll No
Class Name
1
Kutum
Rao
500500
1
Edit Delete
3
Ravi
Kumar
500501
2
Edit Delete
4
Manne
veera
500504
4
Edit Delete
5
Siva
Kumar
500499
7
Edit Delete


  1. Insert a new record
  • Add below method in factory service in your.JS file.
StudentService.addStudent = function (Student) {
// debugger;
var res = $http({
method: "post",
url: '/Student/AddStudent',
data: JSON.stringify(Student),
dataType: "json"

});
return res;
};
  • Add below method in your js controller.
$scope.regStudent = function () {
Student.FristName = $scope.FristName;
Student.LastName = $scope.LastName;
Student.RllNo = $scope.RllNo;
Student.ClassName = $scope.ClassName;
if ($scope.Action == "Save") {
var getData = StudentService.addStudent(Student);
getData.success(function (msg) {
$scope.studentresult = msg;
})
}
}
  • we are passing a student object to 'addStudent' method which is available in StudentService factory. This factory method will pass student object to ‘'addStudent' controller method.
  • Add below code in your .html file.
<table> <tr> <td> <label>FristName</label> </td> <td> <input type="text" ng-model="FristName" /><br /> </td> </tr> <tr> <td> <label>LastName</label> </td> <td> <input type="text" ng-model="LastName" /><br /> </td> </tr>
<tr>
<td><label>RllNo</label></td>
<td><input type="text" ng-model="RllNo" /><br /></td>
</tr>
<tr>
<td><label>ClassName</label></td>
<td><input type="text" ng-model="ClassName" /></td>
</tr>
<tr>
<td>
<button ng-click="reset()">Clear</button>
</td>
<td colspan="2">
<input type="button" class="btnAdd" value={{Action}} ng-click="regStudent()" />
</td>
</tr>
</table>
  • Add below code in Controller.
public ActionResult AddStudent(Tbl_StudentInfo student)
{
if (student!=null)
{
entity.Tbl_StudentInfo.Add(student);
entity.SaveChanges();
}
return RedirectToAction("GetStudents", "Student");
}
  1. Edit
  • Add this new method in factory service
StudentService.getStudentById = function (id) {
var res = $http({
method: "get",
url:
"/Student/GetStudentById",
params: {
id: JSON.stringify(id)
}
})
return res;
}
}
  • Add this method in your .js controller
$scope.GetStudentById = function (stuedent) {
$scope.Action = "Update";
StudentService.getStudentById(stuedent.Id).success(function (data) {
$scope.FristName = data.FristName,
$scope.LastName = data.LastName,
$scope.RllNo = data.RllNo,
$scope.ClassName = data.ClassName;
$scope.Id = data.Id;
});
}


  • Add below code in in your controller.cs file
public JsonResult GetStudentById(int id)
{
var data = entity.Tbl_StudentInfo.Find(id);
return Json(data, JsonRequestBehavior.AllowGet);
}
  • Whenever we click on the edit button respective record data will be populated for editing in the controls.
  • Make changes to the input fields and click on 'Update' button
  • For 'updatestudents' data write below code in your factory service in .JS file.
StudentService.updateStudent = function (Student) {
var res = $http({
method: "post",
url: "/Student/UpdateStudents",
data: JSON.stringify(Student),
dataType: "json"
})
return res;
}
  • JS Controller code: Add below code in your regStudent method's else part
$scope.regStudent = function ()
{
Student.FristName = $scope.FristName;
Student.LastName = $scope.LastName;
Student.RllNo = $scope.RllNo;
Student.ClassName = $scope.ClassName;

if ($scope.Action == "Save") {
var getData = StudentService.addStudent(Student);
getData.success(function (msg) {
$scope.studentresult = msg;
})
}
else {
Student.Id = $scope.Id;
var res = StudentService.updateStudent(Student);
//getStudentList();
res.success(function (msg) {
$scope.studentresult = msg;
})
}
}
  • Controller.cs Code:
public ActionResult UpdateStudents(Tbl_StudentInfo student)
{
if (student != null)
{
var updatedData = entity.Tbl_StudentInfo.Where(x => x.Id == student.Id).FirstOrDefault();
updatedData.FristName = student.FristName;
updatedData.LastName = student.LastName;
updatedData.RllNo = student.RllNo;
updatedData.ClassName = student.ClassName;
entity.SaveChanges();
}

return RedirectToAction("GetStudents", "Student");
}

  1. Delete Code :
  • Add below code in your factory service
StudentService.deleteStudent = function (id) {
var res = $http({
method: "post",
url: "/Student/DeleteStudent",
params: {
id: JSON.stringify(id)
}
})
return res;
}
  • JS Controller Code
$scope.Delete = function (stuedent) {
// debugger;
var data = StudentService.deleteStudent(stuedent.Id);

data.then(function (m) {

})
}
  • Controller.CS code
public ActionResult DeleteStudent(int id)
{
var Sid = entity.Tbl_StudentInfo.Where(x => x.Id == id).FirstOrDefault();
entity.Tbl_StudentInfo.Remove(Sid);
entity.SaveChanges();
return RedirectToAction("GetStudents", "Student");
}



Monday, November 23, 2015

Extension Method



Why Extension Method: Another question is, why do we need to use the extension methods, we can create our own methods in client application or in other class library and we can call those methods from the client application but the important point is, these methods would not be the part of that class (class of the third party dll). So adding the extension methods in the class, you are indirectly including another behavior in that class. I am talking about the class which is the part of the third party dll (Most Important).

So when you create your own extension methods for specific types those methods would be accessible for that type.

This can be easily understood by the following diagram:

ExMtd1.gif

(I am object of the class)

After some time, client application wants to add another behavior in that class; let's say 'talk' then extension methods can be used to add this extra behavior in that class without altering any code.

ExMtd2.gif

Implementation: The following is the structure of the third party class, which is not accessible to the developer. This class contains a method 'Walk'.
public class Class1{
    public String Walk()
    {
        return "I can Walk";    }}
Now it's time to create the Extension Method. Just use the following steps:

Step 1: Create the Static Class

Step 2: Create the Static Method and give any logical name to it. 

Step 3: In the Extension Method Parameter, just pass this along with the object type and 
the object name as given below:

ExMtd3.gif

The client application can access both the method "Walk" and the extension method "TalkExtMethod":
Class1 obj = new Class1 ();
Obj.TalkExtMethod ()  
obj.Walk ()


Benefits: There may be various benefits of using the Extension Methods in your code. Let's say you are using the method1 () of the class in the third party dll and the object instantiation has failed due to another reason; then you will get the object reference error while calling the method1 () if you did not handle the null reference check.
Class1 obj = GetClass1Object ();//If the obj is null, you will get the object reference errorobj.Method1();

Although the following code is safer than previous one but the problem is you will have to include this check every time when you call the Method1 and if the developer forgets to include this check in the code then the program throws an object reference error.
Class1 obj = GetClass1Object ();if (obj!= null)
{
    obj.Method1 ();
}

If we use the extension method to solve this problem we get outstanding results. Instead of checking the null reference every time in the code we handle it in the extension methods which is called by the client application.
public static string Method1ExtMethod(this Class1 objClass)
{
    //If the obj is not null, then call the Method1()
    if (objClass! = null)
    {
        return objClass.Method1 ();
    }
    return string.Empty;    
}
Class1 obj = GetClass1Object ();//Don't include any check whether the object is null or notobj.Method1ExtMethod()

Tuesday, June 16, 2015

Grid Checkbox checked values passing to controller



 $("#btnSubmitRetation").on("click", function (e) {      
        var datatype = [];
      //  console.log($(".row-checkbox").length);
      //  console.log($(".row-checkbox:checked").length);
        $(".row-checkbox").each(function (i) {

            var id = $(this).attr("id");
            var defaultValue = "false";
            if ($(this).is(":checked")) {
                defaultValue = "true";
            }          
            dataSet = {
                "key": id,
                "value": defaultValue
            }
            datatype.push(dataSet);

        });


        $.ajax({
            url: '@Url.Action("SaveRecordsRetention", "RecordsRetention")',          
            type: 'POST',
            data: "jsonOfLog=" + JSON.stringify(datatype),
            dataType: 'text',
            success: function (result) {            
            }
        });

Controller:

 [HttpPost]
        public ActionResult SaveRecordsRetention(string jsonOfLog)
        {
            //  var convertedvalue = Newtonsoft.Json.JsonConvert.DeserializeObject>(data);
            try
            {
                if (jsonOfLog != null)
                {
                    List> values = JsonConvert.DeserializeObject>>(jsonOfLog);

                   


                }

Tuesday, September 23, 2014

jQuery selectors select 2nd cell of 2nd row of 2nd table


 

     
       
         X
         **some text that changes**
         **ssss**
     
 

Jquery:

$(function(){
   var text = $("table:eq(1) tr:eq(1) td:eq(2)").text();
   alert(text);
});

Monday, August 25, 2014

Save Error Log or Exception Log in text file in C#

Add a class file name it as ErrorLog
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Text;
using System.IO;

namespace Save_Error_Log_or_Exception
{
    public class ErrorLog
    {
        public bool WriteErrorLog(string LogMessage)
        {
            bool Status = false;
            string LogDirectory = ConfigurationManager.AppSettings["LogDirectory"].ToString();

            DateTime CurrentDateTime = DateTime.Now;
            string CurrentDateTimeString = CurrentDateTime.ToString();
            CheckCreateLogDirectory(LogDirectory);
            string logLine = BuildLogLine(CurrentDateTime, LogMessage);
            LogDirectory = (LogDirectory + "Log_" + LogFileName(DateTime.Now) + ".txt");

            lock (typeof(ErrorLog))
            {
                StreamWriter oStreamWriter = null;
               try
               {
                   oStreamWriter = new StreamWriter(LogDirectory, true);
                    oStreamWriter.WriteLine(logLine);
                    Status = true;
                }
               catch
              {

               }
                finally
                {
                    if (oStreamWriter != null)
                    {
                        oStreamWriter.Close();
                    }
                }
            }
            return Status;
        }

        private bool CheckCreateLogDirectory(string LogPath)
        {
            bool loggingDirectoryExists = false;
            DirectoryInfo oDirectoryInfo = new DirectoryInfo(LogPath);
            if (oDirectoryInfo.Exists)
            {
                loggingDirectoryExists = true;
            }
            else
            {
                try
                {
                    Directory.CreateDirectory(LogPath);
                    loggingDirectoryExists = true;
                }
                catch
                {
                    // Logging failure
                }
            }
            return loggingDirectoryExists;
        }

        private string BuildLogLine(DateTime CurrentDateTime, string LogMessage)
        {
            StringBuilder loglineStringBuilder = new StringBuilder();
            loglineStringBuilder.Append(LogFileEntryDateTime(CurrentDateTime));
            loglineStringBuilder.Append(" \t");
            loglineStringBuilder.Append(LogMessage);
            return loglineStringBuilder.ToString();
        }


        public string LogFileEntryDateTime(DateTime CurrentDateTime)
        {
            return CurrentDateTime.ToString("dd-MM-yyyy HH:mm:ss");
        }


        private string LogFileName(DateTime CurrentDateTime)
        {
            return CurrentDateTime.ToString("dd_MM_yyyy HH:mm:ss");
        }
    }
}
------------
Page_Load:

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

namespace Save_Error_Log_or_Exception
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            ErrorLog oErrorLog = new ErrorLog();
            try
            {
                int i,j,k;

                i = 100;
                j = 0;
                k =i/j;

               

            }
            catch (Exception ex)
            {
                oErrorLog.WriteErrorLog(ex.ToString());
               
               
            }
        }
    }
}

Thursday, July 10, 2014

How to Find Grid Rows Length In Jquery





var rowCount = $('#grdpayments').find('tr').length;