Tuesday, August 21, 2012

Lazy loading with window scrolling


implmented lazy loading when the window is scolled .

here is the code :-

Javascript:


        $(document).ready(function () {

            function lastPostFunc() {
                $('#divPostsLoader').html('<img src="images/bigLoader.gif">');

                //send a query to server side to present new content
                $.ajax({
                    type: "POST",
                    url: "Default3.aspx/GetDataFromServer",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                       
                        if (data != "") {
                            $("#dd").html(data.d);
                        }
                        $('#divPostsLoader').empty();
                    }

                })
            };

            $(window).scroll(function () {
                if ($(window).scrollTop() == $(document).height() - $(window).height()) {
                    lastPostFunc();
               }
            });

        });


Code behind :


    static public int initialRecord = 2;
    static public int incrementRecord = 2;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            initialRecord = 2;
            ShowData();

        }
         
    }
  
    [WebMethod]
    public static string GetDataFromServer()
    {
        SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
        if (sqlConnection.State == ConnectionState.Closed)
        {
            sqlConnection.Open();
        }
        DataTable dt = new DataTable();

        using (SqlCommand sqlCommand = new SqlCommand("select Top(" + initialRecord + ") * from Image", sqlConnection))
        {

            SqlDataAdapter sqldataAdapter = new SqlDataAdapter(sqlCommand);
            sqldataAdapter.Fill(dt);
        }
        string str = "";
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            str += "<li><img src='image/MidleImages/" + dt.Rows[i]["image"] + "' width='580' height='360' alt='Grass Blades' /></li>";
        }
        initialRecord += 2;
        return str;
       

    }
    public void ShowData()
    {
        SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
        if (sqlConnection.State == ConnectionState.Closed)
        {
            sqlConnection.Open();
        }
        DataTable dt = new DataTable();

        using (SqlCommand sqlCommand = new SqlCommand("select Top(" + initialRecord + ") * from Image", sqlConnection))
        {

            SqlDataAdapter sqldataAdapter = new SqlDataAdapter(sqlCommand);
            sqldataAdapter.Fill(dt);
        }
        string str = "";
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            str += "<li><img src='image/MidleImages/" + dt.Rows[i]["image"] + "' width='580' height='360' alt='Grass Blades' /></li>";
        }
        initialRecord += 2;
        dd.InnerHtml = str;


    }


this will work ...........


LazyLoading in Entity Framework 4


LazyLoading in Entity Framework 4:-


1.  By default Lazy Loading is Enable in Entity Framework. When we are using EF and have       performance issues with their applications this is because number of queries that hit the database to return the data when lazy loading is enables.

Suppose if we have table country,state and city and we run this code on page load :-

      using(var ctx = new CompanyEmployeesEntities())        

{         
            
var query = testContext.tbCountries.Take(5);

            
foreach (var country in query)
            {
                Response.Write(
country.countryName);

                Response.Write(
"<br/>");

                
foreach (var State in country.tbStates)

                {
                    Response.Write(
State.StateName);
                    Response.Write(
"<br/>");
                }
            }

        }

Run your application and you will see that we get the country names and their associated State  names.in this multiple query are fired and compare country with states associated with it. This will cause  performance issues with in their applications.

2.     Turn-off Lazy Loading
We can turn off the lazy loading feature and fetch the related records in one query itself. This   process is termed as eager loading. To turn off Lazy Loading we can set LazyLoadingEnabledproperty of the ContextOptions on context to false.
      ctx.ContextOptions.LazyLoadingEnabled = false;
Now if we run the earlier code, we get the country names from table tbCountries. This is because only the first query is executed. Only You will not see the related entities (countryName) displayed on the screen
It is nice to have options. Use them carefully depending on the specific requirements of your application. 







Friday, August 10, 2012

Software Development Tips and Tricks & Tutorials

Software Development is the process of creating or developing a quality application which will help the business to grow.

