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

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
Happy programming

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

I have already written on post how to track the Visior 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 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

DECLARE @doesExist INT

EXEC xp_fileexist @FileName, @doesExist OUTPUT

-- 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

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+'''
FIELDTERMINATOR ='''+@ColumnDelimier+''',
ROWTERMINATOR ='''+@RowDelimier+''',

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

---- 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


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


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


Data Control Language (DCL) statements. Some examples:

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


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:
User agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: 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.
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 A week ago, i have to implement that code. I have option to use javascipt 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=” =’_blank’;”/> <%-- =’_blank’ will add handler to open new tab--%> protected void btnNewEntry_Click(object sender, EventArgs e) { Response.Redirect(”New.aspx”); } OR Response.Write( "<script> 'pageName.aspx' ); </script>"); Response.End(); // Here we can write javascript code to open new tab -------------------- Happy programming.

Ideal SQL Query For Handling Error & Transcation in MS SQL