जगदीश खोलिया: July 2011

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.