AngularJS, ASP.Net MVC, JavaScript, jQuery, jQuery AJAX, MVC WebAPI

Add Request Header for REST API Calling with AngularJS & jQuery

In the Web World , We always call REST APIs from our Web Applications .

When We call REST APIs through jQuery or AngularJS , they added few default Request Headers .

But many a time , we need to pass Custom Request Headers for different purposes.

A Common scenario is for Authentication we need to pass Customer Request header .

But how we can add this ?

Lets see the below samples :::

for jQuery , we can easily add Request Headers when we do AJAX Calling .

$.ajax({
            type: "POST",
            url: '/api/test',
            data: myObj,
            headers: { 'Custom-Header': 'Value'},
            success: function (resp) {
                alert(resp);
            },
            error: function (x, y, z) {
                alert(x);
            }
        });

In AngularJS , If we use $http for REST API calling , we can add Request Header like below , after we create AngularJS Module , we can do :::

myModule.run(['$route', '$http', function ($route, $http) {
            $http.defaults.headers.common.CustomeHeader = 'Value';
        }]);

Thanks

Advertisements
Standard
AngularJS, ASP.Net MVC, jQuery AJAX, MVC WebAPI

Delete Functionality : REST API with AngularJS $resource and jQuery-Ajax

For every Web Application , an important feature is Delete Functionality . We can not think a single app without it . But we already know how to develop DELETE Functionality inside a Web App . Then why is this article for?

Well , that’s true . But now , we will see how we can develop DELETE Functionality with $resource of AngularJS and/or also with jQuery . and for both cases , we have a REST URL of the server which is doing the real back-end thing .

Lets jump…

First lets see the Server code of REST API Delete Functionality . Here I have used .Net WebAPI . And the Method looks like below :::

public HttpResponseMessage Delete(int id)
        {
            //Delete Related Logics + Data Access calling etc
            return Request.CreateResponse(HttpStatusCode.OK);
        }

Now lets see the client side function of DELETE which is using AngularJS $resource .

$scope.delete = function() {
        $resource('api/Ticket/:id').delete({ id: $scope.ticket.Id }, function (data) {
            alert('Succeeded');
        });
    };

We can do the same thing by jQuery also , if we do not use AngularJS . But after learning AngularJS , you will never use jQuery 🙂 For jQuery lovers , we can do this like below with jQuery Ajax:::

$scope.delete = function () {
        $.ajax({
            url: 'api/Ticket/' + $scope.ticket.Id,
            type: 'DELETE',
            success: function (data) {
                alert('Succeeded');
            },
            error: function (x, y, z) {
                alert('Failed');
            }
        });
    };

Well , Thanks . Hope , you liked it .If you do , please share / subscribe …

Cheers 🙂

Standard
ASP.Net, ASP.Net MVC, C#, EntityFramework

EntityFramework in C# – Part2 : Calling MS SQL StoredProcedure

While we use EntiryFramework as ORM , we can use/call MS SQL StoredProcedure in our C# code . EF allows us to import StoredProcedures into our C# app as Functions .

Now I am gonna show , how we can use SP in EF . To know basic EF,please refer to my another article EntityFramework in C# – Part1 : Welcome To EF

For this demo , I have a simple SP which will return the data from a table.

StoredProcedure for EF in C#

I will fill an ASP.Net Grid with that data , and I am gonna pull the data using EF .

For this, after taking the update of EDMX , I will get the StoredProcedure inside the EDMX , and will add a Function for that SP like below —

EF - Add Function Import

Click Add Function Import and then…

EntityFramework with StoredProcedure - Function Import

Our SP is now ready in our app as a Function and we can just call that function as usual as we do.So my C# code for calling the function is like below :::

ImportantDBEntities dbEntities = new ImportantDBEntities();
            
            //Execute stored procedure as a function
            var employees = dbEntities.GetEmployees();
            if (employees != null)
            {
                employeeGrid.DataSource = employees;
                employeeGrid.DataBind();
            }

So our Grid is ready with data 🙂

Cheers

Standard
ASP.Net, ASP.Net MVC, C#, EntityFramework

EntityFramework in C# – Part1 : Welcome To EF

Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.

I am gonna write an article on EF with an easy approach and i am trying to clearly show a CRUD application with EF .

For this example , I used one DB Table for simplicity . My DB is like below :::

Welcome to EntityFramework

Welcome to EntityFramework

To make the app simple , I took a ASP.Net Form Application which has a UI like below :::

Welcome to EntityFramework ASP.Net C# Web

The Markup code for my UI is like below :::

