Wednesday 24 January, 2007

Configure ASP.NET Application with Web.Config

Web.Config



Application("DSN") = "Server=moon; Driver=Sql Server; Database=Store;
UID=user; PWD=bingo;"

Above declaration in the global.asa file might be
familiar to almost all ASP programmers.


While going through the MSDN, I was overwhelmed, by
looking into the web.config file which handles all configuration for an
application. The replacement for the above declaration in ASP .NET is as
follows:


<configuration>

<appSettings>

<add key="DSN" value="Server=moon;database=Store;Trusted_Connection=yes"
/>

</appSettings>

</configuration>


Then, in your ASPX page, you should have the
following statement to retrieve the value for DSN.


Dim dsn As String =
ConfigurationSettings.AppSettings("DSN")


So, I started to ask the following questions to
myself.


What exactly is web.config?

Does this handles only the above example?

What are the benefits of web.config?

And, following were the results for my questions, and
I would like to share with you all. This is based on Beta2


Introduction


Well, web.config is a XML-based configuration file.
If you see the above example, you can make sure that all the elements
are based on XML standards. Obviously, we can develop a tool for
modifying and editing this configuration file.


A web.config can appear in any directory on an
ASP.NET Web application server. Said this, if you have a web.config file
in the directory "c:\inetpub\wwwroot", then the settings specified in
the web.config is applicable to all the subdirectories under wwwroot.
Each sub-directory can have its own web.config file and it will
overwrite the settings of the web.config file in the parent directory.


There is another file called machine.config, which
provides configuration settings for the entire server. If you change the
contents of any web.config file then the change will be immediately
reflected in the processing of any incoming requests to the web' server.
These settings are calculated only once and then cached across
subsequent requests. ASP.NET automatically watches for file changes and
will invalidate the cache if any of the configuration files change. (For
more information on caching

Click here
)


The root element of a web.config file is always a
<configuration> tag. The <configuration> tag contains three different
types of elements: 1) configuration section handler declarations, 2)
configuration section groups, and 3) configuration section settings.


Following are the list of commonly used Configuation
tags, that, we be used in our web applications and will go thru them


1) Appsettings
2) Authentication
3) Authorization
4) Compilation
5) CustomErrors
6) Globalization
7) Identity
8) MachineKey
9) Pages
10) ProcessModel
11) SessionState
12) Trace

<appSettings>


This can be declared at the machine, site, application and subdirectory
level Include all the custom settings for your application in this
section. Appsettings tag contains two attributes viz; key and value.
<add key="key" value="value"/>

Eg: <add key="DSN" value="Server=moon;database=Store;Trusted_Connection=yes"
/>


<authentication>


All the authentication/security related stuff are declared in this
section. Authentication section contains a single attribute called
"mode". Possible values for "mode" are (a) Forms (b) None (c) Passport
and (d) Windows


Form based authentication can be used, if you want to
use ASP .NET forms-based authentication.


If you want to allow anyonmyous users to access your
website, select none.


Passpost authentication can be used, if you want the
authentication to be based on Microsoft Passport authentication mode.


Use windows mode authentication, if you want to use
Basic, Digest, Integrated Windows authentication (NTLM/Kerberos), or
certificates


Note: If you are using Form based authentication,
then you have several other options such as how the password should be
encrypted, while submitting the form, if login fails, which page should
be shown to the user etc.


As the AuthenTication is included in,
System.Web.Configuration.AuthenticationConfigHandler while setting the
authentication mode, you should code as follows


Eg:





<configuration>

<system.web>

<authentication mode="None" />

</system.web>

</configuration>


<authorization>


This is a very powerful tag, were you can restrict or allow users who
wish to visit your web site. Authorization tag contains two sub tags
such as allow and deny.


Allow tag provides us with three attributes, namely
users, roles and verbs. We can add the list of users seperated by comma
in the users attribute. Also we can specify the role in which each user
belongs too. Important aspect of the attribute verb is that, we can
control users depending upon the web request that the server is getting.
The verb attribute provides us with four options GET, HEAD, POST and
DEBUG.


