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...

what is the use of Icmpenum ?

  Icmpenum is a network reconnaissance tool that uses ICMP messages to identify hosts on a network and determine which ones are live and reachable. It sends out ICMP packets to a range of IP addresses and examines the responses to identify active hosts. Here are some of the uses of Icmpenum: Network scanning: Icmpenum can be used to scan a network and identify which hosts are active and reachable. This can be useful for network administrators who want to maintain an inventory of devices on their network or security professionals who want to identify potential targets for further scanning or testing. Host discovery: Icmpenum can help you identify hosts that are hidden or not responding to other types of network probes. By sending out ICMP packets and examining the responses, it can identify hosts that might not appear in other types of network scans. Troubleshooting: Icmpenum can help you identify network connectivity issues by determining which hosts are live and reachable. If you ...

How to add,edit,update and delete in angularjs, CRUD Operation in angularJS

ADD,UPDATE,EDIT AND DELETE IN ANGULARJS CRUD In AngularJS I am going to show you very easy steps to do crud operation in angularjs. Now you can easily create, delete and update in AngularJS.  Before starting to write angularjs code ,Firstly we need to add library of angularjs in our project. Now, I am creating a Employee table to store employee information. You may check below HTML page , I have added some basic html code and angularjs syntax inside html tag. Some Comments about previous article : - I have explain about how to  Insert , delete , update  and select data using  angularjs . Also posted related to data bind in drop-down list using angularjs <html xmlns="http://www.w3.org/1999/xhtml"> <head>     <title></title>     <script src="../jquery/jquery/jquery-1.11.2.js"></script>     <script src="angular.min.js"></script> ...

Socket Programming in Python

  Example of socket programing in python. Here's a simple example of socket programming in Python: Server Side Code import socket # Create a socket object serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # Get local machine name host = socket.gethostname()                            port = 9999 # Bind to a port serversocket.bind((host, port))                                   # Listen to at most 1 connection at a time serversocket.listen(1) print("Server is ready to receive") while True:     # Establish a connection     clientsocket,addr = serversocket.accept()           print("Got a connection from", addr)     clientsocket.send(b"Thank you for connecting")     clientsocket.close() Client Side Code import socket # Create a socket obje...

Sitecore Personalization and Experience Optimization

 Sitecore Personalization and Experience Optimization Sitecore Personalization: Sitecore Personalization is the process of delivering targeted and personalized content to individual users based on their behavior, preferences, and demographic information. This is achieved by using Sitecore's personalization features to create targeted segments and rules based on user behavior and personal data, and then delivering customized content to those users. For example, a clothing retailer might use Sitecore Personalization to show different product recommendations to users based on their previous purchases, the weather in their location, or their browsing behavior. Sitecore Experience Optimization: Sitecore Experience Optimization is the process of using data and analytics to optimize the user experience on a website. This is achieved by using Sitecore's optimization features to test and evaluate different variations of content, layouts, and designs, and then using that data to improve ...