जगदीश खोलिया

Wednesday, July 20, 2011

Abstract class

Abstract class is a class that has no direct instances, but whose descendants may have direct instances. There are case i which it is useful to define classes for which the programmer never intends to instantiate any objects; because such classes normally are used as bae-classes in inheritance hierarchies, we call such classes abstract classes These classes cannot be used to instantiate objects; because abstract classes are incomplete. Derived classes called concrete classes must define the missing pieces.

Abstract classes normally contain one or more abstract methods or abstract properties, such methods or properties do not provide implementations, but our derived classes must override inherited abstract methods or properties to enable obejcts ot those derived classes to be instantiated, not to override those methods or properties in derived classes is syntax error, unless the derived class also is an abstract class.

In some cases, abstract classes constitute the top few levels of the hierarchy, for Example abstract class Shape with abstract method Draw() has tow derived abstract classe Shape2D & Shape3D inherites the method Draw() & also do not provide any implementation for it. Now we have normal classes Rectangle, Square & Circle inherites from Shape2D, and another group of classes Sphere, Cylinder & Cube inherites from Shape3D. All classes at the bottom of the hierarchy must override the abstract method Draw().

A class is made abstract by declaring it with Keyword abstract.

Example:

public abstract class Shape
{
    //...Class implementation

    public abstract void Draw(int x, int y)
    {
        //this method mustn't be implemented here.
        //If we do implement it, the result is a Syntax Error.
    } 
}


public abstract class Shape2D : Shape
{
    //...Class implementation
    //...you do not have to implement the the method Draw(int x, int y)
}

public class Cricle : Shape2D
{
    //here we should provide an implemetation for Draw(int x, int y)
    public override void Draw(int x, int y)
    {
        //must do some work here
    }

}
Difference between an abstract method & virtual method:

Virtual method has an implementation & provide the derived class with the option of overriding it. Abstract method does not provide an implementation & forces the derived class to override the method.

important Notes:

(a)Any Class with abstract method or property in it must be declared abstract

(b)Attempting to instantiate an object of an abstract class retults in a compilation error

Example:

Shape m_MyShape = new Shape(); //it is Wrong to that.
But we can do that.
Shape m_MyShape = new Circle(); // True
Or
Shape m_MyShape; 
/*

declare refrences only, and the refrences can refer to intances of
any concrete classes derived from abstract class
*/

Circle m_MyCircle = new Circle();
m_MyShape  = m_MyCircle; // Also True
(d)An abstract class can have instance data and non-abstract methods -including constructors-.

Friday, July 15, 2011

CTE in Sql Server

Introduction:
The common table expression is one of the new features in sql server 2005. It can be used instead of temp table or table variables in the stored procedures in the circumstances. Let's see CTE with some example queries.

Background:

Most of the developers while writing the stored procedures they create the temp tables or table variables. They need some table to store the temporary results in order to manipulate the data in the other tables based on this temp result.

The temp variables will be stored on the tempdb and it needs to be deleted in the tempdb database.

The table variable is best when compare with the temp tables. Because the table variable initially will be there in the memory for the certain limit of size and if the size increase then it will be moved to the temp database. However the scope of the table variable is only up to that program. When compare with table variable the CTE is best. It just store the result set like normal view.

CTE (Common Table Expression):

The CTE is one of the essential features in the sql server 2005.It just store the result as temp result set. It can be access like normal table or view. This is only up to that scope.

The syntax of the CTE is the following.

WITH name (Alias name of the retrieve result set fields)
AS
(
//Write the sql query here
)
SELECT * FROM name

Here the select statement must be very next to the CTE. The name is mandatory and the argument is an optional. This can be used to give the alias to the retrieve field of the CTE.

CTE 1: Simple CTE

WITH
ProductCTE
AS(  SELECT ProductID AS [ID],ProductName AS [Name],CategoryID AS [CID],UnitPrice AS [Price]
  FROM Products
)SELECT * FROM ProductCTE

Here all the product details like ID, name, category ID and Unit Price will be retrieved and stored as temporary result set in the ProductCTE.

This result set can be retrieved like table or view.

CTE2:Simple CTE with alias

WITH
ProductCTE(ID,Name,Category,Price)AS(  SELECT ProductID,ProductName,CategoryID,UnitPrice
  FROM Products
)SELECT * FROM ProductCTE

Here there are four fieds retrieves from the Products and the alias name have given in the arqument to the CTE result set name.

It also accepts like the following as it is in the normal select query.

WITH
ProductCTE
AS(  SELECT ProductID AS [ID],ProductName AS [Name],CategoryID AS [CID],UnitPrice AS [Price]
  FROM Products
)SELECT * FROM ProductCTE

CTE 3: CTE joins with normal table

