Introduction:
In this article I will show you that how you
can make a Custom Profile Provider. I will create a small provider that will let
you store the information in your custom database.
The Database Schema:
The database schema is pretty simple. The
database table Users contains four fields which are UserID,UserName,FirstName,
LastName. You can check out the schema below:
if exists (select * from
dbo.sysobjects where id = object_id(N'[dbo].[Users]') and OBJECTPROPERTY(id,
N'IsUserTable') = 1)
drop table [dbo].[Users]
GO
CREATE TABLE [dbo].[Users] (
[UserID] [int] IDENTITY (1, 1) NOT NULL ,
[UserName] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[FirstName] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[LastName] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO |
Configuring Web.config file:
The next thing you have to do is to make some
configuration settings in the Web.config file. Below you can see the settings in
the web.config file.
| <connectionStrings>
<add
name="ConnectionString"
connectionString="Server=localhost;Database=MyDatabase;Trusted_Connection=true"/>
</connectionStrings>
<system.web>
<!--
DEFINING CUSTOM PROFILE
-->
<profile
defaultProvider="MyCustomProfileProvider">
<providers>
<clear/>
<add
name="MyCustomProfileProvider"
type="MyCustomProfileProvider"
connectionStringName="ConnectionString"
updateUserProcedure="usp_UpdateUser"
getUserProcedure="usp_GetUserProcedure"/>
</providers>
<properties>
<add
name="FirstName"/>
<add
name="LastName"/>
</properties>
</profile> |
You can see in the above configuration that I
have named my Profile provider as "MyCustomProfileProvider". Inside the
provider's tags I have an add tag which contains different keys which you will
see later in this article. In the properties section I have declared two
properties which are FirstName and LastName. Since, there is no type specified
hence their default type is String.
Creating the Custom Profile Class:
In order to make your custom profile class your
class must inherit from the ProfileProvider Class. The complete code of this
class is pretty long and that's why I have attached the project files at the end
of this article.
First thing that I did was to override the
Initialize method. The Initialize method is fired whenever you assign a value to
the Profile object. Check out the code below in which I have shown that when the
Initialize method is fired.
| Profile.FirstName =
txtFirstName.Text;
// Initialize method is fired
Profile.LastName = txtLastName.Text;
// Not fired
since the above statement fetched all the data
string
firstName = Profile.FirstName;
// Not fired
string
lastName = Profile.LastName;
// Not fired |
Now, let's see how does the Initialize method
looks like:
|
public
override
void Initialize(string
name, System.Collections.Specialized.NameValueCollection
config) {
this.name
= name;
ConnectionStringSettings connectionStringSettings =
ConfigurationManager.ConnectionStrings[config["connectionStringName"]];
if
(connectionStringSettings == null
|| connectionStringSettings.ConnectionString.Trim() ==
"")
throw
new
HttpException("Connection
String is not defined.");
else
{
connectionString =
connectionStringSettings.ConnectionString;
}
updateProcedure = config["updateUserProcedure"];
if
(updateProcedure == null
|| updateProcedure.Trim() == "")
throw
new
HttpException("updateUserProcedure
is not defined.");
getProcedure = config["getUserProcedure"];
if
(getProcedure == null
|| getProcedure.Trim() == "")
throw
new
HttpException("getProcedure
is not defined.");
} |
The Initialize method takes in the name of the
Provider and the NameValueCollection as the parameters. The name will be simply
whatever you described in the web.config file which in this case will be "MyCustomProfileProvider".
The NameValueCollection will contain all the keys as well as the values which
you have defined in the add tag inside the providers section in web.config file.
| <providers>
<clear/>
<add
name="MyCustomProfileProvider"
type="MyCustomProfileProvider"
connectionStringName="ConnectionString"
updateUserProcedure="usp_UpdateUser"
getUserProcedure="usp_GetUserProcedure"/>
</providers> |
I have made the add tag bold so that you
will know that this is what NameValueCollection contain. After we get the name
and the NameValueCollection we simply retrieve the values out of the keys by
providing the name of the keys. Check out the code below:
| config["connectionStringName"]
// This will return "ConnectionString"
config["updateUserProcedure"] // This will
return "usp_UpdateUser" |
I am sure that you got the idea.
Now, let's implement the GetPropertyValues
method which is fired whenever you assign a value to the Profile property.
|
public
override
SettingsPropertyValueCollection
GetPropertyValues(SettingsContext
context, SettingsPropertyCollection
properties) {
SettingsPropertyValueCollection values =
new
SettingsPropertyValueCollection();
SqlConnection myConnection =
new
SqlConnection(ConnectionString);
SqlCommand
myCommand = new
SqlCommand(getProcedure,
myConnection);
myCommand.CommandType =
CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("@UserName",
(string)
context["UserName"]);
try
{
myConnection.Open();
SqlDataReader reader = myCommand.ExecuteReader(CommandBehavior.SingleRow);
reader.Read();
foreach
(SettingsProperty
property in
properties)
{
SettingsPropertyValue value =
new
SettingsPropertyValue(property);
if
(reader.HasRows)
{
value.PropertyValue = reader[property.Name];
values.Add(value);
}
}
}
finally
{
myConnection.Close();
myCommand.Dispose();
}
return
values;
} |
In the GetPropertyValues method I actually go
to the Custom database and fetch the records of the user based on the UserName.
This fetching is done by using a stored procedure which is called
usp_GetUserProcedure. You can view the stored procedure by downloading the
project files at the end of the article. The values are then inserted into the
SettingsPropertyValueCollection which is then returned to the user.
Just like the GetPropertyValues method there is
also a SetPropertyValues method which is used to retrieve the properties for the
Profile object.
| You should make the
authentication mode to "forms" authentication. Also note that when you
assign a value to the Profile property that does not mean that it will go to
the database and insert the property values into the table. For a Profile
object to work the username should be present in the table. Please also
check the Global.asax file where I have authenticated the user. |
I have attached the source code for this
project. Please feel free to download it.
I hope you liked this article, happy coding!
| If you are one of the
thousands that visit GridViewGuy for your .NET articles and resources, you
might be interested in making a donation. Extra cash helps pay for the
hosting services and speed things up
around here, and makes this website possible.
Make a Donation
Once, again thank you very much and
remember its because of you FINE people that this website
is up and running. |
|
Export Button is a custom control that let's you export your
DataGrid or TextBox data to several different formats. The
control is extremely easy to use and also exposes design time features. In
this article I will discuss some of the features of the Export Button and
how it benefits the developer.
BUY IT
NOW |