What are the Characteristics of the Object-Oriented Approach?


Following are the characteristics of the Object-Oriented Approach:

  • Realistic Modeling
       


The Object-Oriented approach allows you to identify entities as objects having attributes and behavior. Attributes and behavior typically dipct how the object acts and reacts. For example, the car is an object belonging to the class Vehicle. The car has attributes such as speed, color, and power. It displays behavior such as being stationary, moving slowly, or accelerating.

  • Reusability


          In programming word, using existing classes or objects form other application saves resources spent in recreating the classes from scratch. The process of creating a new class by adding some features to an existing class is known as inheritance. The benefit of reputability translates to savings in time and effort, which in turn results in cost benefits.

  • Resilience to Change
          In the object-oriented system, this requirement does not mean that the new car needs to be built from scratch. The new features can be easily incorporated in the old system without modifying the base attributes.

          Resilience to change also results in easier maintenance. This feature of object-oriented methodology is known as extensibility. The ability of a class to inherit features from another class also makes object-oriented programs more extensible. For the same reason, even during construction, parts of the system under development can be refined without any major changes to other parts.

  • Existence as Different Forms
          Using the object-oriented approach, objects can be made to respond differently to the same message. the response is decided based on the information or parameters provided with the message. This ability to react differently based on the information associated with the message is known as polymorphisum.


What are the new features of C# 6.0?


C# 6.0 is the latest version which ships with Visual Studio 2015. You to start learning the new features to update yourselves for many different reasons. C# 6.0 is not yet completed and Microsoft is releasing few features now and then. For interview point of view, just mentioned the following items and you should be satisfying the interviewer question.

Following are few features of C# 6.0

1. $ sign

The purpose for it is to simplify string based indexing. Its not some thing like current dynamic features of  C# since it internally uses regular indexing functionality. To understand lets consider following example:

  var col = new Dictionary()
            {
                // using inside the intializer
                $first = "Hassan"
            };

   //Assign value to member

   //the old way:
   col["first"] = "Hassan";
 
   // the new way
   col.$first = "Hassan";

2. Exception filters:

Exception filters are already supported in VB compiler but now they are coming into C#. exception filters lets you specify a condition for a catch block. the catch block gets executed only if the condition is satisfied, this one is my favorite feature, so let's look at an example:

            try
            {
                throw new Exception("Me");
            }
            catch (Exception ex) if (ex.Message == "You")
            {
                // this one will not execute.
            }
            catch (Exception ex) if (ex.Message == "Me")
            {
                // this one will execute
            }

3. await in catch and finally block:

As far as I know, no one know why in C# 5 using await keyword in catch and finally block was not available, any way its now possible to use though. this is great because often we want to perform I/O operation in order to log the exception reason in catch block or such things in finally block and they Need asynchrony.

            try
            {
                DoSomething();
            }
            catch (Exception)
            {
                await LogService.LogAsync(ex);
            }

4. Declaration expressions

This feature simply allows you to declare local variable in the middle of an expression. It is as simple as that but really destroys a pain. I have been doing a lot of asp.net web form projects in the past and this was my every day code:

long id;
if (!long.TryParse(Request.QureyString["Id"], out id))
{ }
which can be improved to this:
Hide   Copy Code
if (!long.TryParse(Request.QureyString["Id"], out long id))
{ }

The scoping rules for this kind of declaration is same as general scoping rules in C#.

5. using Static

This feature allows you to specify a particular type in a using statement after that all static members of that type will be accessible is subsequent code.

using System.Console;

namespace ConsoleApplication10
{
    class Program
    {
        static void Main(string[] args)
        {
            //Use writeLine method of Console class
            //Without specifying the class name
            WriteLine("Hellow World");
        }
    }
}

6. Auto property initializer:

With C# 6 initialize auto properties just like a field at declaration place. The only thing to notice here is that this initialization dose not cause the setter function to be invoked internally. the value of backing field is set directly. so here is an example:

public class Person
    {
        // You can use this feature on both
        //getter only and setter / getter only properties

        public string FirstName { get; set; } = "Hassan";
        public string LastName { get; } = "Hashemi";
    }

