September 12, 2007

Interfaces in .Net a Value Type or a Reference Type

Interface methods can’t contain any implementation; hence, interface types are incomplete
abstract. Also Interfaces dont derive from System.Object or any derived type. Interfaces can be implemented by Reference types as well as Value types. Actually CLR treats interfaces in a different way.

Same interface can be implemented by value stype and reference type. For Example -


public interface ISampleInterface
{
int MYProp1 { get; set; }
void DoWork1();
}

public struct SampleStruct1 : ISampleInterface
{

public int MYProp1 { get { return 0; } set { } }
public void DoWork1() { }
}

public class SampleClass1 : ISampleInterface
{
public int MYProp1 { get { return 0; } set { } }
public void DoWork1() { }
}

ISampleInterface t = new SampleStruct1();
MessageBox.Show(t.ToString());
//result - "SampleStruct1"

ISampleInterface t1 = new SampleClass1();
MessageBox.Show(t1.ToString());
//result - "SampleClass1"


This shows that an interface is nothing more than declaration and its behaviour will depend whether a value type implements it or a reference type.

Labels: ,

September 11, 2007

Interfaces in .Net

What is an Interface?
Interface can be defined as collection of declaration of Properties, Methods, Procedures(VB.Net), Functions and Events. No member of an interface can have a definition, also interfaces cannot be initialized like concrete classes. All declarations of an interface are by default Public, infact Interface itself is Public in .Net and because of this property of an interface , in .net, you do not need to write access modifiers while creating an interface.

