ASP.Net MVC, 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 MVC, 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 MVC, 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
Uncategorized

Bind C# List of object data with HTML without using ASP.Net control in ASP.Net

In ASP.Net we always use so may ASP.Net controls . But we also know ASP.Net controls have ViewState , so we should ignore using ASP.Net controls as much as possible to reduce the Load time of DOM .

In my example , I will show how we can bind and show the data to HTML without using ASP.Net Control in ASP.Net.

I have a List of a custom object like below :

protected List<voNote> notes = new List<voNote>();

This is a list of a ViewModel . and the ViewModel of my example is like below :::

public class voNote
    {
        public string Note { get; set; }

        public DateTime Date { get; set; }

        public string NoteCreatedBy { get; set; }

        public string TicketUrgency { get; set; }
    }

Let, We have populated the List from Database Server . Now we have to show/Bind the Data to the UI .

So my markup code will be just simple like below :

<%
        foreach (voNote note in notes)
        {
    %>
            <hr class="NoteBorder" />
            <div><%=note.Date %> | <%=note.NoteCreatedBy %> | <%= note.TicketUrgency %></div>
           
            <div class="NoteDiv"><%=note.Note %></div>
    <%
        }
    
    %>

So , its done 🙂

Standard
JavaScript

Show JavaScript Confirmation message while deleting ASP.Net Grid Row

Many a time , we need a confirmation Message on deleting ASP.Net Gird Row . Coz if any User mistakenly clicks the delete button , the data will be gone . So its always the Best to use Confirmation on Deleting .

We will see a demo now how to Show JavaScript/Client Side Confirmation Msg while deleting an ASP.Net Grid Row .

A long time ago ,I had to use more brain processing power to do this requirement 🙂 So I thought to share with all .

Lets see the below image for what I am gonna do :

Show JavaScript Confirmation message while deleting  ASP.Net Grid Row

Show JavaScript Confirmation message while deleting ASP.Net Grid Row

Add this markup inside your ASP.Net Grid .

<asp:TemplateField HeaderText="" ShowHeader="False" HeaderStyle-HorizontalAlign="Left">
                            <ItemTemplate>      
                                      <asp:LinkButton ID="lnkDelete" runat="server" CausesValidation="False" CommandName="Delete"
                                    Text="Delete" OnClientClick="ConfirmDelete(this.id)" ></asp:LinkButton>
                            </ItemTemplate>
                            <HeaderStyle HorizontalAlign="Left" />
                      </asp:TemplateField>

And the JavaScript method implementation of the ConfirmDelete(this.id) is like below –

function ConfirmDelete(RowId)
     {
         var rowNoStr = RowId.split('_');
         rowNo = parseInt(rowNoStr[3]) + 1;              
    
         var confirm_value = document.createElement("INPUT");
         confirm_value.type = "hidden";
         confirm_value.name = "confirm_value";

         var grid = document.getElementById('<%=gvTicketDetails.ClientID%>');

         var delText = "Are you sure to delete - ";
         var ticketNo ="Tk " + grid.rows[rowNo].cells[0].innerText + " : ";
         var ticketTitle = grid.rows[rowNo].cells[1].innerText + " ?";
         var delMsg = delText.concat(ticketNo, ticketTitle);

         var answer = confirm(delMsg);
         if (answer)
         {
             confirm_value.value = "Yes";
         }
         else
         {
             confirm_value.value = "No";
         }
         document.forms[0].appendChild(confirm_value);       
     }

And now using the below code , you can easily get the confirmation value at server side .

protected void gvTicketDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string confirmValue = Request.Form["confirm_value"];
            if (confirmValue.ToUpper() == "YES")
            {
                
            }
        }

You are done 🙂 Cheers

Standard
Cross Domain, jQuery, jQuery AJAX

Using CORS in ASP.NET MVC Web API

