Tuesday, December 14, 2010

Garbage Collector

Overview:

This article gives the brief introduction of Garbage Collector, Generations in the heap memory, Phases of Garbage collection, destructor and the benefits of Garbage collector.

Garbage Collector:
Garbage Collector was invented by John McCarthy around 1959.
Garbage Collector in .NET Framework manages the allocation and releases the memory for the application.
To the new objects created, CLR (Common language runtime) allocates space in the managed heap as long as the space is available in the managed heap. But the size of heap is limited and all allocations done on heap must be de allocated. So, based upon the allocations being made, garbage collector gets activated to release some memory.
Before reclaiming the memory, garbage collector checks whether the objects in the heap are unreferenced. Only when the objects are no longer being used, it performs its operations.



In the above figure as Data 2 is unreferenced, it is ready for garbage collection.
Except the thread that triggered the garbage collection, all the managed threads are suspended before a garbage collection starts.

Garbage Collection:
To optimize the work of garbage collector, Microsoft has divided the heap memory into three equal parts called Generations. They are GEN0, GEN1, GEN2.This is compact garbage collection. New objects are always created in GEN0 and are promoted to other generations based on their lifespan. Long lived objects would be destroyed last as these objects would move from GEN0 to GEN1 and from GEN1 to GEN2.
In .Net the address of object can change at runtime as it goes from one generation to another.
The object once created are never guaranteed to be destroyed because they might get promoted in higher generations and garbage collector would not visit those generations as memory is mostly available in lower generations itself.



Conditions for a Garbage Collection:
Only when one of the following conditions is true, garbage collection occurs:
· If the physical memory of system is low.
· On the managed heap, if the threshold of acceptable memory usage exceeded.
· If the GC.Collect () is called. This method is rarely used because the garbage collector runs continuously.
The Garbage collector can be forced at a certain point in the code by calling System.GC.Collect (). System .GC class is a class which represents the garbage collector, and Collect () method initiates a garbage collection.

Garbage Collection Phases:
Every application in .net has set of roots known as Application roots. The storage locations are being identified by these roots, which refer to objects on the managed heap or to the unreferenced objects.

The Phases in Garbage collection are:
· Marking Phase: Find and creates list of all live objects or application roots.
· Relocating Phase: Updates the references to the objects that will be compacted.
· Compact Phase: Reclaims the space occupied by the dead objects and compacts the surviving objects.

Destructor:
Destructor of a class in .Net is mainly used for destroying COM objects which are created by it in unmanaged heap. Unmanaged heap is not managed by garbage collector.
A destructor is used to release the resources that an object is holding, when an object is ready to be destroyed Finalize method / Destructor is called on that object.

VB

C#(A destructor in C# cannot have any specific modifiers))

Protected Overrides Sub Finalize()

End Sub

~()

{}



Because it’s not predictable when the Destructor method is going to be executed, it’s not recommended to only rely on destructor for releasing of resources and thus Microsoft has suggested two methods that can be invoked by the programmer for the release of resources
1. Close()
2. Dispose()
If any of these methods are invoked by the programmer before losing the reference to an object, care must be taken to avoid Finalize() method to be invoked on the same object when it is garbage collected and that can be done using GC.SuppressFinalize().
Syntax:
Public sub Dispose () or Close ()
-------Code to release resources--------
GC.SuppressFinalize (Me)
End Sub
In VB.Net only the above mentioned form of Finalize is treated as Destructor. There are multiple overloaded forms of Finalize but the other forms are not treated as destructors.
Close() or dispose() methods are custom methods and hence they have to be explicitly called just before unreferencing an object is done. Whereas destructor is automatically called when the object is destroyed by Garbage Collector.

Benefits:
· Without having to free memory, it enables to develop the application.
· In the Managed heap, objects are allocated memory efficiently.
· Clears the memory of unreferenced objects and keeps the memory available for future allocations.
· Memory safety is being provided making sure that one object cannot use the content of another object.

Summary:
Garbage collection in the Microsoft .NET common language runtime environment manages the allocation and releases the memory for application. It gets activated when the managed heap is full and there is need for release of memory. Before GC performs its action it checks whether the object is unreferenced.
Unmanaged heap is not managed by garbage collector. Destructor of a class in .Net is mainly used for destroying COM objects which are created by it in unmanaged heap.

Order of Exceptions

Order of Catch blocks is very importent while implementing the Catch Blocks.For Example if my code is expected to throw DivideByZeroException , If you know the exception type properly you have to write the specifice expected exception then write generic exception. See below example
Ex:
public class Mathematics
{
public int DivisionResult(int x, int y)
{
try
{
return x / y;
}
catch (DivideByZeroException de)
{
return -0;
}
catch (Exception)
{
return -1;
}
}
}


Note1: In the above example if you change the order of Catch you will get compile time error “A previous catch clause already catches all exceptions of this are of a super type (‘System.Exception’)”. This is because of all the exceptions can be caught by the generic catchblock.
Note2: How many catch blocks can i have for a single try block . Answer is no limit.
Note3 : Can i have a try without a catch. Ans: a try should always either have a catch or finally. try will never exist alone ( try cannot be a bachelor ).