<h2>
        Welcome to EntityFramework!
    </h2>
  

  <table>
   <tr>
    <td>    
       Name
    </td>  
    <td>
    :
    </td>
    <td>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
    </td>
   </tr>
  

    <tr>
    <td>    
       Address
    </td>  
    <td>
    :
    </td>
    <td>
        <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox>
    </td>
   </tr>

    <tr>
    <td>    
       Salary
    </td>  
    <td>
    :
    </td>
    <td>
        <asp:TextBox ID="txtSalary" runat="server"></asp:TextBox>
    </td>
   </tr>

     <tr>
    <td>    
   
    </td>  
    <td></td>
   
    <td>
        <asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />
    </td>
   </tr>

  </table>

  <br />
       <asp:GridView ID="employeeGrid" runat="server">
    </asp:GridView>

<h1>Delete One Row By Id</h1>

  <table>
   <tr>
    <td>    
       Put Delete Id
    </td>  
    <td>
    :
    </td>
    <td>
        <asp:TextBox ID="txtDeleteId" runat="server"></asp:TextBox>
    </td>
    <td>
       <asp:Button ID="btnDelete" runat="server" Text="Delete"
            onclick="btnDelete_Click"  />
    </td>
   </tr>
  </table>

   <h1>Update Value By Id</h1>

  <table>
   <tr>
    <td>    
       Put Update Id
    </td>  
    <td>
    :
    </td>
    <td>
        <asp:TextBox ID="TxtUpdateId" runat="server"></asp:TextBox>
    </td>

     <td>    
       Put New Address
    </td>  
    <td>
    :
    </td>
    <td>
        <asp:TextBox ID="txtUpdateAddress" runat="server"></asp:TextBox>
    </td>

    <td>
       <asp:Button ID="btnUpdate" runat="server" Text="Update" onclick="btnUpdate_Click"
             />
    </td>
   </tr>
  </table>

I have Three buttons for CREATE , UPDATE , DELETE and have a method for READ .

Lets see CREATE first .

protected void btnSave_Click(object sender, EventArgs e)
        {
            ImportantDBEntities dbEntities = new ImportantDBEntities();            
            EF_Employee employee = new EF_Employee();
            employee.Name = txtName.Text;
            employee.Address = txtAddress.Text;
            employee.Salary = Convert.ToDecimal(txtSalary.Text) ;

            dbEntities.EF_Employee.AddObject(employee);
            dbEntities.SaveChanges();

            FillEmployeeGrid();
        }

Here ImportantDBEntities is my SQL Server DB Context as you saw the DB image that my DB name is ImportantDB.

And That FillEmployeeGrid() method is my READ method which will pull the data from DB table .

private void FillEmployeeGrid()
        {
            ImportantDBEntities dbEntities = new ImportantDBEntities();

            if (dbEntities.EF_Employee != null)
            {
                var employees = dbEntities.EF_Employee;
                employeeGrid.DataSource = employees;
                employeeGrid.DataBind();
            }
        }

We can also Delete a record of an ID.

protected void btnDelete_Click(object sender, EventArgs e)
        {
            int Id = Convert.ToInt32(txtDeleteId.Text);

            ImportantDBEntities dbEntities = new ImportantDBEntities();
            EF_Employee employee = dbEntities.EF_Employee.SingleOrDefault(i => i.Id == Id);
            dbEntities.EF_Employee.DeleteObject(employee);
            dbEntities.SaveChanges();

            FillEmployeeGrid();
        }

Update is also not a big deal .

protected void btnUpdate_Click(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(TxtUpdateId.Text);

            ImportantDBEntities dbEntities = new ImportantDBEntities();
            EF_Employee employee = dbEntities.EF_Employee.SingleOrDefault(i => i.Id == id);
            employee.Address = txtUpdateAddress.Text;
            dbEntities.SaveChanges();

            FillEmployeeGrid();
        }

Hope , it helps them who are new to EF .
I will write more deeper things related to EF in Part 2 .So keep an eye on my Site.

Till Then , Cheers …

Standard
ASP.Net, ASP.Net MVC, C#, EntityFramework, MVC WebAPI

Runtime error on REST WebAPI : failed to serialize the response body for content type ‘application/xml; charset=utf-8

In a Relational Database system , we may get this type of runtime error when calling WebAPI for a composite Object .

The exception looks like this :::

The ‘ObjectContent`1’ type failed to serialize the response body for content type ‘application/xml; charset=utf-8

We can solve this problem by adding the below lines in WebApiConfig.cs file under App_Start folder inside WebAPI project .

var json = config.Formatters.JsonFormatter;
            json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;

Will write few full step by step articles on EntityFramework and WebAPI on this blog , so Please Keep an eye on this Blog .

Thanks 🙂

Standard