About Me

Professional Practical HumanBeing

Saturday, January 7, 2012

What is View State

The view state is a key element of an ASP.NET page because it is the primary means to persist the state of the Web server controls. Whenever the page posts back, the state is restored, updated using the current form parameters, then used to run the postback event handler. Normally, the view state is a hashed string encoded as Base64 and stored in a hidden field called __VIEWSTATE. In this way, the view state is not cached on the client, but simply transported back and forth with potential issues both for security and performance. As I said, you could keep the view state on the server, which requires only minimal coding. You will pay extra overhead because you're accessing a file off the disk or a database, but you'll be returning much slimmer pages while taking less of a security risk. Although in this column I considered persistent storage on the server (file or database), nothing would really prevent you from using the Cache object, thus combining server-side storage and speed of execution

Difference Between StoredProc and Function

Procedure can return zero or n values whereas function can return one value which is mandatory.

Procedures can have input,output parameters for it whereas functions can have only input parameters.

Procedure allow select as well as DML statement in it whereas function allow only select statement in it.

Functions can be called from procedure whereas procedures cannot be called from function.

Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function.

We can go for transaction management in procedure whereas we can't go in function.

Procedures can not be utilized in a select statement whereas function can be embedded in a select statement.



Functions are compiled and executed at run time.
Stored procedures are stored in parsed and compiled format in the database.

Functions cannot affect the state of the database which means we cannot perform insert,delete,update and create operations on the database.
Stored Procedures can affect the state of the database by using insert,delete,update and create operations.

Functions are basically used to compute values. We passes some parameters to functions as input and then it performs some operations on the parameter and return output.
Stored procedures are basically used to process the task.

Function can not change server environment and our operating system environment.
Stored procedures can change server environment and our operating system environment.

Functions can not be invoked from SQL Statements. Execute. SELECT
operating system can be invoked from SQL Statements. Execute. SELECT

Functions can run an executable file from SQL SELECT or an action query.
operating system use Execute or Exec to run

Monday, January 3, 2011

What is the Main difference between String and StringBuilder and why do we use StringBuilder

Note 1 :-

Use StringBuilder if you are planning to change/concatenate a string a lot, as it's slightly more efficient.

This is because a string type is immutable within the CLR, this means that if you do this:

string test = String.Empty();

test = test + "Hello";

test = test + " World!";

You've actually created 3 strings, one for each time it's been changed

Whereas

StringBuilder test = new StringBuilder();

test.Append("Hello");

test.Append(" World!");

This has created just ONE StringBuilder

StringBuilder in the Java world is called StringBuffer. I think!

Hope this has cleared it up!

Note 2:-

String are Immutable (Not Modifiable). If you try to modify  the string it actually creates 
a new string and the old  string will be then ready for garbage collection.
StringBuilder when instantiated, creates a new string with  predefined capacity and upto that 
capacity it can  accodomate string without needing to create a new memory  location for the 
string....i mean it is modifiable and can  also grow as and when needed. 
When the string needs to be modified frequently, preferably  use StringBuilder as its optimized 
for such situations.

Note 3 :-

Both String and StringBuilder are classes used to handle the strings.
The most common operation with a string is concatenation. This activity has to be 
performed very efficiently.
When we use the "String" object to concatenate two strings, the first string is 
combined to the other string by creating a new copy in the memory as a string object,
and then the old string is deleted.
This process is a little long. Hence we say "Strings are immutable".
When we make use of the "StringBuilder" object, the Append method is used. 
This means, an insertion is done on the existing string.
Operation on StringBuilder object is faster than String operations, as the copy 
is done to the same location. Usage of StringBuilder is more efficient in case large
amounts of string manipulations have to be performed.

SQL SERVER – Get Common Records From Two Tables Without Using Join

I really enjoy answering questions which I receive from either comments or Email. My passion is shared by SQL Server Expert Imran Mohammed. He frequently SQL community members by answering their questions frequently and promptly.

Sachin Asked:

Following is my scenario,
Suppose Table 1 and Table 2 has same column e.g. Column1
Following is the query,

1. Select column1,column2 From Table1
2. Select column1 From Table2

I want to find common records from these tables, but i don’t want to use Join clause bcoz for that i need to specify the column name for Join condition. Will you help me to get common records without using Join condition? I am using SQL Server 2005.

Imran Mohammed Replied:

If you are using SQL Server 2005, then you can use Intersect Key word, which gives you common records.

SELECT column1
FROM table1
INTERSECT
SELECT
column1
FROM table2

If you want in the output both column1 and column2 from table1 which has common columns1 in both tables.

