Tuesday, October 6, 2009

Basic Differences in .Net



  1. Difference between == and .Equals Method?
  2. Difference between Close() and Dispose() Method
  3. Difference between Copy and Clone Method
  4. Value Type Vs Reference Type
  5. Struct Vs Class
  6. Static Member, Static Method, Static Constructor
  7. Difference between ADO and ADO.net Technology
  8. Difference between ADO.net Dataset and ADO Recordset
  9. Localization Vs Globalization
  10. Difference Between String and StringBuilder
  11. Response.Redirect(url,true) Vs Response.Redirect(url,false)
  12. Finalize Method Vs Destructor
  13. Difference between ExecuteReader, ExecuteNonQuery and ExecuteScalar.
  14. Difference between Dataset and DataReader
  15. “out” keyword Vs “ref” keyword
1.
What is Difference between == and .Equals() Method?
For Value Type: == and .Equals() method 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:
True
True



For Reference Type: == performs an identity comparison, i.e. it will only return true if both references point to the same object. While Equals() method 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(“Yes”);
StringBuilder s2 = new StringBuilder(“Yes”);
Console.WriteLine(s1 == s2);
Console.WriteLine(s1.Equals(s2));


Will display:
False
True


In above example, s1 and s2 are different objects hence “==” returns false, but they are equivalent hence “Equals()” method returns true. Remember there is an exception of this rule, i.e. when you use “==” operator with string class it compares value rather than identity.
When to use “==” operator and when to use “.Equals()” method?
For value comparison, with Value Tyep use “==” operator and use “Equals()” method while performing value comparison with Reference Type.
2.

Difference between Close() and Dispose() Method

Close() Vs Dispose Method

The basic difference between Close() and Dispose() is, when a Close() method is called, any managed resource can be temporarily closed and can be opened once again. It means that, with the same object the resource can be reopened or used. Where as Dispose() method permanently removes any resource ((un)managed) from memory for cleanup and the resource no longer exists for any further processing.

Example showing difference between Close() and Dispose() Method:


using System;
using System.Data;
using System.Data.SqlClient;
public class Test
{
private string connString = "Data Source=COMP3;Initial Catalog=Northwind;User Id=sa;Password=pass";
private SqlConnection connection;
public Test()
{
connection = new SqlConnection(connString);
}
private static void Main()
{
Test t = new Test();
t.ConnectionStatus();
Console.ReadLine();
}
public void ConnectionStatus()
{
try
{
if(connection.State == ConnectionState.Closed)
{
connection.Open();
Console.WriteLine("Connection opened..");
}

if(connection.State == ConnectionState.Open)
{
connection.Close();
Console.WriteLine("Connection closed..");
}
// connection.Dispose();

if(connection.State == ConnectionState.Closed)
{
connection.Open();
Console.WriteLine("Connection again opened..");
}
}
catch(SqlException ex)
{
Console.WriteLine(ex.Message+"\n"+ex.StackTrace);
}
catch(Exception ey)
{
Console.WriteLine(ey.Message+"\n"+ey.StackTrace);
}
finally
{
Console.WriteLine("Connection closed and disposed..");
connection.Dispose();
}
}
}

In the above example if you uncomment the "connection.Dispose()" method and execute, you will get an exception as, "The ConnectionString property has not been initialized.".This is the difference between Close() and Dispose().

3.
What is the difference between Copy and Clone Method.
Copy Vs Clone Method
Clone will copy the structure of a data where as
Copy will copy the complete structure as well as data .
4.
Value Type and Reference Type Concept in .Net

A variable is value type or reference type is solely determined by its data type.
Eg: int, float, char, decimal, bool, decimal, struct, etc are value types, while object type such as class, String, Array, etc are reference type.


Value Type

1) As name suggest Value Type stores “value” directly.
2) For eg:
//I and J are both of type int
I = 20;
J = I;
int is a value type, which means that the above statements will results in two locations in memory.
3) For each instance of value type separate memory is allocated.
4) Stored in a Stack.
5) It Provides Quick Access, because of value located on stack.

Reference Type

