Friday, May 28, 2010


FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0','c:\db1.mdb';'Admin';, TEST)

Thursday, May 27, 2010


Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack = False Then
End If
End Sub

Private Sub PopulateGridView()
Dim colObjects As New Generic.List(Of MyObject)
For intCount As Integer = 1 To 20
Dim objNew As New MyObject(intCount, "Object number " + intCount.ToString())
Me.GridView1.DataSource = colObjects
End Sub

Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
Select Case e.CommandName
Case "DoAction"
Me.litMessage.Text = "DoAction called for Id " + e.CommandArgument
End Select
End Sub

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound

' Make sure this isn't the header
If e.Row.DataItem IsNot Nothing Then
Dim intCurrentId As Integer = CType(e.Row.DataItem, MyObject).Id
If intCurrentId Mod 10 = 0 Then
' Add a row before this record
Dim tblGrid As Table = CType(Me.GridView1.Controls(0), Table)
' Get the rowindex of the current row
Dim intIndex As Integer = tblGrid.Rows.GetRowIndex(e.Row)
' Create a new row to hold our subheading
Dim gvrSubHeading As New GridViewRow(intIndex, intIndex, DataControlRowType.Separator, DataControlRowState.Normal)
' Create a table cell for the row
Dim cellHeader As New TableCell()
' Set the colspan of the cell to the width of the table
cellHeader.ColumnSpan = Me.GridView1.Columns.Count
' Set the text
cellHeader.Text = "Subheading here"
' Add the cell to the row
' Add the row to the table
tblGrid.Controls.AddAt(intIndex, gvrSubHeading)
End If
End If

End Sub
End Class

Public Class MyObject

Private _intId As Integer
Private _strName As String

Public ReadOnly Property Id() As Integer
Return Me._intId
End Get
End Property

Public Property Name() As String
Return Me._strName
End Get
Set(ByVal value As String)
Me._strName = value
End Set
End Property

Public Sub New(ByVal pId As Integer, ByVal pName As String)
Me._intId = pId
Me._strName = pName
End Sub

End Class

c# FAQ


* 1. Introduction
o 1.1 What is C#?
o 1.2 How do I develop C# apps?
o 1.3 Does C# replace C++?
o 1.4 Does C# have its own class library?
* 2. Types
o 2.1 What standard types does C# use?
o 2.2 Is it true that all C# types derive from a common base class?
o 2.3 So I can pass an instance of a value type to a method that takes an object as a parameter?
o 2.4 What are the fundamental differences between value types and reference types?
o 2.5 Okay, so an int is a value type, and a class is a reference type. How can int be derived from object?
o 2.6 Are C# references the same as C++ references?
o 2.7 Can I use typedefs in C#?
* 3. Classes and Structs
o 3.1 Structs are largely redundant in C++. Why does C# have them?
o 3.2 Does C# support multiple inheritance (MI)?
o 3.3 Is a C# interface the same as a C++ abstract class?
o 3.4 Are C# constructors the same as C++ constructors?
o 3.5 Are C# destructors the same as C++ destructors?
o 3.6 If C# destructors are so different to C++ destructors, why did MS use the same syntax?
o 3.7 Are all methods virtual in C#?
o 3.8 How do I declare a pure virtual function in C#?
o 3.9 Can I call a virtual method from a constructor/destructor?
o 3.10 Should I make my destructor virtual?
* 4. Exceptions
o 4.1 Can I use exceptions in C#?
o 4.2 What types of object can I throw as exceptions?
o 4.3 Can I define my own exceptions?
o 4.4 Does the System.Exception class have any cool features?
o 4.5 When should I throw an exception?
o 4.6 Does C# have a 'throws' clause?
* 5. Run-time Type Information
o 5.1 How can I check the type of an object at runtime?
o 5.2 Can I get the name of a type at runtime?
o 5.3 What is the difference between typeof and GetType()?
* 6. Miscellaneous
o 6.1 How do I do a case-insensitive string comparison?
o 6.2 Does C# support a variable number of arguments?
o 6.3 How can I process command-line arguments?
o 6.4 Does C# do array bounds checking?
o 6.5 How can I make sure my C# classes will interoperate with other .NET languages?
o 6.6 How do I use the 'using' keyword with multiple objects?
o 6.7 What is the difference between == and object.Equals?
o 6.8 How do I enforce const correctness in C#?
* 7. C# 2.0
o 7.1 What are the new features in C# 2.0?
o 7.2 Are C# generics the same as C++ templates?
* 8. C# 3.0
o 8.1 What's new in C# 3.0?
* 9. Resources
o 9.1 Books

1. Introduction

1.1 What is C#?

C# is a general-purpose object-oriented programming language designed by Microsoft. It is loosely based on C/C++, and is very similar to Java. You can download the C# 3.0 spec here.

1.2 How do I develop C# apps?

Visual C# Express is the easiest way to get started. On Linux you can use Mono.
1.3 Does C# replace C++?

There are three options open to the Windows developer from a C++ background:

* Stick with standard C++. Don't use .NET at all.
* Use C++ with .NET. Microsoft supply a .NET C++ compiler that produces IL rather than machine code. (To make full use of the .NET environment (e.g. garbage collection), a set of extensions are required to standard C++, called C++/CLI.)
* Forget C++ and use C#.

Each of these options has merits, depending on the developer and the application, but for most general purpose applications C# is a much more productive environment than C++. Where existing C++ code must be used with a new application, the existing code can be wrapped using C++/CLI to allow it to interop with C#.
1.4 Does C# have its own class library?

Not exactly. The .NET Framework has a comprehensive class library, which C# can make use of. C# does not have its own class library.
2. Types

2.1 What standard types does C# use?

C# supports a very similar range of basic types to C++, including int, long, float, double, char, string, arrays, structs and classes. However, don't assume too much. The names may be familiar, but many of the details are different. For example, a long is 64 bits in C#, whereas in C++ the size of a long depends on the platform (typically 32 bits on a 32-bit platform, 64 bits on a 64-bit platform). Also classes and structs are almost the same in C++ - this is not true for C#. Finally, chars and strings in .NET are 16-bit (Unicode/UTF-16), not 8-bit like C++.
2.2 Is it true that all C# types derive from a common base class?

Yes and no. All types can be treated as if they derive from object (System.Object), but in order to treat an instance of a value type (e.g. int, float) as object-derived, the instance must be converted to a reference type using a process called 'boxing'. In theory a developer can forget about this and let the run-time worry about when the conversion is necessary, but in reality this implicit conversion can have side-effects that may trip up the unwary.
2.3 So I can pass an instance of a value type to a method that takes an object as a parameter?

Yes. For example:

class CApplication
public static void Main()
int x = 25;
string s = "fred";

DisplayMe( x );
DisplayMe( s );

static void DisplayMe( object o )
System.Console.WriteLine( "You are {0}", o );

This would display:

You are 25
You are fred

2.4 What are the fundamental differences between value types and reference types?

C# divides types into two categories - value types and reference types. Most of the intrinsic types (e.g. int, char) are value types. Structs are also value types. Reference types include classes, arrays and strings. The basic idea is straightforward - an instance of a value type represents the actual data, whereas an instance of a reference type represents a pointer or reference to the data.

The most confusing aspect of this for C++ developers is that C# has predetermined which types are represented as values, and which are represented as references. A C++ developer expects to take responsibility for this decision.

For example, in C++ we can do this:

int x1 = 3; // x1 is a value on the stack
int *x2 = new int(3) // x2 is a pointer to a value on the heap

but in C# there is no control:

int x1 = 3; // x1 is a value on the stack
int x2 = new int();
x2 = 3; // x2 is also a value on the stack!

2.5 Okay, so an int is a value type, and a class is a reference type. How can int be derived from object?

It isn't, really. When an int is being used as an int, it is a value. However, when it is being used as an object, it is a reference to an integer value (on the managed heap). In other words, when you treat an int as an object, the runtime automatically converts the int value to an object reference. This process is called boxing. The conversion involves copying the int to the heap, and creating an object instance which refers to it. Unboxing is the reverse process - the object is converted back to a value.

