, , , , , , ,

How to make Human Verification Code or Image Verification Code in c#.net

Now, on many sites we can see image verification or human verification codes.

By entering the verification code shown on the web page when a user sign up, the web site or application can prevent automated registrations. This reduces system loads and ensures better performance and security of web site or application. This tutorial will show you how to create the randomly generated verification code in ASP.NET 2.0 and C#.

Now, questions arises how to make these code. Now, time to say thanks to .net who had given a wonderfull library with the name of System.Drawing.

Before stating any thing import System.Drawing.

Copy this code:

Using System.Drawing;

In order to create a random verification code, we create a method called CreateRandomCode at first

public string CreateRandomCode(int codeCount)
string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
string[] allCharArray = allChar.Split(',');
string randomCode = "";
int temp = -1;

Random rand = new Random();
for (int i = 0; i < codeCount; i++)
if (temp != -1)
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
int t = rand.Next(36);
if (temp != -1 && temp == t)
return CreateRandomCode(codeCount);
temp = t;
randomCode += allCharArray[t];
return randomCode;

Then we generate verification code character string as exported image.

private void CreateImage(string checkCode)
System.Drawing.Bitmap image = new System.Drawing.Bitmap(Convert.ToInt32(Math.Ceiling((decimal)(checkCode.Length * 14))), 22);
Graphics g = Graphics.FromImage(image);

Random random = new Random();

for (int i = 0; i < 25; i++)
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);

g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);

Font font = new System.Drawing.Font("Tahoma", 12, System.Drawing.FontStyle.Bold);
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(checkCode, font, new SolidBrush(Color.Red), 2, 2);

for (int i = 0; i < 100; i++)
int x = random.Next(image.Width);
int y = random.Next(image.Height);

image.SetPixel(x, y, Color.FromArgb(random.Next()));
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ContentType = "image/Gif";

Transfer function on Page_load

protected void Page_Load(object sender, EventArgs e)
string checkCode = this.CreateRandomCode(6);
Session["CheckCode"] = checkCode;
Read More
, ,

How to encrypt and decrypt a file by using Visual C#

Encryption and decryption

The System.Security.Cryptographic namespace in the Microsoft .NET Framework provides a variety of tools to help you with encryption and with decryption. The CryptoStream class is one of the many classes that is provided. The CryptoStream class is designed to encrypt or to decrypt content as it is streamed out to a file.

You can download working example also.

This is a basic example so, if you have any more questions please let me know.
Read More

How to Compare Files -File Compare

In contemporary world we have so many powerfull tools for version control like VSS, Tortoise SVN etc.

With help of there tools we can check different version of file with dates and other information.

But, what if I have to simply compare two files like notepad, word etc.

Let's take an simle example. I had made a file .cs file a year ago. I had made so many changes in that a year.

Now I am facing some problem in my code. I have only option to check older versions of my file, which is a time consuming job.

Means after each version I have to build and test my code.

Let me suggest you a simple solution which I had found on net using scootter softwares (Download Beyond Compare)

Beyond Compare allows you to quickly and easily compare your files and folders. By using simple, powerful commands you can focus on the differences you're interested in and ignore those you're not. You can then merge the changes, synchronize your files, and generate reports for your records.

You can compare entire drives and folders at high speed, checking just sizes and modified times. Or, thoroughly verify every file with byte-by-byte comparisons. FTP sites and zip files are integrated seamlessly, so you can update your website with the touch of a button.

Once you've found specific files you're interested in, Beyond Compare can intelligently pick the best way to compare and display them. Text files can be viewed and edited with syntax highlighting and comparison rules tweaked specifically for documents, source code, and HTML. Data files, executables, binary data, and images all have dedicated viewers as well, so you always have a clear view of the changes.

Now, get a one year older version of your file and your current file to compare.

pass both files to this tool it will mark all the changed, newly insertred and all the other alteration made in both the files with different colour combinations.

with the help of this tool you can easily come to conclusion which line has been changed and updated.

please let me know if you face any problem while using this tool or contact mailto:support@scootersoftware.com
Read More
, , ,

