Saturday, February 22, 2014

MVC With CURD Operations

File->New Project




Select Asp.net MVC 3 or MVC4 web application






Select the type of Template as Internet Application
View Engine: Razor

And Click on Ok Button.


Goto Views (Layout.cs.html)





And do the following changes in the code as below screen shot

    <li>@Html.ActionLink("Employee","Employee","Employee")</li>

In the above line

First parameter- Text

Second parameter-Method name or Action Name

Third parameter- Controller Name



Next Go to Model and create a class.










Give the name of the class as Employee.cs
Employees.cs

public class Employees
    {
        public int? Eno { get; set; }

        public string Ename { get; set; }

        public string Address { get; set; }


        public List<Employees> GetAllEmployees()
        {
            DataTable objTbl = new DataTable();
     List<Employees> employeeList = newSystem.Collections.Generic.List<Employees>();
            SqlConnection objCon = new SqlConnection();
            objCon.ConnectionString = "";
            SqlDataAdapter objAdp = new SqlDataAdapter("select * from employees", objCon);
            objAdp.Fill(objTbl);
            foreach (DataRow dr in objTbl.Rows)
            {
                employeeList.Add(new Employee()
                {
                    Eno = Convert.ToInt32(dr["ENO"]),
                    Ename = Convert.ToString(dr["Ename"]),
                    Address = Convert.ToString(dr["Address"])
                });
            }
            return employeeList;
        }
     

    }
Now the model is ready.

Next go to controller.

Add->Controller









And write the following code









Right click on the page




Select Add View






Now the view is created.


And run the application to test the summary Page.





To create:


Write the following lines of code in Employee Controller






Again write click on the controller









And click on Add Button


And run the application.



And click on Create New.



And again write the following lines of code in Employee Controller

[HttpPost]
        public ActionResult Create(Employees obj)
        {
            Employees objemp = new Employees();
            objemp.SaveEmployeeDetails(obj);
            return RedirectToAction("Employee");
        }







And write the following code in Employees.cs

And write the following code in Employees.cs
public void SaveEmployeeDetails(Employees obj)
        {
            SqlConnection objCon = new SqlConnection();
            objCon.ConnectionString = "";
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "insert into Employees(Eno,Ename,Address) values(" + obj.Eno + ",'"+ obj.Ename + "','" + obj.Address + "')";
            objCon.Open();
            cmd.Connection = objCon;
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
            objCon.Close();

        }




Details:


Now go to Employee.cshtml (View Folder)




And modify the following lines of code.

  @Html.ActionLink("Details", "Details", new { id=item.Eno  })


Here Eno is the primary key of my table.





Go to Employee controller.cs

public ActionResult Details(int id)
        {
            Employees obj = Employees.GetEmployeesById(id);
            if (obj == null)
            {
                return HttpNotFound();
            }
            return View(obj);
        }

Go to Employees.cs and write the following code.


  public static Employees GetEmployeesById(int Eno)
        {
            DataTable objTbl = new DataTable();

            SqlConnection objCon = new SqlConnection();
            objCon.ConnectionString = "";

            SqlDataAdapter objAdp = new SqlDataAdapter("select * from employees where eno =" + Eno, objCon);

            objAdp.Fill(objTbl);

            Employees objEmployees = new Employees() { Eno = Convert.ToInt32(objTbl.Rows[0]["Eno"]), Ename = Convert.ToString(objTbl.Rows[0]["Ename"]), Address = Convert.ToString(objTbl.Rows[0]["Address"]) };

            return objEmployees;
        }



And right click on the Employee Controller and select Add View








Edit

Employee.cshtml


@Html.ActionLink("Details", "Details", new { id=item.Eno  }) 





Go to Employee Controller and write the following Code

[HttpGet]
        public ActionResult Edit(int id)
        {
            Employees obj = Employees.GetEmployeesById(id);
            if (obj == null)
            {
                return HttpNotFound();
            }
            return View(obj);
        }




Again Right Click on the Employee Controller and Add View







And click on Add Button.


And test the application.



And click on Edit Button.



Again go to Employee Controller.cs and write the following code to save the modified values.