Deny tag has the same attributes as the allow tag
has. Other aspect of both these tags are, we can use two special symbols
? and * to specify anonymous users and "all users" respectively.


Eg:




<configuration>

<system.web>

<authorization>

<allow roles="Admins" />

<deny users="*" />

</authorization>

</system.web>

</configuration>


<compilation>


It is in this tag, you set all your compilcation options. This tag
contains three sub-tags and seven attributes, which are discussed below.


Attributes

debug specifies whether to compile retail binaries or debug binaries.
True specifies debug binaries and False specifies Retail binaries


defaultLanguage can be used to specify the language
names to use in dynamic compilation files.


use explicit attribute to turn on explicit option or
to turn off. This takes either true or false, were true means explicit
is enabled.


We can also do a batch compiliation by specifying the
attribute bath as true. If we have batch compiliation, then we might
face the timeout problem. Then we may also want to use the batchTimeout
attribute to set the time for batch timeout.


numRecompilesBeforeApprestart is the next attribute.
This attribute indicates the number of dynamic recompiles of resources
that can occur before the application restarts. This attribute is
supported at the global and application level but not at the directory
level.


Strict attribute indicates the settings of the visual
basic strict compile option. supports two values, TRUE and FALSE.


SubTags

Compilers tag contains many or one compiler tag, were we define new
compiler options. Assemblies and Namespaces specifies ASP .NET
processing directives


Eg:





<configuration>

<system.web>

<compilation defaultLanguage="VB" debug="true">

<compilers>

<compiler language="VB;VBScript" extension=".cls"
type="Microsoft.VB. VBCodeProvider,System" />

<compiler language="C#;Csharp" extension=".cs"
type="Microsoft.CSharp. CSharpCodeProvider,System" />

</compilers>

<assemblies>

<add assembly="ADODB" />

<add assembly="*" />

</assemblies>

<namespaces>

<add namespace="System.Web" />

<add namespace="System.Web.UI" />

<add namespace="System.Web.UI.WebControls" />

<add namespace="System.Web.UI.HtmlControls" />

</namespaces>

</compilation>

</system.web>

</configuration>


<customErrors>


As the name says all about, customErros provides information about
custom error messages for an ASP.NET application. CustomErrors tag
provides us with three attributes.


defaultRedirect can be used to specify the URL to
direct a browser, if any unexpected error occurs. The mode attribute
takes three values On, Off or RemoteOnly. Remeteonly specifies that
custom errors are shown only to remote clients.


The subtag <error> might be very useful in a variety
of way. We can specify the error status code and ask the browser to
redirect to a specific page. We should use the attribute, statusCode to
specify the error status code and the redirect attribute to specify the
redirect URL.


Eg:





<configuration>

<system.web>

<customErrors defaultRedirect="error.aspx" mode="RemoteOnly">

<error statusCode="500" redirect="InternalError.htm"/>

</customErrors>

</system.web>

</configuration>


<globalization>


Configures the globalization settings of an application. Two important
attributes of this tag are requestEncoding and responseEncoding. Default
values for both encoding are "iso-8859-1", which is English. Eg:





<configuration>

<system.web>

<globalization requestEncoding="iso-8859-1"
responseEncoding="iso-8859-1">

<globalization/>

</system.web>

</configuration>


<identity>


Controls the application identity of the Web application. Supports three
attributes. Impersonate is the first attribute, which specifies whether
client impersonation is used on each request to the web server. Takes
either TRUE or FALSE. If the impersonation is FALSE, then we should
specify the values for the attributes, username and password. Eg:





<configuration>

<system.web>

<identity impersonate="true" />

</system.web>

</configuration>


<machineKey>


Configures keys to use for encryption and decryption of Forms
authentication cookie data. This section can be declared at the machine,
site, and application levels but not at the subdirectory level. This tag
supports three attributes; validationKey, decryptionKey and validation.


ValidationKey and DecryptionKey takes the default
value, which is AutoGenerate. We can also specify a key and it should be
length of 128 hexadecimal characters. The validation attribute can be
used to specify the alogrithm to be used while encryption. Possible
values are SHA1, MD5 and 3DES.