The result set of the CTE can be joined with any table and also can enforce the relationship with the CTE and other tables.

WITH
OrderCustomer
AS(  SELECT DISTINCT CustomerID FROM Orders
)SELECT C.CustomerID,C.CompanyName,C.ContactName,C.Address+', '+C.City AS [Address] FROM Customers C INNER JOIN OrderCustomer OC ON OC.CustomerID = C.CustomerID

Here the Ordered Customers will be placed in the CTE result set and it will be joined with the Customers details.

CTE 4: Multiple resultsets in the CTE

WITH
MyCTE1
AS(  SELECT ProductID,SupplierID,CategoryID,UnitPrice,ProductName FROM Products
), 
MyCTE2
AS(  SELECT DISTINCT ProductID FROM "Order Details"
)SELECT C1.ProductID,C1.ProductName,C1.SupplierID,C1.CategoryID FROM MyCTE1 C1 INNER JOIN MyCTE2 C2 ON C1.ProductID = C2.ProductID

Here, there are two result sets that will be filtered based on the join condition.

CTE 5: Union statements in the CTE

WITH
PartProdCateSale
AS(SELECT ProductID FROM Products WHERE CategoryID = (SELECT CategoryID FROM Categories WHERE CategoryName='Condiments')UNION ALL
SELECT
ProductID FROM Products WHERE CategoryID = (SELECT CategoryID FROM Categories WHERE CategoryName='Seafood')
)
SELECT OD.ProductID,SUM(OD.UnitPrice*OD.Quantity) AS [Total Sale] FROM "Order Details" OD INNER JOIN PartProdCateSale PPCS ON PPCS.ProductID = OD.ProductID
GROUP BY OD.ProductID

Normally when we combine the many result sets we create table and then insert into that table. But see here, we have combined with the union all and instead of table, here CTE has used.

CTE 6: CTE with identity column

WITH
MyCustomCTE
   AS   (      SELECT CustomerID,row_number() OVER (ORDER BY CustomerID) AS iNo FROM
         Customers
   )SELECT * FROM MyCustomCTE

ASP.NET Cookieless Session

Cookies are basically text data which a web site may store of the user's machine. Cookies are not considered as safe medium to store data as they could be dangerous in some scenario. Also there might be the case that user has cookies turned off on his machine or the browser doesn't supports the cookies. Our application might get failed if it is depended on cookies support on client side. Most of the time session id is stored at client side in cookies. Therefore we won't be able to retrieve session's data in the case when cookies are not enable.

ASP.NET Cookieless Support

ASP.NET support cookieless execution of the application when the client doens't have cookies support. When to chose cookieless, the session id is transferred via the request url. Each and every request of the application page contains the session id embedded in its url. So the web application need not to request the session from the cookies.
To set Cookieless session in an ASP.NET application set following value in web.config file
<sessionstate cookieless="true" />
When you have cookieless session then the url may look like this
http://www.dailycoding.com/Posts/(_entv9gVODTzHuenph6KAlK07..)/test.aspx

Monday, July 11, 2011

What is DLR in .NET 4.0 framework?

What is DLR in .NET 4.0 framework?
DLR
Due to DLR runtime, dynamic languages like ruby, python, JavaScript etc can integrate and run seamlessly with CLR. DLR thus helps to build the best experience for your favorite dynamic language. Your code becomes much cleaner and seamless while integrating with the dynamic languages. Integration with DLR is not limited to dynamic languages. You can also call MS office components in a much cleaner way by using COM interop binder. One of the important advantages of DLR is that it provides one central and unified subsystem for dynamic language integration. 

C# 4.0 Language Innovation

  • Dynamically Typed Objects
  • Optional and Named Parameters
  • Improved COM Interoperability
  • Co and Contra variance
Dynamic types

What are the advantages and disadvantage of dynamic keyword?

We all still remember how we talked bad about VB6 (Well I loved the language) variant keyword and we all appreciated how .NET brought in the compile time check feature, well so why are we changing now.  Well, bad developers will write bad code with the best programming language and good developers will fly with the worst programming language. Dynamic keyword is a good tool to reduce complexity and it's a curse when not used properly.
So advantages of Dynamic keyword:
Helps you interop between dynamic languages.
Eliminates bad reflection code and simplifies code complexity.
Improves performance with method call caching.
Disadvantages:
Will hit performance if used with strongly typed language.

Jquery Ajax Calling functions

there are 5 diffrent function that used to make ajax call to page and to fetch data. I am going to discuss about that five function one by one.

Following is list of that five function availale in jquery libaray to make ajax call.
  1. Load
  2. getJson
  3. GET
  4. POST
  5. Ajax