SELECT column1, column2
FROM table1
WHERE column1 IN
(
SELECT column1
FROM table1
INTERSECT
SELECT
column1
FROM table2
)

To do this, make sure your column1 is unique and do not have duplicate records.

This is good answer. INTERSECT is new operator in SQL Server which gives you similar answer without using JOIN. I have previously written article where I have compared INTERSECT with INNER JOIN I suggest that all user read that article for further clarity.


SQL SERVER – 2005 – Difference Between INTERSECT and INNER JOIN – INTERSECT vs. INNER JOIN

INTERSECT operator in SQL Server 2005 is used to retrieve the common records from both the left and the right query of the Intersect Operator. INTERSECT operator returns almost same results as INNER JOIN clause many times.

When using INTERSECT operator the number and the order of the columns must be the same in all queries as well data type must be compatible.

Let us see understand how INTERSECT and INNER JOIN are related.We will be using AdventureWorks database to demonstrate our example.

Example 1: Simple Example of INTERSECT

SELECT *
FROM HumanResources.EmployeeDepartmentHistory
WHERE EmployeeID IN (1,2,3)
INTERSECT
SELECT
*
FROM HumanResources.EmployeeDepartmentHistory
WHERE EmployeeID IN (3,2,5)

ResultSet:

Explanation:
The ResultSet shows the EmployeeID which are common in both the Queries, i.e 2 and 3.

Example 2: Using simple INTERSECTbetween two tables.

SELECT VendorID,ModifiedDate
FROM Purchasing.VendorContact
INTERSECT
SELECT
VendorID,ModifiedDate
FROM Purchasing.VendorAddress

ResultSet:



Explanation:

The Resultset shows the records that are common in both the tables. It shows 104 common records between the tables.

Example 3: Using INNER JOIN.

SELECT va.VendorID,va.ModifiedDate
FROM Purchasing.VendorContact vc
INNER JOIN Purchasing.VendorAddress va ON vc.VendorID = va.VendorID
AND vc.ModifiedDate = va.ModifiedDate

ResultSet:


Exlanation :
The resultset displays all the records which are common to both the tables. Additionally in example above INNER JOIN retrieves all the records from the left table and all the records from the right table. Carefully observing we can notice many of the records as duplicate records. When INNER JOIN is used it gives us duplicate records, but that is not in the case of INTERSECT operator.

Example 4: Using INNER JOIN with Distinct.

SELECT DISTINCT va.VendorID,va.ModifiedDate
FROM Purchasing.VendorContact vc
INNER JOIN Purchasing.VendorAddress va ON vc.VendorID = va.VendorID
AND vc.ModifiedDate = va.ModifiedDate

ResultSet:

Explanation:
The resultset in this example does not contain any duplicate records as DISTINCT clause is used in SELECT statement. DISTINCT removes the duplicate rows and final result in this example is exactly same as example 2 described above. In this way, INNER JOIN can simulate with INTERSECT when used with DISTINCT.

Summary :

INNER JOIN can simulate with INTERSECT when used with DISTINCT.


Source :-

http://blog.sqlauthority.com/2008/10/17/sql-server-get-common-records-from-two-tables-without-using-join/

http://blog.sqlauthority.com/2008/08/03/sql-server-2005-difference-between-intersect-and-inner-join-intersect-vs-inner-join/

Thursday, December 23, 2010

The Ever-Useful $get and $find ASP.NET AJAX Shortcut Functions

$get

Overview

$get can be used as shorthand for the document.getElementById and element.getElementById functions. The $get shortcut function points to the Sys.UI.DomElement.getElementById JavaScript function which is defined as part of the ASP.NET AJAX client side library (which means you will need to include a ScriptManager on the page to be able to use it). $get accepts two parameters, the first is the ID of the DOM element you want to retrieve, the second is the parent element of where the search starts. The second parameter is optional and when it is not supplied defaults to the document element. Here is the official API reference.

Ex:- $get('divid')

On Master Page:-

Ex:- var div = $get('<%= this.label.ClientID %>');

$find

Overview

The $find shortcut function allows you to look up an ASP.NET AJAX client side Component by it's ID. Here is a link to the $find shortcut's documentation and below is the API description.

Use $find to Fetch an AjaxControlToolkit Extender Behavior

Many of the extender controls of the AjaxControlToolkit include a client side JavaScript API that allows your page to interact with the extender control from the client. While the documentation on the toolkit is well above average, it focuses on the most common properties/attributes of the control and skims over the other less used properties/attributes as well as the client side API. I have found the best way to learn about the client side API is to download the toolkit and browse the code.