[HttpPost]
        public ActionResult Edit(Employees obj)
        {
            Employees objemp = new Employees();
            objemp.UpdateEmployeeDetails(obj);
            return RedirectToAction("Employee");


        }






Employees.cs and write the following code


Now update the values and check the summary page.

Delete

Goto Employee.cshtml and modified  the following code .

           @Html.ActionLink("Edit", "Edit", new { id=item.Eno  }) |
            @Html.ActionLink("Details", "Details", new{ id=item.Eno  }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Eno })

Then go to EmployeeController.cs and write the following code in it.

public ActionResult Delete(int id)
        {
            Employees objemp = new Employees();
            objemp.DeleteEmployeeDetails(id);
            return RedirectToAction("Employee");
        }



Go To Employee.cs and write the following code.



Points to Remember

Here int id in the parameter should be same as
  @Html.ActionLink("Details", "Details", new { id=item.Eno  })

Both the names should be same

Sunday, November 24, 2013

Introduction to JSON

What is JSON

Json Stands JavaScript Object Notation.

JSON is a lightweight text-based open standard data-interchange format.

JSON files are saved with .json extension. Internet media type of JSON is "application/json".

JSON is derived from a subset of JavaScript programming language (Standard ECMA-262 3rd Edition—December 1999).

It is entirely language independent and can be used with most of the modern programming

Similaries between XML & JSON

No end tag like XML
Shorter than XML
Quicker to read and write when compare to XML
Can be parsed using built-in JavaScript functions like eval() and parse()
Uses arrays – Efficient for handling huge data
No reserved words

Data Types in JSON
JSON supports following datatypes:



JSON Syntax


=====================

How to - Solve SQL Server 2012 Identity Problem. Identity increased from 6 to 1000 ............

During application development, we often input dummy data into our database for testing purposes. But then we we want all records of the table to be deleted and also want to start the identity column values from 0. For this, we delete the truncate command. This will delete data from table and also reset the identity column value to 0.

Example
truncate table [table_name]

truncate table product

But truncate command fails to delete the data if there is a relationship given to the table and the identity column is not reset.
So, in this case, first you need to delete data from the child. 

After deleting data, fire this command and it will reset 

your identity column to 0.


DBCC CHECKIDENT('[table_name]', RESEED, [new_reseed_value])

-- for example
DBCC CHECKIDENT('product', RESEED, 0)


Question

Say I have a table which uses an int auto identity as a primary key it is sporadically skipping increments, for example:
1, 2, 3, 4, 5, 1004, 1005

You can use below two choices

Use trace flag 272 , this will cause a log record to be generated for each generated identity value. The performance of identity generation may be impacted by turning on this trace flag.

Solution 1:

     1. Open "SQL Server Configuration Manager"
      2.                Click "SQL Server Services" on the left     pane
     3.                Right-click on your SQL Server instance name on the right pane ->Default: SQL Server(MSSQLSERVER)
    4.               Click "Properties"
    5.                Click "Startup Parameters"
    6.               On the "specify a startup parameter" textbox type "-T272"
   7.               Click "Add"
8.Confirm the changes 










CLICK ON aDD bUTTON

And then restart your sql server.


Use a sequence generator with the NO CACHE setting

solution 2

CREATE SEQUENCE MySeq AS int
  START WITH 1
  INCREMENT BY 1
  NO CACHE;

Friday, November 8, 2013

Installation of SQL SERVER 2012 ( In Windows 8 operating System)

In windows 8 operating system
first install windows 7 service pack1  and then install sql server .

Otherwise u might get an error as sql server cluster fail over




Select New SQL SERVER STAND ALONE INSTALLATION .


Click on Ok


Click on Next


Click on Next


Click on Next Button


Click on Install Button

Click on Next



Click on Next Button




SELECT ALL (Click on SELECT ALL BUTTON) and click on Next Button.



Click on Next Button



Click on Next Button




Server Configuration:
Click on Next Button



select Mixed Mode and enter password.

Click on Add Current User and Click on Next Button





Click on Add Current User and Click on Next



Click on Next Button





Click on Add Current User and Click on Next


Controller Name: leave empty
Click on Next



Click on Next Button
the following screen appears and click on Install.














Sunday, November 3, 2013

REST BASED SERVICES USING WCF