Load
Method allow to make ajax call to the page and allows to send using both Get and Post methods.
var loadUrl = "TestPage.htm";
$(document).ready(function () {
$("#load_basic").click(function () {
$("#result").html(ajax_load).load(loadUrl, function (response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#dvError").html(msg + xhr.status + " " + xhr.statusText);
}
}
);
return false;
});
As you can see in above code you can easily make call to any page by passing it Url. The call back function provide more control and allows to handle the error if any by making use of the Status value.

One of the important thing about the load method is its allow to load part of page rather than whole page. So get only part of the page call remains same but the url is
var loadUrl = "TestPage.htm #dvContainer";   
So by the passing above url to load method it just load content of the div having id=dvContainer. Check the demo code for detail.



Firebug shows the repose get return by when we call the page by Load method.

Important Feature
  • Allow make call with both Get and Post request
  • Allow to load part of the page.
getJson

Method allow get json data by making ajax call to page. This method allows only to pass the parameter by get method posting parameter is not allowed. One more thing this method treat the respose as Json.
var jsonUrl = "Json.htm";
$("#btnJson").click(function () {
$("#dvJson").html(ajax_load);
$.getJSON(jsonUrl, function (json) {
var result = json.name;
$("#dvJson").html(result);
}
);
return false;
});
Above code make use of getJSON function and displays json data fetch from the page.

Following is json data return by the Json.htm file.
{
"name": "Hemang Vyas",
"age" : "32",
"sex": "Male"
}

Following image displays the json Data return as respose.



Important Feature
  • Only send data using get method, post is not allowed.
  • Treat the response data as Json only

get

Allow to make ajax request with the get method. It handles the response of many formats including xml, html, text, script, json, and jonsp.
var getUrl = "GETAndPostRequest.aspx";
$("#btnGet").click(function () {
$("#dvGet").html(ajax_load);
$.get(getUrl, { Name: "Pranay" }, function (result) {
$("#dvGet").html(result);
}
);
return false;
});
As in code I am passing Name parameter to the page using get request.

On server side you can get the value of the Name parameter in request object querycollection.
if (Request.QueryString["Name"]!=null)
{
txtName.Text = Request.QueryString["Name"].ToString();
} 
The firebug shows the parameter passe by me as Get request  and  value of the parameter is pranay



Important Feature
  • Can handle any type of the response data.
  • Send data using get method only.

post

Allow to make ajax request with the post method. It handles the response of many formats including xml, html, text, script, json, and jonsp. post does same as get but just send data using post method.
var postUrl = "GETAndPostRequest.aspx";
$("#btnPost").click(function () {
$("#dvPost").html(ajax_load);
$.post(postUrl, { Name: "Hanika" }, function (result) {
$("#dvPost").html(result);
}
);
return false;
});
As in code I am passing Name parameter to the page using post request.

On server side you can get the value of the Name parameter in request object formcollection.
if (Request.Form["Name"] != null)
{
    txtName.Text = Request.Form["Name"].ToString();
}

The firebug shows the parameter passe by me as Get request  and  value of the parameter is Hanika



Important Feature
  • Can handle any type of the response data.
  • Send data using post method only.

ajax

Allow to make the ajax call. This method provide more control than all other methods we seen. you can figure out the difference by checking the list of parameter.
var ajaxUrl = "Json.htm";
$("#btnAjax").click(function () {
$("#dvAjax").html(ajax_load);
$.ajax({
type: "GET", //GET or POST or PUT or DELETE verb
url: ajaxUrl, // Location of the service
data: "", //Data sent to server
contentType: "", // content type sent to server
dataType: "json", //Expected data format from server
processdata: true, //True or False
success: function (json) {//On Successfull service call
var result = json.name;
$("#dvAjax").html(result);
},
error: ServiceFailed// When Service call fails
});
return false;
});
In above code you can see the all the parameter and comment related to each parameter describe the purpose of each one.

Fire bug shows the called page return json data and Ajax function treat the respose as Json because in code datatype = json



Important Feature
  • Provide more control on the data sending and on response data.
  • Allow to handle error occur during call.
  • Allow to handle data if the call to ajax page is successful.
Summary

So each method of jQuery ajax is different and can use for the difference purpose.

Saturday, June 25, 2011

JSON overview

JSON is a lightweight format for exchanging data between the client and server. It is often used in Ajax applications because of its simplicity and because its format is based on JavaScript object literals. We will start this lesson by learning JavaScript's object-literal syntax and then we will see how we can use JSON in an Ajax application.

Object Literals

We saw earlier how to create new objects in JavaScript with the Object() constructor. We also saw how we could create our constructors for our own objects. In this lesson, we'll examine JavaScript's literal syntax for creating arrays and objects.

Arrays

Array literals are created with square brackets as shown below:
var Beatles = ["Paul","John","George","Ringo"];
This is the equivalent of:
var Beatles = new Array("Paul","John","George","Ringo");

Objects

Object literals are created with curly brackets:
var Beatles = {
 "Country" : "England",
 "YearFormed" : 1959,
 "Style" : "Rock'n'Roll"
}
This is the equivalent of:
var Beatles = new Object();
Beatles.Country = "England";
Beatles.YearFormed = 1959;
Beatles.Style = "Rock'n'Roll";
Just as with all objects in JavaScript, the properties can be references using dot notation or bracket notation.
alert(Beatles.Style); //Dot Notation
alert(Beatles["Style"]); //Bracket Notation

Arrays in Objects

Object literals can contain array literals:
var Beatles = {
 "Country" : "England",
 "YearFormed" : 1959,
 "Style" : "Rock'n'Roll",
 "Members" : ["Paul","John","George","Ringo"]
}

Objects in Arrays

Array literals can contain object literals:
var Rockbands = [
 {
  "Name" : "Beatles",
  "Country" : "England",
  "YearFormed" : 1959,
  "Style" : "Rock'n'Roll",
  "Members" : ["Paul","John","George","Ringo"]
 },
 {
  "Name" : "Rolling Stones",
  "Country" : "England",
  "YearFormed" : 1962,
  "Style" : "Rock'n'Roll",
  "Members" : ["Mick","Keith","Charlie","Bill"]
 }
]

JSON

On the JSON website (http://www.json.org), JSON is described as:
  1. a lightweight data-interchange format
  2. easy for humans to read and write
  3. easy for machines to parse and generate
Numbers 1 and 3 are certainly true. Number 2 depends on the type of human. Experienced programmers will find that they can get comfortable with the syntax relatively quickly.

JSON Syntax

The JSON syntax is like JavaScript's object literal syntax except that the objects cannot be assigned to a variable. JSON just represents the data itself. So, the Beatles object we saw earlier would be defined as follows:
{
 "Name" : "Beatles",
 "Country" : "England",
 "YearFormed" : 1959,
 "Style" : "Rock'n'Roll",
 "Members" : ["Paul","John","George","Ringo"]
}

JSON Parsers

As JSON is just a string of text and not an object in and of itself, it needs to be converted to an object before to make it useful. Although this can be done in JavaScript with the eval() function, it is safer to use a JSON parser. You can download the JavaScript JSON parser at http://www.json.org/json.js. Including this file on a web page allows you to take advantage of the JSON object, which has the following very useful methods:
  • JSON.parse(strJSON) - converts a JSON string into a JavaScript object.
  • JSON.stringify(objJSON) - converts a JavaScript object into a JSON string.
The process for sending data between the browser and server with JSON is as follows:
  1. On the client-side:
    • Create a JavaScript object using the standard or literal syntax.
    • Use the JSON parser to stringify the object.
    • Send the URL-encoded JSON string to the server as part of the HTTP Request. This can be done using the HEAD, GET or POST method by assigning the JSON string to a variable. It can also be sent as raw text using the POST method, but this may create extra work for you on the server-side.
  2. On the server-side:
    • Decode the incoming JSON string and convert the result to an object using a JSON parser for the language of your choice. At http://www.json.org, you'll find JSON parsers for many modern programming languages. The methods available depend upon which parser you are using. See the parser's documentation for details.
    • Do whatever you wish with the object.
    • If you wish to send JSON back to the client:
      • Create a new object for storing the response data.
      • Convert the new object to a string using your JSON parser.
      • Send the JSON string back to the client as the response body (e.g, Response.Write(strJSON), echo $strJSON, out.write(strJSON) etc.).
  3. On the client-side:
    • Convert the incoming JSON string to an object using the JavaScript JSON parser.
    • Do whatever you wish with the object.
    • And so on...
The examples below show how to transfer data to the server using JSON. 

Code Sample: JSON/Demos/SendJson.html

<html>
<head>
<script type="text/javascript" src="../../prototype.js"></script>
<script type="text/javascript" src="../../json.js"></script>
<script type="text/javascript">
 function SendRequest(MSG)
 {
  document.getElementById("ResponseDiv").innerHTML="";
  var objJSON = {
   "msg" : MSG
  };
  var strJSON = encodeURIComponent(JSON.stringify(objJSON));
  new Ajax.Request("ReceiveJSON.jsp",
   {
    method: "post",
    parameters: "strJSON=" + strJSON,
    onComplete: Respond
   });
 }

 function Respond(REQ)
 {
  document.getElementById("ResponseDiv").innerHTML=REQ.responseText;
 }
</script>
<title>Using JSON</title>
</head>

<body>
<h1>Request</h1>
<form>
 <input type="button" value="Hi There!" onClick="SendRequest(this.value)"/>
 <input type="button" value="Good bye!" onClick="SendRequest(this.value)" />
</form>
<h1>Response</h1>
<div id="ResponseDiv">Waiting...</div>
</body>
</html>

Code Sample: JSON/Demos/ReceiveJSON.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" import="java.net.*,org.json.simple.*"%>
<%
 try
 {
  URLDecoder decoder = new URLDecoder();
  String strJSON = decoder.decode(request.getParameter("strJSON"));
  JSONObject objJSON = (JSONObject) JSONValue.parse(strJSON);
  
  String Message = objJSON.get("msg").toString();
  if (Message.equals("Hi There!"))
  {
   out.write("And hi there to you!");
  }
  else
  {
   out.write("Later Gator!");
  }
 }
 catch (Exception e)
 {
  out.write(e.toString());
 }
%>
Code Explanation
This code is relatively simple. The client-side script:
  • creates a simple JSON object with one property holding the passed in MSG string.
  • converts the JSON object to a string and encodes it.
  • passes the string as a parameter of our Ajax request (using Prototype).
  • outputs the responseText to the page.
The server-side script:
  • decodes the passed in string and converts it to a JSON object.
  • outputs an appropriate response.

Friday, June 24, 2011

ADO .NET Architecture

ADO .NET
Most applications need data access at one point of time making it a crucial component when working with applications. Data access is making the application interact with a database, where all the data is stored. Different applications have different requirements for database access. VB .NET uses ADO .NET (Active X Data Object) as it's data access and manipulation protocol which also enables us to work with data on the Internet. Let's take a look why ADO .NET came into picture replacing ADO.
Evolution of ADO.NET
The first data access model, DAO (data access model) was created for local databases with the built-in Jet engine which had performance and functionality issues. Next came RDO (Remote Data Object) and ADO (Active Data Object) which were designed for Client Server architectures but, soon ADO took over RDO. ADO was a good architecture but as the language changes so is the technology. With ADO, all the data is contained in a recordset object which had problems when implemented on the network and penetrating firewalls. ADO was a connected data access, which means that when a connection to the database is established the connection remains open until the application is closed. Leaving the connection open for the lifetime of the application raises concerns about database security and network traffic. Also, as databases are becoming increasingly important and as they are serving more people, a connected data access model makes us think about its productivity. For example, an application with connected data access may do well when connected to two clients, the same may do poorly when connected to 10 and might be unusable when connected to 100 or more. Also, open database connections use system resources to a maximum extent making the system performance less effective.
Why ADO.NET?
To cope up with some of the problems mentioned above, ADO .NET came into existence. ADO .NET addresses the above mentioned problems by maintaining a disconnected database access model which means, when an application interacts with the database, the connection is opened to serve the request of the application and is closed as soon as the request is completed. Likewise, if a database is Updated, the connection is opened long enough to complete the Update operation and is closed. By keeping connections open for only a minimum period of time, ADO .NET conserves system resources and provides maximum security for databases and also has less impact on system performance. Also, ADO .NET when interacting with  the database uses XML and converts all the data into XML format for database related operations making them more efficient.

The ADO.NET Data Architecture
Data Access in ADO.NET relies on two components: DataSet and Data Provider.
DataSet
The dataset is a disconnected, in-memory representation of data. It can be considered as a local copy of the relevant portions of the database. The DataSet is persisted in memory and the data in it can be manipulated and updated independent of the database. When the use of this DataSet is finished, changes can be made back to the central database for updating. The data in DataSet can be loaded from any valid data source like Microsoft SQL server database, an Oracle database or from a Microsoft Access database.
Data Provider
The Data Provider is responsible for providing and maintaining the connection to the database. A DataProvider is a set of related components that work together to provide data in an efficient and performance driven manner. The .NET Framework currently comes with two DataProviders: the SQL Data Provider which is designed only to work with Microsoft's SQL Server 7.0 or later and the OleDb DataProvider which allows us to connect to other types of databases like Access and Oracle. Each DataProvider consists of the following component classes:
The Connection object which provides a connection to the database
The Command object which is used to execute a command
The DataReader object which provides a forward-only, read only, connected recordset
The DataAdapter object which populates a disconnected DataSet with data and performs update

Data access with ADO.NET can be summarized as follows:
A connection object establishes the connection for the application with the database. The command object provides direct execution of the command to the database. If the command returns more than a single value, the command object returns a DataReader to provide the data. Alternatively, the DataAdapter can be used to fill the Dataset object. The database can be updated using the command object or the DataAdapter.

ADO .NET Data Architecture
Component classes that make up the Data Providers
The Connection Object
The Connection object creates the connection to the database. Microsoft Visual Studio .NET provides two types of Connection classes: the SqlConnection object, which is designed specifically to connect to Microsoft SQL Server 7.0 or later, and the OleDbConnection object, which can provide connections to a wide range of database types like Microsoft Access and Oracle. The Connection object contains all of the information required to open a connection to the database.
The Command Object
The Command object is represented by two corresponding classes: SqlCommand and OleDbCommand. Command objects are used to execute commands to a database across a data connection. The Command objects can be used to execute stored procedures on the database, SQL commands, or return complete tables directly. Command objects provide three methods that are used to execute commands on the database:
ExecuteNonQuery: Executes commands that have no return values such as INSERT, UPDATE or DELETE
ExecuteScalar: Returns a single value from a database query
ExecuteReader: Returns a result set by way of a DataReader object

The DataReader Object
The DataReader object provides a forward-only, read-only, connected stream recordset from a database. Unlike other components of the Data Provider, DataReader objects cannot be directly instantiated. Rather, the DataReader is returned as the result of the Command object's ExecuteReader method. The SqlCommand.ExecuteReader method returns a SqlDataReader object, and the OleDbCommand.ExecuteReader method returns an OleDbDataReader object. The DataReader can provide rows of data directly to application logic when you do not need to keep the data cached in memory. Because only one row is in memory at a time, the DataReader provides the lowest overhead in terms of system performance but requires the exclusive use of an open Connection object for the lifetime of the DataReader.
The DataAdapter Object
The DataAdapter is the class at the core of ADO .NET's disconnected data access. It is essentially the middleman facilitating all communication between the database and a DataSet. The DataAdapter is used either to fill a DataTable or DataSet with data from the database with it's Fill method. After the memory-resident data has been manipulated, the DataAdapter can commit the changes to the database by calling the Update method. The DataAdapter provides four properties that represent database commands:
SelectCommand
InsertCommand
DeleteCommand
UpdateCommand

When the Update method is called, changes in the DataSet are copied back to the database and the appropriate InsertCommand, DeleteCommand, or UpdateCommand is executed. 

Thursday, June 16, 2011

Using the Eval and Bind Method

Using the Eval Method



The Eval method evaluates late-bound data expressions in the templates of data-bound controls such as the GridView, DetailsView, and FormView controls. At run time, the Eval method calls the Eval method of the DataBinder
object, referencing the current data item of the naming container. The
naming container is generally the smallest part of the data-bound
control that contains a whole record, such as a row in a GridView control. You can therefore use the Eval method only for binding inside templates of a data-bound control.


The Eval method takes the
name of a data field and returns a string containing the value of that
field from the current record in the data source. You can supply an
optional second parameter to specify a format for the returned string.
The string format parameter uses the syntax defined for the Format method of the String class.



Using the Bind Method



The Bind method has some similarities to the Eval method, but there are significant differences. Although you can retrieve the values of data-bound fields with the Bind method, as you can with the Eval method, the Bind method is also used when data can be modified.


In ASP.NET, data-bound controls such as the gridview, detailsview, and formview
controls can automatically use the update, delete, and insert
operations of a data source control. For example, if you have defined
SQL Select, Insert, Delete, and Update statements for your data source
control, using Bind in a gridview, detailsview, or formview

control template enables the control to extract values from child
controls in the template and pass them to the data source control. The
data source control in turn performs the appropriate command for the
database. For this reason, the Bind function is used inside the EditItemTemplate or InsertItemTemplate of a data-bound control.


The Bind method is typically used with input controls such as the textbox control rendered by a gridview
row in edit mode. When the data-bound control creates these input
controls as part of its own rendering, it can extract the input values.

Wednesday, June 15, 2011

Asp.Net Basics

1. Explain the life cycle of an ASP .NET page.?

Following are the events occur during ASP.NET Page Life Cycle:



1)Page_PreInit

2)Page_Init