<pages>


As the name indicates, we should use this tag to specify the page-specific
configuration settings. It supports six attributes. We will dicsuss each one of
them.


Buffer attribute specifies, whether resources are buffered or
not. This takes three values On, Off and Readonly.


We can enable the session state or disable the session by
using the attribute, enableSessionState. This takes two values, either TRUE or
FALSE.


pageBaseType can be used to specify code-behind class that an
.aspx page inherits. userControlBaseType specifies a code behind class that
UserControls inherit.


If you want to disable any event firing in the page, you can
use the attribute autoEventWireup. This too takes either TRUE or FALSE.


Eg:





<configuration>

<system.web>

<pages buffer="true" enableSessionState="true" autoEventWireup="true">

</pages>

</system.web>

</configuration>


<processModel>


This section is mainly for the Web Administrators. We should use this tag
responsibly. We can use use tag to specify the timeout for when a new worker
process should start in place of current one, the idleTimeout which specifies
the minutes that ASP .NET automatically shuts down the worker process. One of
the important attribute of this tag is requestQueueLimit, were you can specify
the number of requests allowed in the queue before ASP .NET begins returning
"503" (Server too busy error). Default is 5000. Eg:





<configuration>

<system.web>

<processModel enable="true" timeout="10" idleTimeout="20"
requestQueueLimit="100">

</processModel>

</system.web>

</configuration>


<sessionState>


This tag can be used to specify, were we are storing the session. This can be
specified in the mode attribute. Supported values mode are Off, InProc,
StateServer and SqlServer. InProc indicates that, session states is stored
locally. StateServer indicates that session state is stored on a remote server
and sqlserver can be used to indicate that the session state is stored on a sql
server.


We also have the choice to use cookies to store the sessions.
This can be set using the attribute cookieless. Session timeout can be specified
using the attribute called timeout. By default, the session timeout is 20
minutes (same as classic ASP).


Eg:





<configuration>

<system.web>

<sessionState mode="Inproc" cookieless="true" timeout="20">

</sessionState>

</system.web>

</configuration>


<trace>


This is a very useful tag to debug our programs. We can use the trace tag to
show all the information for the page processed by the server. By default, all
the traces are stored on the server. We can specify the number of traces stored
in the memory by using the attribute called requestLimit. Default is 10. We can
either append the trace to the page or can be viewed using the trace utility.
This is specified by the attribute called pageOutput. Eg:





<configuration>

<system.web>

<trace enabled="false" requestLimit="15" pageOutput="true">

</trace>

<system.web>

</configuration>


There are some more tags available which can be used in the
web.config file. Those are <httpHandlers>, <httpModules>, <httpRuntime>, <securityPolicy>,
<webServices>, <trust> and <browserCaps>. You may want to look into these.

Inserting Images to SqlServer in ASP .NET

Introduction

There will be many occassion, in which we will be urged to store images in the Database. In some applications we may have some sensitive information which cannot be stored in a file system, since if anything is in the file system, then it may be very easy for the users to hack the pictures/images.

In this article, we will discuss about, how we can insert images to a SqlServer 2000.

We will be learning the following aspects in this article.
  1. Prerequistes for inserting an image file
  2. Working with the Stream Object
  3. Finding the Size and Type of the image that is going to be uploaded
  4. How to use the InputStream method?
Prerequistes for inserting an image file

Two primary things that we need before the upload begins are

# The property enctype of the Form tag should be set to enctype="multipart/form-data"
# We should have a which allows the user to select the necessary image file (which will be inserted into the database)
# Also we need to Import the Namespace, System.IO to deal with the Stream object.

The above three points applies to an ASPX page. Also we need to have the following prerequistes in the SqlServer.

# We should have a Table with atleast one of the field of type Image.
# It will be better, if we have another field of type Varchar to hold the image type.

So, we have a Sql Table with the field type of Image and we have a (HTMLFile control). We also need a Submit button, where user can click after selecting the image. In the OnClick event of the button, we need to read the content of the image file and finally we insert the image to the table. Let us take a look at the OnClick event of the button, which reads the image and inserts into the sql table.