Software development process includes the following steps.
  • Understanding the business or Domain : Now you may have a question that "Why should I know the business/domain?. As a programmer my job is only writing codes and developing the application. then why?". The answer is very simple, if you are aware on the domain, I would say it is definitely an added advantage to the software development process.
  • Understanding requirements: Understanding client requirement is one of the important factor in software development.
  • Design: Once we completed the requirement analysis, next we need to design the application. Mostly its done by creating a high level design document and low level design document.
  • Development: Develop the application based on the design document and functional requirement document. While do coding ensure all business validations and requirements are under coverage.
  • Testing: Testing is an investigation conducted to provide the information about the quality of the product/application.
  • Implementation: In this step, we will be deploying the final solution/application which is tested and completed on to the server. While deploying/releasing we will also develop a release document which will help the end user to deploy the application in their enviornment.
  • Maintanance: Maintanance is the modification of a software product after delivery to correct faults or to improve performance.
I hope now you are clear on the Software Development Life Cycle (SDLC) mentioned above. 

Here are some Tips and Tricks that might be improve the quality of software development
  • Love your profession
  • Simplify the complex logic by splitting.
  • Be an innovator and expert in technology
  • Be a good learner
  • Be aware of latest technologies
  • Learn the process
  • Minimum amount of sleep should be 6 hours
  • Be social
  • Enjoy holidays and free time
  • Involve in any games during work hours
  • Think positively.

Asp.net 4.5 framework New Features


Asynchronously Reading and Writing HTTP Requests and Responses

ASP.NET 4 introduced the ability to read an HTTP request entity as a stream using the HttpRequest.GetBufferlessInputStream method. This method provided streaming access to the request entity. However, it executed synchronously, which tied up a thread for the duration of a request.
ASP.NET 4.5 supports the ability to read streams asynchronously on an HTTP request entity, and the ability to flush asynchronously. ASP.NET 4.5 also gives you the ability to double-buffer an HTTP request entity, which provides easier integration with downstream HTTP handlers such as .aspx page handlers and ASP.NET MVC controllers.

Improvements to HttpRequest handling

The Stream reference returned by ASP.NET 4.5 fromHttpRequest.GetBufferlessInputStream supports both synchronous and asynchronous read methods. The Stream object returned from GetBufferlessInputStream now implements both the BeginRead and EndRead methods. The asynchronous Streammethods let you asynchronously read the request entity in chunks, while ASP.NET releases the current thread between each iteration of an asynchronous read loop.
ASP.NET 4.5 has also added a companion method for reading the request entity in a buffered way: HttpRequest.GetBufferedInputStream. This new overload works likeGetBufferlessInputStream, supporting both synchronous and asynchronous reads. However, as it reads, GetBufferedInputStream also copies the entity bytes into ASP.NET internal buffers so that downstream modules and handlers can still access the request entity. For example, if some upstream code in the pipeline has already read the request entity using GetBufferedInputStream, you can still useHttpRequest.Form or HttpRequest.Files.

Asynchronously flushing a response

Sending responses to an HTTP client can take considerable time when the client is far away or has a low-bandwidth connection. Normally ASP.NET buffers the response bytes as they are created by an application. ASP.NET then performs a single send operation of the accrued buffers at the very end of request processing.
If the buffered response is large (for example, streaming a large file to a client), you must periodically call HttpResponse.Flush to send buffered output to the client and keep memory usage under control. However, because Flush is a synchronous call, iteratively calling Flush still consumes a thread for the duration of potentially long-running requests.
ASP.NET 4.5 adds support for performing flushes asynchronously using theBeginFlush and EndFlush methods of the HttpResponse class. Using these methods, you can create asynchronous modules and asynchronous handlers that incrementally send data to a client without tying up operating-system threads. In betweenBeginFlush and EndFlush calls, ASP.NET releases the current thread. This substantially reduces the total number of active threads that are needed in order to support long-running HTTP downloads.

More features:

Support for await and Task-Based Asynchronous Modules and Handlers

New ASP.NET Request Validation Features