7. Primary Constructor:

The main purpose for it is using constructor parameters for initialization. When declaring a primary constructor all other constructors must call the primary constructor using :this().
here is an example finally:

    //this is the primary constructor:
    class Person(string firstName, string lastName)
    {
        public string FirstName { get; set; } = firstName;
        public string LastName  { get; } = lastName;
    }

notice that declaration of primary constructor is at the top of the class.

8- Dictionary Initializer:

Some people believed that the old way of initiailzing dictionaries was dirty so the C# team dicided to make it cleaner, thanks to them. here is an example of the old way and new way:


            // the old way of initializing a dictionary
            Dictionary oldWay = new Dictionary()
            {
                { "Afghanistan", "Kabul" },
                { "United States", "Washington" },
                { "Some Country", "Some Capital city" }
            };

            // new way of initializing a dictionary
            Dictionary newWay = new Dictionary()
            {
                // Look at this!
                ["Afghanistan"] = "Kabul",
                ["Iran"] = "Tehran",
                ["India"] = "Delhi"
            };

Note: To play around and know more about C# 6.0 download Visual Studio 2015 click here

Confirmation dialog box in Code Behind using C#( C-Sharp ) in ASP.NET


You can call a confirmation dialog box from code behind using c#. Copy follow the code in respective files.

Copy this is HTML

<p>
        <asp:Button id="btnSave" runat="server" Text="Save and Update 'RFFM'" OnClientClick="return UpdateRFFM();" />
    </p>

Copy this in C# code behind.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Text;
using ADI.Web;

namespace SIS
{
    public partial class update_sis : System.Web.UI.Page
    {
        SqlCommand cmd;
        SqlParameter pm;
        string strForm = "";
        StringBuilder sb;
        string strError = "";
        int UpdateStatus = -1;
        string strEmailTemplate = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentType = "text/plain";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            if (Request["form_name"] == null)
            {
                Response.Write("");
                Response.End();
            }
            strForm = Utils.ToStringNullSafe(Request["form_name"]);
            sb = new StringBuilder();

            if (Session["ApplicationId"] == null)
            {
                Response.Write("Bad Request...");
                Response.End();
            }

            int ApplicationId = int.Parse(Session["ApplicationId"].ToString());