3)Page_InitComplete

4)Page_PreLoad

5)Page_Load

6)Control Events

7)Page_LoadComplete

8)Page_PreRender

9)SaveViewState

10)Page_Render

11)Page_Unload



Among above events Page_Render is the only event which is raised by page. So we can't write code for this event.



2. how does the cookies work in asp.net?

we know Http is an state-less protocol which is required for interaction between clinet and server .



so there is an need to remeber state of request raised by an web browser so that 

web server can recognize you have already previously visited or not.



There are two types of state management techniques:

a) Client side state management

b) Server - side statemanagement



Using cookies comes under clinet side statemanagement .In HttpResponse we write 

Cookie containing sessionId and other information within it.



when a browser made a request to the web server the same cookie is sent
to the server where server recognize the session id and get other
information stored to it previously.



3. What is Ispostback method in ASP.Net? Why do we use that??


Basically Post back is an action performed by a interactive Webpage.
When it goes to the server side for a non-client Operation Server again
posts it back to the client and hence the name.

Ex:



if(!IsPostBack)



will not allow the page to post back again n again bcoz it reduces the performance.



4. Can User Control be stored in library?.

I will say "NO"



there are 3 types of controls:

1) User Control

2) Custom Control

3) Web parts



you can reuse User control in the current project in which you have
built it, but you can't move it to other project as unless you just copy
paste the same file there and make the changes for that project ( which
violets the concept of library).