int x = 3; // new int value 3 on the stack
object objx = x; // new int on heap, set to value 3 - still have x=3 on stack
int y = (int)objx; // new value 3 on stack, still got x=3 on stack and objx=3 on heap

2.6 Are C# references the same as C++ references?

Not quite. The basic idea is the same, but one significant difference is that C# references can be null . So you cannot rely on a C# reference pointing to a valid object. In that respect a C# reference is more like a C++ pointer than a C++ reference. If you try to use a null reference, a NullReferenceException is thrown.

For example, look at the following method:

void displayStringLength( string s )
Console.WriteLine( "String is length {0}", s.Length );

The problem with this method is that it will throw a NullReferenceException if called like this:

string s = null;
displayStringLength( s );

Of course for some situations you may deem a NullReferenceException to be a perfectly acceptable outcome, but in this case it might be better to re-write the method like this:

void displayStringLength( string s )
if( s == null )
Console.WriteLine( "String is null" );
Console.WriteLine( "String is length {0}", s.Length );

2.7 Can I use typedefs in C#?

No, C# has no direct equivalent of the C++ typedef. C# does allow an alias to be specified via the using keyword:

using IntList = System.Collections.Generic.List;

but the alias only applies in the file in which it is declared. A workaround in some cases is to use inheritance:

public class IntList : List { }

The pros and cons of this approach are discussed here.
3. Classes and Structs

3.1 Structs are largely redundant in C++. Why does C# have them?

In C++, a struct and a class are pretty much the same thing. The only difference is the default visibility level (public for structs, private for classes). However, in C# structs and classes are very different. In C#, structs are value types (instances stored directly on the stack, or inline within heap-based objects), whereas classes are reference types (instances stored on the heap, accessed indirectly via a reference). Also structs cannot inherit from structs or classes, though they can implement interfaces. Structs cannot have destructors. A C# struct is much more like a C struct than a C++ struct.
3.2 Does C# support multiple inheritance (MI)?

No, though it does support implementation of multiple interfaces on a single class or struct.
3.3 Is a C# interface the same as a C++ abstract class?

No, not quite. An abstract class in C++ cannot be instantiated, but it can (and often does) contain implementation code and/or data members. A C# interface cannot contain any implementation code or data members - it is simply a group of method names & signatures. A C# interface is more like a COM interface than a C++ abstract class.
3.4 Are C# constructors the same as C++ constructors?

Very similar, but there are some significant differences. First, C# supports constructor chaining. This means one constructor can call another:

class Person
public Person( string name, int age ) { ... }
public Person( string name ) : this( name, 0 ) {}
public Person() : this( "", 0 ) {}

Another difference is that virtual method calls within a constructor are routed to the most derived implementation - see Can I Call a virtual method from a constructor.

Error handling is also somewhat different. If an exception occurs during construction of a C# object, the destuctor (finalizer) will still be called. This is unlike C++ where the destructor is not called if construction is not completed. (Thanks to Jon Jagger for pointing this out.)

Finally, C# has static constructors. The static constructor for a class runs before the first instance of the class is created.

Also note that (like C++) some C# developers prefer the factory method pattern over constructors. See Brad Wilson's article.
3.5 Are C# destructors the same as C++ destructors?

No. They look the same but they are very different. The C# destructor syntax (with the familiar ~ character) is just syntactic sugar for an override of the System.Object Finalize method. This Finalize method is called by the garbage collector when it determines that an object is no longer referenced, before it frees the memory associated with the object. So far this sounds like a C++ destructor. The difference is that the garbage collector makes no guarantees about when this procedure happens. Indeed, the algorithm employed by the CLR garbage collector means that it may be a long time after the application has finished with the object. This lack of certainty is often termed 'non-deterministic finalization', and it means that C# destructors are not suitable for releasing scarce resources such as database connections, file handles etc.

To achieve deterministic destruction, a class must offer a method to be used for the purpose. The standard approach is for the class to implement the IDisposable interface. The user of the object must call the Dispose() method when it has finished with the object. C# offers the 'using' construct to make this easier.

Note that it's rarely necessary to define a destructor for a C# class - it only makes sense where the class holds direct references to unmanaged resources, which is very unusual. Implementing IDisposable is somewhat more commonly required, but still only necessary for a small minority of classes.
3.6 If C# destructors are so different to C++ destructors, why did MS use the same syntax?

Presumably they wanted C++ programmers to feel at home. I think they made a mistake.
3.7 Are all methods virtual in C#?

No. Like C++, methods are non-virtual by default, but can be marked as virtual.
3.8 How do I declare a pure virtual function in C#?

Use the abstract modifier on the method. The class must also be marked as abstract. Note that abstract methods cannot have an implementation (unlike pure virtual C++ methods).
3.9 Can I call a virtual method from a constructor/destructor?

Yes, but it's generally not a good idea. The mechanics of object construction in .NET are quite different from C++, and this affects virtual method calls in constructors.