Once you discover the capabilities of an extender's the client side API, you are going to need to obtain a reference to the component so you can interact with it from your page. All of the extender controls in the toolkit expose a property called BehaviorID (it is defined on the ExtenderControlBase so all toolkit controls inherit it by default). You can set the BehaviorID in the controls markup, or you can leave it blank, in which case it will have the same ID of the control. The 2 code samples below show both of these options. In the first one, no BehaviorID is specified so this attribute takes on the same value as the ID. In the second sample, I am explicitly specifying a BehaviorID of 'rceBehaviorID', so that is what I can use to look up the Component.

The behavior for this extender can be fetched using the following syntax:

var behavior = $find('rce1ID');

ajaxToolkit:ResizableControlExtender ID="rce1ID" runat="server" ... />

The behavior for this extender can be fetched using the following syntax:

var behavior = $find('rceBehaviorID');

ajaxToolkit:ResizableControlExtender ID="rce2ID" BehaviorID="rceBehaviorID" runat="server" ./>



Sunday, December 19, 2010

When we go for Abstract and Interface

In real time how the abstraction and interface uses when we go for those concept in real time.

Both abstract classes and interfaces are used when there is a difference in behaviour among the sub-types extending the abstract class or implementing the interface.

When the sub-types behaviour is totally different then you use an interface, when the sub-types behaviour is partially common and different with respect to the supertype an abstract class is used. In an abstract class the partially common behaviour is given a concrete implementation. Since there is no common behaviour between an interface and a sub-type an interface does not have an implementation for any of its behaviour.

Lets assume you are developing a framework for a 'killer' competition where the people who participate have to demonstrate their killing skills. Members participating in the competetion have their own ways of killing.

It could be as different as 'using a gun to kill', 'throwing the victim up in the air and kicking his balls when he victim comes down, 'slitting his throat or behaeding the victim'

The expected behaviour here is to 'KILL', though all the members do have that behaviour 'KILL" each member manifests the behaviour in a different way. Since the behaviour manifestation varies from member to member this scenario calls for an interface.

Interface KilingCompetition{
Corpse kill();
}

Each member will implement this interface and give an implementation in his/her own way.

Now, lets consider a karate competition(is it called sparring?). Here each member has to follow certain things as laid out by the organizers or the karate protocol. It may include things like bowing to the opponent before and after the fight starts, taking a stand etc. Now these behaviours are common and has to manifested in the same way by every paticipating member. But the behaviour 'fight' will differ from member to member. So now we have a set of common behaviour and also a behaviour which manifests differently from member to member. this calls for an abstract class where you give implementation to the common behaviour and make the differeing behaviour abstract and hence the class abstract.

public abstract class KarateFight{
public void bowOpponent(){
//implementation for bowing which is common
// for every participant
}

public void takeStand(){
//implementation which is common
// for every participant
}

public abstract boolean fight(Opponent op);
//this is abstract because it differs from
// person to person
}

Vinay.

What is the difference between interface and abstract class?

* interface contains methods that must be abstract; abstract class may contain concrete methods.
* interface contains variables that must be static and final; abstract class may contain non-final and final variables.
* members in an interface are public by default, abstract class may contain non-public members.
* interface is used to "implements"; whereas abstract class is used to "extends".
* interface can be used to achieve multiple inheritance; abstract class can be used as a single inheritance.
* interface can "extends" another interface, abstract class can "extends" another class and "implements" multiple interfaces.
* interface is absolutely abstract; abstract class can be invoked if a main() exists.
* interface is more flexible than abstract class because one class can only "extends" one super class, but "implements" multiple interfaces.
* If given a choice, use interface instead of abstract class.


When to use an Abstract Class and an Interface

For some odd reason, work allows me to handle phone screens and interviews. Each time I give an interview, I try to do three things. First I ask them about general programming questions. This might be OO questions. It might be methodology questions. It might be design pattern questions. Next I like to ask them more specific technologies questions, such as questions “how do you do ABC in Flex? Java?”. Lastly I want to know what they do in their spare time. What books they read? Do they code outside of work? How they go about researching new technologies? Etc.

However, the place I find people getting stuck are basic/general programming knowledge. Recently I conducted an interview, and this person just missed every question I asked. I don’t mind if people miss questions. Sometimes, it just takes some leading and they will get the correct answer. There are certain things though that if you miss entirely, then we have a problem. This has inspired me for this new section that I would like to call “Learn This”. These are topics that I find rather important for a potential candidate to know. There are a few past articles I could think about putting into this section, but I will start fresh.

