Skip to main content

Featured post

XM Cloud content sync from prod to uat or UAT to prod step by step

When working with Sitecore, it’s common to need content synchronization across environments. Today, I’ll walk you through the steps to sync content from Production to UAT/TEST and vice versa. Steps to Follow 1. Set Up Your Workspace Create a folder on your computer where you will manage the script files and exported data. Open the folder path in PowerShell to begin scripting. We need to run some scripts in PowerShell to update the folder with the basic requirements for syncing content. PS C:\Soft\ContentSync> dotnet new tool-manifest PS C:\Soft\ContentSync> dotnet nuget add source -n Sitecore https://nuget.sitecore.com/resources/v3/index.json PS C:\Soft\ContentSync> dotnet tool install Sitecore.CLI PS C:\Soft\ContentSync> dotnet sitecore cloud login If the above error occurs, you will need to run a different command to resolve the issue. PS C:\Soft\ContentSync> dotnet sitecore init now, Again run above command to open and authenticate with XM Cloud. It will be there a...

Insert,delete,update,select using angularjs with mvc

Asp.net MVC with AngularJS is boom in the current environment of development in .net platform.
I am going to show you how to insert delete and update data by using angularjs with asp.net mvc.

I will explain you step by step to create a projet by using angularjs with mvc.

Details of point to be discuss in this tutorial is as follows.

1.   How to create Project using asp.net mvc with AngularJS.
2.   Installing the package of AngularJS in project of Asp.net MVC.
3.   Process to create module, services and controller in AngularJs.
4.   How to extract data from server using C#.
5.   How to bind data on HTML Page using AngularJS method like bind,fill and load from server side.
6.   How to do perform operation to insert, delete,update and edit by using AngularJS

Before starting of project we should know some basic information about AngularJS. Which can help us to understand and developed best application by using this technologies.

What is angularjs?
AngularJS is a client side scriptng language which can help us to develop dynamic single page application.It provide dynamic data binding in html .It has unit testable so this is trend in market.

Now we should know about advantage and limitation of angularjs
Now you may check some advantages of AngularJS .
1.   Scope
2.   Controller
3.   Databinding
4.   Services
5.   Unit Testable Code
6.   Dependency Injection
7.   Single Page application development

Some of limitation of AngularJS which developer should know before developing any application using this technologies.
1.   Not Secure :- Server side authentication and authorization is must as it is all code written in java script.
2.   Complex Life Cycle : - AngularJS Application life cycle is very complex.
3.   Not Degradebale  :-AngularJS will not work when you off javascript in browser.

Let’s get start to create project using visual studio 2012.

First you need to open visual studio 2012.Now click on file menu and then go to create New Project>>Select Asp.net MVC 4 from windows and give the suitable project name.

Now Select Basic option from new open window which is shown below.
Add caption


Now Add AngularJS package in your project by using nugget package console.

Step to install angularjs package in project by below command.
PM>Install-Package angularjs
Another one is
PM>Install-Package Angularjs.Route
In this way you complete to add angularjs libarary in your project.

Step1 :-   First we need to create model in asp.net mvc project .model is used for database record we can create first model using entity framework.

Now, I am creating employee table by using ID is primary key and it is a identity.

Create table dbo.employee
(
ID int identity(1,1),
Name nvarchar(100) NULL,
EmailID nvarchar(50) Null,
Address navarchar(200) NULL,
PRIMARY KEY CLUSTURED (ID ASC)
)
Now ,by using entity framework add entity data model.


And select database model from dropdown as you may see in below image .Now we created model .


 Step2 :  In this step now I am going to create controller in mvc project. Controller name is HomeController,


In this controller created method of insert delete and update method for this please see  bellow method.