Syntax of Interface (C#) --

public interface ISampleInterface
{
event EventHandler CustomEvent1;
int MYProp1
{
get;
set;
}
void DoWork1();
}

Syntax of Interface (VB.Net) --

Interface ISampleInterface

Event CustomEvent1 As EventHandler

Property MyProp1() As Integer

Sub DoWork1()

End Interface

We can provide either Public or Internal(C#)/Friend(VB.Net) access modifier to an interface. Where Internal/Friend will restrict the accessiblity of the interface to the defining assembly only.


Interfaces are implemented not inherited. When a class implements an interface, compiler will force it to implement each and every member of that interface. So we can also say that Interface is kind of contract which any implementing class has to adhere and that class cannot voilate that contract.

So where to use interfaces?
Interfaces are ideally used in situations where you just want to control the definitions of any software. For Example, in a project where core object structure is developed and then business objects are releazed for further development to third parties, it would be good idea to create interfaces for classes and enforce third parties to implement those interfaces. This way all the classes created will adhere to one standard and there will be less chance of design error in project.

Even in cases where single party is involved in development interfaces provide clean and understandable implement of design. Interface can make object structure more understandable.

Microsoft has exposed many interfaces to maintain a uniform implementation, for example IDisposable.

Labels: , , , ,

Abstract Classes with examples

What is an Abstract Class? How and Where to use an abstract class?

These are some common questions but a bit tricky to answer. Bellow I am providing my views and understanding of abstract classes.

Abstract classes are classes that embody coherent and cohesive, but incomplete, concepts, and in turn, make these characteristics available to their specializations via inheritance. People sometimes use the terms "partial type" and "abstract superclass" as synonyms for abstract class. While we would never create instances of abstract classes, we most certainly would make their individual characteristics available to more specialized classes via inheritance.
source - http://www.toa.com/pub/oobasics/oobasics.htm#ac

According to this definition abstract classes can have methods/properties with body and methods/properties with declarations only. In .net all method/property declarations of an abstract class have to be public, but concrete method/property have no such restriction. Also abstract classes can not be initialized. Any concrete class can inherit an abstract class, but all method/property declaration of abstract class have to be implemented by concrete class. If concrete class does not implement all methods/properties .net compiler will give error.

Syntax to use Abstract Classes (VB.Net)

Public MustInherit Class Sample

' Default Constructor
Public Sub New()
'Some Code
End Sub

Public MustOverride Sub DoWorkSub1()

Public MustOverride Function DoWorkFunction1() as System.Int32

Public MustOverride ReadOnly Property Prop1() as String

Private Sub DoWorkSub2()
'Write code
End Sub

End Class

Public Class ConcreteSample1 : Inherits Sample

Public sub New()

MyBase.New()
'Further Code
End Sub

Public Overrides Sub DoWorkSub1()

End Sub

Public Overrides Function DoWorkFunction1() as System.Int32
return 12
End Function

Public Overrides Property Prop1() as String
Get
return ""
End Get
End Property

End Class



Syntax to use Abstract Classes (C#)


public abstract class Sample
{

// Default Constructor
public Sample() { //Some Code }

public abstract void DoWorkSub1();

public abstract int DoWorkFunction1();

public abstract string Prop1 { get; }

private void DoWorkSub2() { //Write code }

}

public class ConcreteSample1 : Sample
{

public ConcreteSample1() : base() { //Further Code }
public override void DoWorkSub1() { }
public override int DoWorkFunction1() { return 12; }
public override string Prop1 { get { return ""; } }

}

Use Abstract(C#)/MustInherit(VB.Net) keyword to declare an abstract class. Any abstract method, procedure(VB.Net), property or function should have abstract/MustInherit keyword in its declaration. No abstract member can be private in an abstract class.

When a concrete class inherits this abstract class it will have to override each and every abstract member of that class. Use override(C#)/Overrides(Vb.Net) keyword to implement abstract member of an abstract class in a concrete class.

Now comes the big question, where should one use an abstract?

Tactically an abstract class should be used at places where more than one class share certain number of same set of functions but also have some some different functions. For Example,
if Class A, Class B and Class C have two functions which have same functionality, then it is better to create abstract Class MasterABC and inherit this class in other concrete class. But be careful with this as we can only inherit from one class. So your decision of creating an abstract class should be based on through analysis of design.

A more practical example of abstract classes can be seen in Data Access Layer classes. Suppose we are creating data access layer for a database, and there is going to be one class for each Stored Procedure and these stored procedures perform normal CRUD functions on the database.

So I am going to write common functionalities of these classes in one abstract class DataEntity and then inherit my concrete classes (for each SP) with this class.

Before this I would like to mention base logic of my data access layer. Each class will use a datatable to store data either to provide it as argument to any SP or store result-set of any Stored Procedure. DataEntity class will hold all the functions to create, access and loop through the datatable.


'Namespaces

Public MustInherit Class DataEntity

Private m_connectionString As String
Protected m_dataRow As DataRow = Nothing
Protected m_dataTable As DataTable = Nothing
Protected m_enumerator As IEnumerator = Nothing
Private m_mappingName As String = ""
Protected m_EOF As Boolean = True

Public Sub New()
End Sub

Public Sub New(ByVal connectionString As String)
End Sub

''' This is used by GetDateTimeAsString, for more informaton see "about DateTimeFormatInfo class" in the Visual Studio Help. The default is "MM/dd/yyyy".
'''

Public StringFormat As String = "MM/dd/yyyy"

''' AddNew is how you add a new record to your Entity, when saved this row will be an INSERT. All Identity columns and calculated columns are present and available after calling Save().
'''

Public MustOverride Sub AddNew()

''' This is the connection string used in relation for this object.
Public Property ConnectionString() As String
End Property

''' True if MoveNext() moves past the last row or there are 0 rows.
Public ReadOnly Property EOF() As Boolean
End Property

''' After loading your BusinessEntity you can filter (temporary hide) rows. To disable the filter set this property to String.empty. After filter using Iteration via MoveNext will properly respect any filter you have in place.
'''

Public Property Filter() As String
End Property

''' After loading your BusinessEntity you can sort the rows. To disable the sort set this property to String.empty. After settign Sort iteration via MoveNext will properly respect the sort order.
'''

Public Property Sort() As String
End Property

''' After loading your BusinessEntity you can add custom columns, this is typically done to create a calculated column, however, it can be used to add a column just to hold state, it will not be saved to the database of course.
'''

Public Function AddColumn(ByVal name As String, ByVal dataType As System.Type) As DataColumn
End Function

''' You can use this to determine the rowstate of a given row in your BusinessEntity, examples are Added, Deleted, Modified.
'''

Public Function RowState() As DataRowState
End Function

''' The number of rows in your BusinessEntity or Zero if none.
Public ReadOnly Property RowCount() As Integer
End Property

''' Resets the interation process back to the first row.
Public Sub Rewind()
End Sub

''' Advances the enumerator to the next element of the collection.
Public Function MoveNext() As Boolean
End Function

''' This method flushes the Data in the DataTable and nulls out the Current Row, including any DynamicQuery Data. You can call FlushData() and then reload an object.
'''

Public Overridable Sub FlushData()
End Sub

''' Gets a customized view of the table that may include a filtered view, or a cursor position.
Public ReadOnly Property DefaultView() As DataView
End Property

''' This is the ADO.NET DataTable, it holds the data for your BusinessEntity. It is protected so your derived class can have access to it but the consumers of your BusinessEntity cannot. Exposing this publically is not a good idea as your data would be able to be modified without going through you business logic.
'''

Protected Friend Property DataTable() As DataTable
End Property

'''
''' This is the ADO.NET DataRow, it holds the data for your BusinessEntity. It is protected so your derived class can have access to it but the consumers of your BusinessEntity cannot. Exposing this publically is not a good idea as your data would be able to be modified without going through you business logic.
'''

Protected Friend Property DataRow() As DataRow
End Property

End Class


Most of the functionality to create and access datatable is present in this class. Now lets create a concrete class which inherits this abstract class. Concrete class will be used to call a stored procedure which returns a result set.


Public Class GetProduct : Inherits DataEntity

Private m_searchParams As Parameters

Public Sub New()
MyBase.New()
End Sub

Public Sub New(connectionString)
MyBase.New(connectionString)
End Sub

Friend Overrides Sub CreateTable()
m_dataTable = New DataTable
With m_dataTable
.TableName = "GetProduct"
End With
End Sub

Public Overrides Sub AddNew()
End Sub

Public Property SearchParameters() As Parameters
Get
If (m_searchParams Is Nothing) Then m_searchParams = New Parameters
Return m_searchParams
End Get
Set(ByVal value As Parameters)
m_searchParams = Value
End Set
End Property


'''
''' Executes the stored procedure.
'''

'''
Public Overrides Sub Execute()

Dim _cmd As SqlCommand = New SqlCommand
Dim _connection As SqlConnection = New SqlConnection(MyBase.ConnectionString)

With _cmd
.Connection = _connection
.CommandType = CommandType.StoredProcedure
.CommandText = "pGetProduct"

If Me.SearchParameters.ProductID = 0 Then
.Parameters.Add(New SqlParameter("@" + SearchColumnNames.ProductID, SqlDbType.Int))
Else
.Parameters.Add(New SqlParameter("@" + SearchColumnNames.ProductID, Me.SearchParameters.ProductID))
End If


End With

_cmd.Connection.Open()
m_dataTable = New DataTable
m_dataTable.Load(_cmd.ExecuteReader, LoadOption.OverwriteChanges)
_cmd.Connection.Close()
_cmd = Nothing
End Sub

Public Class Parameters

Private m_ProductID As Integer

'''The ProductID property.
'''
'''
Public Property ProductID() As Integer

End Property
End Class
End Class


This concrete class provides implementation to all abstract properties and methods of DataEntity class. Similarly classes can be created for any number of stored procedures without repeating the datatable code.

Labels: , , , ,

September 07, 2007

Important TIPS on GROUP DISCUSSION

I have got this nice Information about GROUP DISCUSSION..

Go through it...

GROUPDISCUSSION
A group discussion (GD) is a simulated exercise, where you cannot suddenly put up a show, since the evaluators will see through you easily. In this page you can find tips on GD and how to handle them to ensure a positive outcome.

Here's how most group discussions work Normally groups of 8-10 candidates are formed into a leaderless group, and are given a specific situation to analyze and discuss within a given time limit.

The group may be given a case study and asked to come out with a solution for a problem.

The group may be given a topic and asked to discuss on the same. A panel will observe the proceedings and evaluate the members of the group.

OBJECTIVE
Lets start from the basic. One needs to know what one's objective in the group is. A good definition of your objective is - to be noticed to have contributed meaningfully in an attempt to help the group reach the right consensus. What does this essentially mean?
The first implication is that you should be noticed by the panel. Merely making a meaningful contribution and helping the group arrive at a consensus is not enough. You have to be seen by the evaluating panel to have made the meaningful contribution. What does that mean in practice?

You must ensure that the group hears you. If the group hears you, so will the evaluator. That does not mean that you shout at the top of your voice and be noticed for the wrong reasons.

You have to be assertive. If you are not a very assertive person, you will have to simply learn to be assertive for those 15 minutes. Remember, assertiveness does not mean being bull-headed or being arrogant.

And most importantly, you have to make your chances. Many group discussion participants often complain that they did not get a chance to speak. The fact is that in no group discussion will you get a chance to speak. There is nothing more unacceptable in a GD than keeping one's mouth shut or just murmuring things which are inaudible.

Participate in as many practice GDs as possible before you attend the actual GD. There is nothing like practice to help you overcome the fear of talking in a GD.

The second important implication is that making just any sort of contribution is not enough. Your contribution has to be meaningful. A meaningful contribution suggests that You have a good knowledge base You are able to put forth your arguments logically and are a good communicator.

The quality of what you said is more valuable than the quantity. There is this myth amongst many group discussion participants that the way to succeed in a group discussion is by speaking loudly and at great length. One could not be more wrong. You must have meat in your arguments.

Therefore, think things through carefully.

Always enter the room with a piece of paper and a pen. In the first two minutes jot down as many ideas as you can.

When you jot down points, keep these pointers in mind. If it is a topic where you are expected to take a stand, say for example, "Should India sign the Comprehensive Test Ban Treaty?" note down points for both sides of the argument. It will be useful on two counts -

One, if you do not start the GD and are not amongst the first five speakers and find that everyone in the group is talking for the topic, then it makes sense to take the alternate approach and oppose the topic even if you initially intended to talk for the topic.

Second, it helps to have a knowledge of how group members who take a stand diametrically opposite to yours will put forth their argument and to be prepared with counter arguments.

Everybody else will state the obvious. So highlight some points that are not obvious. The different perspective that you bring to the group will be highly apprecaited by the panel. Some pointers on being relevant while having a different perspective are:
Be careful that the "something different" you state is still relevant to the topic being debated.

Can you take the group ahead if it is stuck at one point? Can you take it in a fresh and more relevant direction?

The last implication is that you must be clearly seen to be attempting to build a consensus.

Gaining support or influencing colleagues is the mantra adopted by many a successful Business Leaders.

Nobody expects a group of ten intelligent, assertive people, all with different points of view on a controversial subject to actually achieve a consensus. But what matters is "Did you make attempts to build a consensus?"

The reason why an attempt to build a consensus is important is because in most work situations you will have to work with people in a team, accept joint responsibilities and take decisions as a group.

You must demonstrate the fact that you are capable and inclined to work as part of a team.

Suppress JavaScript Errors on a WebPage

Bellow I am providing a way to suppress to client side scripting errors. Many times you might want to just neglect a javascript error, so just use the code written bellow.


<script language="JavaScript">

function OnErrorSuppress() { return true; }

window.onError = OnErrorSuppress;

</script>

Although I am not in favor of this technique, one should always handle error using Try Catch mechanism.

Labels:

Dynamic Paging Technique using SQL Server stored procedures

Here is a completely dynamic version of paging technique in the form of a stored procedure. Just pass in a short SQL statement, the Order By clause, and the start row and end row you'd like to return in the result-set. The stored procedure will process your SQL in the order specified and return only the rows indicated.

The basic idea is to process as few rows as possible; this means finding the starting point, and then returning all rows "past" that starting point until the desired number of rows has been returned.

The stored procedure is called "ReturnPage" and uses the following arguments:

@Select = the select statement to return
@OrderBy = the order by clause; don't include the "ORDER BY" part, just
the columns. You must include ASC or DESC for each column in the sort
@StartRow = the first row to return
@EndRow = the end row to return
Let's start with some examples from northwind:

returnpage 'select contactTitle, City, CustomerID from customers',
'ContactTitle ASC, City DESC, CustomerID ASC', 1, 10

returnpage 'select * from Orders','EmployeeID ASC, OrderDate DESC,
OrderID ASC',12,31

returnpage 'select * from [order details]','productID ASC, Quantity
DESC, OrderID asc',30,45



CREATE PROCEDURE ReturnPage(@Select varchar(1000), @OrderBy
varchar(1000),

@StartRow int, @EndRow int)

AS

BEGIN

declare @ColList varchar(2000);

declare @Where varchar(2000);

declare @i int;

declare @i2 int;

declare @tmp varchar(1000);

declare @dec varchar(1000);

declare @f varchar(100);

declare @d varchar(100);

declare @Symbol char(2);

declare @SQL varchar(5000);

declare @Sort varchar(1000);

set @Sort = @OrderBy + ', '

set @dec = ''

set @Where = ''

set @SQL = ''

set @i = charindex(',' , @Sort)

while @i != 0

begin

set @tmp = left(@Sort,@i-1)

set @i2 = charindex(' ', @tmp)

set @f = ltrim(rtrim(left (@tmp,@i2-1)))

set @d = ltrim(rtrim(substring (@tmp,@i2+1,100)))

set @Sort = rtrim(ltrim(substring (@Sort,@i+1,100)))

set @i = charindex(',', @Sort)

set @symbol = case when @d = 'ASC' then '>' else '<' end + case when @i=0 then '=' else '' end set @dec = @dec + 'declare @' + @f + ' sql_variant; ' set @ColList = isnull(replace(replace (@colList,'>','='),'<' ,'=') + ' and ','' ) + @f + @Symbol + ' @' + @f set @Where = @Where + ' OR (' + @ColList + ') ' set @SQL = @SQL + ', @' + @f + '= ' + @f end set @SQL = @dec + ' ' + 'SET ROWCOUNT ' + convert(varchar(10), @StartRow) + '; ' + 'SELECT ' + substring(@SQL,3,7000) + ' from (' + @Select + ') a ORDER BY ' + @OrderBy + '; ' + 'SET ROWCOUNT ' + convert(varchar(10), 1 + @EndRow - @StartRow) + '; ' + 'select * from (' + @Select + ') a WHERE ' + substring(@Where,4,7000) + ' ORDER BY ' + @OrderBy + '; SET ROWCOUNT 0;' exec (@SQL) END

Labels:

Uniqueidentifier vs. IDENTITY Column in SQL Server

For those of you who are not familiar with the uniqueidentifier datatype, here's the lowdown:

1) Uniqueidentifiers are also referred to as GUIDs. (Globally Unique IDentifier)

2) GUID is always guaranteed to be a unique value across space and time. I don't know the full mechanics of creating a GUID, but I seem to remember that it has something to do with the MAC address on your network card and the system time.

3) To get a GUID in SQL Server (7.0+), you call the NEWID() function.

4) The uniqueidentifier data type in SQL Server is stored natively as a 16-byte binary value.

Now, unlike an IDENTITY column, a uniqueidentifier column doesn't automatically gets an assigned value when a row is inserted into a table. You either need to place a default on the uniqueidentifier column (DEFAULT NEWID()), or do something like the following:

DECLARE @GUID uniqueidentifier
SET @GUID = NEWID()
INSERT Item VALUES (@GUID,'Hello World')

The major advantage of using GUIDs is that they are unique across all space and time. This comes in handy if you're consolidating records from multiple SQL Servers into one table, as in a data warehousing situation or in Smart Client which have local data storage in MSDE etc. GUIDs are also used heavily by SQL Server replication to keep track of rows when they're spread out among multiple SQL Servers.

The main disadvantage to using GUIDs as key values is that they are BIG. At 16 bytes a pop, they are one of the largest datatypes in SQL Server. Indexes built on GUIDs are going to be larger and slower than indexes built on IDENTITY columns, which are usually integers (4 bytes). Also value of an IDENTITY columns cab be retrieved by using @@IDENTITY or SCOPE_IDENTITY().

@@IDENTITY and SCOPE_IDENTITY() will return the last identity value generated in any table in the current session. However, SCOPE_IDENTITY returns the value only within the current scope; @@IDENTITY is not limited to a specific scope.

Labels: , ,

September 06, 2007

How to Convert Unicode Character to HTML string?

Use function provided below to get HTML code for a Unicode String.
Its quite usefull when you want to write characters outside ASCII
limit.


//language c#
public static string GetUnicode(string unicodeText)
{
int unicodeVal = 0;
string encoded = "";
foreach( char c in unicodeText)
{
unicodeVal = Convert.ToInt32(c);
//Debug.WriteLine(c.ToString & " : " & unicodeVal.ToString)
if((unicodeVal >= 49) && (unicodeVal <= 122))
{
//in 'ascii' range x30 to x7a which is 0-9A-Za-z plus some punctuation
encoded += c; // leave as-is
}
else
{
// outside 'ascii' range - encode
encoded += String.Concat("&#",
unicodeVal.ToString(System.Globalization.NumberFormatInfo.InvariantInfo),
";");
}
}


return encoded;
}

Labels: , , , ,

JavaScript Cross Browser Copy to Clipboard function

<!-- Copy code the script tag and its content in the HTML section of webpage -->
<script>
<!--


function copy_clip(meintext)
{
if (window.clipboardData)
{

window.clipboardData.setData("Text", meintext);


}
else if (window.netscape)
{


netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');


var clip = Components.classes['...@mozilla.org/widget/clipboard;1']
.createInstance(Components.interfaces.nsIClipboard);
if (!clip) return;


var trans = Components.classes['...@mozilla.org/widget/transferable;1']


.createInstance(Components.interfaces.nsITransferable);
if (!trans) return;


trans.addDataFlavor('text/unicode');


var str = new Object();
var len = new Object();


var str = Components.classes["@mozilla.org/supports-string;1"]


.createInstance(Components.interfaces.nsISupportsString);


var copytext=meintext;


str.data=copytext;


trans.setTransferData("text/unicode",str,copytext.length*2);


var clipid=Components.interfaces.nsIClipboard;


if (!clip) return false;


clip.setData(trans,null,clipid.kGlobalClipboard);


}
return false;


}


//-->
</script>


<!-- usage -->
<input type="button" value="Button" name="B3" onclick="copy_clip('This
is dummy text. This is dummy text. This is dummy text. This is dummy
text. This is dummy text. This is dummy text. This is dummy text. ')">

Labels: