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

How to use WS_Ping_Pro ?

  WS_Ping_Pro is a network troubleshooting tool that allows you to ping and trace route different network hosts to determine connectivity issues. Here's how to use WS_Ping_Pro: Download and install WS_Ping_Pro on your computer. You can download it from the developer's website or from a trusted software repository. Launch WS_Ping_Pro and enter the IP address or hostname of the target host in the "Host" field. You can also choose the type of ping to perform from the "Ping Type" drop-down menu. The options include ICMP, TCP, UDP, and HTTP. Click the "Ping" button to initiate the ping. WS_Ping_Pro will send packets to the target host and measure the response time. You can view the results in the "Ping Results" section, which shows the number of packets sent, received, and lost, as well as the minimum, maximum, and average response times. If you want to perform a trace route, click the "Trace" button. WS_Ping_Pro will send packets ...

Denial of Service (DoS) attack

  A Denial of Service (DoS) attack is a type of cyber attack that targets computer systems or networks by overwhelming them with a flood of traffic, thereby preventing legitimate users from accessing the system or network. DoS attacks are typically carried out using botnets, which are networks of compromised computers that are controlled by a hacker. Here's an example of a DoS attack: Suppose an attacker wants to disrupt the operations of a popular e-commerce website during the holiday shopping season. They could launch a DoS attack against the website's servers, flooding them with a massive amount of traffic and requests. The attacker could use a botnet to generate the traffic, using techniques such as IP spoofing or amplification to make the traffic appear to come from many different sources. The traffic flood will quickly overwhelm the web servers and prevent legitimate users from accessing the website, leading to loss of revenue and reputation damage for the e-commerc...

What is object in C#

Object  : - Object is a instance of class. We can create more than one object a class according to requirements. Suppose we have a class name employee then create obect name of class . In the previous section we have discuss Office Owner will access and use all the Cabinof the Office and its Items. Similarly, to access all Class Method and Variable we use Objects. Example  : Class Employee {  --------- ---------- } Employee emp = new Employee(); here emp is an object of employee Class.

How to Setting up an XM Cloud environment and project ?

   Setting up an XM Cloud environment and project requires the following steps: Sign up for an XM Cloud account: To use XM Cloud, you will need to sign up for an account on their website. You can choose between a free trial or a paid subscription. Create a project: Once you have signed up, you can create a new project in the XM Cloud dashboard. A project represents a set of resources and configurations that are used to manage your customer interactions. Configure your project: You can configure your project by defining settings such as the messaging channels you want to use, the language and region settings, and any other custom settings you need. You can also configure integrations with other systems, such as your CRM or marketing automation platform. Create a conversation flow: A conversation flow is a series of messages and interactions between a customer and your business. You can create conversation flows in XM Cloud using a visual flow designer that allows you to drag an...

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