public ActionResult Index()
      {
          return View();
      }

      public JsonResult getDetails()
      {
          using (SampleDBEntities dataContext = new SampleDBEntities())
          {
              var employeeList = dataContext.Employees.ToList();
              return Json(employeeList, JsonRequestBehavior.AllowGet);
          }
      }

      public JsonResult getEmpByNo(string EmpNo)
      {
          using (SampleDBEntities dataContext = new SampleDBEntities())
          {
              int no = Convert.ToInt32(EmpNo);
              var employeeList = dataContext.Employees.Find(no);
              return Json(employeeList, JsonRequestBehavior.AllowGet);
          }
      }
      public string UpdateEmp(Employee Emp)
      {
          if (Emp != null)
          {
              using (SampleDBEntities dataContext = new SampleDBEntities())
              {
                  int no = Convert.ToInt32(Emp.Id);
                  var employeeList = dataContext.Employees.Where(x => x.Id == no).FirstOrDefault();
                  employeeList.name = Emp.name;
                  employeeList.mobil_no = Emp.mobil_no;
                  employeeList.email = Emp.email;
                  dataContext.SaveChanges();
                  return "Employee Has been Updated";
              }
          }
          else
          {
              return "Invalid Operations";
          }
      }
      public string AddEmp(Employee Emp)
      {
          if (Emp != null)
          {
              using (SampleDBEntities dataContext = new SampleDBEntities())
              {
                  dataContext.Employees.Add(Emp);
                  dataContext.SaveChanges();
                  return "Employee Has been Updated";
              }
          }
          else
          {
              return "Invalid Operations";
          }
      }

      public string DeleteEmp(Employee Emp)
      {
          if (Emp != null)
          {
              using (SampleDBEntities dataContext = new SampleDBEntities())
              {
                  int no = Convert.ToInt32(Emp.Id);
                  var employeeList = dataContext.Employees.Where(x => x.Id == no).FirstOrDefault();
                  dataContext.Employees.Remove(employeeList);
                  dataContext.SaveChanges();
                  return "Employee Has been Deleted";
              }
          }
          else
          {
              return "Invalid Operation";
          }
      }

I have created some method in above class which is described in below section .

getDetails() :-This is use to get all details of all employee in JSON format.
getEmpByNo() :- This method is use for to get details of employee by specified ID.
updateEmp() :- This method is used for to update the existing employee data in database.
AddEmp() :- This method is used to add new employee details in database.
DeleteEmp() :- This method is use for delete existing employee from database.

ADD view :-
Now We need to add View for the above controller . so right click on Index() method and click on add view from pane , it will automatically add index.cshtml file in your view folder.
For angularjs  I am using the following directives for the operations.

Ng-Click : This directive allow us fire click event when you click so we can do any operation after firing of click event.

Ng-Controller : - This is use to attach controller class with view.

Ng-Repeat  :-  It is use to instantiate template per item from a collection. Each item has it’s own scope.$index is use to set item index.

Ng-Model :- it is use to binding the view  into model.

Now you may see the below design of index page.

<div ng-controller="myCntrl">
     <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

   <h1> Employee Details Page</h1>

    <br />

        <input type="button" class="btnAdd" value=" Add Employee" ng-click="AddEmpDiv()" />

    <div class="divList">
        <p class="divHead">Employee Details list</p>
        <table cellpadding="12" class="table table-bordered table-hover">
            <tr>
                <td><b>ID</b></td>
                <td><b>Name</b></td>
                <td><b>Email</b></td>
                <td><b>Address</b></td>
                <td><b>Actions</b></td>
            </tr>
            <tr ng-repeat="employee in employees">
                <td>
                    {{employee.Id}}
                </td>
                <td>
                    {{employee.name}}
                </td>
                <td>
                    {{employee.email}}
                </td>
                <td>
                    {{employee.Address}}
                </td>
                <td>
                    <span ng-click="editEmp(employee)" class="btnAdd">Edit</span>
                    <span ng-click="deleteEmp(employee)" class="btnRed">Delete</span>
                </td>
            </tr>
        </table>
    </div>

    <div ng-show="divEmployee">
        <p class="divHead">{{Action}} Employee</p>
        <table>
            <tr>
                <td><b>Employee Id</b></td>
                <td>
                    <input type="text" disabled="disabled" ng-model="employeeId" />
                </td>
            </tr>
            <tr>
                <td><b>Employee Name</b></td>
                <td>
                    <input type="text" ng-model="employeeName" />
                </td>
            </tr>
            <tr>
                <td><b>Email ID</b></td>
                <td>
                    <input type="text" ng-model="employeeEmail" />
                </td>
            </tr>
            <tr>
                <td><b>Address</b></td>
                <td>
                    <input type="text" ng-model="employeeAddress" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="button" class="btnAdd" value="Save" ng-click="AddUpdateEmp()" />
                </td>
            </tr>
        </table>
    </div>