but custom control can be shared between projects. and you can
precompile them even as a dll, so this means you can use them in library
of any type.



5. what is the difference between application state and caching?

Application Object and Cached Object both falls under Server side State Management.



Application object resides in InProc i.e. on the same server where we hosted our application.

Cache Object resides on server side/ DownStream/Client Side.



Application Object will be disposed once application will stop.

Cache Object can be disposed using Time based cache dependency.



Only one user can access Application Object at a time hence we have to lock it every time we modify it.



6. what is boxing and unboxing?

Boxing is what happens when a value-type object is assigned to a reference-type variable.

Unboxing is what happens when a reference-type variable is assigned to a value-type variable.






7. What are the uses of Reflection??

Reflection is a concept using which we can 



1) Load assemblies dynamically

2) Invoke methods at runtime

3) Retriving type information at runtime.



8. What is the use of AutoWireup in asp.net?

AutoEventWireup attribute is used to set whether the events needs to be automatically generated or not.

In the case where AutoEventWireup attribute is set to false (by default)
event handlers are automatically required for Page_Load or Page_Init.
However when we set the value of the AutoEventWireup attribute to true
the ASP.NET runtime does not require events to specify event handlers
like Page_Load or Page_Init.



9. what events will occur when a page is loaded?

Below are the events occures during page load.