            switch (strForm)
            {
                case "rffm_create_user":
                    if (Session["email"] == null)
                    {
                        Response.Write("Bad Request");
                        Response.End();
                    }
                    Session["errmsg"] = "";
                    try
                    {
                        cmd = new SqlCommand("usp_SIS_PutUser");

                        // output parameter
                        pm = new SqlParameter("@UpdateStatus", SqlDbType.Int);
                        pm.Direction = ParameterDirection.Output;
                        cmd.Parameters.Add(pm);

                        // input parameters
                        cmd.Parameters.Add("Id", SqlDbType.Int).Value = 0;
                        cmd.Parameters.Add("@UserName", SqlDbType.VarChar, 50).Value = Session["Email"].ToString();

                        string strPassword = System.Guid.NewGuid().ToString().Substring(0, 8);
                        
                        cmd.Parameters.Add("@Password", SqlDbType.VarChar, 50).Value = Utils.base64Encode(strPassword);
                        cmd.Parameters.Add("@Active", SqlDbType.Bit).Value = false;
                        int ClubId = int.Parse(Session["ClubId"].ToString());
                        if (ClubId > 0)
                        {
                            cmd.Parameters.Add("@Group_Id", SqlDbType.Int).Value = 31;
                            cmd.Parameters.Add("@Club_Id", SqlDbType.Int).Value = ClubId;
                            cmd.Parameters.Add("@NonClub_Id", SqlDbType.Int).Value = (object)DBNull.Value;
                        }
                        else
                        {
                            cmd.Parameters.Add("@Group_Id", SqlDbType.Int).Value = 32;
                            cmd.Parameters.Add("@Club_Id", SqlDbType.Int).Value = (object)DBNull.Value;
                            cmd.Parameters.Add("@NonClub_Id", SqlDbType.Int).Value = int.Parse(Session["Non_ClubId"].ToString());
                        }

                        Utils.executeSP(cmd);
                        Session.Remove("emil");
                        strError = "";

                        if (Session["errmsg"].ToString() != "") 
                            strError = "-1" + Session["errmsg"].ToString();

                        if (strError == "")
                        {
                            int UpdateStatus = int.Parse(cmd.Parameters["@UpdateStatus"].Value.ToString());
                            if (UpdateStatus < 0)
                                strError = "-1There was a problem when creating new user. Please contact Admin";
                            else
                            {
                                // send email
                                strEmailTemplate = Utils.ReadTemplate("newuser.txt");
                                strError = "00" + SIS_Site.SendEmail(UpdateStatus, strEmailTemplate);
                            }
                        }
                    } catch (Exception ex) {
                        strError = "-1" + ex.Message;
                    }
                    break;
                case "rffm_SendVerificationEmail":
                    // send email
                    if (Session["UserId"] == null)
                    {
                        Response.Write("Bad Request");
                        Response.End();
                    }
                    strError = "";
                    strEmailTemplate = Utils.ReadTemplate("newuser.txt");
                     strError = "00" + SIS_Site.SendEmail(int.Parse(Session["UserId"].ToString()), strEmailTemplate);
                    Session.Remove("UserId");
                    break;
                case "rffm_UserSetupVerify":
                    strError = "";
                    try
                    {
                        cmd = new SqlCommand("usp_SIS_UserSetupVerify");

                        // output parameter
                        pm = new SqlParameter("@UpdateStatus", SqlDbType.Int);
                        pm.Direction = ParameterDirection.Output;
                        cmd.Parameters.Add(pm);

                        SqlParameter pm2 = new SqlParameter("@EMail", SqlDbType.VarChar, 500);
                        pm2.Direction = ParameterDirection.Output;
                        cmd.Parameters.Add(pm2);

                        SqlParameter pm3 = new SqlParameter("@Updatetext", SqlDbType.VarChar, 200);
                        pm3.Direction = ParameterDirection.Output;
                        cmd.Parameters.Add(pm3);

                        SqlParameter pm4 = new SqlParameter("@UserId", SqlDbType.Int);
                        pm4.Direction = ParameterDirection.Output;
                        cmd.Parameters.Add(pm4);

                        // input parameters
                        cmd.Parameters.Add("@ApplicationId", SqlDbType.Int).Value = ApplicationId;

                        Utils.executeSP(cmd);

                        if (Session["errmsg"] != null)
                            strError = Session["errmsg"].ToString();

                        if (strError == "")
                        {
                            UpdateStatus = int.Parse(cmd.Parameters["@UpdateStatus"].Value.ToString());
                            if (UpdateStatus < 0)
                                strError = "There was an error when processing your request";
                        }

                        Session["email"] = cmd.Parameters["@EMail"].Value.ToString();
                        Session["UserId"] = cmd.Parameters["@UserId"].Value.ToString();
                        Session["Updatetext"] = cmd.Parameters["@Updatetext"].Value.ToString();

                        switch (UpdateStatus)
                        {
                           case 1:
                                strError = "1";
                                break;
                            case 2:
                                strError = "2";
                                break;
                            case 3:
                                strError = "3";
                                break;
                            case 4:
                                strError = Session["Updatetext"].ToString();
                                break;
                            case 5:
                                strError = "5" + Session["Updatetext"].ToString();
                                break;
                            default:
                                break;
                        }
                    }
                    catch (Exception ex)
                    {
                        strError = ex.Message;
                    }
                    break;

                case "rffm":
                    Session["current_tab"] = "rffm";
                    try
                    {
                        cmd = new SqlCommand("usp_SIS_PutProjectProfile");

                        // output parameter
                        pm = new SqlParameter("@UpdateStatus", SqlDbType.Int);
                        pm.Direction = ParameterDirection.Output;
                        cmd.Parameters.Add(pm);

                        // input parameters
                        cmd.Parameters.Add("@ApplicationId", SqlDbType.Int).Value = ApplicationId;
                        cmd.Parameters.Add("@LastSavedBy", SqlDbType.VarChar, 50).Value = Session["user"].ToString();

                        cmd.Parameters.Add("@FeasibilityStudyDocument", SqlDbType.VarChar, 8000).Value = Request["FeasibilityStudy"];
                        cmd.Parameters.Add("@PlanningPermissionNotRequired", SqlDbType.VarChar, 8000).Value = Request["PlanningPermissionNotRequired"];
                        cmd.Parameters.Add("@Sustainable", SqlDbType.VarChar, 8000).Value = Request["Sustainable"];

                        string strRDMRecommendation = Request["RDMRecommendation"];
                        cmd.Parameters.Add("@RDMRecommendation", SqlDbType.VarChar, 8000).Value = (strRDMRecommendation == null) ? (object)DBNull.Value : strRDMRecommendation;

                        cmd.Parameters.Add("@Risk", SqlDbType.VarChar, 10).Value = Request["Risk"];
                        cmd.Parameters.Add("@Region", SqlDbType.VarChar, 50).Value = Request["Region"];
                        cmd.Parameters.Add("@RDMName", SqlDbType.VarChar, 50).Value = Session["user"].ToString();
                        cmd.Parameters.Add("@RDMReviewDate", SqlDbType.DateTime).Value = DateTime.Now;
                        cmd.Parameters.Add("@DesignAndPlanningPermission", SqlDbType.VarChar, 8000).Value = Request["DesignAndPlanningPermission"];
                        cmd.Parameters.Add("@RecommendationOfProjectNeedAgainstSDA", SqlDbType.VarChar, 8000).Value = Request["RecommendationOfProjectNeedAgainstSportsDevelopmentActivity"];
                        cmd.Parameters.Add("@ValueForMoneyAssessment", SqlDbType.VarChar, 8000).Value = Request["ValueForMoneyAssessment"];
                        cmd.Parameters.Add("@ActionId", SqlDbType.Int).Value = int.Parse(Request["ActionId"].ToString());
                        cmd.Parameters.Add("@ActionNotes", SqlDbType.VarChar, 500).Value = "RFFM";

                        Utils.executeSP(cmd);

                        if (Session["errmsg"] != null)
                            strError = Session["errmsg"].ToString();

                        if (strError == "")
                        {
                            UpdateStatus = int.Parse(cmd.Parameters["@UpdateStatus"].Value.ToString());
                            if (UpdateStatus < 0)
                                strError = "There was an error when processing your request";
                            else
                                Session["current_tab"] = "";
                        }
                    }
                    catch (Exception ex)
                    {
                        strError = ex.Message;
                    }
                    break;

                case "check_session":
                    if (Session["ApplicationId"] != null)
                    {
                        string hfID = Request["hf_ApplicationId"].ToString();
                        string sfID = Session["ApplicationId"].ToString();

                        if (hfID != sfID)
                        {
                            strError = "-1";
                        }
                    }
                    break;
                default:
                    strError = "Bad request";
                    break;

            }
            