REST stands for Representational state transfer
Very popular for services
Principle: is if there is any resource then everyone has to access that resource. Rest also defines that URL should be friendly.



REST URL should be as must as plane URL

REST is the term coined by Ray Fielding in PH.D to describe an architecture style of networking systems.

There are Rest services & Rest –Like services which uses XML and HTTP.

Rest outlines the philosophy of mapping.
HTTP Verbs to Create, retrieval, update, delete

Rest is not only for services, it is the for Html 5.
Rest architecture says everything should be a resources.

Rest say we will develop a program and give the URL to everyone.
REST is not approved by W3 till now.

Note:

When we talk about the Database as a resource we usually talk in terms of CRUD operations. I.e. Create, Retrieve, Update and Delete. Now, What REST says is that for a remote resource all these operations should be possible and they should be possible using simple HTTP protocols

Actually only the difference is how clients access our SERVICE .Normally, a WCF service will use SOAP, but if you build a REST service, clients will be accessing your service with a different architectural style (calls, serialization like JSON, etc.)

We have to prepare help File for Rest for the client, saying that what are the methods somewhat we have to give the reply to client.

Now the basic CRUD operations are mapped to the HTTP protocols in the following manner:

·         GET: This maps to the R (Retrieve) part of the CRUD operation. This will be used to retrieve the required data (representation of data) from the remote resource.

·         PUT: This maps to the U (Update) part of the CRUD operation. This protocol will update the current representation of the data on the remote server.

·         POST: This maps to the C (Create) part of the CRUD operation. This will create a new entry for the current data that is being sent to the server.

·         DELETE: This maps to the D (Delete) part of the CRUD operation. This will delete the specified data from the remote server.

Now, the list of Employee Details can be retrieved as

To retrieve specific employee details from the Employee Table we have an Id Column in the database. To access the details of particular employee


Since these are GET requests, data can only be retrieved from the server. To perform other operations, if we use the similar URI structure with PUT, POST or DELETE operation, we should be able to create, update and delete the resource from the server. 

WCF Rest supports for REST

        Programming Model
        WebGetAttribute
WebInvokeAttribute
WebServiceHost

Channels & Dispatcher Infrastructure.
WebHttpBinding
WebHttpBehaviour

Utility Classes & Extensibility Points

        Uri Template
       Uri Template Table
        Query String Converter
        WebHttpDispatchOperationSelector

WebGet:
Is the attribute which make our [Operation Contract] as web method enabled to consume as Rest Style & Binding is WebHttpBinding

[WebGet]
[Operation Contract]
Void Add ();

Web InvokeAttribute:àWeb Get +All Others

Now, How to Call this Method


Here Add is the method name

If it returns string, we will get result also as string.

WebServiceHostFactory

To make Rest Enabled all the following things are required

System.ServiceModel.dll
System.ServiceModel.Web.dll

To make URL as Friendly we use uri Template

Example

It is not friendly URL

So friendly URL is


To make URL as friendly:

[WebGet(UriTemplate=”Add/{a}/{b}”)]
[operationContract]
Void Add(int a, int b)

Note: Webhttpbinding does not support SOAP format. what format is Json,pox


In visual studio 2010 we have two ways to create Restful Services:

Start a WCF Service as usual and add Operation Contract as required

Additionally add Rest attribute that is web get /web invoke

System. Service model namespace & system. Service model. Web namespaces to be added.

Go to web.config and add End Points with WebHttpBinding only. 

This binding is enough for consuming and also hosting.


Go to service directive .svc file and add factory=”webservicehostfactory” attribute to this directive.



Difference between Web Services, WCF, WCF Rest

Web Service:
 It is based on SOAP and return data in XML form.
    It support only HTTP protocol.
   It is not open source but can be consumed by any client that understands XML.
It can be hosted only on IIS

WCF
It is also based on SOAP and return data in XML form.
It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.
The main issue with WCF is, its tedious and extensive          configuration.
It is not open source but can be consumed by any                client that understands XML.
     It can be hosted with in the application or on IIS or               using WINDOWS SERVICE. 

WCF REST

  To use WCF as WCF Rest service you have to enable webHttpBindings.
   It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.
  To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files
  Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified
  It support XML, JSON


Kubernetes

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