About Me

Professional Practical HumanBeing

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

DataSet AcceptChanges and RejectChanges

AcceptChanges and RejectChanges

The AcceptChanges( ) and RejectChanges( ) methods either accept or reject the changes that have been made to the DataSetsince it was last loaded from the data source or sinceAcceptChanges( ) was last called.
The AcceptChanges( ) method commits all pending changes within the DataSet. Calling AcceptChanges( ) changes the RowState ofAdded and Modified rows to Unchanged. Deleted rows are removed. The Original values for the DataRow are set to theCurrent values. Calling the AcceptChanges( ) method has no effect on the data in the underlying data source.
The AcceptChanges( ) method is implicitly called on a row when the DataAdapter successfully updates that row back to the data source when the Update( ) method is called. As a result, when aDataAdapter is used to update the data source with the changes made to the DataSet, AcceptChanges( ) doesn't need to be called. Calling AcceptChanges( ) on a DataSet filled using aDataAdapter effectively removes all information about how theDataSet has been changed since it was loaded. This makes it impossible to reconcile those changes back to the data source using the Update( ) method of the DataSet.
The following example demonstrates the AcceptChanges( ) method:
ds.AcceptChanges();
The RejectChanges( ) method cancels any pending changes within the DataSet. Rows marked as Added are removed from theDataSet. Modified and Deleted rows are returned to theirOriginal state. The following example demonstrates theRejectChanges( ) method:
ds.RejectChanges();
The following example illustrates the concepts just explained:
// create a table with one column
DataTable dt = new DataTable();
dt.Columns.Add("MyColumn",  typeof(System.String));
 
// add three rows to the table
DataRow row;
 
row = dt.NewRow();
row["MyColumn"] = "Item 1";
dt.Rows.Add(row);
 
row = dt.NewRow();
row["MyColumn"] = "Item 2";
dt.Rows.Add(row);
 
row = dt.NewRow();
row["MyColumn"] = "Item 3";
dt.Rows.Add(row);
 
dt.AcceptChanges();
 
// modify the rows
 
dt.Rows[0]["MyColumn"] = "New Item 1"; // DataRowState=Modified
dt.Rows[1].Delete();                   // DataRowState=Deleted
//dt.Rows[2]                           // DataRowState=Unchanged
 
dt.Rows[0].AcceptChanges();            // DataRowState=Unchanged,
                                       // MyColumn value="New Item 1";
dt.Rows[1].RejectChanges();            // DataRowState=Unchanged,
                                       // row not deleted
The DataTable and DataRow objects also expose anAcceptChanges( ) method and a RejectChanges( ) method. Calling these methods on the DataSet implicitly calls these methods for all DataRow objects in the DataSet.

HasChanges and GetChanges

The HasChanges( ) method of the DataSet indicates whether theDataSet has changes, including Added, Deleted, or Modifiedrows. The method accepts an optional DataRowState argument that causes the method to returns a value from the DataSetRowenumeration if the DataSet has changes:
// check if there are any changes to the DataSet
Boolean hasChanges = ds.HasChanges();
 
// check if there are modified rows in the DataSet
Boolean hasModified = ds.HasChanges(DataRowState.Modified);
The GetChanges( ) method creates a copy of the DataSetcontaining all the changes that have been made since it was last loaded or since AcceptChanges( ) was called. The method takes an optional DataRowState argument that specifies the type of row changes the DataSet should include. The GetChanges( ) method can select the data that has been modified in a DataSet so that only the changed data rather than the entire DataSet is returned. This subset of the DataSet that contains just the changed data can improve performance of disconnected applications by reducing the amount of information that needs to be transmitted between different application domains.
The HasChanges( ) method can be called first to determine whetherGetChanges( ) needs to be called. The following example show how to use the HasChanges( ) and GetChanges( ) methods:
// check to see whether GetChanges needs to be called
if (ds.HasChanges())
{
    // create a DataSet containing all changes made to DataSet ds
    DataSet dsChange = ds.GetChanges();
 
    // create a DataSet containing only modified rows in DataSet ds
    DataSet dsModified = ds.GetChanges(DataRowState.Modified);
}


Source :-