            Response.Write(strError);
        }
    }
} 
 
 
 
Copy this in Javascript file

function UpdateRFFM()
{
    var msg;
    var status_code;
    var rffmAction = $(".rffmAction").val();
    var Risk = $(".ddlRisk").val();
    var Region = $(".ddlRegion").val();
    var strError = "";
    
    if (rffmAction == "151") {
        if (Risk == "")
            strError = strError + "Please select a Risk\n";
        if (Region == "")
            strError = strError + "Please select a Region\n";                
    }
    
    if (strError != "") {
        alert(strError);
        return false;
    }
    
    var reply = false;

    if (rffmAction == "151") {
        $.post(getFullPath("update_sis.aspx"), 
            {form_name: 'rffm_UserSetupVerify'}, function(data) {
            if (data.length > 0)
                status_code = data.substring(0, 1);
            else
                status_code = '';
            
            switch(status_code) {
                case '0':
                    UpdateRFFM_Normal();
                    break;
                case '1':
                    $.post(getFullPath("update_sis.aspx"),
                        {form_name: 'rffm_create_user'}, function(data) {
                            status_code = data.substring(0, 2);
                            msg = data.substring(2);
                            if (status_code == "-1") 
                                alert(msg);
                            else {
                                alert('created new user account\n\n' + msg);
                                UpdateRFFM_Normal();
                            }                                    
                        });
                    break;
                case '2':
                    UpdateRFFM_Normal();
                    break;
                case '3':
                     $.post(getFullPath("update_sis.aspx"),
                        {form_name: 'rffm_SendVerificationEmail'}, function(data) {
                            status_code = data.substring(0, 2);
                            msg = data.substring(2);
                            if (status_code == "-1") 
                                alert(msg);
                            else {
                                alert('verification email sent\n\n' + msg);
                                UpdateRFFM_Normal();
                            }
                        });
                    break;
                case '4':
                    alert(data);
                    break;
                case '5':
                    msg = data.substring(1);
                    if (confirm(msg) == true) {
                      $.post(getFullPath("update_sis.aspx"),
                        {form_name: 'rffm_SendVerificationEmail'}, function(data) {
                            status_code = data.substring(0, 2);
                            msg = data.substring(2);
                            if (status_code == "-1") 
                                alert(msg);
                            else 
                                alert('verification email was sent\n\n' + msg);
                                UpdateRFFM_Normal();
                        });
                    }
                    break;                                                                                                
                default:
                    alert(data);
                    break;
            }
        });
    } else
        UpdateRFFM_Normal();

    return reply;
}
function UpdateRFFM_Normal() {
    var reply = false;         
    $.post(getFullPath("update_sis.aspx"), {form_name: 'rffm',
        FeasibilityStudy: $(".FeasibilityStudy").val(),
        PlanningPermissionNotRequired: $(".PlanningPermissionNotRequired").val(),
        Sustainable: $(".Sustainable").val(),
        RDMRecommendation: $(".RDMRecommendation").val(),
        Risk: $(".ddlRisk").val(),
        Region: $(".ddlRegion").val(),
        DesignAndPlanningPermission: $(".DesignAndPlanningPermission").val(),
        RecommendationOfProjectNeedAgainstSportsDevelopmentActivity: $(".RecommendationOfProjectNeedAgainstSportsDevelopmentActivity").val(),
        ValueForMoneyAssessment: $(".ValueForMoneyAssessment").val(),
        ActionNotes: $(".ActionNotes").val(),
        ActionId: $(".rffmAction").val()
        }, function(data) {
           if (data.length > 0) {
                alert(data);
                return false;
            } else {
                window.location = getFullPath("application_form.aspx");
                return false;
            }
        });
}