Code in the OnClick event of the Submit button.
Dim intImageSize As Int64
Dim strImageType As String
Dim ImageStream As Stream

' Gets the Size of the Image
intImageSize = PersonImage.PostedFile.ContentLength

' Gets the Image Type
strImageType = PersonImage.PostedFile.ContentType

' Reads the Image
ImageStream = PersonImage.PostedFile.InputStream

Dim ImageContent(intImageSize) As Byte
Dim intStatus As Integer
intStatus = ImageStream.Read(ImageContent, 0, intImageSize)

' Create Instance of Connection and Command Object
Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
Dim myCommand As New SqlCommand("sp_person_isp", myConnection)

' Mark the Command as a SPROC
myCommand.CommandType = CommandType.StoredProcedure

' Add Parameters to SPROC
Dim prmPersonImage As New SqlParameter("@PersonImage", SqlDbType.Image)
prmPersonImage.Value = ImageContent
myCommand.Parameters.Add(prmPersonImage)

Dim prmPersonImageType As New SqlParameter("@PersonImageType", SqlDbType.VarChar, 255)
prmPersonImageType.Value = strImageType
myCommand.Parameters.Add(prmPersonImageType)

Try
myConnection.Open()
myCommand.ExecuteNonQuery()
myConnection.Close()
Response.Write("New person successfully added!")
Catch SQLexc As SqlException
Response.Write("Insert Failed. Error Details are: " & SQLexc.ToString())
End Try

How it works?

The Object, PersonImage is the name of the HTMLInputFile control. First we need to get the size of the image that is going to be inserted and that is done by

intImageSize = PersonImage.PostedFile.ContentLength

. Then we retrieve the image type using the property ContenType. Then the most important thing is, we need to get the Image Stream and that is done by

ImageStream = PersonImage.PostedFile.InputStream

. We have an array of Bytes, ImageContent, which is ready to hold the image content. The entire image is read using the method Read of the Stream Object. The method read takes three arguments, viz;

# Target Location that the Image Content to be copied
# Starting position for the purpose of read
# Number of bytes that needs to be read

. And the Read statement is

intStatus = ImageStream.Read(ImageContent, 0, intImageSize)

. Now, we have read the entire image content. Next we need to insert this into a sql table. We are going to use a stored procedure which inserts the image type and the image to a sql table. If you go through the above code listing, then you can see that we use the datatype as SqlDbType.Image. That is it. We have successfully inserted an image to SqlServer.


Tuesday 23 January, 2007

Using Source Safe in Asp.net - Start to End

Dear friends,

When we have to use multiple development users in a single application. We need some Software to manage all the development from users into single application. Source Safe is the right place in which we can manage all these.

But we face some problems like
How Source Safe is working?
How to Add source safe into our project?
How to Remove source safe from our project?

Links : http://msdn2.microsoft.com/en-us/library/ms972977.aspx

Gives the complete guide for this.
Dear friends,

It is much complex task to delete the duplicated data from the database. We generall work in many steps to delete all these including creating temparory table and so on.

This is the single statement which will work for you.

All you need to do is compare the table to itself to find out which candidates are duplicates. Do this by assigning aliases to the table so you can use it twice, once as A and again as B, like this:

delete from jobs where job_desc in
( select a.job_desc from jobs a, jobs b where a.job_desc = b.job_desc
group by a.job_desc
having count(a.job_desc) >1
)


When you do this you’ll get a count based on the column value you think is duplicated. I used “desc” because the IDs will be different, so the description is the thing that is the candidate for repetition. Join the table to itself on that candidate to find matches of it. Everything will match to itself at least once that’s why you group by the thing you think is a duplicate. Applying the HAVING clause to it squeezes out all the “ones” or singletons, leaving only the rows that have counts that are more than one in other words, your duplicate rows.

By the way, this code trashes all the records that are duplicates. If you want to save one, add a comparison for the IDs to be different in the WHERE clause.

Hits4Pay