Abstract Class vs an Interface.

I normally used this “What is the difference between an Abstract Class and an Interface” as a quick way to gauge someone. Lots of times, its the first or second question I will ask. I cannot tell you how many times people will mess this question up. 9 times out of 10, people read about it at some www.basicinterviewquestions.com (not a real site hehe), giving the canned response of “You can define default functionality in an abstract class and you can just define functions in an interface”. The curve ball is thrown when you ask “Why would you use one over the other?”. That will earn you the ‘deer in headlights’ look. The other 1 out of 10 you will get a “I never had to use that so I don’t know”.

At the top level, the are a few basic difference. Abstract classes allow for default default function definition. This means that whatever class extends the abstract class will have access to this. If we have a base class where all the classes will perform the same function, then we can define that in our Abstract class. An interface is a list of functions or properties that if a class implements it, it will have to have those functions defined within it. It is a situation of “Is-A” vs “Can-Do-this”. Objects that extends an Abstract class “Is-A” base class. Objects that implement “Can-Do-This”. Now if I asked this question and got the answer, yes, that would be the correct answer. However, I want to know why one would want to use an interface over an abstract class, and vice versa.

When to prefer an interface

Back when I wrote about the importance of composition, I mentioned that it is extremely useful when you don’t want a massive hierarchical type framework. The same applies to interfaces. This isn’t my example, but its the best one Ive come across. Lets say you have an interface for a Director and another interface for a Actor.

public interface Actor{    Performance say(Line l); }
public interface Director{    Movie direct(boolean goodmovie); }

In reality, there are Actors who are also Directors. If we are using interfaces rather than abstract classes, we can implement both Actor and Director. We could even define an ActorDirector interface that extends both like this:

public interface ActorDirector extends Actor, Director{ ... }

We could achieve the same thing using abstract classes. Unfortunately the alternative would require up to 2^n (where n is the number of attributes) possible combinations in order to support all possibilities.

When to prefer an Abstract class

Abstract classes allow you to provide default functionality for the subclasses. Common knowledge at this point. Why is this extremely important though? If you plan on updating this base class throughout the life of your program, it is best to allow that base class to be an abstract class. Why? Because you can make a change to it and all of the inheriting classes will now have this new functionality. If the base class will be changing often and an interface was used instead of an abstract class, we are going to run into problems. Once an interface is changed, any class that implements that will be broken. Now if its just you working on the project, that’s no big deal. However, once your interface is published to the client, that interface needs to be locked down. At that point, you will be breaking the clients code.

Speaking from personal experiences, frameworks is a good place to show when and where to use both an abstract class and an interface. Another general rule is if you are creating something that provides common functionality to unrelated classes, use an interface. If you are creating something for objects that are closely related in a hierarchy, use an abstract class. An example of this would be something like a business rules engine. This engine would take in multiple BusinessRules as classes perhaps? Each one of these classes will have an analyze function on it.

public interface BusinessRule{    Boolean analyze(Object o); }

This can be used ANYWHERE. It can be used to verify the state of your application. Verify data is correct. Verify that the user is logged in. Each one of these classes just needs to implement the analyze function, which will be different for each rule.

Where as if we were creating a generic List object, the use of abstract classes would be better. Every single List object is going to display the data in a list in some form or another. The base functionality would be to have it go through its dataprovider and build that list. If we want to change that List object, we just extend it, override our build list function, change what we want and call super.buildList();

Almost everyone knows that interfaces means you are just defining a list of functions and that abstract classes has the option of providing default functionality. The snags come when you drop the ‘why would I use one over the other?’. Abstract classes and interfaces are some of the most important fundamentals of object oriented programming. Just knowing the differences between the two is not enough. When you can look at a situation and make a strong recommendation, you will known you have a much stronger knowledge of object oriented programming. Also it helps during interviews. :P .


Choosing between Abstract and Interface

Abstract classes and interfaces offer similar functionality, but both have unique pros and cons. Because abstract classes can offer implementations in addition to just an interface, they can make versioning much simpler. Thus, they are the default recommendation, although there are some scenarios in which interfaces make sense too.

As an example of the versioning difficulties they can introduce, imagine that you have released an abstract class and interface with two methods, void A() and void B(). You are basically stuck with them. That is, you cannot remove them without breaking classes that had derived from your class or implemented your interface. With abstract classes, however, you can extend your class over time. If you wanted to add a newvoid C() method, for example, you could add this on the abstract class with some default implementation. Similarly, if you want to add convenience overloads, you are free to do so with abstract classes. With interfaces, you simply cannot.