Factorial of a number in C#(CSharp)


The following is an example of the factorial number. It is also recursive method. Have a look:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        public int factorial(int n)
        {
            int result;
            if (n == 1)
                return 1;
            else
            {
                result = factorial(n - 1) * n;
                return result;
            }
        }
        static void Main(string[] args)
        {
            Program obj = new Program();
            Console.WriteLine("Factorial of 3 is " + obj.factorial(3));
            Console.WriteLine("Factorial of 4 is " + obj.factorial(4));
            Console.WriteLine("Factorial of 5 is " + obj.factorial(5));

            Console.ReadLine();
        }
    }
}

Output:

Factorial

Fibonacci Series Using C#(CSharp)


Following program generates the Fibonacci series up to 200.

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {       
        static void Main(string[] args)
        {
            int number1, number2;
            number1 = 0;
            number2 = 1;

            Console.WriteLine("{0}", number1);
            while (number2 < 200)
            {
                Console.WriteLine("{0}", number2);
                number2 = number2 + number1;
                number1 = number2 - number1;
            }

            Console.ReadLine();

        }
    }
}

Output

Fibonacci Series

C# Program to perform Addition, Subtraction, Multipilcation and Division operation.


The following program perform mathematical operation such as Addition, Subtraction, Multipilcation and Division operation.

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        int Number1, Number2;
        char option; 

        public void Number()
        {
            Console.WriteLine("Enter the First Number:");
            Number1 = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Enter the Second Number:");
            Number2 = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Main Menu");
            Console.WriteLine("1. Addition");
            Console.WriteLine("2. Subtraction");
            Console.WriteLine("3. Multiplication");
            Console.WriteLine("4. Division");

            Console.WriteLine("Enter the Operation you want to perform");
            option = Convert.ToChar(Console.ReadLine());

            switch (option)
            {
                case '1':                    
                    Console.WriteLine("The result of Addition is:{0}", Number1 + Number2);
                    break;
                case '2':                    
                    Console.WriteLine("The result of Subtraction is:{0}", Number1 - Number);
                    break;
                case '3':                     
                    Console.WriteLine("The result of Multiplication is:{0}", Number1 * Number2);
                    break;
                case '4':                    
                    Console.WriteLine("The result of Division is:{0}", Number1 / Number2);
                    break;
                default:
                    Console.WriteLine("Invalid Option");
                    break;
            }
            Console.ReadLine();
        }

        static void Main(string[] args)
        {
            Program objProgram = new Program();
            objProgram.Number();            
        }
    }
} 