By default, ASP.NET performs request validation — it examines requests to look for markup or script in fields, headers, cookies, and so on. If any is detected, ASP.NET throws an exception. This acts as a first line of defense against potential cross-site scripting attacks.
ASP.NET 4.5 makes it easy to selectively read unvalidated request data. ASP.NET 4.5 also integrates the popular AntiXSS library, which was formerly an external library.
Developers have frequently asked for the ability to selectively turn off request validation for their applications. For example, if your application is forum software, you might want to allow users to submit HTML-formatted forum posts and comments, but still make sure that request validation is checking everything else.
ASP.NET 4.5 introduces two features that make it easy for you to selectively work with unvalidated input: deferred ("lazy") request validation and access to unvalidated request data.

Deferred ("lazy") request validation

In ASP.NET 4.5, by default all request data is subject to request validation. However, you can configure the application to defer request validation until you actually access request data. (This is sometimes referred to as lazy request validation, based on terms like lazy loading for certain data scenarios.) You can configure the application to use deferred validation in the Web.config file by setting the requestValidationMode attribute to 4.5 in the httpRUntime element, as in the following example:
<httpRuntime requestValidationMode="4.5" ... />
 

AntiXSS Library

Due to the popularity of the Microsoft AntiXSS Library, ASP.NET 4.5 now incorporates core encoding routines from version 4.0 of that library.

To do this, add the following attribute to the Web.config file: 
<httpRuntime ...
  encoderType="System.Web.Security.AntiXss.AntiXssEncoder,
System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
When the encoderType attribute is set to use the AntiXssEncoder type, all output encoding in ASP.NET automatically uses the new encoding routines.
  • Using multi-Core JIT compilation for faster startup

    If you want to disable this feature, make the following setting in the Web.config file:

    <configuration>
      
      <system.web>
       <compilation profileGuidedOptimizations="None"  />
    
         
     
  • Tuning garbage collection to optimize for memory 

            To enable GC memory tuning, add the following setting to the Windows\Microsoft.NET\Framework  \v4.0.30319\aspnet.config file:
<configuration>
<!-- ... -->
  <runtime>
    <performanceScenario value="HighDensityWebHosting"  />

Tuesday, August 7, 2012

paging from database


WITH PAGING AS(
 
  SELECT   ROW_NUMBER() OVER (ORDER BY  DATESENT DESC) AS SRNO, [LogID]
      ,[TemplateID]
      ,[MailFrom]
      ,[MailTo]
      ,[Subject]
      ,[IsAttachment]
      ,[MailStatus]
      ,[DateSent]
      ,[EmailContent]
  FROM tablename )
  )
  SELECT *,(SELECT COUNT(*) FROM PAGING) AS TotalRecords FROM PAGING AS  PG WHERE SrNo BETWEEN(@PageIndex- 1) * @PageSize +1 AND @PageIndex*@PageSize  
   

Sql Data Reader


SQL DATA READER:

Data Reader object allows you to perform forward only read only operations over the database. Data Reader is another connected class of Ado.net and is one of the two available data storages objects of Ado.net object model.



//Read the value of connectionstring form the 
web.config file and assign it to cnnstring variable.
cnnstring = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
//Initialize the connection object.
SqlConnection cnn = new SqlConnection(cnnstring);
//pass the sql query to retrieve the records.
SqlCommand cmd = new SqlCommand("select * from employeedetails", cnn);
cnn.Open();
//Initialize the data reader object.
SqlDataReader reader = cmd.ExecuteReader();
//Read the values and bind to the controls.
while (reader.Read())
    {
       txtemployeeid.Text = reader.GetInt32(0).ToString();
       txtempname.Text = reader.GetString(1);
       txtphoneno.Text = reader.GetString(2);
       txtaddress.Text = reader.GetString(3);
       txtdob.Text = reader.GetString(4);
    }
//finally close the reader and connection.
reader.Close();
cnn.Close();
Multiple Active Result Sets: 
Data Reader allows you to read the values in faster way, but if you are using multiple data reader objects then you will end up ‘invalidoperationexception’ error. In order to overcome this problem you can use MARS property of the data reader object. You need set ‘MultipleActiveResultSets = true’ in the connection string. ConnectionString:
<connectionStrings>
 <add name="cnn" connectionString="Data Source=.\SQLEXPRESS;
 AttachDbFilename=|DataDirectory|\Tutorial.mdf;Integrated Security=True;
 User Instance=True; MultipleActiveResultSets = True"/>
 </connectionStrings>
The following code explains about working with multiple active result sets. 
//Read the value of connectionstring form the web.config
file and assign it to cnnstring variable.
cnnstring = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
//Initialize the connection object.
SqlConnection cnn = new SqlConnection(cnnstring);
//pass the sql query to retrieve the records.
SqlCommand cmd = new SqlCommand("select * from employeedetails", cnn);
SqlCommand cd = new SqlCommand("select employeename from employeedetails" +
                         " where empolyeeid ='100' ", cnn);
cnn.Open();
//Initialize the data reader object.
SqlDataReader reader = cmd.ExecuteReader();
//Read the values and bind to the controls.
SqlDataReader empnamereader = cd.ExecuteReader();
    while (empnamereader.Read())
    {
      string employeename = empnamereader.GetString(0);
      Response.Write("<h1>Employee Name:" + employeename + "</h1>");
    }
    empnamereader.Close();
    while (reader.Read())
    {
        txtemployeeid.Text = reader.GetInt32(0).ToString();
        txtempname.Text = reader.GetString(1);
        txtphoneno.Text = reader.GetString(2);
        txtaddress.Text = reader.GetString(3);
        txtdob.Text = reader.GetString(4);
    }
//finally close the reader and connection.
reader.Close();
cnn.Close();

Sql Command


SQL COMMAND:

Sql Command is a connected class of Ado.Net Object model. Sql Command Class is used to perform various database operations over a given connection object (Sql server Database). Sql Command Class is used to perform both synchronous and asynchronous operations. The available methods and properties of Command Object allow you to execute a Sql query or stored procedure.

Synchronous Operation:

ExecuteNonQuery: 
ExecuteNonQuery method of command object allows performing insert, deleting or updating the records in the database. The following steps are involved to execute a Command Object:
  1. Initialize the SqlConnection object with the connection string.
  2. Initialize the SqlCommand object and use the connection property and command text property.
  3. Open the connection and use the ExecuteNonQuery method of Command Object to execute the query and then close the connection.
To demonstrate the command object methods, consider a sample Employee Details Table. Open Visual Studio and create a Windows Form Application Project, give it a name and save the application.
Drag and drop five label and five textbox controls to the form and change the properties of the controls. Change the Text Property of all label controls to Employee ID, Employee Name, Employee Phone no, Employee Address and Employee DOB respectively. Now change the Name Property of all the textbox controls to txtemployeeid, txtemployeename, txtphoneno, txtemployeeaddress and txtemployeedob respectively.
The following query is used to design the Table in the Sql server database.
Create database demo
Create table EmployeeDetails
 create database Demo
 use demo
 create table employeedetails
 (
  EmpolyeeID int identity primary key,
  EmployeeName varchar(235),
  EmployeePhoneNO varchar(235),
  EmployeeAddress varchar(235),
  EmployeeDOB varchar(235),
 ) 
Method 1: Using Properties (Command Text, Command Type and Connection): 
The following code snippet shows u the usage of the default constructor to execute the sql query statement. The following query is used to insert the record(s) to the database using the above said properties. 
 //Read the value of connectionstring form the web.config file
 and assign it to cnnstring variable.
 cnnstring = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
 SqlConnection cnn = new SqlConnection();
 //connection properties.
 cnn.ConnectionString = cnnstring;
 SqlCommand cmd = new SqlCommand();
 cmdtext = "Insert into employeedetails values('" + txtemployeeid.Text +
    "','" + txtempname.Text + "','" + txtphoneno.Text + "','" 
 + txtaddress.Text + "','" +          txtdob.Text + "')";
 //cmd text and cmd connection properties.
 cmd.CommandText = cmdtext;
 cmd.Connection = cnn;
 // Open the connection and execute the query and then close the connection.
 cnn.Open();
 cmd.ExecuteNonQuery();
 cnn.Close();