1) Page_PreInit

2) Page_Init

3) Page_InitComplete

4) Page_PreLoad



10. Where is the View state Data stored?

ViewState data is stored in the hidden field. When the page is submitted
to the server the data is sent to the server in the form of hidden
fields for each control. If th viewstate of the control is enable true
the value is retained on the post back to the client when the page is
post backed.



11. What is the difference between custom web user control and a custom web server control?

Web User Control:

1) Easy to Create.

2) It Can be used inside the same Application.(To use it in other application we need to add it to that project.)

3) It Can take advantage of Caching Technique.



Web Server Control:

1) Bit tuff to create as compare to User Control.

2) Easy to use.

3) Can be added to ToolBox.



12. Where do the Cookie State and Session State information be stored?

Cookie Information will be stored in a txt file on client system under a 

folder named Cookies. Search for it in your system you will find it.


Coming to Session State

As we know for every process some default space will be allocated by OS.


In case of InProc Session Info will be stored inside the process where our 

application is running.

In case of StateServer Session Info will be stored using ASP.NET State Service.

In case of SQLServer Session info will be stored inside Database. Default DB 

which will be created after running InstallSQLState Script is ASPState.


13. What is the difference between adding reference in solution Explorer and adding references by USING
?


Adding reference in solution explorer is
used to add the DLL for that project for reference only. If you want to
utilize that DLL methods/functions in our aspx.cs/.cs file etc you must
write using that nameclass library name in file.