Output:

Leap Year program using C# or CSharp.


The following code checks whether the year entered by the user is a Leap Year. If the condition specified in the if statement is true, the statements in the if block are executed. And if the condition specified in the if statement is false , the statement in the else block are executed.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int Year;
            Console.WriteLine("Enter the year: ");
            Year = Convert.ToInt32(Console.ReadLine());
            if ((Year % 4 == 0) && (Year % 100 != 0 || Year % 400 == 0))
            {
                Console.WriteLine("The Year you have entered is a Leap Year {0}.", Year);
            }
            else
            {
                Console.WriteLine("The Year you have entered is not a Leap Year {0}.", Year);
            }
            Console.ReadLine();
        }
    }
}

Output:

Creating a Sample C# program using Classes and objects.


A C# program can be written by using Visual Studio or any editor. Consider the following code, which declares the Car class and creates the object MyCar of the same class:

using System;
class Car
{
    //Following are the Member variables of a class.
    string Engine;
    int NoOfWheels;
    //Following are the Member function of a class.
    public void AcceptDetails()
    {
         Console.WriteLine("Enter the Engin Model");
         Engine = Console.ReadLine();
         Console.WriteLine("Enter the number of Wheels");
         NoOfWheels = Convert.ToInt32(Console.ReadLine());
    }

    public void DisplayDetails()
    {
         Console.WriteLine("The Engine Model is:{0}", Engine);
         Console.WriteLine("The number of Wheels are:{0}", NoOfWheels);
    }

    //Class used to instantiate the Car Class.
    class ExecuteClass
    {
        public static void Main(string[] args)
        {
             Car MyCar = new Car();
             MyCar.AcceptDetails();
             MyCar.DisplayDetails);
    
             Console.ReadLine();
        }
    }

Output:
Enter the Engine Model
800CC
Enter the number of Wheels
4
The Engine Model is: 800CC
The number of Wheels are: 4

Hello, World! in C#


You can learn to create classes in the C# language. Consider the following code example, which define a class:

using System;
public class Hello
{
   public static void Main(string[] args)
   {
        System.Console.WriteLine("Hello, World!\n");
   }
}

Output: Hello, World!

The preceding class declaration provides a method Main() that will display the message "Hello, World!" on your screen.

How can I bind Data in ASP.NET GridView?


You can easy bind data in ASP.NET. You don't even need to write a single line of code for that. You only need to follow the steps:

1. Fire-up Microsoft Visual Studio IDE. Navigate to File - New -Project. You will find New Project dialog box open. Now select appropriate language from Project Type, Select ASP.NET Web Application from Templates enter name of the project and set the location for it.

Data Binding in ASP.NET Step-1
2. Once you open a new project you will get some default files in Visual Studio Solution Explorer. Open Default.aspx in Design Mode and Add a GridView control from the Toolbox to the Design surface as shown in image below.

Data Binding in ASP.NET Step-2

3. You will find a smart tag on top of the GridView Control, click that. You will see GridView Task window. Click on Choose Data Source Drop Down Control and Select >




Data Binding in ASP.NET Step-3
4. Once you select that you will get Choose a Data Source Type screen, Select DataBase and click Next.


Data Binding in ASP.NET Step-4
5. Now click New Connection button and Select Microsoft SQL Server and Click Continue button and then Click Next button.