Tuesday, December 7, 2010

STATIC in C# .NET

In C#, whenever you declare a variable which is bound to an instance (object) of a class, your variable by default gets its own copy of all the fields in the class. So for example, if you write:

CreditCardAccountPremium cp1 = new CreditCardAccountPremium();
CreditCardAccountPremium cp2 = new CreditCardAccountPremium();
cp1.setFirstName("George");
cp2.setFirstName("Harry");

-- the instances cp1 and cp2 each contain their own string called FirstName. Changing the FirstName in cp2 has no effect on the value of the FirstName in cp1. However, there are some cases where you do not want this behavior. Maybe you would like to set a maximum value for a CashAdvance that is common to the entire CreditCardAccountPremium class. This would be universally applied to all instances of CreditCardAccountPremium.

We really want the "maxCashAdvance" to be stored in memory only once, no matter how many instances of the class we instantiate. To do this, we place the keyword static before the field declaration:

public class CreditCardAccountPremium
{
private static uint maxCashAdvance = 300;
private string FirstName;
private string LastName;
....


Fields declared with the static keyword are referred to as static fields or static data., while the other fields like FirstName are called instance fields. So an instance field belongs to an object, and a static field belongs to the class as a whole. Static fields exist from the moment the assembly containing the class is loaded, and are initialized by the runtime, independent of whether you actually declare any instances of the class. Consequently, we can also have static constructors, which serve no other purpose than to assign initial values to static data:

public class CreditCardAccountSuper
{
private static uint maxCashAdvance;
staticCreditCardAccountSuper()
{
maxCashAdvance = 300;
}


If you were to invoke a CreditCardAccountSuper.maxCashAdvance property, there is no need to assign an initial value within the Main() method; the static constructor does this automatically. Note that the static constructor in which the maxCashAdvance default value is set has the same name as the class, and cannot take any arguments.

Just as is the case with fields, you can declare methods as static provided they don't try to access instance data or any other instance methods. You might want to provide a method to allow users of the class to view the maxCashAdvance value:

public class CreditCardAccountPremium
{
private static uint maxCashAdvance = 300;
private string FirstName;
private string LastName;

public static uint GetMaxCashAdvance()
{
return maxCashAdvance;
}


You access static methods and fields associated with a class differently that you access them as objects (instances of a class). Instead of specifying the name of the instance to access the method (cp1.GetMaxCashAdvance) you will specify the name of the class: CreditCardAccountPremium.GetMaxCashAdvance(). The static modifier can be used with fields, methods, properties, operators, and constructors, but cannot be used with indexers, destructors, or types. C# trashes the whole concept of global functions, variables, and constants. Instead, you can create static class members, making your C# code not only easier to read, but less likely to cause naming and other conflicts.

source:eggheadcafe

More on Static Class

http://www.c-sharpcorner.com/UploadFile/4d790c/5736/

Tuesday, November 16, 2010

Insert multiple rows from gridview into database

you can use Sql bulk copy for this purpose

private void StartImport()
{
SqlBulkCopy bulkCopy = new SqlBulkCopy("Server=ServerName;Database=test;Trusted_Connection=True;",
SqlBulkCopyOptions.TableLock);
bulkCopy.DestinationTableName = "dest table Name";

DataTable dt = CreateDataTableFromFile();
bulkCopy.WriteToServer(dt);
}


private DataTable CreateDataTableFromFile()
{

//create a datatable and fill it with the values from the grridview

return the Datatable;
}


Friday, November 12, 2010

Difference Between Sql-server 2000 & 2005

I've been asked this question every time that there's a new version and yet I've never been able to give what I think is a nice, concise, logical answer that satisfies the asker. Probably it's a lack of my ability to easily form words in my mouth and get them out in the proper order, so I decided it might make some sense to do this on paper (metaphorically speaking) and help others out.

Like many of you, I usually get this question from someone
outside of SQL Server. A windows admin, a network guy, etc.,
someone who has little contact with SQL Server. Or maybe it's
someone who's been stuck with admin'ing a SQL Server instance.

In any case, I wanted to try and explain this concisely for the
non-DBAs. As I began this project, however I soon realized that
it's not easy to just give a good general answer. As with
everything else in SQL Server it seems that "it depends" is the
best general answer, so I broke this up into a few areas. This
part will look at the administrative differences and the next
will cover more of the development differences.

The Administrative Differences
Administering a SQL Server instance to me means making sure the
server service runs efficiently and is stable and allows clients
to access the data. The instance should keep data intact and
function according to the rules of the code implemented while
being well maintained.

Or for the non-DBAs, it means that you are the sysadmin and it
just works.

The overall differences are few. Sure we use Management Studio
instead of Enterprise Manager, but that's not really a big deal.
Really many of the changes, like being able to change connections
for a query, are superficial improvements that don't really
present a substantial change. If you think they do, you might be
in the wrong job.

Security is one area that is a very nice improvement. The
separation of the schema from the owner makes administrative
changes easier, but that is a big deal because it greatly
increases the chances you won't keep an old account active
because it's a pain to change owners on objects. There's also
more granularity and ease of administration using the schema as
another level of assigning permissions.

Another big security change is the ability to secure your web
services using certificates instead of requiring authentication
using a name and password. Add to that the capability to encrypt
data, and manage the keys, can make a big difference in the
overall security of your data. You have to carefully ensure your
application and access is properly secured, but just the
marketing value of encryption when you have credit card,
financial, or medical data is huge. SQL Server 2000 had no real
security features for data, allowing an administrator to see all
data. You could purchase a third party add-on, but it was
expensive and required staff training. Not that you don't need to
learn about SQL Server 2005, but it should be a skill that most
DBAs will learn and be able to bring to your organization over time.

High availability is becoming more and more important to all
sizes of businesses. In the past, clustering or log shipping were
your main choices, but both were expensive and required the
Enterprise Edition. This put these features out of the reach of
many companies, or at least, out of many DBAs' budgets. With SQL
Server 2005, you can now implement clustering, log shipping, or
the new Database Mirroring with the Standard edition. With the
ability of Database Mirroring to use commodity hardware, even
disparate hardware between the primary and mirror databases, this
is a very reasonable cost solution for almost any enterprise.

There are also online indexes, online restores, and fast recovery
in the Enterprise Edition that can help ensure that you take less
downtime. Fast recovery especially can be an important feature,
allowing the database to be accessed as the undo operations
start. With a log of open transactions when a database is
restarted, this can really add up to significant amounts of time.
In SQL Server 2000, you had to have a complete, intact database
before anyone could access it. With redo/undo operations
sometimes taking a significant amount of time, this could delay
the time from Windows startup to database availability by minutes.

Data sizes always grow and for most companies, performance is
always an issue on some server. With SQL Server 2000, you were
limited to using 2GB of RAM and 4 CPUs on the Standard Edition.
The number of CPUs hasn't changed, but you can now use as much
RAM as the OS allows. There also is no limit to the database
size, not that the 1,048,516 TB in SQL Server 2000. Since RAM is
usually a limiting factor in the performance of many databases,
upgrading to SQL Server 2005 could be something you can take
advantage of. SQL Server 2005 also has more options and
capabilities on the 64-bit platform than SQL Server 2000.

Why Upgrade?
This is an interesting question and one I've been asked quite a
bit over the last 18 months since SQL Server 2005 has been
released. The short answer is that if SQL Server 2000 meets your
needs, then there's no reason to upgrade. SQL Server 2000 is a
strong, stable platform that has worked well for millions of
installations. If it meets your needs, you are not running up
against the limits of the platform, and you are happy with your
system, then don't upgrade.

However, there is a caveat to this. First the support timeline
for SQL Server 2000 shows mainstream support ending next year, in
April 2008. I can't imagine that Microsoft wouldn't extend that
given the large number of installations of SQL Server 2000, but
with the next version of SQL Server likely to come out next year,
I can see this being the point at which you cannot call for
regular support. The extended support timeline continues through
2013, but that's an expensive option.

The other consideration is that with a new version coming out
next year, you might want to just start making plans to upgrade
to that version even if you're happy with SQL Server 2000. If the
plan is to release a new version every 2-3 years, you'll need to
upgrade at least every 5-6 years to maintain support options.

Be sure that in any case you are sure the application you are
upgrading, if it's a third party, is supported on SQL Server 2005.

Lastly, if you have multiple servers and are considering new
hardware for more than 1 of them, it might make some sense to be
sure to look at buying one large 64-bit server and performing
some consolidations. I might recommend that you wait for the next
version of SQL Server if you are worried about conflicts as I
have heard rumors of switches to help govern the resource usage
in Katmai (SQL Server 2008).

A quick summary of the differences:

Feature SQL Server 2000 SQL Server 2005
Security Owner = Schema, hard to remove old users at times Schema
is separate. Better granularity in easily controlling security.
Logins can be authenticated by certificates.
Encryption No options built in, expensive third party options
with proprietary skills required to implement properly.
Encryption and key management build in.
High Availability Clustering or Log Shipping require Enterprise
Edition. Expensive hardware. Clustering, Database Mirroring or
Log Shipping available in Standard Edition. Database Mirroring
can use cheap hardware.
Scalability Limited to 2GB, 4CPUs in Standard Edition. Limited
64-bit support. 4 CPU, no RAM limit in Standard Edition. More
64-bit options offer chances for consolidation.
Conclusion
These seem to be the major highlights from my perspective as an
administrator. While there are other improvements, such as the
schema changes flowing through replication, I'm not sure that
they represent compelling changes for the non-DBA.
**************************************************************************************************************************************************************************

2005sqlser support try catch which is not possible in 2000
In SQL Server 2000 , a row cannot exceed 8000 bytes in
size ... To solve this problem, Microsoft introduced the
VARCHAR(MAX), NVARCHAR(MAX), and VARBINARY(MAX) data types
in SQL Server 2005. These data types can hold the same
amount of data BLOBs can hold (2 GB)
**************************************************************************************************************************************************************************

--Reference:
http://stackoverflow.com/questions/198478/advantages-of-ms-
sql-server-2008-over-ms-sql-server-2005

SQL SERVER 2000:

1.Query Analyser and Enterprise manager are separate.
2.No XML datatype is used.
3.We can create maximum of 65,535 databases.
4.Nill
5.Nill
6.Nill
7.Nill
8.Nill
9.Nill
10.Nill
11.Nill
12.Nill
13.cant compress the tables and indexes.
14.Datetime datatype is used for both date and time.
15.No varchar(max) or varbinary(max) is available.
16.No table datatype is included.
17.No SSIS is included.
18.CMS is not available.
19.PBM is not available.
20.PIVOT and UNPIVOT functions are not used.
SQL SERVER 2005:

1.Both are combined as SSMS(Sql Server management Studio).
2.XML datatype is introduced.
3.We can create 2(pow(20))-1 databases.
4.Exception Handling
5.Varchar(Max) data type
6.DDL Triggers
7.DataBase Mirroring
8.RowNumber function for paging
9.Table fragmentation
10.Full Text Search
11.Bulk Copy Update
12.Cant encrypt
13.Can Compress tables and indexes.(Introduced in 2005 SP2)
14.Datetime is used for both date and time.
15.Varchar(max) and varbinary(max) is used.
16.No table datatype is included.
17.SSIS is started using.
18.CMS is not available.
19.PBM is not available.
20.PIVOT and UNPIVOT functions are used.

SQL SERVER 2008:

1.Both are combined as SSMS(Sql Server management Studio).
2.XML datatype is used.
3.We can create 2(pow(20))-1 databases.
4.Exception Handling
5.Varchar(Max) data type
6.DDL Triggers
7.DataBase Mirroring
8.RowNumber function for paging
9.Table fragmentation
10.Full Text Search
11.Bulk Copy Update
12.Can encrypt the entire database introduced in 2008.
--check it(http://technet.microsoft.com/en-
us/library/cc278098(SQL.100).aspx)

(http://www.sqlservercentral.com/articles/Administration/imp
lementing_efs/870/)
(http://www.kodyaz.com/articles/sql-server-2005-
database-encryption-step-by-step.aspx)
(http://www.sql-server-
performance.com/articles/dev/encryption_2005_1_p1.aspx)

(http://geekswithblogs.net/chrisfalter/archive/2008/05/08/en
crypt-documents-with-sql-server.aspx)
13.Can compress tables and indexes.
-http://www.mssqltips.com/tip.asp?tip=1582
14.Date and time are seperately used for date and time
datatype,geospatial and timestamp with internal timezone
is used.
15.Varchar(max) and varbinary(max) is used.
16.Table datatype introduced.
17.SSIS avails in this version.
18.Central Management Server(CMS) is Introduced.
-http://msdn.microsoft.com/en-
us/library/bb934126.aspx
-http://www.sqlskills.com/BLOGS/KIMBERLY/post/SQL-
Server-2008-Central-Management-Servers-have-you-seen-
these.aspx
19.Policy based management(PBM) server is Introduced.
-http://www.mssqltips.com/tip.asp?tip=1492
-http://msdn.microsoft.com/en-
us/library/bb510667.aspx
20.PIVOT and UNPIVOT functions are used.
-http://blog.sqlauthority.com/2008/06/07/sql-server-
pivot-and-unpivot-table-examples/


SOURCE:allinterview

Wednesday, November 3, 2010

How to display a link without underline and display underline when mouseover on the link using CSS?

Write following css class.

a

{

text-decoration:none;

}



a:hover

{

text-decoration:underline;

}

The first class will force all anchor tag (link)to not display any docoration (underline) and second class will force all anchor tag (link) to display text decoration as underline when mouse over it (ie. display underline when mouse over).


Friday, October 22, 2010

Partial Classes

Partial types is a new feature in programming that is introduced in Visual Studio.Net 2005. This feature helps you to divide your types such as class, interface or any type definition across multiple files. At present, when you write any class you need to have the class in a single file, i.e., you need to start the class and end the class in the same file. In VS.Net 2005, you have the option of separating your code for the class across different files. You may split a single class across different files based on functionality, so that you have different developers work on different methods.

There is no modification done in the CLR for partial classes. The implementation of partial classes is done by the compiler for VB.Net and C# in Visual Studio .Net itself. For the CLR, whether you implement the code using partial classes or the class being in a single file, is the same. The compiler, when compiling the code in VS.Net 2005, looks for the partial classes and combines them so that the end result will look as if the code were written in a single class. After compilation the IL produced will look the same for both the implementation.

In Visual Studio .Net 2005, if you try to write some code for an event of a control, in the code-behind file now you will not see the codes that were automatically generated by VS.Net. Instead you will see the code-behind file for an .aspx page which will be a partial class for that page. Since, a class file can be slit across different files, the automatic code generated are placed in a different file which will have a partial class for that .aspx page. Thus, you will see very little code in the code-behind file.

Partial classes are declared using the "partial" keyword. Let us look at the sample code that is given below in C#, which implements a class as partial classes in different files.
Example

//FirstFile.cs
using System;
interface IPartialClass
{
void PrintAString(string s);
void PrintAString();
}
partial class MyPartialClass
{
private string s = "Variable from a separate Partial Class.";
}
class MainClass
{
static void Main(string[] args)
{
MyPartialClass PClass = new MyPartialClass();
PClass.PrintAString("String from a Partial Class.");
PClass.PrintAString();
Console.ReadLine();
}
}
//SecondFile.cs
using System;
public partial class MyPartialClass : IPartialClass
{
public void PrintAString(string str)
{
Console.WriteLine(str);
}
}
//ThirdFile.cs
using System;
partial class MyPartialClass
{
public void PrintAString()
{
Console.WriteLine(s);
}
}


The code given above has three different files, FirstFile.cs, SecondFile.cs, and ThirdFile.cs. The first file has an interface IPartialClass declared in it. This interface is implemented in two other files, SecondFile.cs and ThirdFile.cs. You may note that the method PrintAString(string str) is implemented in the SecondFile.cs and the method PrintAString() is implemented in the ThirdFile.cs. You may note that the string variable 's' is declared in the FirstFile.cs. The IL produced after compiling this code in VS.Net 2005 will look the same as if compiled in earlier versions of VS.Net 2005 and the CLR finds no difference in the IL produced.

If you are not implementing all of the methods in the interface in the partial classes, you will get a compilation error stating that you have not implemented all of the methods. This is the same type of error that you get if you have a single class in a single file.

The PrintAString method in the above example is an overloaded method. A unique overloaded method is implemented in the SecondFile.cs and the ThirdFile.cs respectively. If the signature for the overloaded method in different files does not differ, you will get an error stating that the signature are the same, which is again the same type of error that you get when you have a single class instead of partial classes.

The intelligence in Visual Studio .Net 2005 recognizes the partial class and the implementation of the interfaces across different files. You may note that the private string variable declared in the FirstFile, has the scope in the ThirdFile.cs in which that string variable is actually used.

This type of splitting the class across different files, help in increasing the productivity, as a single big class running into thousands of lines of code can be split into different files. Each of these file can have a different functionality to be developed, which can be given to different developers.

Retrieving Data Using a C# .NET DataReader

http://www.akadia.com/services/dotnet_data_reader.html

Assemblies

Using Assemblies in Microsoft .NET and C#
GlobalAssemblies

WCF

Implementing WCF

Monday, August 16, 2010

FB/twitter/buzz etc etc share a link code

Put follwing code in your aspx page

<p>

<!-- AddThis Button BEGIN -->
<script type="text/javascript">
var addthis_pub = "test";
var addthis_brand = "test";
var addthis_header_color = "#ffffff";
var addthis_header_background = "#2689C7";
</script>
<a href="http://www.addthis.com/bookmark.php?v=20"
onmouseover="return addthis_open(this, '', '[URL]', '[TITLE]')"
onmouseout="addthis_close()"
onclick="return addthis_sendto()">
<img src="http://s7.addthis.com/static/btn/lg-share-en.gif"
width="125" height="16" alt="Bookmark and Share" style="border:0"/></a>
<script type="text/javascript" src="http://s7.addthis.com/js/200/addthis_widget.js"></script>
<!-- AddThis Button END -->

</p>

Tuesday, July 20, 2010

DIFFERENCE BETWEEN 3-TIER AND 3-LAYER ARCHITECTURE

The terms tier and layer are frequently used interchangeably, but actually there is a difference between them: Tiers indicate a physical separation of components, which may mean different assemblies such as DLL, EXE etc on the same server or multiple servers; but layers refers to a logical separation of components, such as having distinct namespaces and classes for the Database Access Layer (DAL), Business Logic Layer (BLL) and User Interface Layer (UIL). Therefore, tier is about physical separation and units of deployment, and layers are about logical separation and units of design.

Creating a multi tier project design is more suitable and advisable to mid to large-size projects, whereas a good multi-layered design is suitable for small to mid-size projects.

Tuesday, June 15, 2010

Generics in C#

Introduction

Some New features have been added to C# language with version 2.0 of .NET. which are:

Generics
Iterators
Anonymous methods
Partial classes
In this Article I will explain about Generics Feature with some examples.

Generics

Generics are used to help make the code in the software components much more reusable. They are a type of data structure that contains code that remains the same. The data type of the parameters can change with each use.The usage within the data structure adapts to the different data type of the passed variables.

Each time the generic is used, it can be customized for different data types without needing to rewrite any of the internal code. Generics permit classes, structs, interfaces, delegates, and methods to be parameterized by the types of data they store and manipulate.

We can refer to a class, where we don't force it to be related to any specific Type, but we can still perform work with it in a Type-Safe manner. An example where we could implement Generics is in dealing with collections of items (integers, strings, Orders etc.). We can create a generic collection than can handle any Type in a generic and Type-Safe manner. For example, we can have a single array class to store a list of Users or even a list of Items, and when we actually use it, we will be able to access the items in the collection directly as a list of Users or Items, and not as objects (with boxing/unboxing, casting).

Generics Implementation

Let us explore an example to understand the need for Generics and the Implementation part of it. Normally we write the Arraylistclass as:

class MyArrayList
{
private object[] items;
private int count=0;
...
public void Add(object item)
{
items[count++] = item;
}
public object GetItem(int index)
{
return items[index];
}
}

In this code, any untyped object can be added to the list and be read. While adding an untyped object is possible in a direct manner , there has to be an explicit type conversion on a read access. The untyped declaration of the list results in two problems.

The compiler has no chance to verify the content of the list and the necessary type conversions.
Type failures will be recognized only at runtime-or maybe never recognized at all.
You can solve both problems by using typed classes. The base class library provides an abstract base class, CollectionBase in the System.Collections namespace, that will enable you to create typed collections easily. You have to implement the body for the different methods and the indexer. Internally, the objects are stored in an untyped ArrayList, and calls are forwarded to this class. For reference types, this approach works very well, although a new class has to be explicitly developed for each data type. However, collections for value types created in this way are inefficient, because the data needs to be (un)boxed to be stored in the ArrayList internally. The solution for problems like this is the use of generic classes. A blueprint of the class is created just once. Instead of using a particular data type or object, a specific placeholder is added.

// Defining a Generic Class
class MyArrayList
{
private ItemType[] items;
private int count;
...
public void Add(ItemType item)
{
items[count] = item;
}
public ItemType GetItem(int index)
{
return items[index];
}

The class MyArrayList can be specialized for any data-type which would, later in the class, be referenced using the name ItemType class MyArrayList

We replaced the data type of items with ItemType.

Now we can utilize MyArrayList for various types.

For example, the code

MyArrayList iList = new MyArrayList();
Will create an instance of MyArrayList class that accepts and return only integers or that has replaced ItemType in class definition with int. Now we can only add and retrieve integers from iList.

static void Main()
{
MyArrayList iList = new MyArrayList();
iList.Add(25);
int iValue2 = iList.GetItem(1);
}
Similarly for user defined type 'Employee'
static void Main()
{
MyArrayList pList = new MyArrayList();
pList.Add(new Employee("John"));
}

Using Multiple Types

We can define more than one type in Generic Definition. A practical example is a dictionary that can be typed individually on both the key and the value.

In this case, it allows multiple placeholders. They have to be specified in angle brackets, separated by commas.

public class MyDictionary
{
public void Add(KeyType key, ValueType value)
{
// ...
}
public ValueType this[KeyType key]
{
get { return ValueType.default; }
}
}

Although using Generics is type safe, you don't have type-safe access while developing the class itself. Because the type with which the generic class is used later is absolutely unknown, it's internally assumed to be object. Specific members of the data type can only be accessed after an explicit and therefore unsafe conversion. Possible failures will only be detected at run time.

Using Methods

Methods are another exciting field of use for Generics. Generic methods will allow you to pass one or more data types. An Example is given below.

public class MyClass
{
protected ItemType MyMethod(ItemType item)
{
return item;
}
}


Conclusion

Generics are very important and useful if you work, for example, with any kind of collections. Because of the backwards compatibility of ASP.NET 2.0, the existing collections couldn't be modified. Instead, a new namespace named System.Collections.Generic was created. It contains a lot of generic classes, structures, and interfaces like the following:

Dictionary
List
Queue
SortedDictionary
Stack
In the case of C#, generics are declared and type checked at compile time while instantiated at runtime just like any other object. C#Generics has the following advantages:

The Program becomes statically typed, so errors are discovered at compile-time.
No runtime casts are required and the program runs faster.
Primitive type values (e.g int) need not be wrapped. Hence the program is faster and uses less space.
Reference : ASP.NET 2.0 Revealed, by Patrick Lorenz.

Friday, April 23, 2010

Cookies in asp.net

Introduction

Cookies are a very small text file placed on your hard drive by a Web Page server. It is essentially your identification card, and cannot be executed as code or deliver viruses. It is uniquely yours and can only be read by the server that gave it to you

cookies purpose is to tell the server that you returned to that Web page

It may help you by saving your time

If you personalize pages, or register for products or services, a cookie helps Microsoft remember who you are.

Next time you return, we know to show you the information you requested. Or, when you register for another product or service, all you need to do is type in your e-mail address and a password. We then fill in any questions you've already answered. Of course, if you never register or leave personal information with Microsoft, then the server only knows that someone with your cookie has returned to the Web site. You are in charge of deciding whether we know anything about you. But the more you tell us about yourself, the more we can help you find information or products you want

how to use it

in order to handle a cookie in your system you should aware of 2 thing:

1-how to create them

2- how to delete them

so,first in order to create a cookie you have 2 variable must be defined as they are the cookie name and the duration of the cookie before it expired

in order to create a cookie it looks like this one
////////////SET THE COOKIE//////////////

Response.Cookies["test"].Value = UserName.Text ;

Response.Cookies["test"].Expires = DateTime.Now.AddYears(30);


where test is the cookie name

and the username.text is the textbox that will be used to define the cookies information

in order to delete a cookie use this
Response.Cookies["test"].Expires = DateTime.Now.AddYears(-30);

in order to check whether the cookie is found or not and retrieve the cookies information use this
/////////check to see if cookie presented//////////

if (Request.Cookies["test"] == null)

TextBox2.Text = "No cookie found";

else

TextBox2 .Text = Request.Cookies["test"].Value;

/////////END check to see if cookie presented//////////

Source:http://www.codeproject.com/KB/aspnet/cookies_in_c_.aspx

Wednesday, April 21, 2010

open popup window in asp.net

script language="javascript" type="text/javascript">

var win=null;

function NewWindow(mypage,myname,w,h,scroll,pos)
{
if(pos=="random"){LeftPosition=(screen.width)?Math .floor(Math.random()*(screen.width-w)):100;TopPosition=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;}
if(pos=="center"){LeftPosition=(screen.width)?(screen.width-w)/2:100;TopPosition=(screen.height)?(screen.height-h)/2:100;}
else if((pos!="center" && pos!="random") || pos==null){LeftPosition=0;TopPosition=20}
settings='width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',l ocation=no,directories=no,status=no,menubar=no,too lbar=no,resizable=yes';
win=window.open(mypage,myname,settings);
}


/script>

input type="button" value="Add Course" onclick="NewWindow('RegisterCourse.aspx','Register','800','550','yes','center');return false" onfocus="this.blur()" />


from: http://p2p.wrox.com/asp-net-1-0-1-1-basics/36479-open-popup-window-asp-net.html

Friday, January 8, 2010

How to add a new row in DataTable?

To add a new row in DataTable, we can use NewRow() method of the DataTable object.(Here assume that there are two columns Name, Address in the DataTable.

DataTable dTable = new DataTable();

DataRow row = null;



for (int i = 0; i < 5; i++)

{

row = dTable.NewRow ();

row["Name"] = i + " - Raja";

row["Address"] = "USA";

dTable.Rows.Add(row);

}

How to create a column in the DataTable

To create a column in the DataTable we can use the Columns.Add method of the DataTable object and pass DataColumn object as parameter.


DataTable dTable = new DataTable();

// create another column

DataColumn name = new DataColumn("Name", typeof(string));

dTable.Columns.Add(name);

How to add auto increment column in the DataTable?

To add auto increment column in the DataTable, we can set the AutoIncrement property of the DataColumn object as true and specify the seed value after adding that field into the DataTable object.

// create columns for the DataTable

DataTable dTable = new DataTable();

DataColumn auto = new DataColumn("AutoID", typeof(System.Int32));

dTable.Columns.Add(auto);

// specify it as auto increment field

auto.AutoIncrement = true;

auto.AutoIncrementSeed = 1;

auto.ReadOnly = true;

What is the best way to add items from an Array into ArrayList?

Use AddRange method of the ArrayList.


string[] arr = new string[] { "ram", "shyam", "mohan" };

ArrayList arrList = new ArrayList();

arrList.AddRange(arr);

Write a single line of code to create a text file and write contents into it.

Use following code

System.IO.File.WriteAllText(@"c:\MyTextFile.txt", "MyContents");

Write a single line of code to read the entire content of the text file.

User following code

string strContent = System.IO.File.ReadAllText(Server.MapPath("~/MyTextFile.txt"));

What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?

The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.

How to Find Number of Days for provided date range?

Code extract :

TimeSpan DayDifference = Convert.ToDateTime("2009-1-7").Subtract(Convert.ToDateTime("2009-1-1"));


To find the difference of the days, here we have used Subtract method. The Subtract method does not take start date into consideration. Hence, to get the exact number of days for the date range we need to add one more day to the result.

Response.Write("Number of Days : " + DayDifference.Days+1);

What is the difference between a.Equals(b) and a == b?

For value types : “==” and Equals() works same way : Compare two objects by VALUE
Example:
int i = 5;
int k= 5;
i == k > True
i.Equals(k) > True

For reference types : both works differently :
“==” compares reference – returns true if and only if both references point to the SAME object while
"Equals" method compares object by VALUE and it will return true if the references refers object which are equivalent
Example:
StringBuilder sb1 = new StringBuilder(“Mahesh”);
StringBuilder sb2 = new StringBuilder(“Mahesh”);
sb1 == sb2 > False
sb1.Equals(sb2) > True

But now look at following issue:
String s1 = “Mahesh”;
String s2 = “Mahesh”;
In above case the results will be,
s1 == s2 > True
s1.Equals(s2) > True
String is actually reference type : its a sequence of “Char” and its also immutable but as you saw above, it will behave like Value Types in this case.
Exceptions are always there ;)

Now another interesting case:
int i = 0;
byte b = 0;
i == b > True
i.Equals(b) > False
So, it means Equals method compare not only value but it compares TYPE also in Value Types.

Recommendation :
For value types: use “==”
For reference types: use Equals method.

Some interesting facts:

Why to prefer Equals method in especially VB.Net?
Consider following snippet:
Public Sub doSomething()
Dim s1 As String = “Mahesh”
Dim s2 As String = “Mahesh”
If s1 = s2 Then
MessageBox.Show(“Same!”)
End If
If s1.Equals(s1) Then
MessageBox.Show(“Not same!”)
End If
End Sub

Now if you will compile this stuff, and check generated IL code [Use ILDASM.exe ships with .Net Framework], you will find,
in doSomething section, “=” will create,
IL_0010: call int32 [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StringType::StrCmp(string,string,bool)

And, Equals method will create,
IL_0026: callvirt instance bool [mscorlib]System.String::Equals(string)

The second approach, using Equals uses mscorlib and its smaller and faster than the “=” because “=” uses VB.NET specific string comparison logic instead of core .Net implementation.
Single comparison operation may not give you performance hit but looping or at some critical part of you code, it can.
So Equals just give some efficient code.

More interesting thing that in C#, for the above code snippet, “==” and “Equals” both will result in same IL code. so no ambiguity in C#.
But if you used to code in both the language, then its obviously preferable to use Equals method.


/////////////////////////////////////////////////////////////////////////////////////

Both are used for comparison of variables, can be overloaded and return a Boolean value.

The differences are:-

Consider two variables of different types:
1) int a = 20;
string b = "20";

//Compiler error (== cannot be applied to int and string)
Console.WriteLine(a == b);

//output: False
Console.WriteLine(a.Equals(b));

2)int c = 455;
long f = 455;
//True
Console.WriteLine(c == f);
//False
Console.WriteLine(c.Equals(f));

//Equals strictly checks that 2 variables should be of the same type

// == gives True if 2 variables ' data types allow for similar values(Example: int and long)

3)List y = new List();
y.Add("one");
List z = new List();
z.Add("one");
Console.WriteLine(y == z);
Console.WriteLine(y.Equals(z));

Both will give False.

Thursday, January 7, 2010

Diff b/w custom control and user control

Custom controls are controls that are developed by the developer
or a third party vendor. Custom controls are not provided along with
.NET.

Difference between Custom Controls and User Controls.

1.User Control is a page file with extension .ascx which can only be used within
a single application. But custom controls are assemblies(dll files) that can be
used in multiple applications.

2.User Controls cannot be added to the ToolBox of VS.NET . To use a user Control with in an
aspx page u have to drag the user Control from the solution Explorer to designer page.
But Custom Controls can be added to ToolBox of VS.NET.

3.User Controls can be viewed as a sort of generic controls during the design time.
The proper GUI of user controls can be viewed only during the run time.
But Custom Controls can be viewed during the design time.

4. User controls are created from existing Webserver and html server controls .
But a developer who creates custom controls have to render every thing from the scratch.

5.Since the dll assembly of a custom control is being used,a custom control developed in C# can be used in a project developed in VB.NET or any other managed code and vice versa.
This is not possible with user controls.They are language spefic

We cannot give any examples for custom controls since they are developed either by a developer of a third party vendor.

Difference B/W Finalize() and Dispose() in .Net?

Both are ways to destroy the object. By object i mean when you have some unmanaged resources used in your class, you have to make sure that you write the logic to destroy them in the finalize() method. But this is the implicit way of destroying the unmanaged resources, as finalize is called by garbage collector when it find thats there is no reference to this object from the stack. There is an explicit way to destroy the unmanaged resources. That is by implementing IDisposable interface. By implementing this interface, ie you have to write the code to destroy the resource in Dispose() method, you can call the object to destroy itself when ever required in your code.when we write the destructor in c#,the runtime replaces the destructor with the finalize method in IL code,so we dont know at what time the destructor is called by the garbage collector.so the finalizer is non deterministic.if we want to do the garbage collection for unmanages resources,we have to implement our own destructor or finlizer method.but,the runtime will take two round trips to remove those objects from the heap.if runtime calls the own destructor,it will take onely one round trip. to remove the unmanaged resources without the performance issues,we have to inherit the System.Idisposable interface and implement the Dispose() method.here one problem is there,we have to write a code in a way that,the dsipose method must and should execute. for that reason we have to keep the dispose methos for the objcets in the finally block. problem with the dispose is that,some times because of some problmes dispose() methos may not execute. so the good practice is to use both to achieve the desied performance.

Tuesday, January 5, 2010

Show duplicate rows and delete duplicate rows

Show:
select customerid from tbl_customer group by customerid having count(customerid)>1
it will give u duplicate customerid in that particular table
Delete:
Here table name:tbl_places...columns:place
now add one identity column to this table
alter table tbl_places add I int identity
now delete
delete from tbl_places where I NOT IN(select min(i) from tbl_places group by place)

Using ROW_NUMBER() to paginate your data with SQL Server 2005 and ASP.NET

http://www.codeproject.com/KB/database/row_number.aspx

Parsing website using asp.net/C#

using System.Net;
using System.IO;

protected void Page_Load(object sender, EventArgs e)
{
string url = @"http://www.gmail.com";
HttpWebRequest reqObj = (HttpWebRequest)WebRequest.Create(url);
reqObj.Method = "GET";
HttpWebResponse resObj = (HttpWebResponse)reqObj.GetResponse();
StreamReader sr = new StreamReader(resObj.GetResponseStream());
string result = sr.ReadToEnd();
Response.Write(result);


}