C++ constructs objects from base to derived, so when the base constructor is executing the object is effectively a base object, and virtual method calls are routed to the base class implementation. By contrast, in .NET the derived constructor is executed first, which means the object is always a derived object and virtual method calls are always routed to the derived implementation. (Note that the C# compiler inserts a call to the base class constructor at the start of the derived constructor, thus preserving standard OO semantics by creating the illusion that the base constructor is executed first.)

The same issue arises when calling virtual methods from C# destructors. A virtual method call in a base destructor will be routed to the derived implementation.
3.10 Should I make my destructor virtual?

A C# destructor is really just an override of the System.Object Finalize method, and so is virtual by definition.
4. Exceptions

4.1 Can I use exceptions in C#?

Yes, in fact exceptions are the recommended error-handling mechanism in C# (and in .NET in general). Most of the .NET framework classes use exceptions to signal errors.
4.2 What types of object can I throw as exceptions?

Only instances of the System.Exception classes, or classes derived from System.Exception. This is in sharp contrast with C++ where instances of almost any type can be thrown.
4.3 Can I define my own exceptions?

Yes, just derive your exception class from System.Exception.

Note that if you want your exception to cross remoting boundaries you'll need to do some extra work - see for details.
4.4 Does the System.Exception class have any cool features?

Yes - the feature which stands out is the StackTrace property. This provides a call stack which records where the exception was thrown from. For example, the following code:

using System;

class CApp
public static void Main()
catch( Exception e )
Console.WriteLine( "System.Exception stack trace = \n{0}", e.StackTrace );

static void f()
throw new Exception( "f went pear-shaped" );

produces this output:

System.Exception stack trace =
at CApp.f()
at CApp.Main()

Note, however, that this stack trace was produced from a debug build. A release build may optimise away some of the method calls which could mean that the call stack isn't quite what you expect.
4.5 When should I throw an exception?

This is the subject of some debate, and is partly a matter of taste. However, it is accepted by most that exceptions should be thrown only when an 'unexpected' error occurs. How do you decide if an error is expected or unexpected? This is a judgement call, but a straightforward example of an expected error is failing to read from a file because the seek pointer is at the end of the file, whereas an example of an unexpected error is failing to allocate memory from the heap.
4.6 Does C# have a 'throws' clause?

No, unlike Java, C# does not require (or even allow) the developer to specify the exceptions that a method can throw.
5. Run-time Type Information

5.1 How can I check the type of an object at runtime?

You can use the is keyword. For example:

using System;

class CApp
public static void Main()
string s = "fred";
long i = 10;

Console.WriteLine( "{0} is {1}an integer", s, (IsInteger(s) ? "" : "not ") );
Console.WriteLine( "{0} is {1}an integer", i, (IsInteger(i) ? "" : "not ") );

static bool IsInteger( object obj )
if( obj is int || obj is long )
return true;
return false;

produces the output:

fred is not an integer
10 is an integer

5.2 Can I get the name of a type at runtime?

Yes, use the GetType method of the object class (which all types inherit from). For example:

using System;

class CTest
class CApp
public static void Main()
long i = 10;
CTest ctest = new CTest();

DisplayTypeInfo( ctest );
DisplayTypeInfo( i );

static void DisplayTypeInfo( object obj )
Console.WriteLine( "Type name = {0}, full type name = {1}", obj.GetType(), obj.GetType().FullName );

produces the following output:

Type name = CTest, full type name = CTest
Type name = Int64, full type name = System.Int64

5.3 What is the difference between typeof and GetType()?

Apart from the obvious (i.e. typeof operates on a type whereas GetType operates on an object), the main thing to watch out for is that GetType returns the underlying type of the object, which may not be the same as the type of the reference to the object. For example:

class Base { }
class Derived : Base { }

class Program
static void Main()
ShowType( new Derived() );

static void ShowType( Base b )

gives the following output:


6. Miscellaneous

6.1 How do I do a case-insensitive string comparison?

Use the string.Compare method. Its third parameter specifies case sensitivity.

"fred" == "Fred" // false
string.Compare( "fred", "Fred", StringComparison.CurrentCultureIgnoreCase ) == 0 // true

For more control over the comparison, e.g. exotic features like width-sensitivity, consider using System.Globalization.CompareInfo.Compare(), e.g.

"fred", "Fred",
CompareOptions.IgnoreCase |
CompareOptions.IgnoreKanaType |

6.2 Does C# support a variable number of arguments?

Yes, using the params keyword. The arguments are specified as a list of arguments of a specific type, e.g. int. For ultimate flexibility, the type can be object. The standard example of a method which uses this approach is System.Console.WriteLine().
6.3 How can I process command-line arguments?

Like this:

using System;

class CApp
public static void Main( string[] args )
Console.WriteLine( "You passed the following arguments:" );
foreach( string arg in args )
Console.WriteLine( arg );

(Take a look at Charles Cook's NOptFunc project for easy command-line parsing.)
6.4 Does C# do array bounds checking?

Yes. An IndexOutOfRange exception is used to signal an error.
6.5 How can I make sure my C# classes will interoperate with other .NET languages?

Make sure your C# code conforms to the Common Language Subset (CLS). To help with this, add the [assembly:CLSCompliant(true)] global attribute to your C# source files. The compiler will emit an error if you use a C# feature which is not CLS-compliant.
6.6 How do I use the 'using' keyword with multiple objects?

You can nest using statements, like this:

using( obj1 )
using( obj2 )

However consider using this more aesthetically pleasing (but functionally identical) formatting:

using( obj1 )
using( obj2 )

6.7 What is the difference between == and object.Equals?

For value types, == and Equals() usually compare two objects by value. For example:

int x = 10;
int y = 10;
Console.WriteLine( x == y );
Console.WriteLine( x.Equals(y) );

will display:


However things are more complex for reference types. Generally speaking, for reference types == is expected to perform an identity comparison, i.e. it will only return true if both references point to the same object. By contrast, Equals() is expected to perform a value comparison, i.e. it will return true if the references point to objects that are equivalent. For example:

StringBuilder s1 = new StringBuilder("fred");
StringBuilder s2 = new StringBuilder("fred");
Console.WriteLine( s1 == s2 );
Console.WriteLine( s1.Equals(s2) );

will display:


s1 and s2 are different objects (hence == returns false), but they are equivalent (hence Equals() returns true).

Unfortunately there are exceptions to these rules. The implementation of Equals() in System.Object (the one your class inherits by default) compares identity, i.e. it's the same as operator==. So Equals() only tests for equivalence if the class author overrides the method (and implements it correctly). Another exception is the string class - its operator== compares value rather than identity.

Bottom line: If you want to perform an identity comparison use the ReferenceEquals() method. If you want to perform a value comparison, use Equals() but be aware that it will only work if the type has overridden the default implementation. Avoid operator== with reference types (except perhaps strings), as it's simply too ambiguous.
6.8 How do I enforce const correctness in C#?

You can't - at least not in the same way you do in C++. C# (actually, the CLI) has no real concept of const correctness, For example, there's no way to specify that a method should not modify an argument passed in to it. And there's no way to specify that a method does not modify the object on which it is acting.

To get a feel for the angst this causes among some C++ programmers, read the feedback on this post from Raymond Chen.

There are of course ways of addressing this issue. For example, see Brad Abram's post (and associated feedback) for some ideas on adding optional read-only behaviour to collection classes.
7. C# 2.0

7.1 What are the new features in C# 2.0?

Support for all of the new framework features such as generics, anonymous methods, partial classes, iterators and static classes. See the .NET FAQ for more on these features.

Delegate inference is a new feature of the C# compiler which makes delegate usage a little simpler. It allows you to write this:

Thread t = new Thread(ThreadFunc);

instead of this:

Thread t = new Thread( new ThreadStart(ThreadFunc) );

Another minor but welcome addition is the explicit global namespace, which fixes a hole in namespace usage in C# 1.x. You can prefix a type name with global:: to indicate that the type belongs to the global namespace, thus avoiding problems where the compiler infers the namespace and gets it wrong.

Finally C# 2.0 includes some syntactic sugar for the new System.Nullable type. You can use T? as a synonym for System.Nullable, where T is a value type. As suggested by the name, this allows values of the type to be 'null', or 'undefined'.
7.2 Are C# generics the same as C++ templates?

No, not really. There are some similarities, but there are also fundamental differences. See the .NET FAQ for more details.
8. C# 3.0

8.1 What's new in C# 3.0?

Support for LINQ was the driving force behind the main enhancements in C# 3.0. Query expressions are the most obvious example, but lambda expressions, extension methods and anonymous types also fall into this category. However most of these enhancements are useful beyond LINQ.

Query expressions allow a SQL-like query syntax to be used in C#, e.g.

var nameList = new List { "jack", "jill", "sue" };

var results = from name in nameList
where name.StartsWith("j")
select name;

Query expressions are just syntactic sugar - they resolve to standard method calls. For example the query expression above can be rewritten as:

var results = nameList.Where(name => name.StartsWith("j"));

The argument to Where() is a lambda expression, which represents an anonymous method. However a lambda expression is not just a more concise way to represent executable code - it can also be interpreted as a data structure (known as an expression tree), which allows the expression to be easily analysed or transformed at runtime. For example, LINQ-to-SQL makes use of this feature to transform C# queries to SQL queries, which gives much better performance than a simple in-memory filtering of results (as offered by DataTable.Select(), for example).

The Where() method shown above is an example of another new C# 3.0 feature: extension methods. Extension methods allow extra methods to be 'attached' to an existing type - any type, even sealed types or types you don't have the source code for. For example, the Where() method can be applied to any type that implements IEnumerable.

Another new feature of C# 3.0 is the var keyword, which allows the compiler to infer the type of a variable from context, which is required for anonymous types but can be used with standard named types too:

var list = new List() { "jack", "jill", "sue" }; // optional use with named types

var person = new { name = "jack", age = 20 }; // anonymous type

These examples also demonstrate the new object initializer and collection initializer syntax.

Finally, there are implicitly typed arrays and auto-implemented properties:

var names = new [] { "jack", "jill", "sue" }; // implicitly string[]

public string Name { get; set; } // auto-implemented property - private backing field auto-generted


What is a Garbage Collector? How it is Used?
Posted by admin on August 3, 2006 Leave a comment (0) Go to comments

Again, this is a very basic, but detailed question about object oriented languages. You may also be asked to describe the advantages and disadvantages of using garbage collector, or how it is used in a specific language such as C++ or Java. Here I just give you some basic concepts of garbage collector:

Why garbage collector is needed? – When an object is no longer referenced by another object, then it is necessary to reclaim the system resources such as cache memory previously allocated by this object. A garbage collector periodically scans the active object space for objects no longer being referenced and released the system resources for any such objects.

Advantages – This automatic process relieves the application programmer from the duties of freeing objects that are no longer needed. This represents a substantial saving in the amount of detailed, low-level programming that the programmer must do.

Disadvantages – The garbage collection process is typically not under control of the application. This can lead to unpredictable delays in processing.


“With a Master’s degree in Computer Science from nagarjuna university, I have been in IT industry for 3 years. I’ve gained extensive experience in all aspects of software engineering, including software design, systems architecture, application programming, and QA testing. Currently I’m a software engineer with LitmusInfoSec and have worked on several software development projects for our clients. As the lead developer, I designed and developed a web-based food processing management system for RedFields Producers to help the company increase productivity by 30%. I’m skilled in the latest techniques such as web services and SOA, proficient with the new languages like C# and Rudy on Rail. I’m always focused on building robust software systems to meet our customer’s needs. One of my major strengths is that I work very hard and continually look for ways to provide the highest quality products and services while reducing the time and costs to complete the project. I am self-motivated and enjoy working in a team environment. I’m looking for an opportunity to work for a growing company where I can contribute my hands-on experience and grow my career with the company. By some research I found that yours is the type of companies I really want to work with.”

Please describe your experience preparing written documents? Who was your audience?
Posted by admin on September 15, 2008 0 comments
Business Analyst Questions, Soft Skill QuestionsDocumentation

Give all documentations you made or you may have created.

“I’ve created tons of documentations in my past jobs, such as…”

Here’s list of documentations common for IT:

Requirement Analysis document
Functional Specification
Technical Specification
User’s Manual
Technical Guide
Operational Procedures Guide
Coding Convention Doc
Project Proposal
RFP – Requirement for Proposal
RFO – Request for Offer
FSR – Feasibility Study Report
BCP – Budget Change Proposal

Wednesday, May 26, 2010

Using jQuery to select/deselect Gridview checkboxes

Using jQuery to select/deselect Gridview checkboxes

I’ve been using jQuery more and more lately. I’ve been studying it closely now specially how to work with its API and has been well surprised at the cool things that it can do. After several hours (more like days and days) of examining its capabilities, I was able to put together a project with several pages of demos that highlights some of its functions, events, DOM manipulation, etc. Learning how cool it can accomplish things, I’d though of what practical applications can I use it for in the real world. None of this will matter if I can’t apply it anywhere else besides building fancy highlighting of text, etc.

jQuery in real world application:
So why not start somewhere such as a Gridview? One common application of Javascript that’s common in tabular type control such as the Gridview is the ability to select/deselect several checkboxes at the time. I’ve seen codes after codes of this implementation but line composes of many lines and none seems to be simple and straight-forward. Since jQuery extends Javascript, the challenge here is to iterate through the input checkboxes by means of minimal or somehow smaller lines of codes.

I’m pretty sure there’s a handful ways of accomplishing this task and one might argue about the usage of $().each() which is a function that iterates through the context of all matched element(s). As far as I know, there’s two easy ways to accomplish the task without using an iteration. One is to refer the input name/id of the checkbox, assuming that you have an id for the input (which would be exactly the same for each row).

Markup of the Gridview:









In your script, you can easily refer to each instances of the rowcheck by doing this, then perform a function accordingly (see code below). This is probably a safer approach since you’re pointing to a specific id. This is perfect if you have another column that also uses a checkbox control.

1: $("#rowcheck").attr("checked", function(){});

A more generic approach would be as follows (see code below). The grdWhatever refers to the id of the Gridview. Something like the code below would work only if only 1 column uses a checkbox since this approach would get every single checkboxes within that specific id of the Gridview that has an input type of checkbox. In most cases, checkboxes are rarely used no more than in a single column.

1: $("#grdWhatever input:checkbox").attr("checked", function() { });

Putting it all together:

1: $(document).ready(function() {

2: $("#headercheck").click(function() {

3: this.checked = !(this.checked == true);

4: var ischecked = !(this.checked == true);

5: $("#grdWhatever input:checkbox").attr("checked", function() {

6: this.checked = ischecked;

7: });

8: });

9: });

The headercheck refers to the header input checkbox that triggers the event to select/deselect the underlying checkboxes. Line 3 reverses the current selection then a variable was introduced to hold whatever the selection was. It then proceeds the iteration of all checkboxes within grdWhatever and apply the same selection to them.With only 7 lines of codes (less the document.ready function), you can't go wrong with this type of implementation. It's readable and very simple to implement.

Tuesday, May 25, 2010


Microsoft Data Development Technologies At-a-Glance


Top Ten Questions and Answers on Data

WCF Data Services and OData At-a-Glance



developers search engine





step by step ebook downloaded link bellow

wcf interview question

Icons list in msdn

question and answer asking for wcf link helpful(ok),category,Architecture.aspx



Domain Knowledge


* Communications
* Financial Services
* Healthcare and Health Plans
* Manufacturing and Retail

code samples

share point


Saturday, May 22, 2010

SQL SERVER – @@IDENTITY vs SCOPE_IDENTITY() vs IDENT_CURRENT – Retrieve Last Inserted Identity of Record

SQL SERVER – @@IDENTITY vs SCOPE_IDENTITY() vs IDENT_CURRENT – Retrieve Last Inserted Identity of Record

It returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value.
@@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get the identity that was created last, even if it was the trigger that created it.

It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value.
SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a user defined function.

It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.
IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

To avoid the potential problems associated with adding a trigger later on, always use SCOPE_IDENTITY() to return the identity of the recently added row in your T SQL Statement or Stored Procedure.

Friday, May 14, 2010


ModalPopupExtender Example for Editing Rows in a GridView (Master/Detail Scenario)

displaying a picture in an image control from stream??(FROM ASP.NET)


Thursday, May 13, 2010

Gridview tips_Tricks

#Export Gridview to xls

The below code will export the gridview contents to the excel file

protected void Button1_Click(object sender, EventArgs e)
Response.AddHeader("content-disposition", "attachment;filename=ExportData.xls");
Response.Charset = String.Empty;
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter strWr = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmWr = new HtmlTextWriter(strWr);

#Summary in the footer of the gridview
To display the summary in the footer of the gridview , try the following code.

decimal priceTotal = 0;
int quantityTotal = 0;
void detailsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow)
// add the UnitPrice and QuantityTotal to the running total variables
priceTotal += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, _
quantityTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, _
else if (e.Row.RowType == DataControlRowType.Footer)
e.Row.Cells[0].Text = "Totals:";
// for the Footer, display the running totals
e.Row.Cells[1].Text = priceTotal.ToString();
e.Row.Cells[2].Text = quantityTotal.ToString();

e.Row.Cells[1].HorizontalAlign = _
e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Right;
e.Row.Font.Bold = true;

#Confirmation message on button click in GridView

To ask the user for the confirmation message on the button click, try the below code

#Change the back color of a GridView Row based on some condition

To change the gridview row color based on some conditions on record, try the below code


protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow)
Label lbl = (Label)e.Row.Cells[1].FindControl("lblFlagNew");
if (lbl.Text == "True")
e.Row.BackColor = System.Drawing.Color.Red;
e.Row.BackColor = System.Drawing.Color.Black;