1) As name suggest Reference Type stores “reference” to the value
2) For e.g.:
Vector X, Y; //Object is defined. (No memory is allocated.)
X = new Vector(); //Memory is allocated to Object. //(new is responsible for allocating memory)
X.value = 30; //Initialising value field in a vector class
Y = X; //Both X and Y points to same memory location. //No memory is created for Y.
Console.writeline(Y.value); //displays 30, as both points to same memory
Y.value = 50;
Console.writeline(X.value); //displays 50
Note: If a variable is reference it is possible to indicate that it does not refer to any object by setting its value to null;
3) Reference type are stored on Heap
4) It provides comparatively slower access, as value located on heap


Note:
The behavior of strings is different, strings are immutable (unchangeable) if we alter a strings value, we create an entirely new string), so strings don’t display the typical reference-type behavior. Any changes made to a string within a method call won’t affect the original string.

5.
Difference between Struct and Class

Struct are Value type and are stored on stack, while Class are Reference type and are stored on heap.

Struct “do not support” inheritance, while class supports inheritance. However struct can implements interface.

Struct should be used when you want to use a small data structure, while Class is better choice for complex data structure.

Choosing between struct and class

Use of structure in following condition is desirable.
When you have small data structure
Data Structure does not require to extent the functionality.
When you want to perform faster operation on data structure. (As structure are stored on stack, operation performed on it are faster.)

Use of class in following condition is desirable.
When you have complex data structure
Data Structure requires to extend functionality.
When you want to optimize memory usage. (As class is stored on heap, they are about to be garbage collected when no reference pointing to an object.)


What is the difference between instantiating structures with and without using the new Keyword?
When a structure is instantiated using the new keyword, a constructor (no-argument or custom, if provided) is called which initializes the fields in the structure. When a structure is instantiated without using the new keyword, no constructor is called. Hence, one has to explicitly initialize all the fields of the structure before using it when instantiated without the new keyword.
6.

Static Members of the class
“static members” belong to the whole class rather than to individual object

How to access static member of class?
Static members are accessed with the name of class rather than reference to objects. Example: className.StaticMemberName

Example of Static Member

class Test
{
public int rollNo;
public int mathsMarks;
public static int totalMathMarks;
}

class TestDemo
{
public static void main()
{
Test stud1 = new Test();
stud1.rollNo = 1;
stud1.mathsMarks = 40;

stud2.rollNo = 2;
stud2.mathsMarks = 43;

Test.totalMathsMarks = stud1.mathsMarks + stud2.mathsMarks;
}
}



Static Method of the class
- Static Method is Method that you can call directly without first creating an instance of a class. Example: Main() Method, Console.WriteLine()
- You can use static fields, methods, properties and even constructors which will be called before any instance of the class is created.
- As static methods may be called without any reference to object, you can not use instance members inside static methods or properties, while you may call a static member from a non-static context. The reason for being able to call static members from non-static context is that static members belong to the class and are present irrespective of the existence of even a single object.


Static Constructor
In C# it is possible to write a static no-parameter constructor for a class. Such a class is executed once, when first object of class is created.

One reason for writing a static constructor would be if your class has some static fields or properties that need to be initialized from an external source before the class is first used.
Example
Class MyClass
{
static MyClass()
{
//Initialization Code for static fields and properties.
}
}

7.

Difference between ADO and ADO.net
1. ADO used connected data usage, while ADO.net used disconnected data environment.
2. ADO used OLE DB to access data and is COM-based, while ADO.net uses XML as the format for transmitting data to and from your database and web application.
3. In ADO, Record set, is like a single table or query result, while in ADO.net Dataset, can contain multiple tables from any data source.
4. In ADO, it is sometime problematic because firewall prohibits many types of request, while in ADO.net there is no such problem because XML is completely firewall-proof.

8.

Difference between ADO.net Dataset and ADO Recordset
1 A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.
2 A DataSet is designed to work without any continuing connection to the original data source.
3 Data in a DataSet is bulk-loaded, rather than being loaded on demand.
There's no concept of cursor types in a DataSet.
4 DataSets have no current record pointer You can use For Each loops to move through the data.
5 You can store many edits in a DataSet, and write them to the original data source in a single operation.
6 Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.