What is SQL Injection Attack Part -II

Recommended reading part I

Use Type-Safe SQL Parameters

The Parameters collection in SQL Server provides type checking and length validation. If you use the Parameters collection, input is treated as a literal value instead of as executable code. An additional benefit of using the Parameters collection is that you can enforce type and length checks. Values outside the range will trigger an exception. The following code fragment shows using the Parameters collection:

SqlDataAdapter myCommand = new SqlDataAdapter("AuthorLogin", conn);

myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;

SqlParameter parm = myCommand.SelectCommand.Parameters.Add("@au_id",SqlDbType.VarChar, 11);

parm.Value = Login.Text;

In this example, the @au_id parameter is treated as a literal value instead of as executable code. This value is checked for type and length. If the value of @au_id does not comply with the specified type and length constraints, an exception will be thrown.

Use Parameterized Input with Stored Procedures

Stored procedures may be susceptible to SQL injection if they use unfiltered input. For example, the following code is vulnerable:

SqlDataAdapter myCommand = new SqlDataAdapter("LoginStoredProcedure '" + Login.Text + "'", conn);

If you use stored procedures, you should use parameters as their input.'
Use the Parameters Collection with Dynamic SQL

If you cannot use stored procedures, you can still use parameters, as shown in the following code example:

SqlDataAdapter myCommand = new SqlDataAdapter("SELECT au_lname, au_fname FROM Authors WHERE au_id = @au_id", conn);

SQLParameter parm = myCommand.SelectCommand.Parameters.Add("@au_id", SqlDbType.VarChar, 11);

Parm.Value = Login.Text;

Filtering Input

Filtering input may also be helpful in protecting against SQL injection by removing escape characters. However, because of the large number of characters that may pose problems, this is not a reliable defense. The following example searches for the character string delimiter.

private string SafeSqlLiteral(string inputSQL)
return inputSQL.Replace("'", "''");

LIKE Clauses

Note that if you are using a LIKE clause, wildcard characters still must be escaped:

s = s.Replace("[", "[[]");
s = s.Replace("%", "[%]");
s = s.Replace("_", "[_]");

Reviewing Code for SQL Injection

You should review all code that calls EXECUTE, EXEC, or sp_executesql. You can use queries similar to the following to help you identify procedures that contain these statements. This query checks for 1, 2, 3, or 4 spaces after the words EXECUTE or EXEC.

SELECT object_Name(id) FROM syscomments





OR UPPER(text) LIKE '%EXEC (%'

OR UPPER(text) LIKE '%EXEC (%'

OR UPPER(text) LIKE '%EXEC (%'

OR UPPER(text) LIKE '%EXEC (%'


Wrapping Parameters with QUOTENAME() and REPLACE()

In each selected stored procedure, verify that all variables that are used in dynamic Transact-SQL are handled correctly. Data that comes from the input parameters of the stored procedure or that is read from a table should be wrapped in QUOTENAME() or REPLACE(). Remember that the value of @variable that is passed to QUOTENAME() is of sysname, and has a maximum length of 128 characters.

@variable Recommended wrapper

Name of a securable QUOTENAME(@variable)