Conversely, abstract classes take over derived classes’ type hierarchy. A class can implement an interface yet still maintain some type hierarchy that makes sense. With abstract classes, this is not so. Furthermore, with interfaces you achieve multiple interface inheritance, whereas with abstract classes you cannot.


Source:- http://www.sap-img.com/java/when-we-go-for-abstract-and-interface.htm

http://codeofdoom.com/wordpress/2009/02/12/learn-this-when-to-use-an-abstract-class-and-an-interface/

http://en.csharp-online.net/Common_Type_System%E2%80%94Choosing_between_Abstract_and_Interface

Saturday, December 4, 2010

DataRowState Enumeration:-


The DataRowState enumeration is returned by the RowState property of the DataRow class.


Member nameDescription
Supported by the .NET Compact FrameworkAddedThe row has been added to a DataRowCollection, andAcceptChanges has not been called.
Supported by the .NET Compact FrameworkDeletedThe row was deleted using the Delete method of the DataRow.
Supported by the .NET Compact FrameworkDetachedThe row has been created but is not part of anyDataRowCollection. A DataRow is in this state immediately after it has been created and before it is added to a collection, or if it has been removed from a collection.
Supported by the .NET Compact FrameworkModifiedThe row has been modified and AcceptChanges has not been called.
Supported by the .NET Compact FrameworkUnchangedThe row has not changed since AcceptChanges was last called.

DataRow Class :-

The DataRow and DataColumn objects are primary components of a DataTable. Use theDataRowobject and its properties and methods to retrieve and evaluate; and insert, delete, and update the values in the DataTable. The DataRowCollection represents the actual DataRow objects in theDataTable, and the DataColumnCollection contains the DataColumn objects that describe the schema of the DataTable. Use the overloaded Item property to return or set the value of aDataColumn.

Use the HasVersion and IsNull properties to determine the status of a particular row value, and theRowState property to determine the state of the row relative to its parent DataTable.

To create a new DataRow, use the NewRow method of the DataTable object. After creating a newDataRow, use the Add method to add the new DataRow to the DataRowCollection. Finally, call theAcceptChanges method of the DataTable object to confirm the addition. For more information about adding data to a DataTable, see Adding Data to a Table.

You can delete a DataRow from the DataRowCollection by calling the Remove method of theDataRowCollection, or by calling the Delete method of the DataRow object. The Removemethod removes the row from the collection. In contrast, Delete marks the DataRow for removal. The actual removal occurs when you call AcceptChanges method. By calling Delete, you can programmatically check which rows are marked for removal before actually deleting them. For more information, seeDeleting a Row from a Table.


Deleting Row from a Table :-

There are two methods you can use to delete a DataRow object from a DataTable object: theRemovemethod of the DataRowCollection object, and the Delete method of the DataRow object. Whereas theRemove method deletes a DataRow from the DataRowCollection, the Delete method only marks the row for deletion. The actual removal occurs when the application calls theAcceptChanges method. By using Delete, you can programmatically check which rows are marked for deletion before actually removing them. When a row is marked for deletion, its RowState property is set to Deleted.

When using a DataSet or DataTable in conjunction with a DataAdapter and a relational data source, use the Delete method of the DataRow to remove the row. The Delete method marks the row asDeleted in the DataSet or DataTable but does not remove it. Instead, when theDataAdapterencounters a row marked as Deleted, it executes its DeleteCommand method to delete the row at the data source. The row can then be permanently removed using theAcceptChanges method. If you use Remove to delete the row, the row is removed entirely from the table, but the DataAdapter will not delete the row at the data source.

If a row is marked for deletion and you call the AcceptChanges method of the DataTable object, the row is removed from the DataTable. In contrast, if you call RejectChanges, the RowState of the row reverts to what it was before being marked as Deleted.

Note:-

If the RowState of a DataRow is Added, meaning it has just been added to the table, and it is then marked as Deleted, it is removed from the table

Difference between Delete and Remove in ADO.Net (DataTable):-

Delete is a Soft Delete( you can roll back,since the row will be just marked for deletion)

Remove is a Hard Delete, you will not be able to roll back the datarow

The Delete method performs only a logical deletion by marking the row as Deleted. Hence when the Dataset batch update is done the row is removed from the datasource.

The Remove method, instead, physically removes the row from the Rows collection. As a result, a row deleted through Remove is not marked for deletion and subsequently not processed during batch update.

The basic rule of the thumb to be followed is this, if the goal of your deletion is removing the row from the data source, then use Delete