#Alternative rows back color in gridview

To display the gridview with alternative rows back color, try the below code


you can also use css class , try the below code


#Message for empty grid


#generate row number in the grid

<%# Container.DataItemIndex + 1 %>


math equation Editor


Thursday, May 6, 2010

msdn links


component based programming(Interface Introduction)

Interfaces are constructs having abstract members only. This means that they have the signature or declaration of members only and no functionality implementation is done. The motive behind the use of interfaces is to provide service abstraction i.e. separation of interface from implementation which is a core concept in component based programming.

Also with the use of interfaces, service providers i.e. the classes which implement the interface elements are independent to change their implementation details without any interaction with clients as clients and these service providers are connected in loose coupling.

Before discussing the interface implementation there are some important points about interfaces you should know like interfaces can’t be instantiated and they have public members only. Also all the interface members must be implemented by the class which is implementing the interface.

An interface can extend other interfaces and a class can implement multiple interfaces. Now for understanding the interface implementation by a class consider the following example:

public interface IMyfirstInterface
void Method11();
void Method12();

public class ImplementorClass : IMyfirstInterface
public void Method11()
public void Method12()

In order to implement an interface a class is required which should derive it. Here in the example an interface IMyfirstInterface is defined which has two method’s signatures. For the implementation of this interface a class named ImplementorClass is defined which has implemented both of its methods. This method of implementing interface is called implicit interface implementation.

