Thursday, August 13, 2020

Difference between Deferred execution and Immediate execution

August 13, 2020

 LINQ queries are always executed when the query variable is iterated over, not when the query variable is created. This is called deferred execution. You can also force a query to execute immediately, which is useful for caching query results.


There are two type of linq query execution are given below:

Deferred query execution

In deferred execution query is executed when the query variable is iterated by using loop.
Deferred execution enables multiple queries to be combined or queries to be extended. when a query is extended, it is modified to include the new operations, and the eventual execution will reflect the changes.

DataContext objcontext = new DataContext();
var query = from customer in objcontext.Customers
where customer.City == "Pune" select customer; // Query does not execute foreach (var Customer in query) // Query executes { Console.WriteLine(Customer.Name); }

Deferred execution provides the facility of query reusability since it always fetches the uploaded data from the data source which exists at the time of each execution.

Immediate Query Execution

In immediate execution query is executed at the point of its declaration. It is the query that return a singleton value are executed immediately. Some example of singleton queries are
Average, Count, First and Max . These execute immediately because the query must produce a sequence to calculate the singleton result.

DataContext objcontext = new DataContext();
var query = (from customer in objcontext .Customers
where customer.City == "Pune" select customer).Count(); // Query execute
Immediate execution does not provide the facility of query re-usability. you could also force execution by putting the foreach or For Each loop immediately after the query expression, but by calling ToList or ToArray you cache all the data in single collection object.





Friday, June 19, 2020

Populate dropdownlist using jquery

June 19, 2020


Step 1-

 Create the required tables and stored procedures

Table Script -

Create Table DepartmentTable
(
 Id int identity primary key,
 DepartmentName nvarchar(20)
)
Go

Insert into DepartmentTable values ('Science')
Insert into DepartmentTable values ('Arts')
Insert into DepartmentTable values ('Commerce')
Go

Stored Procedure -

CREATE PROCEDURE USP_GetDepartment
AS
BEGIN
 Select IdDepartmentName from DeparmentTable 
END
GO

Step 2-

Create new asp.net web application project. Name it JqueryDemo. 


Step 3-

Include a connection string in the web.config file to your database.
<add name="CS"
      connectionString="server=.;database=SampleDB;integrated security=SSPI"/>


Step 4-

Add a class file to the project. Name it Department.cs. Copy and paste the following code. 

namespace JqueryDemo
{
    public class Department
    {
        public int Id { getset; }
        public string DepartmentName getset; }
    }
}


Step 5-

Add a WebService (ASMX) to the project. Name it WebService.asmx. Copy and paste the following code. 

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;

namespace JqueryDemo
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class WebService: System.Web.Services.WebService
    {
        [WebMethod]
        public void GetDepartment()
        {
            string cs = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
            List<DepartmentDepartmentnew List<Department>();
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("USP_GetDepartment", con);
                cmd.CommandType = CommandType.StoredProcedure;
                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    Department ObjDepartment = new Department();
                    ObjDepartment.Id = Convert.ToInt32(rdr["Id"]);
                    ObjDepartment.Name = rdr["DepartmentName"].ToString();
                    Department.Add(ObjDepartment);
                }
            }
            JavaScriptSerializer js = new JavaScriptSerializer();
            Context.Response.Write(js.Serialize(Department));
        }


Step 6-

 Add a WebForm to the ASP.NET project. Copy and paste the following HTML and jQuery code. 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
  
    </style>
    <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var DDLDepartment = $('#DDLDepartment');
            $.ajax({
                url: 'WebService.asmx/GetDepartment',
                method: 'post',
                dataType: 'json',
                success: function (data) {
                    DDLDepartment.append($('<option/>', { value: -1, text: 'Select Department' }))
                    $(data).each(function (index, item) {
                        DDLDepartment.append($('<option/>', { value: item.Id, text: item.DepartmentName }));
                    });
                },
                error: function (err) {
                    alert(err);
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>

            <table align="center" style="width: 261px">
                <tr>
                    <td>
                        <asp:Label ID="lblDepartment" runat="server" Text="Department : "></asp:Label></td>
                    <td>
                        <asp:DropDownList ID="DDLDepartment" runat="server">
                        </asp:DropDownList></td>
                </tr>
            </table>

        </div>
    </form>
</body>
</html>

Saturday, June 6, 2020

How to Integrate AutoMapper in ASP.NET Core

June 06, 2020

What is AutoMapper ?


AutoMapper is a mapper between two objects, it means that AutoMapper is object-object mapper. It maps properties of two different Objects by transforming input object of one type to output object of another type.




Integrate AutoMapper-


Step 1-

Go to NuGet Package Manager and add package AutoMapper.Extensions.Microsoft.DependencyInjection 

Step 2-

Create two files Customer.cs and CustomerModel.cs and add two classes Customer,CustomerModel

public class Customer {  
    public int CustomerId { get; set; }  
    public string CompanyName { get; set; }  
    public string FirstName { get; set; }  
    public string MiddleName { get; set; }  
    public string LastName { get; set; }  
    public string Address { get; set; }  
    public string Phone { get; set; }  
    public string Country { get; set; }  
    public string City { get; set; }  
    public string Pincode { get; set; }  

public class CustomerModel {  
    public int CustomerId { get; set; }  
    public string FullName { get; set; }  
    public string Phone { get; set; }  
    public string Country { get; set; }  
    public string City { get; set; }  
    public string Pincode { get; set; }  
}  

Step 3-

Create Mapping profile as CustomerProfile.cs

public class CustomerProfile : Profile {  
    public CustomerProfile () {  
        // Mapping properties from Customer to CustomerModel  
        CreateMap<Customer, CustomerModel> ()  
            .ForMember (dest =>  
                dest.FullName,  
                opt => opt.MapFrom (src => src.FirstName + " " + src.MiddleName + " " + src.LastName));  
        // ForMember is used incase if any field doesn't match  
    }  
}  

Step 4-

To invoke mapped object in code

public class HomeController : Controller {  
    private readonly IMapper _mapper;  
    public HomeController (IMapper mapper) {  
        _mapper = mapper;  
    }  
    public IActionResult Index () {  
        Customer customerdetails = new Customer () {  
            CustomerId = 1,  
            CompanyName = "ABC",  
            Address = "Banaglore",  
            Phone = "000",  
            FirstName = "Shwetha",  
            MiddleName = "Amit",  
            LastName = "Naik",  
            City = "Bangalore",  
            Country = "India",  
            Pincode = "560091"  
        };  
        var customerModel = _mapper.Map<CustomerModel> (customerdetails);  
        var fullname = customerModel.FullName;  
        var address = customerModel.City;  
        return View ();  
    }  
}