10.
Difference Between String and StringBuilder

String Class
StringBuilder
Once the string object is created, its length and content cannot be modified.
Even after object is created, it can be able to modify length and content.
Slower
Faster

11.

To avoid ThreadAbortException while Redirect

You don't need to put the redirect in a try-catch block. Just replace all calls to Response.Redirect(url) with the following two lines:

Response.Redirect(url, false);

That will avoid the exception being thrown and gracefully end execution of the thread and event chain. See http://www.c6software.com/CodeSolutions/dotnet/ThreadAbortException.aspx for a full solution explanation.

12.

What is difference between ExecuteReader, ExecuteNonQuery and ExecuteScalar.
  • ExecuteReader : Use for accessing data. It provides a forward-only, read-only, connected recordset.
  • ExecuteNonQuery : Use for data manipulation, such as Insert, Update, Delete.
  • ExecuteScalar : Use for retriving 1 row 1 col. value., i.e. Single value. eg: for retriving aggregate function. It is faster than other ways of retriving a single value from DB.
13.
Difference between Dataset and DataReader : Points to be consider while choosing between the DataSet and DataReader objects

DataSet object

DataReader object

Read/Write access
Read-only access
Supports multiple tables from different databases
Supports a single table based on a single SQL query of one database
Disconnected mode
Connected mode
Bind to multiple controls
Bind to a single control
Forward and backward scanning of data
Forward-only scanning of data
Slower access to data
Faster access to data
Greater overhead to enable additional features
Lightweight object with very little overhead
Supported by Visual Studio .NET tools
Must be manually coded

14.

What is “out” keyword in C# ??

“out Keyword” in C#.

out keyword is used for passing a variable for output purpose. It has same concept as ref keyword, but passing a ref parameter needs variable to be initialized while out parameter is passed without initialized.
It is useful when we want to return more than one value from the method.

Point to be kept in mind while using out keyword.
You must assigned value to out parameter in method body, otherwise the method won’t compiled.

Example of “out keyword”:
class Test
{
public static void Main()
{
int a; // may be left un-initialized
DoWork(out a); // note out
Console.WriteLine("The value of a is " + a);
}

public static void DoWork(out int i) // note out
{
i=4; //must assigned value.
}
}

The program will result : The value of a is 4
15. ---------------------------

.Net managed code enjoy's benefits of CLR, which automatically checks for object scope and if it is not referenced by any object than it is removed from memory.

But you can also manually frees memory....

Finalize() Method of Object class
Each class in C# is automatically (implicitly) inherited from the Object class which contains a method Finalize(). This method is guaranteed to be called when your object is garbage collected (removed from memory). You can override this method and put here code for freeing resources that you reserved when using the object.
Example of Finalize Method
Protected override void Finalize()

{

try

{

Console.WriteLine(“Destructing Object….”);//put some code here.

}

finally

{

base.Finalize();

}

}



Destructor

1) A destructor is just opposite to constructor.
2) It has same as the class name, but with prefix ~ (tilde).
3) They do not have return types, not even void and therefore they cannot return values.
4) destructor is invoked whenever an object is about to be garbage collected

Example of Destructor in .Net
class person

{

//constructor

person()

{

}



//destructor

~person()

{

//put resource freeing code here.

}

}



What is the difference between the destructor and the Finalize() method? When does the Finalize() method get called?

Finalize() corresponds to the .Net Framework and is part of the System.Object class. Destructors are C#'s implementation of the Finalize() method. The functionality of both Finalize() and the destructor is the same, i.e., they contain code for freeing the resources when the object is about to be garbage collected. In C#, destructors are converted to the Finalize() method when the program is compiled. The Finalize() method is called by the .Net Runtime and we can not predict when it will be called. It is guaranteed to be called when there is no reference pointing to the object and the object is about to be garbage collected.


Garbage Collection Concept