There is a different technique too where each interface member has to qualify with the interface name which declares it or whose member it is. This technique allows the separation of interface from the implementation and known as explicit interface implementation. Consider the following example to understand how this is done:

public interface IMyfirstInterface
void Method11();
void Method12();

public class ImplementorClass : IMyfirstInterface
void IMyfirstInterface .Method11()
void IMyfirstInterface .Method12()

.NET allows to mix the both techniques but it should be avoided in order to maintain consistency. In C# you can not extend more than one class at a time i.e multiple inheritance is not allowed. To overcome this limitation interfaces are used as there is no restriction in implementing multiple interfaces, so in .NET interface also provide a way to maintain scalability and flexibility.

One construct which also defines the signature of members leaving the functionality implementation is abstract class and it was used as a mechanism to provide service abstraction in earlier object oriented languages. Though abstracts classes sounds similar to the interfaces, both of them have some fundamental differences.

A class in .NET can extend from only one base class, no matter if the base class is abstract. But as stated earlier it can implement multiple interfaces. Also abstract classes can have constructors, variables and even non-abstract methods but interfaces are not allowed to have any of these.

Abstract classes can derive from one base class or multiple interfaces but interfaces can derive from other interfaces only. These restrictions in interfaces enable .NET to isolate the definition of implementation (in interfaces) from the actual implementation code (in the classes implementing the interfaces).


Monday, May 3, 2010

listview imp links


Comparing ListView with GridView,DataList and Repeater

The ListView control is a new data presentation control that was added in ASP.Net 3.5.You may wonder why its added to the framework , and what it provide .

From what i have seen, ListView control was added to provide The following functionalities :

1.A very flexible and customizable layout.
2.A built in data paging support with the new DataPager control.
3.Support data grouping (repeating items) in a flexible way.
4.Built in support for deleting,inserting,paging,sorting,and updating the data.
Now , to compare the ListView control with the dataList,GridView and repeater control , lets look at the table below :

Supported Funcationalities
Control Paging Data Grouping Provide Flexible Layout Update,Delete Insert Sorting
ListView supported supported supported supported supported supported
GridView supported Not supported Not Supported supported Not Supported supported
DataList Not supported supported supported Not supported Not supported Not supported
Repeater Not supported Not supported supported Not supported Not supported Not supported

* Supported: means that it's provided out of the box without any custom code or hacks.

* Not Supported: means that it's not provided out of the box by the control but it could be possible to implement it using custom code \ hacks.

The GridView : it supports paging but it doesn't provide a flexible layout , since its mainly used to display the data in a table based layout.And If we looked at data inserting , the Gridview doesn't have a built in support for inserting data( since it doesn't call the insert method of it underlying data source when you click on a button with a CommadName set to "Insert" ).

The DataList : it support data grouping ( through its RepeatColumns property) , but it doesn't have a built in support for paging,inserting ,deleting , updating the data. and if you looked at its laout , you will find that by default the datalist renders as html table and you will have to set its flowLayout to "Flow" to stop that behaviour.

The Repeater control : you will find that it provides a flexible layout but it doesn't support data grouping ,inserting,deleting , updating and paging through the data .

Summary :

The ListView control was added to provide a rich data control that can support all the required functionalities at the same time , so now you can easily display a fully customizable layout that supports Grouping,paging , inserting , deleting , updating and sorting the data.

useful link

Saturday, April 17, 2010


OOPS - Object Oriented Programming Languages & Systems.
Everything in the world is an object. The type of the
object may vary. In OOPS, we get the power to create
objects of our own, as & when required.

Class - A class is an organized store-house in
object-oriented programming that gives coherent
functional abilities to a group of related code. It is
the definition of an object, made up of software code.
Using classes, we may wrap data and behaviour together
(Encapsulation). We may define classes in terms of
classes (Inheritance). We can also override the
behaviour of a class using an alternate behaviour

Using inhertance, we may assign different traits to different
classes. Yet, the child classes will inherit some common
traits from the base class. As in the figure above, the
classes for "Permanent" and "Wage Worker" will inherit
some common traits from the class of "Employee".

A class may contain class members like fields, properties,
events & methods with different types of access modifiers
like private, public, protected or friend, to process the
way they are accessed. In VB.NET, a class may be declared
as below...

Public Class SampleClass
'define class members
End Class

Key Concepts of .NET - To work with classes and modules,
the key concepts to know are definition, access, inheritance,
constructors, destructors, delegates, abstract classes & interfaces..

Class members - The different types of entities in a class,
like fields, properties, events & methods.

Object - An object is an instance of a class. This instance
may be used to access the members of the class. It is pretty
easy to define an object. See sample code below...

Dim objSampleObject as SampleClass

Structure - It is a bit similar to a class. Semantically,
structures are known as value types, while classes as reference types. We do'nt instantiate an object using the New keyword while working with a structure. We can not inherit from a structure.

Public Structure Student
Public RollNo as Integer
Public Name as String
End Structure

Dim objStud as Student

Here, note that the object objStud is not exactly an instance,
it is a simple object (object of a structure) that is used to
access the members of this structure. It would have behaved
differently had it been an object of a class, as it would have
invoked the constructor associated with the class.

Public Class ClassCalc
Public Function FnAdd(ByVal dblA as double, ByVal dblB _

as double) as Double
FnAdd = dblA + dblB
End Function
End Class

Now, lets make use of the method FnAdd defined in the class
above. To use it, first create an object of this class, say
objX. Using this object, we can invoke the methods of this
class. See code below...

Dim objX as ClassCalc
Dim dblResult as Double
dblResult = objX.FnAdd(4.56,2.35)

Property - A property is a thing that describes the features of an object. A property is a piece of data contained within a class that has an exposed interface for reading/writing. Looking at that definition, you might think you could declare a public variable in a class and call it a property. While this assumption is somewhat valid, the true technical term for a public variable in a class is a field. The key difference between a field and a property is in the inclusion of an interface.

We make use of Get and Set keywords while working with
properties. We prefix the variables used within this code block with an underscore. Value is a keyword, that holds the value
which is being retrieved or set.

Private _Color As String
Public Property Color()
Return _Color
End Get
Set(ByVal Value)
_Color = Value
End Set
End Property

Event - An action that an object does. When something happens, we say an event has happened. For example, when a button is clicked, we say it is the click( ) event. When a mouse hovers on an image, we say the mouseover( ) event has taken place.

Access Modifiers - Keywords used to vary the way members of a class are used. Following are different types...

1) Public - These classes can be used anywhere in the code.
There are no restrictions.

Available only to code outside our class

2) Private - These classes are accessible only within their
declaration contexts. This includes nested procedures. When a variable is declared Public inside a Private class, it is
accessible only from inside that class.

Available only to code inside our class

3) Protected - These classes extend the accessibility of their
members to their child classes (means, to the classes that derive from them). They extend their members to both themselves & their child classes.

Available only to classes that inherit from our class

4) Friend - Friend access means that elements are accessible only within the program. Friend is the default access modifer for any class that does not have a modifier.

Available only to code within our project/component

5) Protected Friend - Available only to classes that inherit from our class (in any project) or to code within our project/component. This is a combination of Protected and Friend.

Default - A Default property is a single property of a class that can be set as the default. This allows developers that use your class to work more easily with your default property because they do not need to make a direct reference to the property. Default properties cannot be initialized as Shared or Private and all must be accepted at least on argument or parameter. Default properties do not promote good code readability, so use this option sparingly.