14. What are the different types of sessions in ASP.Net? Name them.?

Session Management can be achieved in two ways



1)InProc

2)OutProc



OutProc is again two types

1)State Server

2)SQL Server



InProc

Adv.:

1) Faster as session resides in the same process as the application

2) No need to serialize the data


DisAdv.:

1) Will degrade the performance of the application if large chunk of data is stored

2) On restart of IIS all the Session info will be lost


State Server

Adv.:

1) Faster then SQL Server session management 

2) Safer then InProc. As IIS restart 

won't effect the session data


DisAdv.:

1) Data need to be serialized

2) On restart of ASP.NET State Service session info will be lost

3)Slower as compared to InProc


SQL Server

Adv.:

1) Reliable and Durable

2) IIS and ASP.NET State Service 

restart won't effect the session data

3) Good place for storing large chunk of data


DisAdv.:

1) Data need to be serialized

2) Slower as compare to InProc and State Server

3)Need to purchase Licensed 

version of SQL Serve


15. How do you design a website with multilingual support in ASP.NET?

Multilingual website can be created using Globalization and Localization.


Using Globalization we change the Currency Date Numbers etc to Language Specific Format.


To change the string which is there in the label button etc to language specific string we use Localization.


In Localization we have to create different Resource files for different languages.

During this process we use some classes present in System.Resources System.Globalization System.Threading namespaces.

16. What is caching? What are different ways of caching in ASP.NET?

Caching is a technique of persisting the data in memory for immediate
access to requesting program calls. This is considered as the best way
to enhance the performance of the application.



Caching is of 3 types:


Output Caching - Caches the whole page.

Fragment Caching - Caches a part of the page