</div>

Step 3:  Now going to create MVC code for AngularJS. MVC means model view and controller .
Create javascript file name as
1.   Model.js
2.   Controller.js
3.   Service.js

Model.js :-
Angular.Modules : - It is a container part of an applications and use to configure $injector.

Example is : var app=angular.module(“myFirstApp”,[]);

Service.JS: - In this file I am going to create services for different
operations. in this services we use $http to call server side method.


app.service("myService", function ($http) {

    //get All Eployee Details
    this.getEmployees = function () {
        debugger;
        return $http.get("Home/GetDetails");
    };

    // get Employee By Id
    this.getEmployee = function (employeeID) {
        var response = $http({
            method: "post",
            url: "Home/getEmpByNo",
            params: {
                id: JSON.stringify(employeeID)
            }
        });
        return response;
    }

    // Update Employee
    this.updateEmp = function (employee) {
        var response = $http({
            method: "post",
            url: "Home/UpdateEmp",
            data: JSON.stringify(employee),
            dataType: "json"
        });
        return response;
    }

    // Add Employee
    this.AddEmp = function (employee) {
        var response = $http({
            method: "post",
            url: "Home/AddEmp",
            data: JSON.stringify(employee),
            dataType: "json"
        });
        return response;
    }

    //Delete Employee
    this.DeleteEmp = function (employeeId) {
        var response = $http({
            method: "post",
            url: "Home/DeleteEmp",
            params: {
                employeeId: JSON.stringify(employeeId)
            }
        });
        return response;
    }

Controller.JS: - I have used this file to call services. Please see below how I called service in controller js file.

app.controller("myCntrl", function ($scope, myService) {
    $scope.divEmp = false;
    GetAllEmployee();
    //To Get All Data from table
    function GetAllEmployee() {
        debugger;
        var getData = myService.getEmployees();
        debugger;
        getData.then(function (emp) {
            $scope.employees = emp.data;
        },function () {
            alert('Error in getting records');
        });
    }

    $scope.editEmployee = function (employee) {
        debugger;
        var getData = myService.getEmployee(employee.Id);
        getData.then(function (emp) {
            $scope.employee = emp.data;
            $scope.employeeId = employee.Id;
            $scope.employeeName = employee.name;
            $scope.employeeEmail = employee.email;
            $scope.employeeAge = employee.Age;
            $scope.Action = "Update";
            $scope.divEmployee = true;
        },
        function () {
            alert('Error in getting records');
        });
    }

    $scope.AddUpdateEmployee = function ()
    {
        debugger;
        var Employee = {
            Name: $scope.employeeName,
            Email: $scope.employeeEmail,
            Age: $scope.employeeAge
        };
        var getAction = $scope.Action;

        if (getAction == "Update") {
            Employee.Id = $scope.employeeId;
            var getData = myService.updateEmp(Employee);
            getData.then(function (msg) {
                GetAllEmployee();
                alert(msg.data);
                $scope.divEmployee = false;
            }, function () {
                alert('Error in updating record');
            });
        } else {
            var getData = myService.AddEmp(Employee);
            getData.then(function (msg) {
                GetAllEmployee();
                alert(msg.data);
                $scope.divEmployee = false;
            }, function () {
                alert('Error in adding record');
            });
        }
    }

    $scope.AddEmployeeDiv=function()
    {
        ClearFields();
        $scope.Action = "Add";
        $scope.divEmployee = true;
    }

    $scope.deleteEmployee = function (employee)
    {
        var getData = myService.DeleteEmp(employee.Id);
        getData.then(function (msg) {
            GetAllEmployee();
            alert('Employee Deleted');
        },function(){
            alert('Error in Deleting Record');
        });
    }

    function ClearFields() {
        $scope.employeeId = "";
        $scope.employeeName = "";
        $scope.employeeEmail = "";
        $scope.employeeAge = "";
    }
});
Step 4: - in this step now we need to call js file in html file. I am going to call js file in layout.cshtml page.
Please see below code to understand .Now we success fully created all those process which we required to insert, delete, update and select  data and show on user interface by using angularJS with Asp.net MVC.

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />

   <title>@ViewBag.Title</title>

    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/Content/Angular/Module.js"></script>
    <script src="~/Content/Angular/Service.js"></script>
    <script src="~/Content/Angular/Controller.js"></script>
    @Styles.Render("~/Content/css")
    <style>
      
    </style>
</head>
<body>
    @RenderBody()

    @Scripts.Render("~/bundles/jquery")

    @RenderSection("scripts", required: false)
</body>
</html>




Comments

Popular posts from this blog

Sitecore pipeline implementation

 Sitecore pipeline implementation Sitecore pipelines are a key concept in Sitecore architecture, allowing developers to add custom logic and process data at specific points during a request. Here's a general guide for implementing Sitecore pipelines: 1.        Create a custom class that inherits from the Sitecore.Pipelines.PipelineProcessor class. 2.        Override the Process method to add your custom logic. 3.        Register the pipeline processor in the Sitecore configuration file (usually the Web.config or Sitecore.config file). 4.        Determine the appropriate point in the pipeline to insert your custom logic. Sitecore provides many predefined pipelines, such as the httpRequestBegin pipeline, that you can use to insert your custom logic. 5.        Add a new node to the pipeline in the configuration file, specifying the cla...

Homework 2.2 MongoDB for .Net Development

Download JSON data from homework 2.2 MongoDB of .Net development and use it to restore in MongoDB Database. Dataset contains four scores which each has two hundred students. First confirm that you have restored data correctly. Use below command to check your restored data. Data count should be 800. use students db.grades.count() Now , Lets find student who holds 101st across among grades. See the below query to find. db.grades.find().sort( { 'score' : -1 } ).skip( 100 ).limit( 1 ) Correct result is given below by executing the above query. { "_id" : ObjectId("50906d7fa3c412bb040eb709"), "student_id" : 100, "type" : "homework", "score" : 88.50425479139126 } Use below query for sorting of  data, Here I have use limit of 5 show it will show five record. db.grades.find( { }, { 'student_id' : 1, 'type' : 1, 'score' : 1, '_id' : 0 } ).sort( { 'student_id' : 1, ...

How to upload image in asp.net using file upload control

Here i am going to explain how to upload image on server. First add one file upload control on your page  and button give the suitable name of both file upload control and button control. Click on button control it will fire event on the name of button and it will redirect it to code behind file. It will also check the image content length and type of image Now see below code of code behind file. protected void Button1_Click( object sender, System. EventArgs e)     {         if (fu1.HasFile)         {             if (fu1.PostedFile.ContentLength <= 2097152)             {                 string fileexe = Path .GetExtension(fu1.FileName);        ...

How to use Nmap with example

  Nmap is a popular open source network scanning tool used for network exploration, security auditing, and vulnerability testing. Here's an example of how to use Nmap: Open a command prompt or terminal window on your computer. Type "nmap" followed by the IP address or domain name of the target network or device that you want to scan. For example, to scan a website, you might enter: nmap www.example.com Hit enter to start the scan. Nmap will begin probing the target network or device and will display information about the discovered hosts and open ports. You can use various options and flags to customize the scan. For example, the "-sS" flag specifies a TCP SYN scan, which is a stealthy scan method that can bypass some firewall configurations. The "-p" flag specifies the ports to scan. For example, to scan only ports 80 and 443 on a website, you might enter: nmap -sS -p 80,443 www.example.com Hit enter to start the customized scan. Nmap will d...

Network hacking & scanning tools

NETWORK SCANNING Network scanning is very easy to understand and use but don’t do this in any other network. It’s illegal .so I can’t suggest it do . You may see below protocol and tools to be use for network scanning. Tools to be use to be use for scan and hack network : ·         HTTPort ·         Nmap :- port scan counter measure ·         Pinger ·         WS_Ping_Pro ·         HPING2 ·         KingPing ·         Icmpenum ·         SNMP Scanner ·         Detecting ping sweeps ICMP Queries ·         IPEye ·         IPSECScan ·      ...