Overloads - The Overloads property allows a function to be
described using deferent combinations of parameters. Each
combination is considered a signature, thereby uniquely defining an instance of the method being defined. You can define a function with multiple signatures without using the keyword Overloads, but if you use the Overloads keyword in one, you must use it in all of the function's Overloaded signatures.

Shared -The Shared keyword is used in an inherited or base class to define a property or method as being shared among all instances of a given class. If multiple instances of a class with shared properties or methods are loaded, the shared properties or methods will provide the same data across each instance of the class. When one class alters the value for a shared property, all instances of that class will reflect the change. Shared properties of all instances of the class
point to the same memory location.

Overridable -The Overridable keyword is used when defining a property or method of an inherited class, as overridable by the inheriting class.

Overides - The Overides keyword allows the inheriting class to disregard the property or method of the inherited class and implements ts own code.

NotOverridable - The NotOverridable keyword explicitly declares a property or method as not overridable by an inheriting class, and all properties are "not overridable" by default. The only real advantage to using this keyword is to make your code more readable.

MustOverride - The MustOverride keyword forces the inheriting class to implement its own code for the property or method.

Shadows - The Shadows keyword will effectively hide all of the other methods in the baseclass. It is like forcefully getting rid of the overloading that has been done on the methods of the base class.
The Shadows keyword works like the Overloads keyword except that with shadows we do not have to follow rules such as implementing the same signature. The Shadows keyword does not require the consent (override ability) of the inherited class to replace the property or method's implementation code. A method does not have to be defined as overridable for the Shadows keyword to work. Read the example...

'This is the Base Class
Public Class Parent
Public Sub MyProc(ByVal num As Integer)
MsgBox("Number in Parent is " & num)
End Sub

Public Sub MyProc(ByVal st As String)
MsgBox("String in Parent is " & st)
End Sub
End Class

'This is the Child Class
Public Class Child
Inherits Parent
Overloads Sub MyProc(ByVal num As Integer)
'overloads the method with the same parameter list
MsgBox("Number in Child is " & num)
End Sub

Overloads Sub MyProc(ByVal ch As Char)
' overloads the method
MsgBox("Character in Child is " & ch)
End Sub
End Class

When we execute the following code...
Dim c As New Child()

' prints out "String in Parent is Hello Wazzup!"
c.MyProc("Hello Wazzup!")

' prints out "Number in Child is 12"

' prints out "Character in DerivedClass is B"

When we use Shadows keyword...
Public Class ChildNumber2
Inherits Parent
Shadows Sub MyProc(ByVal num As Integer)
' hides all the different argument list
MsgBox("Number in ChildNumber2 is " & num)
End Sub
End Class

Dim c2 As New DerivedClass2()
c2.MyProc(7) 'only one method is exposed, rest of the
'methods are hidden

Constructor - When a class instance is created in our code,
a special method of that class, called the constructor, is called. Similarly, when the class is destroyed, the destructor
method is called. These are general terms and usually not the actual member names in most object-oriented languages. It is initialized using the keyword New, and is destroyed using the keyword Finalize. In .NET, we tend to forget using Finalize as
the instances(means the object) are automatically destroyed by the Garbage Collecter, when the object is not in use by he CLR(Common Language Runtime).

Dim objSampleObject as New SampleClass
' write the code here...

We can add parameters to the constructors. This was'nt allowed in VB6. We can overload the constructors, change the order of parameters, datatypes of parameters which ultimately change the way the constructor works whenever an instance of that class is invoked.

Also note that a constructor can have any access modifier. If
no argument is added in a constructor, VB.NET adds a no-argument constructor during compile time. It adds the Public Sub New( ) with the class declared, if no argument is passed in the constructor. The following code is added...

Public Class ClassA
Public Sub New( )
End Sub

However, when the constructor is added with parameters, the following code is generated...

Public Class ClassA
Public Sub New(ByVal SomeString as String )
End Sub

When a child class' object is declared, the child class
constructor & its parent class constructor, both are invoked.
Read example below for more clarity...

Public Class Books
Public Sub New()
System.Console.WriteLine("Book's constructor.")
End Sub

Public Sub myProc()
System.Console.WriteLine("This is a book.")
End Sub
End Class

Public Class Authors : Inherits Books
Public Sub New()
System.Console.WriteLine("Author's constructor.")
End Sub
End Class

When the Authors class' constructor is invoked, like in the
following code, the Books class' no-argument constructor is also called.

Dim author As Authors
author = New Authors()

The result on the console will be...

Book's constructor.
Author's constructor.

If the base class does'nt have a no-argument constructor, then it would result in a compiler error. Hence, we need to use the MyBase keyword with the constructor. Our child class will look like this...

Public Class Authors : Inherits Books
Public Sub New(ByVal SomeString As String)
System.Console.WriteLine("Authors's constructor.")
End Sub
End Class

If a class is not inheriting from any base class, then it will
call the base class constructor of System.Object if we are using MyBase.New( ). Summarizing constructors, whenever we initiate a constructor, the following things happen...

Base class constructor is invoked.
Class level variables are initialized.
Code in the class constructor gets executed.
If the argument name passed in the constructor, is same as the variable name used in the constructor, we use the Me keyword to refer to the constructor variable. For example if the variable name is SomeString, and the parameter passed is also SomeString, then the variable is referred as Me.SomeString.

Abstract Class - They are classes that cannot be instantiated. We cannot create an object from such a class for use in our program. We can use an abstract class as a base class, creating new classes that will inherit from it. Creating an abstract class with a certain minimum required level of functionality gives us a defined starting point from which we can derive non-abstract classes.

An abstract class may contain abstract methods & non-abstract methods. When a class is derived from an abstract class, the derived class must implement all the abstract methods declared in the base class. We may use accessibility modifiers in an abstract class (unlike in Interfaces).

An abstract class can inherit from a non-abstract class. In C++, this concept is known as pure virtual method.

Interface - its a kind of class, that has only methods, do not have code, just the definition of the methods. Also, the interface can't be instantiated. Its an abstract class with public abstract methods, all of which must be implemented in the inherited classes. All methods in an interface are public, no other access modifier is used. It is public by default.

Classes can contain code, but interface dont. However, classes that implement an interface do contain code. Keep in mind that there are no instances of interfaces in VB .NET. Every instance is a type that implements an interface, but is itself not an instance of the interface. Also note, in an interface, all methods must be abstract (which is not necessary in an abstract class).

'VB .NET Interface
Public Interface ISalary
Sub CreditSalary(ByVal Amount As Decimal)
ReadOnly Property Incentive() As Decimal
ReadOnly Property Attendance() As Integer
End Interface

To use members of an interface, we make use of the implements keyword.

Public Class Employee
Implements ISalary
Public Function Salary() As Decimal Implements ISalary.CreditSalary()
'code here ...
End Function
End Class

Serializable - This is a class attribute. When we use this attribute with a class, an instance of this class can be taken in whatever state it is, and write it to a disk. The class can then be deserialized, and the class will act as if it is simply stored in the memory.

Boxing & Unboxing - Value Types are stored on the stack and Reference types are stored on the heap. The conversion of value type to reference type is known as Boxing. Converting reference type back to value type
is known as Unboxing.

Value Types - Value types are primitive types that are mapped directly to the FCL. Like Int32 maps to System.Int32, double maps to System.double.
All value types are stored on stack and all the value types are derived from System.ValueType. All structures and enumerated types that are derived from System.ValueType are created on stack, hence known as ValueType.

Reference Types - Reference Types are different from value types in such a way that memory is allocated to them from the heap. All the classes are of reference type. C# new operator returns the memory address of the

Partial Class - This concept has been introduced in .NET framework 2.0. They give you the ability to split a single class into more than one source code (.cs or .vb) file. Here's what a partial class looks like when it's split over two files...

// Stored in file MyClass1.cs
public partial class MyClass
public MethodA()

// Stored in file MyClass2.cs
public partial class MyClass
public MethodB()

