Thursday, October 28, 2010
Wednesday, October 27, 2010
Tuesday, October 26, 2010
Structs
important differences that you should be aware of. First of all, classes are reference types and structs are value types.
By using structs, you can create objects
When you call the New operator on a class, it will be allocated on the heap. However, when you instantiate a struct, it gets created on the stack.
Also, you will not be dealing with references to an instance of a struct as you would with classes. You will be working directly with the struct instance.
when passing a struct to a method, it's passed by value instead of as a reference.
Structs can declare constructors, but they must take parameters. It is an error to declare a default (parameterless) constructor for a struct.
When you create a struct object using the New operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the New operator. If you do not use New, the fields will remain unassigned and the object cannot be used until all the fields are initialized.
The only rule is that you need to initialize all fields of a struct
before using it. You can do that by:
Create object by using new keyword
.calling an overloaded constructor. C# forces you to initialize all fields within every overloaded constructor, so there is no getting around the "initialize-everything" rule.
explicitly setting every field's value.
There is no inheritance for structs as there is for classes. A struct cannot inherit from another struct or class, and it cannot be the base of a class.
A struct can implement interfaces, and it does that exactly as classes do.
This example demonstrates struct initialization using both default and parameterized constructors.
This example demonstrates a feature that is unique to structs. It creates a Point object without using the newoperator. If you replace the word struct with the word class, the program won't compile.
For a reference type, readonly
prevents you from reassigning a reference to refer to some other object. It does not prevent you from changing the state of the referred object.
For value types, however, readonly
is like the const
keyword in C++, it prevents you from changing the state of the object. This implies that you can't reassign it again, as that would result in reinitialization of all fields. The following piece of code demonstrates that.
Thursday, October 14, 2010
Nullable Type in C-Sharp
The syntax T?
- The HasValue property returns true if the variable contains a value, or false if it is null.
- The default value for a nullable type variable sets HasValue to false. The Value is undefined.
- The Value property returns a value if one is assigned, otherwise a System.InvalidOperationException is thrown.
Use the ?? operator to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type, for example
int? x = null;
int y = x ?? -1;
Tuesday, October 12, 2010
Dispose and Finalize methods
Although the .NET framework frees managed memory and resources transparently, it's not as good at freeing unmanaged resources; you have to help it out by implementing the Dispose and Finalize patterns in your code.
When the .NET framework instantiates an object, it allocates memory for that object on the managed heap. The object remains on the heap until it's no longer referenced by any active code, at which point the memory it's using is "garbage," ready for memory deallocation by the .NET Garbage Collector (GC). Before the GC deallocates the memory, the framework calls the object's Finalize() method, but developers are responsible for calling the Dispose() method.
The two methods are not equivalent. Even though both methods perform object cleanup, there are distinct differences between them. To design efficient .NET applications, it's essential that you have a proper understanding of both how the .NET framework cleans up objects and when and how to use the Finalize and Dispose methods. This article discusses both methods and provides code examples and tips on how and when to use them.
An Insight into the Dispose and Finalize Methods:
The .NET garbage collector manages the memory of managed objects (native .NET objects) but it does not manage, nor is it directly able to clean up unmanaged resources. Managed resources are those that are cleaned up implicitly by the garbage collector. You do not have to write code to release such resources explicitly. In contrast, you must clean up unmanaged resources (file handle objects, database connections, etc.) explicitly in your code.
There are situations when you might need to allocate memory for unmanaged resources from managed code.
As an example, suppose you have to open a database connection from within a class. The database connection instance is an unmanaged resource encapsulated within this class and should be released as soon as you are done with it. In such cases, you'll need to free the memory occupied by the unmanaged resources explicitly, because the GC doesn't free them implicitly.
Briefly, the GC works as shown below:
- It searches for managed objects that are referenced in managed code.
- It then attempts to finalize those objects that are not referenced in the code.
- Lastly, it frees the unreferenced objects and reclaims the memory occupied by them.
Finalization is the process by which the GC allows objects to clean up any unmanaged resources that they're holding, before the actually destroying the instance.
An implementation of the Finalize method is called a "finalizer."
The GC attempts to call Finalize method (finalizers) on objects when it finds that the object is no longer in use—when no other object is holding a valid reference to it.
The GC calls an object's Finalize method (finalizer) automatically.You should never rely on Finalize method (finalizer) to clean up unmanaged resources. A class that has no Finalize method implemented but is holding references to unmanaged objects can cause memory leaks, because the resources might become orphaned if a class instance is destroyed before releasing the unmanaged objects.
You must implement Finalize method very carefully; it's a complex operation that can carry considerable performance overhead.
The nature of finalization is "non-deterministic." Further, due to the non-deterministic nature of finalization, the framework cannot guarantee that the Finalize method will ever be called on an instance.
Hence, you cannot rely upon this method to free up any un-managed resources (such as a file handle or a database connection instance) that would otherwise not be garbage collected by the GC.
Note that you cannot call or override the Finalize method. It is generated implicitly if you have a destructor for the class. This is shown in the following piece of C# code:—
The framework implicitly translates the explicit destructor to create a call to Finalize:
protected override void Finalize()
{
try
{
//Necessary cleanup code
}
finally
{
base.Finalize();
}
}
Note that the generated code above calls the base.Finalize method.
You should note the following points when implementing Finalize() method (finalizer):
- Finalizers should always be protected, not public or private so that the method cannot be called from the application's code directly and at the same time, it can make a call to the base.Finalize method
- Finalizers should release unmanaged resources only.
- The framework does not guarantee that a finalizer will execute at all on any given instance.
- Avoid synchronization and raising unhandled exceptions in the finalizers.
- The execution order of finalizers is non-deterministic—in other words, you can't rely on another object still being available within your finalizer.
- Don't create empty destructors. In other words, you should never explicitly define a destructor unless your class needs to clean up unmanaged resources—and if you do define one, it should do some work. If, later, you no longer need to clean up unmanaged resources in the destructor, remove it altogether.
The approved way to release unmanaged resources is to make your class inherit from the IDisposable interface and implement the Dispose() method.
The Dispose Method—Explicit Resource Cleanup:
Unlike Finalize, developers should call Dispose explicitly to free unmanaged resources. The Dispose method generally doesn't free managed memory—
In other words, this method can release the unmanaged resources in a deterministic fashion.
However, Dispose doesn't remove the object itself from memory. The object will be removed when the garbage collector finds it convenient. It should be noted that the developer implementing the Dispose method must call GC.SuppressFinalize(this) to prevent the finalizer from running.
Implementing IDisposable is a good choice when you want your code, not the GC, to decide when to clean up resources. Further, note that the Dispose method should not be called concurrently from two or more different threads as it might lead to unpredictable results if other threads still have access to unmanaged resources belonging to the instance.
The IDisposable interface consists of only one Dispose method with no arguments.
public interface IDisposable
{
void Dispose();
}
The following code illustrates how to implement the Dispose method on a class that implements the IDisposable interface:
class Test : IDisposable
{
private bool isDisposed = false;
~Test()
{
Dispose(false);
}
protected void Dispose(bool disposing)
{
if (disposing)
{
// Code to dispose the managed resources of the class
}
// Code to dispose the un-managed resources of the class
isDisposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
In the preceding code, when the Boolean variable disposed equals true, the object can free both managed and unmanaged resources; but if the value equals false, the call has been initiated from within the finalizer (~Test) in which case the object should release only the unmanaged resources that the instance has reference to.
The Dispose/Finalize Pattern
Microsoft recommends that you implement both Dispose and Finalize when working with unmanaged resources.
The correct sequence then would be for a developer to call Dispose. The Finalize implementation would run and the resources would still be released when the object is garbage collected even if a developer neglected to call the Dispose method explicitly.
Simply put, cleanup the unmanaged resources in the Finalize method and the managed ones in the Dispose method, when the Dispose/Finalize pattern has been used in your code.
Suppressing Finalization
After the Dispose method has been called on an object, you should suppress calls to the Finalize method by invoking the GC.SuppressFinalize method as a measure of performance optimization. Note that you should never change the order of calls in the finalization context (first Dispose(true) and then GC.SupressFinalize) to ensure that the latter gets called if and only if the Dispose method has completed its operation successfully.
The following code illustrates how to implement both the Dispose and Finalize pattern for a class.
public class Base: IDisposable
{
private bool isDisposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(!isDisposed)
{
if (disposing)
{
// Code to dispose the managed resources
// held by the class
}
}
// Code to dispose the unmanaged resources
// held by the class
isDisposed = true;
base.Dispose(disposing);
}
~Base()
{
Dispose (false);
}
}
You should not reimplement IDisposable for a class that inherits from a base class in which IDispose has already been implemented. The following code snippet may help you understand this concept:
public class Base: IDisposable
{
private bool isDisposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(!isDisposed)
{
if (disposing)
{
// Code to dispose managed resources
// held by the class
}
}
// Code to dispose unmanaged resources
// held by the class
isDisposed = true;
base.Dispose(disposing);
}
~Base()
{
Dispose (false);
}
}
public class Derived: Base
{
protected override void Dispose(bool disposing)
{
if (disposing)
{
// Code to cleanup managed resources held by the class.
}
// Code to cleanup unmanaged resources held by the class.
base.Dispose(disposing);
}
// Note that the derived class does not // re-implement IDisposable
}
In the preceding code, what if the Dispose method were to throw an exception? In that case, the Finalize method would exit prematurely, and the memory would never be reclaimed. Hence, in such situations, it is advisable to wrap the Dispose method in a try-catch block. This will prevent finalization exceptions from orphaning the object.
Note the following points when implementing disposable types:
- Implement IDisposable on every type that has a finalizer
- Avoid using an object after the Dispose method has been called on it.
- Call Dispose on all IDisposable types once you are done with them
- Allow Dispose to be called multiple times without raising errors.
- Suppress later calls to the finalizer from within the Dispose method using the GC.SuppressFinalize method
- Avoid throwing exceptions from within Dispose methods
Joydip Kanjilal has over 10 years of industry experience with C, C++, Java, C#, VB, VC++, ASP.Net, XML, Design Patterns, UML, etc. He currently works as a Senior Project Leader in a reputable multinational company in Hyderabad, India, and has contributed articles on .NET and related techonlogies to www.aspalliance.com.
Monday, October 4, 2010
Candidate key, Alternate key, Composite key
Candidate key is formed on a column which identifies each row of the table uniquely. Generally, a candidate key becomes Primary key of the table. If a table has more than one Candidate key, one is used as Primary key and rest of the candidate keys are called Alternate keys.
* Composite key:
A primary key can consist of one or more fields on a table. When multiple fields are used as a primary key, then the key is called a composite key.
CREATE TABLE table_name
( column_name_1 data_type,
column_name_2 data_type,
column_name_3 data_type not null,
CONSTRAINT PK_table_name PRIMARY KEY (column_name_1,column_name_2)
)
* Primary Key..
1.It will not accept null values.
2.There will be only one primary key in a table.
3.Clustered index is created in Primary key.
4.Primary key allows each row in a table to be uniquely identified and ensures that no duplicate rows exist.
* Unique Key..
1.Null values are accepted.
2.More than one unique key will be there in a table.
3.Non-Clustered index is created in unique key.
4.Unique key constraint is used to prevent the duplication of key values within the rows of a table and allow null values.
Delay Sign in Assembly
What is delay Signing?
Delay signing allows you to place a shared assembly in the GAC by signing the assembly with just the public key. This allows the assembly to be signed with the private key at a later stage when the development process is complete and the component or assembly is ready to be deployed. This process enables developers to work with shared assemblies as if they were strongly named and it secures the private key of the signature from being accessed at different stages of development.
How to do it for an assembly?
Step 1. Create a public Key File for Delay Signing
To create a public key file for delay signing
Create a key pair for your organization.sn.exe -k keypair.snk
Extract the public key from the key pair file. sn -p keypair.snk publickey.snk
Protect Keypair.snk, which contains both the private and public keys. For example, put it on a compact disc or other hardware device, such as a smart card, and physically secure it.
Make Publickey.snk available to all developers. For example, put it on a network share.
Step 2. Delay sign your assembly
This procedure is performed by developers.
To delay sign an assembly
In Visual Studio .NET 2005, In the Class Project, display the project properties.
Click the Signing tab, and select the Sign the assembly and Delay sign only check boxes.
In the Choose a strong name key file: drop-down box, select <Browse…>.
In the file selection dialog box, browse to the public key (.snk) and click OK.
Build your assembly. The complier will build a strong named assembly signed using the public key from the selected key pair (.snk) file. Note A delay signed project will not run and cannot be debugged. You can, however, use the Strong Name tool (Sn.exe) with the -Vr option to skip verification during development.
The delay signing process and the absence of an assembly signature means that the assembly will fail verification at load time. To work around this, use the following commands on development and test computers.
To disable verification for a specific assembly, use the following command.
sn -Vr assembly.dll
To disable verification for all assemblies with a particular public key, use the following command.
sn -Vr *,publickeytoken
To extract the public key and key token (a truncated hash of the public key), use the following command.
sn -Tp assembly.dll Note Use an uppercase -T switch.
To fully complete the signing process and create a digital signature to make the assembly tamper proof, execute the following command. This requires the private key, and as a result the operation is normally performed as part of the formal build/release process. The following command uses key pair contained in the Keypair.snk file to re-sign an assembly called Assembly.dll with a strong name. sn -R assembly.dll keypair.snk
Sunday, October 3, 2010
AJAX Extension controls
ToolBox -> AjaxExtensions -> ScriptManager
Creating a Simple Application to know Ajax features....
1) Take UpdatePanel from Toolbox and drop it on the form.
Take one dropdown control and textbox control on to the updatepanel. Make sure that these controls are within the UpdatePanel.
2) Repeat step 1 for another 2 times.
3) Now you have 3 update panels with a dropdown and textbox on each.
4) Set autopostback property of each dropdown to true.
5) Write the following code in dropdown's selected index changed event.
protected void DropDown_1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox_1.Text = DropDown_1.SelectedValue;
TextBox_2 .Text = DropDown_1.SelectedValue;
TextBox_3.Text = DropDown_1.SelectedValue;
}
protected void DropDown_2_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox_1.Text = DropDown_2.SelectedValue;
TextBox_2.Text = DropDown_2.SelectedValue;
TextBox_3.Text = DropDown_2.SelectedValue;
}
protected void DropDown_3_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox_1.Text = DropDown_3.SelectedValue;
TextBox_2.Text = DropDown_3.SelectedValue;
TextBox_3.Text = DropDown_3.SelectedValue;
}
6) Run the application
Observations:-
* when you are changed the value of the any dropdown, textbox values in other updatepanel's will change along with the text box value in that particular UpdatePanel.
7) Now, go to the design view of the form, see the properties of the first updatepanel. i.e UpdatePanel1.
8) You will find there one property called as ChildrenAsTriggers. Bydefault this is true. This property indicates whether postbacks coming from the UpdatePanel's child controls will cause the update panel to refresh.
set ChildrenAsTriggers Property of UpdatePanel1 is False.
9) Run the application..
Observations:-
* whenever dropdown1 value is changed its corresponding text box value wont be changed but textbox2 and textbox3 values are changed.
10) Now, go to the design view of the form, see the properties of the first updatepanel. i.e UpdatePanel1.
11) You will find there one property called as UpdateMode. Bydefault this is always. Change this to Conditional.
12) Run the application...
Observations:-
* If we change the dropdown2 or dropdown3 value, all textbox values will change except textbox1 value.
13) Now, go to the design view of the form, see the properties of the first updatepanel. i.e UpdatePanel1.
14) You will find there one property called as Triggers. click the button beside this property and give dropdown3 as the trigger.
15) Run the application...
Observations:-
* since we made the update mode of the updatepanel1 as conditional and offered the dropdown3 as a trigger for this, it will get refreshed for only value changing of dropdown3.