String of ≤ 128 characters QUOTENAME(@variable, '''')

String of > 128 characters REPLACE(@variable,'''', '''''')

When you use this technique, a SET statement can be revised as follows:


SET @temp = N'select * from authors where au_lname='''+ @au_lname + N''''


SET @temp = N'select * from authors where au_lname=''' + REPLACE(@au_lname,'''','''''') + N''''

Injection Enabled by Data Truncation

Any dynamic Transact-SQL that is assigned to a variable will be truncated if it is larger than the buffer allocated for that variable. An attacker who is able to force statement truncation by passing unexpectedly long strings to a stored procedure can manipulate the result. For example, the stored procedure that is created by the following script is vulnerable to injection enabled by truncation.


@loginname sysname,

@old sysname,

@new sysname


-- Declare variable.

-- Note that the buffer here is only 200 characters long.

DECLARE @command varchar(200)

-- Construct the dynamic Transact-SQL.

-- In the following statement, we need a total of 154 characters

-- to set the password of 'sa'.

-- 26 for UPDATE statement, 16 for WHERE clause, 4 for 'sa', and 2 for

-- quotation marks surrounded by QUOTENAME(@loginname):

-- 200 – 26 – 16 – 4 – 2 = 154.

-- But because @new is declared as a sysname, this variable can only hold

-- 128 characters.

-- We can overcome this by passing some single quotation marks in @new.

SET @command= 'update Users set password=' + QUOTENAME(@new, '''') + ' where username=' + QUOTENAME(@loginname, '''') + ' AND password = ' + QUOTENAME(@old, '''')

-- Execute the command.

EXEC (@command)


By passing 154 characters into a 128 character buffer, an attacker can set a new password for sa without knowing the old password.

EXEC sp_MySetPassword 'sa', 'dummy', '123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012'''''''''''''''''''''''''''''''''''''''''''''''''''

For this reason, you should use a large buffer for a command variable or directly execute the dynamic Transact-SQL inside the EXECUTE statement.
Truncation When QUOTENAME(@variable, '''') and REPLACE() Are Used

Strings that are returned by QUOTENAME() and REPLACE() will be silently truncated if they exceed the space that is allocated. The stored procedure that is created in the following example shows what can happen.


@loginname sysname,

@old sysname,

@new sysname


-- Declare variables.

DECLARE @login sysname

DECLARE @newpassword sysname

DECLARE @oldpassword sysname

DECLARE @command varchar(2000)

-- In the following statements, the data stored in temp variables

-- will be truncated because the buffer size of @login, @oldpassword,

-- and @newpassword is only 128 characters, but QUOTENAME() can return

-- up to 258 characters.

SET @login = QUOTENAME(@loginname, '''')

SET @oldpassword = QUOTENAME(@old, '''')

SET @newpassword = QUOTENAME(@new, '''')

-- Construct the dynamic Transact-SQL.

-- If @new contains 128 characters, then @newpassword will be '123... n

-- where n is the 127th character.

-- Because the string returned by QUOTENAME() will be truncated,

-- it can be made to look like the following statement:

-- UPDATE Users SET password ='1234. . .[127] WHERE username=' -- other stuff here

SET @command = 'UPDATE Users set password = ' + @newpassword

+ ' where username =' + @login + ' AND password = ' + @oldpassword;

-- Execute the command.

EXEC (@command)


Therefore, the following statement will set the passwords of all users to the value that was passed in the previous code.

EXEC sp_MyProc '--', 'dummy', '12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678'

You can force string truncation by exceeding the allocated buffer space when you use REPLACE(). The stored procedure that is created in the following example shows what can happen.


@loginname sysname,

@old sysname,

@new sysname


-- Declare variables.

DECLARE @login sysname

DECLARE @newpassword sysname

DECLARE @oldpassword sysname

DECLARE @command varchar(2000)

-- In the following statements, data will be truncated because

-- the buffers allocated for @login, @oldpassword and @newpassword

-- can hold only 128 characters, but QUOTENAME() can return

-- up to 258 characters.

SET @login = REPLACE(@loginname, '''', '''''')

SET @oldpassword = REPLACE(@old, '''', '''''')

SET @newpassword = REPLACE(@new, '''', '''''')

-- Construct the dynamic Transact-SQL.

-- If @new contains 128 characters, @newpassword will be '123...n

-- where n is the 127th character.

-- Because the string returned by QUOTENAME() will be truncated, it

-- can be made to look like the following statement:

-- UPDATE Users SET password='1234…[127] WHERE username=' -- other stuff here

SET @command= 'update Users set password = ''' + @newpassword + ''' where username='''

+ @login + ''' AND password = ''' + @oldpassword + '''';

-- Execute the command.

EXEC (@command)


As with QUOTENAME(), string truncation by REPLACE() can be avoided by declaring temporary variables that are large enough for all cases. When possible, you should call QUOTENAME() or REPLACE() directly inside the dynamic Transact-SQL. Otherwise, you can calculate the required buffer size as follows. For @outbuffer = QUOTENAME(@input), the size of @outbuffer should be 2*(len(@input)+1). When you use REPLACE() and doubling quotation marks, as in the previous example, a buffer of 2*len(@input) is enough.

The following calculation covers all cases:

While len(@find_string) > 0, required buffer size =

round(len(@input)/len(@find_string),0) * len(@new_string)

+ (len(@input) % len(@find_string))
Truncation When QUOTENAME(@variable, ']') Is Used

Truncation can occur when the name of a SQL Server securable is passed to statements that use the form QUOTENAME(@variable, ']'). The following example shows this.


@schemaname sysname,

@tablename sysname,


-- Declare a variable as sysname. The variable will be 128 characters.

-- But @objectname actually must allow for 2*258+1 characters.

DECLARE @objectname sysname

SET @objectname = QUOTENAME(@schemaname)+'.'+ QUOTENAME(@tablename)

-- Do some operations.


When you are concatenating values of type sysname, you should use temporary variables large enough to hold the maximum 128 characters per value. If possible, call QUOTENAME() directly inside the dynamic Transact-SQL. Otherwise, you can calculate the required buffer size
Read More
, , ,

What is SQL Injection Attack

When first time I had heard about SQL Injection attack, I got afraid what the thing about, who can even insert, select and drop my tables from my database.
After searching on internet and visiting many of website I came to some of the conclusions.

What is SQL injection attack?

SQL injection is an attack in which malicious code is inserted into strings that are later passed to an instance of SQL Server for parsing and execution. Any procedure that constructs SQL statements should be reviewed for injection vulnerabilities because SQL Server will execute all syntactically valid queries that it receives. Even parameterized data can be manipulated by a skilled and determined attacker.

The primary form of SQL injection consists of direct insertion of code into user-input variables that are concatenated with SQL commands and executed. A less direct attack injects malicious code into strings that are destined for storage in a table or as metadata. When the stored strings are subsequently concatenated into a dynamic SQL command, the malicious code is executed.

The injection process works by prematurely terminating a text string and appending a new command. Because the inserted command may have additional strings appended to it before it is executed, the malefactor terminates the injected string with a comment mark "--". Subsequent text is ignored at execution time.

The following script shows a simple SQL injection. The script builds an SQL query by concatenating hard-coded strings together with a string entered by the user:

var Shipcity;
ShipCity = Request.form ("ShipCity");
var sql = "select * from OrdersTable where ShipCity = '" + ShipCity + "'";

The user is prompted to enter the name of a city. If she enters Redmond, the query assembled by the script looks similar to the following:

SELECT * FROM OrdersTable WHERE ShipCity = 'Redmond'

However, assume that the user enters the following:

Redmond'; drop table OrdersTable--

In this case, the following query is assembled by the script:

SELECT * FROM OrdersTable WHERE ShipCity = 'Redmond';drop table OrdersTable--'

The semicolon (;) denotes the end of one query and the start of another. The double hyphen (--) indicates that the rest of the current line is a comment and should be ignored. If the modified code is syntactically correct, it will be executed by the server. When SQL Server processes this statement, SQL Server will first select all records in OrdersTable where ShipCity is Redmond. Then, SQL Server will drop OrdersTable.

As long as injected SQL code is syntactically correct, tampering cannot be detected programmatically. Therefore, you must validate all user input and carefully review code that executes constructed SQL commands in the server that you are using. Coding best practices are described in the following sections in this topic.

Solution from Above Problem (Validate All Input)

  • Make no assumptions about the size, type, or content of the data that is received by your application. For example, you should make the following evaluation:
    • How will your application behave if an errant or malicious user enters a 10-megabyte MPEG file where your application expects a postal code?
    • How will your application behave if a DROP TABLE statement is embedded in a text field?
  • Test the size and data type of input and enforce appropriate limits. This can help prevent deliberate buffer overruns.
  • Test the content of string variables and accept only expected values. Reject entries that contain binary data, escape sequences, and comment characters. This can help prevent script injection and can protect against some buffer overrun exploits.
  • When you are working with XML documents, validate all data against its schema as it is entered.
  • Never build Transact-SQL statements directly from user input.
  • Use stored procedures to validate user input.
  • In multitiered environments, all data should be validated before admission to the trusted zone. Data that does not pass the validation process should be rejected and an error should be returned to the previous tier.
  • Implement multiple layers of validation. Precautions you take against casually malicious users may be ineffective against determined attackers. A better practice is to validate input in the user interface and at all subsequent points where it crosses a trust boundary.
  • For example, data validation in a client-side application can prevent simple script injection. However, if the next tier assumes that its input has already been validated, any malicious user who can bypass a client can have unrestricted access to a system.
  • Never concatenate user input that is not validated. String concatenation is the primary point of entry for script injection.
  • Do not accept the following strings in fields from which file names can be constructed: AUX, CLOCK$, COM1 through COM8, CON, CONFIG$, LPT1 through LPT8, NUL, and PRN.
When you can, reject input that contains the following characters.

Input character

Meaning in Transact-SQL


Query delimiter.


Character data string delimiter.


Comment delimiter.

/* ... */

Comment delimiters. Text between /* and */ is not evaluated by the server.


Used at the start of the name of catalog-extended stored procedures, such as

Recommended Read Part - II

Read More
, , , , ,

User Defined Functions in Microsoft Sql Server

With SQL Server 2000, Microsoft has introduced the concept of User-Defined Functions that allow you to define your own T-SQL functions that can accept zero or more parameters and return a single scalar data value or a table data type.

As every one knows the importance of User defined functions. So, while using Sql Server 7. We have repeat a same code for many number of times.

Following is the description about Use Defined Functions which we can create.

There are three types of User-Defined functions in SQL Server 2000 and they are Scalar, Inline Table-Valued and Multi-statement Table-valued.
How do I create and use a Scalar User-Defined Function?

A Scalar user-defined function returns one of the scalar data types. Text, ntext, image and timestamp data types are not supported. These are the type of user-defined functions that most developers are used to in other programming languages. You pass in 0 to many parameters and you get a return value.

Below is an example that is based in the data found in the NorthWind Customers Table.

CREATE FUNCTION whichContinent
(@Country nvarchar(15))
RETURNS varchar(30)
declare @Return varchar(30)
select @return = case @Country
when 'Argentina' then 'South America'
when 'Belgium' then 'Europe'
when 'Brazil' then 'South America'
when 'Canada' then 'North America'
when 'Denmark' then 'Europe'
when 'Finland' then 'Europe'
when 'France' then 'Europe'
else 'Unknown'

return @return

Because this function returns a scalar value of a varchar(30) this function could be used anywhere a varchar(30) expression is allowed such as a computed column in a table, view, a T-SQL select list item. Below are some of the examples that I was able to use after creating the above function definition. Note that I had to reference the dbo in the function name.

print dbo.WhichContinent('USA')

select dbo.WhichContinent(Customers.Country), customers.* from customers

create table test
(Country varchar(15),
Continent as (dbo.WhichContinent(Country)))

insert into test (country)
values ('USA')

select * from test

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Country Continent
--------- ------------------------------------
USA North America

Stored procedures have long given us the ability to pass parameters and get a value back, but the ability to use it in such a variety of different places where you cannot use a stored procedure make this a very powerful database object. Also notice the logic of my function is not exactly brain surgery. But it does encapsulate the business rules for the different continents in one location in my application. If you were to build this logic into T-SQL statements scattered throughout your application and you suddenly noticed that you forgot a country (like I missed Austria!) you would have to make the change in every T-SQL statement where you had used that logic. Now, with the SQL Server User-Defined Function, you can quickly maintain this logic in just one place.

How do I create and use an Inline Table-Value User-Defined Function?

An Inline Table-Value user-defined function returns a table data type and is an exceptional alternative to a view as the user-defined function can pass parameters into a T-SQL select command and in essence provide us with a parameterized, non-updateable view of the underlying tables.

CREATE FUNCTION CustomersByContinent
(@Continent varchar(30))
SELECT dbo.WhichContinent(Customers.Country) as continent,
FROM customers
WHERE dbo.WhichContinent(Customers.Country) = @Continent

SELECT * from CustomersbyContinent('North America')
SELECT * from CustomersByContinent('South America')
SELECT * from customersbyContinent('Unknown')

Note that the example uses another function (WhichContinent) to select out the customers specified by the parameter of this function. After creating the user-defined function, I can use it in the FROM clause of a T-SQL command unlike the behavior found when using a stored procedure which can also return record sets. Also note that I do not have to reference the dbo in my reference to this function. However, when using SQL Server built-in functions that return a table, you must now add the prefix :: to the name of the function.

Example from Books Online: Select * from ::fn_helpcollations()

How do I create and use a Multi-statement Table-Value User-Defined Function?

A Multi-Statement Table-Value user-defined function returns a table and is also an exceptional alternative to a view as the function can support multiple T-SQL statements to build the final result where the view is limited to a single SELECT statement. Also, the ability to pass parameters into a T-SQL select command or a group of them gives us the capability to in essence create a parameterized, non-updateable view of the data in the underlying tables. Within the create function command you must define the table structure that is being returned. After creating this type of user-defined function, I can use it in the FROM clause of a T-SQL command unlike the behavior found when using a stored procedure which can also return record sets.

CREATE FUNCTION dbo.customersbycountry ( @Country varchar(15) )
@CustomersbyCountryTab table (
[CustomerID] [nchar] (5), [CompanyName] [nvarchar] (40),
[ContactName] [nvarchar] (30), [ContactTitle] [nvarchar] (30),
[Address] [nvarchar] (60), [City] [nvarchar] (15),
[PostalCode] [nvarchar] (10), [Country] [nvarchar] (15),
[Phone] [nvarchar] (24), [Fax] [nvarchar] (24)
INSERT INTO @CustomersByCountryTab
SELECT [CustomerID],
FROM [Northwind].[dbo].[Customers]
WHERE country = @Country

SELECT @cnt = COUNT(*) FROM @customersbyCountryTab

IF @cnt = 0
INSERT INTO @CustomersByCountryTab (
[Fax] )
VALUES ('','No Companies Found','','','','','','','','')

SELECT * FROM dbo.customersbycountry('USA')
SELECT * FROM dbo.customersbycountry('CANADA')
SELECT * FROM dbo.customersbycountry('ADF')

What are the benefits of User-Defined Functions?

The benefits to SQL Server User-Defined functions are numerous. First, we can use these functions in so many different places when compared to the SQL Server stored procedure. The ability for a function to act like a table (for Inline table and Multi-statement table functions) gives developers the ability to break out complex logic into shorter and shorter code blocks. This will generally give the additional benefit of making the code less complex and easier to write and maintain. In the case of a Scalar User-Defined Function, the ability to use this function anywhere you can use a scalar of the same data type is also a very powerful thing. Combining these advantages with the ability to pass parameters into these database objects makes the SQL Server User-Defined function a very powerful tool.

So, if you have ever wanted to use the results of a stored procedure as part of a T-SQL command, use parameterized non-updateable views, or encapsulate complex logic into a single database object, the SQL Server 2000 User-Defined function is a new database object that you should examine to see if its right for your particular environment.
Read More
, , , , , ,

How to upload file using c#

File uploading was always been a tedious task for the web developer community.

Either we have to use a third party component or write several lines of code.

Now, ASP.Net had make this easy to implemnet and deploy

With ASP.NET file uploading has become a lot easier, importantly without the need for third party components.

All we have to do is to use the ASP.NET HTML File control and write a few lines of C# code.

In classic ASP we would use the HTML file control for uploading files.
In ASP.net we replace this with the ASP.NET HTML File control.
The declaration of ASP.NET HTML file control is much like normal HTML file control except for the runat attribute set to server. (e.g)

<input type="file" id="myfile" name="myfile" runat="server" />

Similarly we use the ASP.NET button control which the the user will click to upload the file he has selected using the file control.
As ASP.NET follows event based programming model we can attach a server side event which will respond to clicking of the button.
This is done by using the OnClick event handler of the button control.
To this event we assign the name of the method which we want to be executed on the server when the user clicks the button. (e.g)

<asp:button id="cmdUpload" name="cmdUpload" runat="server" OnClick="UploadFile" />

Now we can write C# code within the UploadFile method to save the uploaded file in the server.
This code can be written in two ways depending on the number of file controls we have within the page.
If there is only a single file control then we can use the PostedFile property of the file control to upload files.
This property is of type HttpPostedFile class and contains the following methods and properties which aids file uploading.


Property Description
FileName --- Returns the full path and name of the uploaded file.
ContentType ---- The MIME type of the uploaded file.
ContentLength ---- The size in bytes of the uploaded file.

Methods Description
SaveAs(Path) --- Saves the uploaded file to the specified path.

If we have multiple file controls within the form we can use the Files property of the Request object which returns a reference to the HttpFileCollection class.
HttpFileCollection class has an Item property through which gets individual HttpPostedFile from the file collection either by specifying the name or index.
Read More
, , , , , ,

ASP.NET Web.config

The ASP.NET Web.config file is used to define the configuration settings for an ASP.NET application. ASP.NET and the .NET Framework use .config files to define all configuration options. The .config files, including the ASP.NET Web.config file, are XML files.

Server-wide configuration settings for the .NET Framework are defined in a file called Machine.config. The settings in the Machine.config file can be changed and those settings affect all .NET applications on the server.

Different ASP.NET applications might need different application settings, that’s why defining those settings in the Machine.config file, is usually not practical. The solution for this problem is the ASP.NET Web.config file.

The ASP.NET application configuration settings can be changed by creating a file called Web.config and saving it in the root folder of the application. But what if the Machine.config file defines different settings than the ones defined in your Web.config file? The good news is that the settings in the Web.config file override the settings in the Machine.config file.

This is how the minimal Web.config file should look like:
<?xml version="1.0" encoding="utf-8" ?>
<add key="sConnectionString" value="Provider=SQLOLEDB;Data Source=Your_Server_Name;Initial Catalog=Your_Database_Name;User Id=Your_Username;Password=Your_Password;" />
<system.web />

As you can see, we have added a new section in our Web.config called <appSettings>.

The <appSettings> section defines custom ASP.NET application settings. The <add> child element of the <appSettings> ads a key/value pair, which is accessible from your applications, with the following code:

<customErrors> Web.config section

The <customErrors> section of the Web.config file defines the settings for handling web application errors. Below is the general syntax of this section:

<customErrors defaultRedirect="YourDefaultURL" mode="On|Off|RemoteOnly">
<error statusCode="ErrorStatusCode" redirect="YourRedirectURL"/>

The attribute mode defines how custom error handling works and can be one of the following 3 options:
On: Enabled
Off: Disabled
RemoteOnly: Enabled only for remote clients (requests coming from the local machine are not handled by these custom error settings).

You can use the <customErrors> Web.config section to define how to handle particular error codes. Here is an example of custom handling of 404 error (File Not Found):

<customErrors mode="On">
<error statusCode="404" redirect="Nice-FileNotFound-Page.aspx"/>

<identity> Web.config section

The <identity> Web.config section defines what identity (Windows account) to use when accessing the ASP.NET application. Here is the generic syntax of the <identity> section of the Web.config:

<identity impersonate="true|false" userName="username" password="password"/>

Impersonation is the concept whereby an application executes under the context of the identity of the client that is accessing the application. This is achieved by using the access token provided by IIS.

By default the ASPNET Windows account is used to access ASP.NET resources through the Aspnet_wp.exe process. This account is less powerful, compared to the IUSR_ machinename guest Internet account used by classic ASP for example. In certain situations you might want to use the anonymous IUSR_ machinename account, as the account accessing your ASP.NET application and you can do that by using the following code in your Web.config file:

<identity impersonate="true" />

In this case we use impersonation. In short impersonation is the act of ASP.NET executing code in the context of an authenticated client (Windows account).

If you want you can specify a particular account Windows account to be used instead of the ASPNET Windows account. You can do it like this:

<identity impersonate="true" userName="WindowsDomain\YourUserName" password="YourPassword" />
Read More