Method 2: Constructor with parameters. 
The following code explains the constructor which takes “sql query statement” as parameter. 
 cnnstring = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
 SqlConnection cnn = new SqlConnection(cnnstring);
 cmdtext = "Insert into employeedetails values('" + txtemployeeid.Text + 
      "','" +txtempname.Text + "','" +txtphoneno.Text + 
            "','"+ txtaddress.Text + "','" +txtdob.Text + "')";
 SqlCommand cmd = new SqlCommand(cmdtext);
 cmd.Connection = cnn;
 cnn.Open();
 cmd.ExecuteNonQuery();
 cnn.Close();
Method3: Using SqlParameters: 
In the above example we have directly the textbox properties in the sql query, the Command object allows us to embed these values by using the properties. The following code uses the third constructor from the above table which takes string and connection as parameters.
 cnnstring = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
 SqlConnection cnn = new SqlConnection(cnnstring);
 SqlCommand cmd = new SqlCommand("insert into employeedetails values 
                  (@empid,@empname,@phoneno,@address,@dob)", cnn);
 cnn.Open();
 cmd.Parameters.Add(new SqlParameter("@empid", txtempid.Text));
 cmd.Parameters.Add(new SqlParameter("@empname", txtempname.Text));
 cmd.Parameters.Add(new SqlParameter("@phoneno", txtphoneno.Text));
 cmd.Parameters.Add(new SqlParameter("@dob", txtdob.Text));
 cmd.Parameters.Add(new SqlParameter("@address", txtaddress.Text));
 cmd.ExecuteNonQuery();
 cnn.Close();
ExecuteScalar: 
Execute Scalar method is used to retrieve a single value from the table. It returns the first column of the first row value in the result set. 
The following code demonstrates the use of Execute Scalar Method:
 cnnstring = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
        SqlConnection cnn = new SqlConnection(cnnstring);
        SqlCommand cmd = new SqlCommand("select employeename from employeedetails "+
   "where empolyeeid ='100' ", cnn);
        cnn.Open();
        cmd.ExecuteNonQuery();
        Response.Write("EmployeeName:" + cmd.ExecuteScalar() + "");
        cnn.Close();

Asynchronous Operations:

BeginExecuteNonQuery and EndExecuteNonQuery: 
BeginExecuteNonQuery Method initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by the SqlCommand. (Reference: MSDN library).
cnnstring = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlConnection cnn = new SqlConnection(cnnstring);
SqlCommand cmd = new SqlCommand("Insert into employeedetails 
     values('"+txtemployeeid.Text +
     "','" +txtempname.Text + "','" + txtphoneno.Text + 
     "','"+txtaddress.Text + "','" + txtdob.Text + "')",
     cnn);
IAsyncResult result = cmd.BeginExecuteNonQuery();
cmd.EndExecuteNonQuery(result);
cnn.Close();

Hide/Show a Div using Java Script


The following code is used to show/hide a div using JavaScript:

function toggle() {
            var x = document.getElementById('id');
            if (x.style.display == "none") {
                x.style.display = "block";
            }
            else {
                x.style.display = "none";
            }
}

Javascript Tabs


The following Code is used to develop a Simple Tabbed Navigation Using Javascript:


       var tabs = ["tab1""tab2""tab3"];
       function showtab(e) {
            for (var i = 0; i < 3; i++) {
                    hide(tabs[i]);
            }
            for (var i = 0; i < 3; i++) {
                if (e == i) {
                    toggle(tabs[e]);
                }
            }
        }
       function toggle(e) {
            var x = document.getElementById(e);
            if (x.style.display == "none") {
                x.style.display = "block";
            }
            else {
                x.style.display = "none";
            }
       }
       function hide(e) {
            var x = document.getElementById(e);
            x.style.display = "none";
       }

The HTML Code is as shown below: 


    <div>
    <a href ="#" onclick ="showtab(0)">Tab1a>
    <a href ="#" onclick ="showtab(1)">Tab2a>
    <a href ="#" onclick ="showtab(2)">Tab3a>
    div>
    <table>
    <tr>
    <td><div id ="tab1" style ="display:block">hello World this is div1.div>td>
    <td><div id ="tab2" style ="display:none">hello World this is div2.div>td>
    <td><div id ="tab3" style ="display:none">hello World this is div3.div>td>
    tr>
    table>