1) Garbage collection is the mechanism that reclaims the memory resources of an object when it is no longer referenced by a variable.
2) .Net Runtime performs automatically performs garbage collection, however you can force the garbage collection to run at a certain point in your code by calling System.GC.Collect().
3) Advantage of Garbage collection : It prevents programming error that could otherwise occur by incorrectly deleting or failing to delete objects.


Saturday, September 19, 2009

The Finally block is not really always guaranteed to get executed.

The Finally block is not really always guaranteed to get executed.


If any of these 3 special exceptions do happen, code in Finally won't be executed:

1) OutOfMemoryException,
2) StackOverFlowException
3)
ExecutionEngineException

Those people fortunate who experience all of these exceptions.

That means you had created some global kernel objects, they will indeed hang around and may interfere when user restarts your app. BTW, if you see a code
like catch(Exception ex) {...} or catch{...}, tell the developer that he has committed a sin.


The idea and content taken from this site http://www.shitalshah.com/blog/SomeCoolNetNuggets.aspx
-------------------
Happy programming

Getting The Real IP Of Your Users(Track IP Address)

I have already written on post how to track the Visior information.here i am going to explore how to track the IP Address of Visitor/Client.


The Following code will get the IP Address of visitor/ client.

------------------------------------------------------
C# code to track IP Address
------------------------------------------------------

string ipaddress;

// Look for a proxy address first
ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

// If there is no proxy, get the standard remote address
if (ipaddress == "" || ipaddress == null)

ipaddress = Request.ServerVariables["REMOTE_ADDR"];



-----------------------------------------------
VB Code to track IP Address
-----------------------------------------------

' Look for a proxy address first
Dim _ip As String = Request.ServerVariables("HTTP_X_FORWARDED_FOR")

' If there is no proxy, get the standard remote address
If (_ip = "" Or _ip.ToLower = "unknown") Then _
_ip = Request.ServerVariables("REMOTE_ADDR")

-----------------------------------------------------------
Explaination of above Code
-----------------------------------------------------------

The HTTP_X_FORWARDED_FOR variable is to check that there isn't a non-transparent proxy in the way.When users are behind any proxies or routers the REMOTE_ADDR returns the IP Address of the router and not the client user’s machine. Hence first we need to check HTTP_X_FORWARDED_FOR, since when client user is behind a proxy server his machine’s IP Address the Proxy Server’s IP Address is appended to the client machine’s IP Address. If there are multiple proxy servers the IP Addresses of all of them are appended to the client machine IP Address.

Hence we need to first check HTTP_X_FORWARDED_FOR and then REMOTE_ADDR.


Note: While running this application on your machine it will show IP Address 127.0.0.1 since your client and server is the same machine. when you will run this application on live server it will display the right information.

------------------------
Happy Programming

Friday, September 18, 2009

Bulk Insert From CSV OR Text File In SQL SERVER 2005

One of my friends contacted me recently and said they needed some help creating a stored procedure that imported data from a text file. They wanted the procedure to accept three parameters: PathFileName, ColumnDelimter, and RowDeliter. The PathFileName is simply the name and physical location of the source file on the hard drive, the Delimer are used to identify Columns and rows respectively.
So that i will have give her following store procedure.


Create Proc BulkInsertFromFile
(
@FileName Varchar(500), -- depends on path
@ColumnDelimier Varchar(10), -- delimiter for columns
@RowDelimier Varchar(10)--, -- delimier for Rows  
--@Output varchar(50)  -- used to specify error or success msg
)
As

DECLARE @doesExist INT

SET NOCOUNT ON
EXEC xp_fileexist @FileName, @doesExist OUTPUT
SET NOCOUNT OFF

-- i m creating Temp Table to demonstrate the example
-- Temp table holds the Results copies from FIle

Create Table #Temp
(
[CategoryId] [int],
[UserId] [int] NULL,
[ParentId] [int] NULL,
[CategoryName] [varchar](500),
[Description] [varchar](1000),
[Active] [bit] NULL,
[ImagePath] [varchar](max),
[CreatedDate] [datetime] NULL,
[DeleteStatus] [bit] NULL,
)