When you build the application, Visual Studio .NET tracks down each piece of MyClass and assembles it into a complete, compiled class with two methods, MethodA() and MethodB().

Partial classes don't offer much in the way of solving programming problems, but they can be useful if you have extremely large, unwieldy classes. (Of course, this might be a sign that you haven't properly factored your problem, in which case you should really break your class down into separate classes.) The real purpose of partial classes in .NET is to hide automatically generated designer code.

SQL 2005 Strings

SQL Native Client ODBC Driver

Standard security:

"Driver={SQL Native Client};

Trusted connection:

"Driver={SQL Native Client};

Note: Integrated Security=SSPI equals

Prompt for username and password:

oConn.Properties("Prompt") = adPromptAlways
oConn.Open "Driver={SQL Native Client};

Enabling MARS (multiple active result sets):

"Driver={SQL Native Client};

Note: MultipleActiveResultSets=true equals

Encrypt data sent over network:

"Driver={SQL Native Client};

Attach a database file on connect to a local
SQL Server Express instance:

"Driver={SQL Native Client};Server=.\SQLExpress;


"Driver={SQL Native Client};

(Note: use |DataDirectory| when your database file
resides in the data directory)

SQL Native Client OLE DB Provider

Standard security:


Trusted connection:


Note: Integrated Security=SSPI equals

Prompt for username and password:

oConn.Properties("Prompt") = adPromptAlways
oConn.Open "Provider=SQLNCLI;Server=Aron1;DataBase=pubs;"

Enabling MARS (multiple active result sets):


Note: MarsConn=yes equals
MultipleActiveResultSets=true equals

Encrypt data sent over network:


Attach a database file on connect to a local SQL
Server Express instance:




(Note: use |DataDirectory| when your database file
resides in the data directory)

SqlConnection (.NET)

Standard Security:

"Data Source=UrServerName;
Initial Catalog=pubs;
User Id=myUsername;


User ID=myUsername;

Trusted Connection:

"Data Source=UrServerName;
Initial Catalog=pubs;
Integrated Security=SSPI;"



(Note: use serverName\instanceName as Data Source to use
an specifik SQLServer instance)

Connect via an IP address:

"Data Source=,1433;
Network Library=DBMSSOCN;
Initial Catalog=pubs;
User ID=myUsername;

(Note: DBMSSOCN=TCP/IP instead of Named Pipes,
at the end of the Data Source is the port to use (1433
is the default))

Enabling MARS (multiple active result sets):


Note- Use ADO.NET 2.0 for MARS functionality. MARS is not
supported in ADO.NET 1.0 nor ADO.NET 1.1

Attach a database file on connect to a local SQL Server
Express instance:




(Note: use |DataDirectory| when your database file resides
in the data directory)

Using "User Instance" on a local SQL Server Express

"Data Source=.\SQLExpress;
integrated security=true;
attachdbfilename=|DataDirectory|\mydb.mdf;user instance=true;"

Note: The "User Instance" functionality creates a new SQL
Server instance on the fly during connect. This works
only on a local SQL
Server 2005 instance and only when connecting using windows
authentication over local named pipes. The purpose is to
be able to create a full rights SQL Server instance to
a user with limited administrative rights on the computer.

To enable the functionality: sp_configure
'user instances enabled','1' (0 to disable)
Using SQL Server 2005 Express? Don't miss the server name
syntax: SERVERNAME\SQLEXPRESS (Substitute "SERVERNAME" with the name of the computer)

Context Connection - connecting to "self" from within your CLR stored prodedure/function


using(SqlConnection connection = new SqlConnection("context connection=true"))
// Use the connection

Visual Basic:

Using connection as new SqlConnection("context connection=true")
' Use the connection
End Using

The context connection lets you execute Transact-SQL statements
in the same context (connection) that your code was invoked in the first place.

Saturday, April 10, 2010

Constructor vs Static Constructor

A Constructor is usually used to initialize data. However Static Constructor is used to initialize only static members. Here I am just talking about the Constructors. How they get initialized and how they behave.

Things to know about Static Constructor

1. It is used to initialize static data members.

2. Can't access anything but static members.

3. Can't have parameters

4. Can't have access modifiers like Public, Private or Protected.

Now once you understand the above points, you can appreciate the difference between Static Class and Unstatic Class

1. Static Class cannot be instantiated unlike the unstatic class. You should directly access its Method via the ClassName.MethodName

2. A Program can't tell when it is going to load static class but its definitely loaded before the call.

3. A Static class will always have the static constructor and its called only once since after that its in the memory for its lifetime.

4. A Static class can contain only static members. So all the members and functions have to be static.

5. A Static class is always sealed since it cannot be inherited further. Further they cannot inherit form any other class (except Object)

Let's look at a normal Constructor

class Program
static void Main(string[] args)