Cross-site HTTP requests are HTTP requests for resources from a different domain than the domain of the resource making the request. For instance, a resource loaded from Domain A (http://domaina.example) such as an HTML web page, makes a request for a resource on Domain B (http://domainb.foo), such as an image, using the img element (http://domainb.foo/image.jpg). This occurs very commonly on the web today — pages load a number of resources in a cross-site manner, including CSS stylesheets, images and scripts, and other resources.

As an example –
If my Server is in http://www.shahjada.com and my client (which is hosted at http://www.shahjada-talukdar.com) calls that Server with an AJAX GET , it will give an error for Cross Domain Issue .

If the Client and Server is in the same server but in different port , It will also give Cross Domain error . Only if Client and Server are in same Address , it will work nicely.

Suppose , My ASP.net MVC WebAPI is hosted at http://www.shahjada-talukdar.com and my client is in http://www.shahjada.com , It will throw the error .
We can fix this issue by Using Cross Origin Resource Sharing (CORS) in ASP.NET Web API Server .

For that , We can create a CORS handler and add that handler to GlobalCOnfiguration’s MessageHandler .
My Cors handler is something like this :

public class CorsHandler : DelegatingHandler
    {
        const string Origin = "Origin";
        const string AccessControlRequestMethod = "Access-Control-Request-Method";
        const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
        const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
        const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
        const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            bool isCorsRequest = request.Headers.Contains(Origin);
            bool isPreflightRequest = request.Method == HttpMethod.Options;
            if (isCorsRequest)
            {
                if (isPreflightRequest)
                {
                    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                    response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());

                    string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
                    if (accessControlRequestMethod != null)
                    {
                        response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
                    }

                    string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
                    if (!string.IsNullOrEmpty(requestedHeaders))
                    {
                        response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
                    }

                    TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
                    tcs.SetResult(response);
                    return tcs.Task;
                }
                else
                {
                    return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(t =>
                    {
                        HttpResponseMessage resp = t.Result;
                        resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
                        return resp;
                    });
                }
            }
            else
            {
                return base.SendAsync(request, cancellationToken);
            }
        }
    }

Now Add that to Global.asax.cs like below :

GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());

Now our Server is ready to handle any Cross Domain Client’s Call .

Cheers 🙂

Standard
Uncategorized

Create a Custom GroupBox for selecting multiple choice in ASP.Net and C#

Many a time , We need to create a control for selecting Multiple Inputs in our Web Applications .

I am gonna show a demo how we can create a GroupBox type thing to select multiple items and Get those values in server side .

Lets see an example …

First see the image below :

Custom GroupBox for selecting multiple choice in ASP.Net and C#

Custom GroupBox for selecting multiple choice in ASP.Net and C#

If our requirement is like – User wants to see the report for all the Tasks which are in Open and Close Status.
So User can easily select multiple options .

So Here is my mark up code below :::

<asp:GridView ID="gridTicketStatus" runat="server" AutoGenerateColumns="false">
                <Columns>
                    <asp:TemplateField HeaderText="">
                        <ItemTemplate>
                            <asp:CheckBox ID="selectCheckBox" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Id" Visible="false">
                        <ItemTemplate>
                            <asp:Label ID="lblStatusId" runat="server" Text='<%#Bind("ID") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Select Status">
                        <ItemTemplate>
                            <asp:Label ID="lblTaskStatus" runat="server" Text='<%#Bind("TaskStatus") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>

Here I used a ASP.Net Grid which gets the status from the Database and Binds the Status.And I used another CheckBox , that’s how we can create any custom control . If we also need any DropDown inside it, we can easily add the DropDown with it as same way .

The Grid binding code in C# is like :::

DataTable dtStatus = TaskStatusGateway.GetAllTaskStatuses();
            gridTicketStatus.DataSource = dtStatus;
            gridTicketStatus.DataBind();

And after clicking the Button we can easily get all the selected Statuses by doing like below.

List<int> checkedStatus = new List<int>();

            if (gridTicketStatus.Rows.Count > 0)
            {
                for (int i = 0; i < gridTicketStatus.Rows.Count; i++)
                {
                    if (((CheckBox) (gridTicketStatus.Rows[i].FindControl("selectCheckBox"))).Checked)
                    {
                        int id = Convert.ToInt32(((Label) gridTicketStatus.Rows[i].FindControl("lblStatusId")).Text);
                        checkedStatus.Add(id);
                    }
                }
            }

So we are done .

Cheers 🙂

Standard
JavaScript, jQuery, jQuery AJAX

How to Call ASMX WebService using HTTP GET with jQuery AJAX

By Default , WebMethod of ASMX is not allowed to be called using HTTP GET . So we will see a short demo here . Our HTML Markup of the aspx page is :