Data Binding in ASP.NET Step-5
6. You need to select your SQL Server Database name in Server Name location. Once you select  the name that will populate all the database in Select or enter a database name: field. Select one database and Click on Test Connection button at you bottom. You will get a confirmation that Test Connection Succeeded. Click OK button twice.



Data Binding in ASP.NET Step-6
7. Now click Next button two time. You will get the following image. Select the table and then the column as shown in image below. Click Next

Data Binding in ASP.NET Step-7
8. You will get the Test Query screen. Now you have the query  just click Test Query button to check you query. To test you query is correct or not. Then Click Finish button.

Data Binding in ASP.NET Step-8
9. Now Run you application in Visual Studio to see the output.

Data Binding in ASP.NET Step-9

How to create Session Timeout alert box and Redirect to Login.aspx page in ASP.NET


ASP.NET allows you to save values by using session state, which is an instance of the System.Web.SessionState.HttpSessionState class, for each active Web Application session. If different users are using your application, each user session will have a different session state. You can use session state to accomplish the following tasks:
  1. Uniquely identify browser or client-device requests and map them to an individual session instance on the server.
  2. Store session-sepcific data on the server for user across multiple browser or client-device requests within the same session.
  3. Raise appropriate session management events. In addition, you can write application code that make use of these event.
So, here is how you can redirect a user who's session time is out. Copy the JavaScript and HTML code in you application.



    

Copy this HTML code in your application.

How to make your Web Application Performance Faster.


Hi, following are the most important thinks to note for Web Application performance:

1. Make fewer HTTP requests
              Decreasing the number of components on a page reduces the number of HTTP requests required to render the page, resulting in faster page loads. Some ways to reduce the number of components include: combine files, combine multiple scripts into one script, combine multiple CSS files into one style sheet, and use CSS Sprites and image maps.

2. Content Delivery Network (CDN)
            User proximity to web servers impacts response times. Deploying content across multiple geographically dispersed servers helps users perceive that pages are loading faster.

3. Add Expires headers
           Web pages are becoming increasingly complex with more scripts, style sheets, images, and Flash on them. A first-time visit to a page may require several HTTP requests to load all the components. By using Expires headers these components become cacheable, which avoids unnecessary HTTP requests on subsequent page views. Expires headers are most often associated with images, but they can and should be used on all page components including scripts, style sheets, and Flash.

4. Compress components with gzip
            Compression reduces response times by reducing the size of the HTTP response. Gzip is the most popular and effective compression method currently available and generally reduces the response size by about 70%. Approximately 90% of today's Internet traffic travels through browsers that claim to support gzip.

5. Grade A on Put CSS at top
            Moving style sheets to the document HEAD element helps pages appear to load quicker since this allows pages to render progressively.

6. Put JavaScript at bottom
            JavaScript scripts block parallel downloads; that is, when a script is downloading, the browser will not start any other downloads. To help the page load faster, move scripts to the bottom of the page if they are deferrable.

7. Avoid CSS expressions
            CSS expressions (supported in IE beginning with Version 5) are a powerful, and dangerous, way to dynamically set CSS properties. These expressions are evaluated frequently: when the page is rendered and resized, when the page is scrolled, and even when the user moves the mouse over the page. These frequent evaluations degrade the user experience.

8. Make JavaScript and CSS external
            Using external JavaScript and CSS files generally produces faster pages because the files are cached by the browser. JavaScript and CSS that are inline in HTML documents get downloaded each time the HTML document is requested. This reduces the number of HTTP requests but increases the HTML document size. On the other hand, if the JavaScript and CSS are in external files cached by the browser, the HTML document size is reduced without increasing the number of HTTP requests.

9. Reduce DNS lookups
            The Domain Name System (DNS) maps host-names to IP addresses, just like phone-books map people's names to their phone numbers. When you type URL www.yahoo.com into the browser, the browser contacts a DNS resolver that returns the server's IP address. DNS has a cost; typically it takes 20 to 120 milliseconds for it to look up the IP address for a host-name. The browser cannot download anything from the host until the look-up completes.