/* Note two things

1.Here you get to instantiate the Constructor in the code wherever you like.

2.If you debug you get to goto the Constructor and see what is being done.

MyExample myExample = new MyExample();

public class MyExample
private static int StaticVariable ;
public MyExample()
if (StaticVariable < 10)
StaticVariable = 20;
StaticVariable = 100;

public void Print()

Now consider this second example for static class

class Program
static void Main(string[] args)

/* Note the following

1.You dont get to instantiate for sure so you dont know when the constructor was called.

2.Secondly you can access your method directly.


//MyExampleStatic myExampleStatic = new MyExampleStatic();

static class MyExampleStatic
private static int StaticVariable;
static MyExampleStatic()
if (StaticVariable < 10)
StaticVariable = 20;
StaticVariable = 100;
public static void Print()

The point is that static member could be used only by a static Constructor or static Function. Hope you have a Static Constructing life.


variable declaration

DIM PrinterCheckflag AS Boolean
dim mvarGlobalErrorMsg as string

'Retrieves current default Printer

Dim currentDefault As String
currentDefault = p.PrinterSettings.PrinterName
Dim pkInstalledPrinters As String
' Find all printers installed
For Each pkInstalledPrinters In _
Next pkInstalledPrinters

' Set the combo to the first printer in the list
If cboInstalledPrinters.Items.Count > 0 Then
cboInstalledPrinters.SelectedIndex = 0
End If

Private Function SetDefaultPrinter(ByVal Printername As String) ' Set the default printer
Dim DefaultPrinter As String
Dim regKey As RegistryKey
Dim Sys_var As String
Dim index As Integer
regKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows NT\CurrentVersion\Windows", True)
Sys_var = regKey.GetValue("Device")
DefaultPrinter = Sys_var
index = Sys_var.IndexOf(",")
Sys_var = Sys_var.Remove(0, index)
Sys_var = Printername & Sys_var
regKey.SetValue("Device", Sys_var)
'Sys_var = regKey.GetValue("Device")
PrinterCheckflag = True ' Success in setting default printer
Catch ex As Exception
regKey.SetValue("Device", DefaultPrinter)
PrinterCheckflag = False ' Error in Setting Default printer
mvarGlobalErrorMsg = Printername & " : Failed to set as default Printer."

Sys_var = String.Empty
index = Nothing
End Try
End Function

Wednesday, April 7, 2010

OperationContract with required parameters(WITH other options description)

1.Why are all parameters in all of your services declared as optional when most of the times they really aren't?"

Now if you navigate to SvcFile.svc?xsd=xsd0 (if not that then xsd=xsd1 or xsd=xsd2), you can see the schema for this operation and the xs:element elements for all 3 parameters and the return value have minOccurs="0" attribute. This essentially makes these parameters optional in the WSDL, SOAP UI and proxy/client code generated using some java toolkit they are using. As is pretty obvious, we don't want the control to even enter the Transfer method if the SOAP (1.2/1.1) request comes in without any of those parameters.

2.At least for simple parameters, you can use an IParameterInspector to enforce that they are present (see below). This solution has two limitations: it doesn't change the WSDL (which will still note the parameters are optional), and it doesn't work for nullable types. To work for nullable types you'd actually need a new formatter (basically doing the deserialization of the different parameters yourself).

changing the WSDL to reflect the required nature of parameters is my primary goal.
ts good to see how we can validate that required parameters are actually present in a message at the infrastructure level. However, that is not really a problem for most services because when these required parameters are "validated" by the service, in almost all cases a value of 0 or null is invalid anyways.

In this case, sort of rewriting the WSDL for the service (which is easy to do, if not to maintain - you'll need to save the WSDL+XSD files generated for the service, edit them, and link to them via the ExternalMetadataLocation property of the ServiceMetadataBehavior), you're left with the solution listed in your previous blog post.


I'm looking for a way to make method parameters required in an OperationContract without switching to MessageContract. For example, I want to be able to declare a method like the following:

public int Transfer([DataParameter(IsRequired=true)]int SourceAccount, [DataParameter(IsRequired=true)]int TargetAccount, [DataParameter(IsRequired=true)]double Amount);

and have System.ServiceModel.Description.
DataContractSerializerMessageContractExporter.ExportBody method not put minOccurs="0" in the WSDL for the operation.

OperationContract with required parameters

OperationContract with required parameters

I'm looking for a way to make method parameters required in an OperationContract without switching to MessageContract. For example, I want to be able to declare a method like the following:

public int Transfer([DataParameter(IsRequired=true)]int SourceAccount, [DataParameter(IsRequired=true)]int TargetAccount, [DataParameter(IsRequired=true)]double Amount);

and have System.ServiceModel.Description.
DataContractSerializerMessageContractExporter.ExportBody method not put minOccurs="0" in the WSDL for the operation.

READ AND LEAVE IT(convert all services to MessageContracts)

My enhancement request is to provide a way to tag parameters in an OperationContract as required without switching all our services to MessageContracts.

I'm afraid manually editing the WSDLs and publishing them at different URL is not maintainable at all and is a lot more prone to errors. I would rather convert all services to MessageContracts but the fact is I'm not going to do that either for now. Right now, I'm thinking of investigating the possibility of inheriting from the System.ServiceModel.Description.DataContractSerializerMessageContractExporter class and overriding the ExportBody method and then plugging in that custom DCSMCE into the WCF pipeline. Unfortunately, while DataContractSerializerMessageContractImporter is public, DataContractSerializerMessageContractExporter is an internal class. So I will probably need to do hacky and evil things using reflection, which I would rather not have done either. :)



Contract Type Member Attributes Description
ServiceContract OperationContract Describes the operations a service can perform. Maps CLR types to WSDL.
DataContract DataMember Describes a data structure. Maps CLR types to XSD.
MessageContract MessageBody, MessageHeader Defines the structure of the message on the wire. Maps CLR types to SOAP messages.

Q:I'm not sure when I should use a message contract. In fact why would I use a message? After all my operation parameters get serialized into a soap envelope automatically.

So when would I use a message and when would I use a serilizable class?
2. A data contract describes the data that your service operations exchange. Data contracts describe only the data transferred from one side to the other; generally they do not describe the message that carries the data.A message contract would hold all the required information about the message payload itself ie: itself.

Use Message Contracts to implement SOAP Headers, etc.

3. Not wanting to use DataContract versioning and to keep a open Message type across service operations.

I would think MessageContract is better suited for this purpose since it is specifically for custom defining

the Message Headers and Message Body.

Basically a WCF Message ( ie message contract NOT data contract ) will call the serializer once for each member in the body and add the result to the output message .

Now if you send a DataContract it will serialize the entire stream.

My requirement is that I need to Pass in Additional Header information to the WCFservice, this I can do with Message Contracts but I need to maintain two set of Contracts one for the Request (which will contain Message Header + body) and another for Reply which will contain Body Only.

Alternatively if use DataContract I don't have option to pass the Headers, but this can be done in other means(by using Server and Client Message Inspectors).

Monday, April 5, 2010




Public Interface Interface1
sub test()
End Interface


Public Interface Interface1
sub test()
End Interface


Public Class Class1
implements Interface1,Interface2

sub Interface1test ()implements Interface1.test
end sub
sub test() implements Interface2.test

end sub
End Class


Public Class Form1

Private Sub Form1_Load( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

dim obj_I1 as Interface1=new Class1
dim obj_I2 as Interface2=new Class1
End Sub
End Class


interface Interface1
void TEST();

interface Interface2
void TEST();

class MultInterfaces: Interface1,Interface2

void Interface1.TEST()
int k = 740;

void Interface2.TEST()

int k = 340;

private void Form1_Load(object sender, EventArgs e)
MultInterfaces obj = new MultInterfaces();
Interface1 obj1=new MultInterfaces();
Interface2 obj2 = new MultInterfaces();


Saturday, April 3, 2010

How to show number of online users / visitors for ASP.NET website?

There are many ways to count number of active visitors on your ASP.NET website.
They differ in technique and accuracy.

here is the simplest approach that delivers acceptable accuracy when configured optimally:

Step 1:

- first we need to add these lines to our global.asax file
(if your website do not have it, create it by right-clicking on website in solution explorer,
and choosing Add New Item > Global Application Class option)

void Application_Start(object sender, EventArgs e)


// Code that runs on application startup

Application["OnlineUsers"] = 0;


void Session_Start(object sender, EventArgs e)


// Code that runs when a new session is started


Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;



void Session_End(object sender, EventArgs e)


// Code that runs when a session ends.

// Note: The Session_End event is raised only when the sessionstate mode

// is set to InProc in the Web.config file. If session mode is set to StateServer

// or SQLServer, the event is not raised.


Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;



This will allow us that whenever some distant web visitor opens our website in his browser,
and new session is created for him, our "OnlineUsers" variable in the global HttpApplicationState class instance
is increased.

Also when user closes his browser or does not click on any links in our website, session expires,
and our "OnlineUsers" global variable is decreased.

To know more about ApplicationState and HttpApplicationState class visit this MSDN link:

NOTE: we are using Application.Lock and Application.Unlock methods to prevent multiple threads
from changing this variable at the same time.

By calling Application.Lock we are receiving exclusive right to change the values in Application state.
But we must not forget to call Application.Unlock() afterwards.

Step 2:
In order for this to work correctly we need to enable sessionstate and configure its mode to InProc value (in our web.config file):

In-process mode stores session state values and variables in memory on the local Web server.
It is the only mode that supports the Session_OnEnd event that we used previously.

Timeout value (in minutes, not in seconds) configures how long our sessions are kept 'alive' - in other words
here we set how long our users can be inactive before considered Offline.

In this example timeout is set to 20 minutes, so while our visitors click on some links in our website at least once
in a 20 minutes, they are considered online.
If they do not open any pages on our website longer than 20 minutes, they are considered Offline, and their session
is destroyed, so our online visitor counter is decreased by 1.
(You can experiment with lower or higher values of Timeout settings to see what is the best for your website).

Ok, so now we are done with configuration steps, let us see how to use this:

To show number of online visitors/users on your ASPX page you can use this code:

Visitors online: <%= Application["OnlineUsers"].ToString() %>
Next you could put this code snippet in you UserControl, or inside Asp.Net AJAX UpdatePanel control, and
use Timer to refresh it in regular intervals without refreshing the whole page, but that is another story

How to access Session values from my custom HttpHandler in ASP.NET?
If you try to create a custom HttpHandler in ASP.Net just by creating a custom class that implements only the IHttpHandler interface you will come across a strange limitation: your HttpHandler code wont be able to access the Session object, for example in the ProcessRequest method.

This is because in order to access the Session object (and its values) from your custom HttpHandler you need to implement another interface: IRequiresSessionState

(Don't worry, its just a marker interface and it does not enforce you to add any more methods to your class, it just 'tells' the ASP.NET runtime that you need to access the Session object in your code:

public class CaptchaImageGenerator : IHttpHandler, IRequiresSessionState


// your code that access the Session object comes here...


More info about the topic on this MSDN page: IHttpHandler Interface