<asp:DropDownList ID="DropDownList2" runat="server" Width="150">
           <asp:ListItem Text="Select" Value="-1" />
        </asp:DropDownList>

We will fill this DropDown By calling ASMX Service’s WebMethod using HTTP GET with jQuery Ajax . My Client Code is like below :::

var DropDownList2 = $("#<%= DropDownList2.ClientID %>");
         

         $.ajax({
                type: "GET",
                url:"<%=ResolveUrl("~/MyWebService.asmx") %>/GetAllProjectName",
                data:"{}",
                contentType:"application/json; charset=utf-8",
                dataType:"json",
                success: function(response){
                        var projects = response.d;
                        $.each(projects,function(index,project){
                            DropDownList2.append('<option value="'+ project.ProjectId +'" >' + project.ProjectName + '</option>');                        
                        });
                 }
         });

My Server side code of the WebService is :::

[WebMethod]
         [ScriptMethod(UseHttpGet = true)]
         public List<ProjectOfEmployee> GetAllProjectName()
         {
             return GetProjectName();   
         }

Remember to add the below part of course

[ScriptMethod(UseHttpGet = true)]

Otherwise , It will give 500 Internal Server Error .

So now you are done 🙂 Cheers

Standard
JavaScript, jQuery, jQuery AJAX

jQuery Ajax in Action with ASP.Net aspx Page

Most of the time , We call our custom WebServices/REST Services/Third Party REST APIs from any jQuery AJAX based HTTP Verb . But we can also call direct ASP.Net Form Page( which is aspx page ) using jQuery AJAX .

Here is how we can call ASPX page from another ASPX page’s AJAX Method.

For this example , I have used two ASPX page –

1.AjaxCheckPage.aspx ::: From this page I am gonna call another ASPX Page
2.jQueryAjaxData.aspx ::: This Page will be called by jQuery AJAX

HTML Markup of my AjaxCheckPage.aspx is like below :

<input type="button" id="ajaxButton" value="Load Data using jQuery Ajax" />   

     <div id="divResult"></div>

Ajax calling code of this Page is —

    <script language="javascript" type="text/javascript">

        $("#ajaxButton").click(function () {

            $.ajax({

                type: "POST",
                url: "jQueryAjaxData.aspx",
                data: "a=2&b=3",
                success: function (data) {
                    $("#divResult").text(data);
                }

            });

        });
    
    </script>

So Now , am doing like – If any Data comes from jQueryAjaxData.aspx , that means after successful , am binding the data to the DIV :

Now lets go another Page jQueryAjaxData.aspx from which the Data is gonna come .

protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Form["a"] != null && Request.Form["b"] != null)
            {
                int a = int.Parse(Request.Form["a"]);
                int b = int.Parse(Request.Form["b"]);
                int sum = a + b;
                
                Response.Write("The Sum is : " + sum);
            }
        }

jQuery Ajax in Action with ASP.Net aspx Page

jQuery Ajax in Action with ASP.Net aspx Page

So you can see , when I click the button then It request a POST to jQueryAjaxData.aspx page and am also passing Form Data as you can see it inside the picture above .

So , this is how , we can call ASPX page from jQuery AJAX POST .

Cheers 🙂

Standard
Uncategorized

Get Identity Column Value just after Inserting a row in MS SQL Server Table

Many a time , We need to get the auto Incremented Identity Column value just after Inserting/Saving a row to a Table in MS SQL Server.

In my Case of this Example, When I Insert a New Project to my tblProjects Table , I want the ID column value( which is basically auto incremented Identity Column in SQL Server) of my inserted Row .

For this , TSQL provides us a way to do that like below –

SELECT SCOPE_IDENTITY()

So in C# , our code can be like below :::

Note : We can use StoredProcedue Which is better practice .Then inside the SP ,we will use the code mentioned.

public static int CreateProject(Project projectObj)
        {
            string insertProjectQuery = "INSERT INTO tblProjects VALUES('" + projectObj.ProjectName + "','" + projectObj.TblCustomerId + "','" + projectObj.BClosed + "') SELECT SCOPE_IDENTITY() As ProjectId";
            DataTable dt = QueryGateway.GetDataThroughDataTable(insertProjectQuery);
            return  Convert.ToInt32(dt.Rows[0]["ProjectId"]);
        }

Cheers

Standard