Data Caching - Caches the data



17. What is meant by 3-tier architecture.

We generally split our application into 3-Layers

1)Presentation Layer ( Where we keep all web forms Master Pages and User Controls).

2)Business Layer (Where we keep business logic). e.g
Code related to manipulating data Custom Exception classes Custom
Control classes Login related code if any etc. etc.

3)Data Access Layer (Where we keep code used to
interact with DB). e.g. We can have the methods which are using SQL
Helper (Application Block).


18. Explain the basic functionality of garbage collector?

Garbage Collector in .Net Framework is used for Automatic Memory
Management i.e. it is collect all unused memory area and give to
application. system.gc.collect() is a method for release the memory. But
remember one think it is only an request i.e. we can't explicitly
release the memory by using system.gc.collect().


19. What is the difference between mechine.config and web.config?

machine.config is a system level configuration i.e it is applied on
all application in o/s that the configuration is set where as in
web.config it is applicable to only one application i.e each asp.net
webapplication will contain atleast on web.config file.


20. How can exception be handled with out the use of try catch?

using Exception Management application block


or

Page_error

Application_error objects


21. What is the difference between Response.Redirect and Server.Transfer.

Server.Transfer transfers page processing
from one page directly to the next page without making a round-trip back
to the client's browser. This provides a faster response with a little
less overhead on the server.Server.Transfer does not update the clients
url history list or current url. 


Response.Redirect is used toredirect the
user's browser to another page or site. This performs a trip back to the
client where the client's browser is redirected to the new page. The
user's browser history list is updated to reflect the new address.


22. Where the assembly is stored in asp.net?.

private are stored in application / bin directory and public are stored in GAC.


23. How we implement Web farm and Web Garden concept in ASP.NET?.

A web farm is a multi-server scenario. So we may have a server
in each state of US. If the load on one server is in excess then the
other servers step in to bear the brunt.

How they bear it is based on various models.

1. RoundRobin. (All servers share load equally)

2. NLB (economical)

3. HLB (expensive but can scale up to 8192 servers)

4. Hybrid (of 2 and 3).

5. CLB (Component load balancer).

A web garden is a multi-processor setup. i.e. a single server (not like the multi server above).

How to implement webfarms in .Net:

Go to web.config and

Here for mode you have 4 options.

a) Say mode inproc (non web farm but fast when you have very few customers).

b) Say mode StateServer (for webfarm)

c) Say mode SqlServer (for webfarm)

Whether to use option b or c depends on situation. StateServer
is faster but SqlServer is more reliable and used for mission critical
applications.

How to use webgardens in .Net:

Go to web.config and

Change the false to true. You have one more attribute that is related to webgarden in the same tag called cpuMask.


24. Is there any limit for query string? means what is the maximum size?..

Servers should be cautious about depending on URI lengths above 255
bytes because some older client or proxy implementations may not
properly support these lengths.


Query string length depends on browser compatability 



IE supports upto 255

Firefox supports upto 4000


25. What is the exact purpose of http handlers?

ASP.NET maps HTTP requests to HttpHandlers. Each HttpHandler
enables processing of individual HTTP URLs or groups of URL extensions
within an application. HttpHandlers have the same functionality as ISAPI
extensions with a much simpler programming model


Ex

1.Default HttpHandler for all ASP.NET pages ->ASP.NET Page Handler (*.aspx)

2.Default HttpHandler for all ASP.NET service pages->ASP.NET Service Handler (*.asmx)


An HttpHandler can be either synchronous or asynchronous. A
synchronous handler does not return until it finishes processing the
HTTP request for which it is called. An asynchronous handler usually
launches a process that can be lengthy and returns before that process
finishes

After writing and compiling the code to implement an
HttpHandler you must register the handler using your application's
Web.config file.

Monday, May 2, 2011

Differences Between ItemCreated, ItemDataBound and ItemCommand


Differences Between ItemCreated, ItemDataBound and ItemCommand

The important events raised by DataGrid, DataList, Repeater
  • ItemCreated
  • ItemDataBound
  • ItemComman
When
a datagrid, datalist or repeater is bound to a data source say a
dataset it consists of tables and each table consists of data rows. For
each record in the DataSource, a new DataWebControlNameItem instance is
created and appended to the Web Control. After the
DataWebControlNameItem has been created, its dataitem property is set to
the value of the current DataSource record.

The ItemCreated
event fires once for every DataWebControlNameItem added to the data Web
control. It fires before the DataWebControlNameItem's DataItem property
is assigned.

The ItemDataBound event also fires once for every
DataWebControlNameItem added to the data Web control, but this event
fires after the DataWebControlNameItem's DataItem property is assigned.


Finally, the ItemCommand event fires whenever the Command event for a
Button or LinkButton within the data Web control fires.