10. Minify JavaScript and CSS
            Minification removes unnecessary characters from a file to reduce its size, thereby improving load times. When a file is minified, comments and unneeded white space characters (space, newline, and tab) are removed. This improves response time since the size of the download files is reduced.

11. Avoid URL redirects
            URL redirects are made using HTTP status codes 301 and 302. They tell the browser to go to another location. Inserting a redirect between the user and the final HTML document delays everything on the page since nothing on the page can be rendered and no components can be downloaded until the HTML document arrives.

12.Remove duplicate JavaScript and CSS
            Duplicate JavaScript and CSS files hurt performance by creating unnecessary HTTP requests (IE only) and wasted JavaScript execution (IE and Firefox). In IE, if an external script is included twice and is not cacheable, it generates two HTTP requests during page loading. Even if the script is cacheable, extra HTTP requests occur when the user reloads the page. In both IE and Firefox, duplicate JavaScript scripts cause wasted time evaluating the same scripts more than once. This redundant script execution happens regardless of whether the script is cacheable.

13. Configure entity tags (ETags)
            Entity tags (ETags) are a mechanism web servers and the browser use to determine whether a component in the browser's cache matches one on the origin server. Since ETags are typically constructed using attributes that make them unique to a specific server hosting a site, the tags will not match when a browser gets the original component from one server and later tries to validate that component on a different server.

14. Make AJAX cacheable
            One of AJAX's benefits is it provides instantaneous feedback to the user because it requests information asynchronously from the backend web server. However, using AJAX does not guarantee the user will not wait for the asynchronous JavaScript and XML responses to return. Optimizing AJAX responses is important to improve performance, and making the responses cacheable is the best way to optimize them.

15. GET for AJAX requests
            When using the XMLHttpRequest object, the browser implements POST in two steps: (1) send the headers, and (2) send the data. It is better to use GET instead of POST since GET sends the headers and the data together (unless there are many cookies). IE's maximum URL length is 2 KB, so if you are sending more than this amount of data you may not be able to use GET.

16. Reduce the number of DOM elements
            A complex page means more bytes to download, and it also means slower DOM access in JavaScript. Reduce the number of DOM elements on the page to improve performance.

17. Avoid HTTP 404 (Not Found) error
            Making an HTTP request and receiving a 404 (Not Found) error is expensive and degrades the user experience. Some sites have helpful 404 messages (for example, "Did you mean ...?"), which may assist the user, but server resources are still wasted.

18. Reduce cookie size
            HTTP cookies are used for authentication, personalization, and other purposes. Cookie information is exchanged in the HTTP headers between web servers and the browser, so keeping the cookie size small minimizes the impact on response time.

19. Use cookie-free domains
            When the browser requests a static image and sends cookies with the request, the server ignores the cookies. These cookies are unnecessary network traffic. To workaround this problem, make sure that static components are requested with cookie-free requests by creating a subdomain and hosting them there.
20. Avoid AlphaImageLoader filter
            The IE-proprietary AlphaImageLoader filter attempts to fix a problem with semi-transparent true color PNG files in IE versions less than Version 7. However, this filter blocks rendering and freezes the browser while the image is being downloaded. Additionally, it increases memory consumption. The problem is further multiplied because it is applied per element, not per image.

21. Do not scale images in HTML
            Web page designers sometimes set image dimensions by using the width and height attributes of the HTML image element. Avoid doing this since it can result in images being larger than needed. For example, if your page requires image myimg.jpg which has dimensions 240x720 but displays it with dimensions 120x360 using the width and height attributes, then the browser will download an image that is larger than necessary.

22. Make favicon small and cacheable
            A favicon is an icon associated with a web page; this icon resides in the favicon.ico file in the server's root. Since the browser requests this file, it needs to be present; if it is missing, the browser returns a 404 error (see "Avoid HTTP 404 (Not Found) error" above). Since favicon.ico resides in the server's root, each time the browser requests this file, the cookies for the server's root are sent. Making the favicon small and reducing the cookie size for the server's root cookies improves performance for retrieving the favicon. Making favicon.ico cacheable avoids frequent requests for it.

Recent Posts