IF @doesExist = 1
BEGIN

Declare @SQL  nVarchar(max)  
Declare @Param nVarchar(500)
Set @Param='@FileName Varchar(500),@ColumnDelimier Varchar(20),@RowDelimier Varchar(20)'
SET @SQL = 'BULK INSERT #Temp FROM '''+@FileName+'''
WITH
(
FIELDTERMINATOR ='''+@ColumnDelimier+''',
ROWTERMINATOR ='''+@RowDelimier+''',
FIRE_TRIGGERS
)'

print @SQL
EXEC sp_executesql @SQL,@param,@FileName,@ColumnDelimier,@RowDelimier
--    Set @Output='Bulk insert Completed'
END
--Else
--Begin
--    Set @Output='File does not exist'
--End

---- u can also use the output  param to specify the error msg


Select * From #Temp

Drop table #Temp


What are the difference between DDL, DML and DCL commands

DDL

Data Definition Language (DDL) statements are used to define the database structure or schema. Some examples:

* CREATE - to create objects in the database
* ALTER - alters the structure of the database
* DROP - delete objects from the database
* TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
* COMMENT - add comments to the data dictionary
* RENAME - rename an object

DML

Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:

* SELECT - retrieve data from the a database
* INSERT - insert data into a table
* UPDATE - updates existing data within a table
* DELETE - deletes all records from a table, the space for the records remain
* MERGE - UPSERT operation (insert or update)
* CALL - call a PL/SQL or Java subprogram
* EXPLAIN PLAN - explain access path to data
* LOCK TABLE - control concurrency

DCL


Data Control Language (DCL) statements. Some examples:

* GRANT - gives user's access privileges to database
* REVOKE - withdraw access privileges given with the GRANT command

TCL

Transaction Control (TCL) statements are used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.

* COMMIT - save work done
* SAVEPOINT - identify a point in a transaction to which you can later roll back
* ROLLBACK - restore database to original since the last COMMIT
* SET TRANSACTION - Change transaction options like isolation level and what rollback segment to use

Monday, September 14, 2009

How to trace visitor information in ASP.NET?

It is often required to trace or gather the details of the visitor for maintaining website statistics. This can

be easily done in ASP.NET using the Server variables and the Request information available. Various attributes

such as remote host name, IP address, browser type and version etc can be known using the Server variables.

Source Code to trace Visitor:


<%
Response.Write("<b>Name:</b> " + Request.ServerVariables["REMOTE_HOST"] + "<br />");
Response.Write("<b>IP:</b> " + Request.ServerVariables["REMOTE_ADDR"] + "<br />");
Response.Write("<b>User agent:</b> " + Request.ServerVariables["HTTP_USER_AGENT"] + "<br />");
Response.Write("<b>Language:</b> " + Request.ServerVariables["HTTP_ACCEPT_LANGUAGE"] + "<br />");
Response.Write("<b>Browser:</b> " + Request.Browser.Browser + "<br />");
Response.Write("<b>Type:</b> " + Request.Browser.Type + "<br />");
Response.Write("<b>Version:</b> " + Request.Browser.Version + "<br />");
Response.Write("<b>Major version:</b> " + Request.Browser.MajorVersion + "<br />");
Response.Write("<b>Minor version:</b> " + Request.Browser.MinorVersion + "<br />");
Response.Write("<b>Beta:</b> " + Request.Browser.Beta + "<br />");
Response.Write("<b>Cookies:</b> " + Request.Browser.Cookies + "<br />");
Response.Write("<b>Frames:</b> " + Request.Browser.Frames + "<br />");
Response.Write("<b>Tables:</b> " + Request.Browser.Tables + "<br />");
Response.Write("<b>ActiveX:</b> " + Request.Browser.ActiveXControls + "<br />");
Response.Write("<b>Java Applets:</b> " + Request.Browser.JavaApplets + "<br />");
Response.Write("<b>JavaScript:</b> " + Request.Browser.JavaScript + "<br />");
Response.Write("<b>VBScript:</b> " + Request.Browser.VBScript + "<br />");
Response.Write("<b>Platform:</b> " + Request.Browser.Platform + "<br />");
Response.Write("<b>Crawler:</b> " + Request.Browser.Crawler + "<br />");
%>


Output of above Code:
Name: 119.160.194.218
IP: 119.160.194.218
User agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3
Language: en-us,en;q=0.5
Browser: Firefox
Type: Firefox3.5.3
Version: 3.5.3
Major version: 3
Minor version: 0.5
Beta: False
Cookies: True
Frames: True
Tables: True
ActiveX: False
Java Applets: True
JavaScript: True
VBScript: False
Platform: WinXP
Crawler: False 


The output will vary depending on your browser selection.
Thnx.
Happy programming!

Thursday, September 3, 2009

Open New Tab/Window (Response.Redirect open in new web page)

Hello Friends, Here I am going to explain how to open new tab/window on Button click using asp.net. A week ago, i have to implement that code. I have option to use javascipt windows.open to open new tab. But I have to insert or update some database entry. Yeah i know that there is another way to use client script in code behind to achieve this. But in its simplest form, following code open new tab/window. <asp:Button ID=”btnNewEntry” runat=”Server” CssClass=”button” Text=”New Entry” OnClick=”btnNewEntry_Click” OnClientClick=”aspnetForm.target =’_blank’;”/> <%-- aspnetForm.target =’_blank’ will add handler to open new tab--%> protected void btnNewEntry_Click(object sender, EventArgs e) { Response.Redirect(”New.aspx”); } OR Response.Write( "<script> window.open( 'pageName.aspx' ); </script>"); Response.End(); // Here we can write javascript code to open new tab -------------------- Happy programming.

Thursday, August 27, 2009

What’s the difference between <span> and <div> tags?

<span> and <div> tags both allow a Web designer to style text and add other formatting attributes to their Web page. They are not interchangeable tags, though. <div> tags are block-level elements, whereas <span> tags are not. This article explains this, and other differences, between <span> and <div> tags. Both <span> and <div> tags allow you to apply CSS styles <span> and <div> tags are both fine for applying inline CSS formatting. Consider the following code: <div style="color:#000000;font-weight:bold;font-size:14px">Here’s some text in between div tags</div> The output of this code is the same as: <span style="color:#000000;font-weight:bold;font-size:14px">Here’s some text in between span tags</span> <div> tags are block elements that allow you to position elements contained within them <div> tags are block elements. This means they can "hold" other HTML elements, and they can be positioned anywhere on the screen. For this reason, <div> tags can be used for replacing table-based Web designs. <span> tags are NOT block elements Unlike <div> tags, <span> tags cannot hold other HTML tags. They should only be used for inline styling of text. Consider the following code: <span style="font-size:14px"> <p>This is some text sized at 14 pixels.</p> </span> This code will probably render OK in most browsers, but it is actually incorrect. Remember, since the <span> tag is not a block-level element, it cannot contain other HTML tags. The correct way to write this code would be: <p><span style="font-size:14px"> This is some text sized at 14 pixels. </span></p> While this code is correct, it can be written more efficiently by removing the <span> tag altogether: <p style="font-size:14px"> This is some text sized at 14 pixels. </p> <div> tags create line breaks, <span> tags do not Since <div> tags are block elements, they create line breaks. This is the same effect as a <p> tag. <span> tags do not create line breaks, which makes them perfect for styling text in the middle of a sentence. Here’s an example of a <span> tag used to style text in the middle of a sentence. The same code using <div> instead of <span> would produce undesired results. <p>It's snowing in the Northeast today. Some towns received as much as <span style="font-size:18px;font-style:italic;font-weight:bold;">6 inches</span> of snow.</p> Summary of <span> vs. <div> tags <span> tags are useful if you need to apply specific formatting styles to text in the middle of a sentence, or in one place on your Web page. They are far less powerful than <div> tags, though, as a <div> will allow you to create blocks of content (like table-based Web designs) and position elements on the screen.

Tuesday, August 18, 2009

Programming the web.config File Using C#

What Is web.config?

The web.config file is the application’s configuration file. It is typically used to configure an ASP.NET Web application and define the configuration settings for the Web application. It typically contains the application-wide settings, such as database connection string, culture settings, authentication, and authorization information, etc. In ASP.NET 1.x, much effort was required to manipulate the web.config file programmatically. With ASP.NET 2.0 however, this can be done quite easily and efficiently. The following section discusses how this can be achieved.

The Configuration API in ASP.NET 2.0

The configuration API of ASP.NET 2.0 adds a great level of flexibility in that it allows us to add or edit a configuration file seamlessly in ASP.NET. The WebConfigurationManager class in the System.Web.Configuration namespace has the OpenWebConfiguration method that can be used to open the configuration file of the application as a Configuration object for reading from or writing to the configuration file. The virtual path to the configuration file is specified to this method as a parameter. The following code snippet displays all the keys of the appSettings section of the web.config file:

Configuration configuration = WebConfigurationManager.OpenWebConfiguration(”~”); AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection(”appSettings”); if (appSettingsSection != null) { foreach (string key in appSettingsSection.Settings.AllKeys) { Response.Write(key); } } The following method can be used to modify a specific key — value pair of the web.config file — programmatically using C#:

public void Modify(string key, string value) { Configuration configuration = WebConfigurationManager.OpenWebConfiguration(”~”); AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection(”appSettings”); if (appSettingsSection != null) { appSettingsSection.Settings[key].Value = value; config.Save(); } }

The following method can be used to delete a specific key in the web.config file programmatically using C#:

public void Remove(string key) { Configuration configuration = WebConfigurationManager.OpenWebConfiguration(”~”); AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection(”appSettings”); if (appSettingsSection != null) { appSettingsSection.Settings.Remove(key); config.Save(); } }

Conclusion

Even if modifying a web.config file programmatically can be a handy solution in some situations, it is not recommended to do so frequently in a Web application, as any change in the web.config file will restart the Web server and refresh the cache entries.

Friday, August 7, 2009

GridView with Dynamic columns

To Create dynamic columns in gridview, use template control to create dynamic colums. Following is the simple example which will demonstrate the DataGridTemplate class which is inherited from ITemplate which is base class of all template control. This is the definition of the Template for the columns. Ignore the fact that it is called DataGridTemplate. This used to be a DataGrid, but now it's a GridView, and I just now noticed the name hasn't changed. :) public class DataGridTemplate : ITemplate { private ListItemType pTemplateType; private string pColumnName; private int pTraitID; public int TraitID { get { return pTraitID; } set { pTraitID = value; } } private List pCategoryList = new List(); public DataGridTemplate(ListItemType type, string colname, int traitID, List scoreCats) { pTemplateType = type; pColumnName = colname; pTraitID = traitID; pCategoryList = scoreCats; } public void InstantiateIn(System.Web.UI.Control container) { Literal lc = new Literal(); switch (pTemplateType) { case ListItemType.Header: lc.Text = "" + pColumnName + ""; container.Controls.Add(lc); break; case ListItemType.Item: Label lbl = new Label(); lbl.Visible = false; lbl.Text = TraitID.ToString(); container.Controls.Add(lbl); RadioButtonList rbl = new RadioButtonList(); rbl.ID = "rbl" + pColumnName; for (int i = 0; i < pCategoryList.Count; i++) { rbl.Items.Insert(i, (string)pCategoryList[i]); } TextBox txtComments = new TextBox(); txtComments.ID = "txt" + pTraitID; txtComments.TextMode = TextBoxMode.MultiLine; txtComments.Rows = 4; txtComments.Columns = 30; container.Controls.Add(rbl); container.Controls.Add(txtComments); break; } } } You need to re-create any dynamically generated controls after a postback because unlike static controls they are not instantiated automatically. So, whatever code you have that generates dynamic columns, be sure to run it on Page_Load so it runs after a postback as well as on the inital request. Dynamic controls is an area that is covered in many ASP.NET sites, like the Code Project, and many ASP.NET books cover it very well too. Happy Programming