using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.IO;
using System.Data;
using System.Web.UI.Design;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
namespace ccc.TellaFriend
{
public enum TellaFreindText
{
Your_Name=0,
Your_Email=1,
Friend_Email=2,
Message=3,
Button=4,
Title=5
}
[DefaultProperty("Text"),
ToolboxData("<{0}:TellaFriend runat=server></{0}:TellaFriend>"),
Designer(typeof(ccc.TellaFriend.Design.TellaFriendDesing))]
public class TellaFriend :System.Web.UI.WebControls.WebControl,INamingContainer
{
public Label lbl_title;
public TextBox txt_yourname;
public TextBox txt_yourEmail;
public TextBox txt_friendEmail;
public TextBox txt_message;
public Button btn_send;
public RequiredFieldValidator req1;
public RequiredFieldValidator req2;
public RequiredFieldValidator req3;
public RequiredFieldValidator req4;
public RegularExpressionValidator reg1;
public RegularExpressionValidator reg2;
public ValidationSummary vs;
#region Tell a Friend Text
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string Text
{
get
{
this.EnsureChildControls();
string retVal = "";
switch (TellaFreindText)
{
case TellaFreindText.Your_Name:
retVal = txt_yourname.Text;
break;
case TellaFreindText.Your_Email:
retVal = txt_yourEmail.Text;
break;
case TellaFreindText.Friend_Email:
retVal = txt_friendEmail.Text;
break;
case TellaFreindText.Message:
retVal = txt_message.Text;
break;
case TellaFreindText.Button:
retVal = btn_send.Text;
break;
case TellaFreindText.Title:
retVal = lbl_title.Text;
break;
}
return (retVal);
}
set
{
this.EnsureChildControls();
switch (TellaFreindText)
{
case TellaFreindText.Your_Name:
txt_yourname.Text = value;
break;
case TellaFreindText.Your_Email:
txt_yourEmail.Text = value;
break;
case TellaFreindText.Friend_Email:
txt_friendEmail.Text = value;
break;
case TellaFreindText.Message:
txt_message.Text = value;
break;
case TellaFreindText.Button:
btn_send.Text = value;
break;
case TellaFreindText.Title:
lbl_title.Text = value;
break;
}
}
}
#endregion
#region Tell a Freind CSS
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string TellaFreindCss
{
get
{
this.EnsureChildControls();
string retCss = "";
switch (TellaFreindText)
{
case TellaFreindText.Your_Name:
retCss = txt_yourname.CssClass;
break;
case TellaFreindText.Your_Email:
retCss = txt_yourEmail.CssClass;
break;
case TellaFreindText.Friend_Email:
retCss = txt_friendEmail.CssClass;
break;
case TellaFreindText.Message:
retCss = txt_message.CssClass;
break;
case TellaFreindText.Button:
retCss = btn_send.CssClass;
break;
case TellaFreindText.Title:
retCss = lbl_title.CssClass;
break;
}
return (retCss);
}
set
{
this.EnsureChildControls();
switch (TellaFreindText)
{
case TellaFreindText.Your_Name:
txt_yourname.CssClass = value;
break;
case TellaFreindText.Your_Email:
txt_yourEmail.CssClass = value;
break;
case TellaFreindText.Friend_Email:
txt_friendEmail.CssClass = value;
break;
case TellaFreindText.Message:
txt_message.CssClass = value;
break;
case TellaFreindText.Button:
btn_send.CssClass = value;
break;
case TellaFreindText.Title:
lbl_title.CssClass = value;
break;
}
}
}
#endregion
#region Tell a Freind Width
[Bindable(false), Category("Appearance"), DefaultValue(null),
Description("The width of the button text in between the decorations for Text mode buttons. The full width of the button for Button mode buttons. Not used for Image mode buttons.")]
public Unit TellafriendWidth
{
get
{
Unit retWidth = System.Web.UI.WebControls.Unit.Percentage(50);
switch (TellaFreindText)
{
case TellaFreindText.Your_Name:
retWidth = txt_yourname.Width;
break;
case TellaFreindText.Your_Email:
retWidth = txt_yourEmail.Width;
break;
case TellaFreindText.Friend_Email:
retWidth = txt_friendEmail.Width;
break;
case TellaFreindText.Message:
retWidth = txt_message.Width;
break;
case TellaFreindText.Button:
retWidth = btn_send.Width;
break;
case TellaFreindText.Title:
retWidth = lbl_title.Width;
break;
}
return (retWidth);
}
set
{
this.EnsureChildControls();
switch (TellaFreindText)
{
case TellaFreindText.Your_Name:
txt_yourname.Width = value;
break;
case TellaFreindText.Your_Email:
txt_yourEmail.Width = value;
break;
case TellaFreindText.Friend_Email:
txt_friendEmail.Width = value;
break;
case TellaFreindText.Message:
txt_message.Width = value;
break;
case TellaFreindText.Title:
lbl_title.Width = value;
break;
}
}
}
#endregion
#region Tell a Freind Height
[Bindable(false), Category("Appearance"), DefaultValue(null),
Description("The width of the button text in between the decorations for Text mode buttons. The full width of the button for Button mode buttons. Not used for Image mode buttons.")]
public Unit TellafriendHeight
{
get
{
Unit retHeight = System.Web.UI.WebControls.Unit.Percentage(50);
switch (TellaFreindText)
{
case TellaFreindText.Your_Name:
retHeight = txt_yourname.Height;
break;
case TellaFreindText.Your_Email:
retHeight = txt_yourEmail.Height;
break;
case TellaFreindText.Friend_Email:
retHeight = txt_friendEmail.Height;
break;
case TellaFreindText.Message:
retHeight = txt_message.Height;
break;
case TellaFreindText.Button:
retHeight = btn_send.Height;
break;
case TellaFreindText.Title:
retHeight = lbl_title.Height;
break;
}
return (retHeight);
}
set
{
this.EnsureChildControls();
switch (TellaFreindText)
{
case TellaFreindText.Your_Name:
txt_yourname.Height = value;
break;
case TellaFreindText.Your_Email:
txt_yourEmail.Height = value;
break;
case TellaFreindText.Friend_Email:
txt_friendEmail.Height = value;
break;
case TellaFreindText.Message:
txt_message.Height = value;
break;
case TellaFreindText.Title:
lbl_title.Height = value;
break;
}
}
}
#endregion
#region Tell a FriendText
[Bindable(false), Category("Appearance"),
Description("")]
public TellaFreindText TellaFreindText
{
get
{
this.EnsureChildControls();
TellaFreindText retVal;
if (ViewState["textid"] == null)
retVal = TellaFreindText.Your_Name;
else
retVal = (TellaFreindText)ViewState["textid"];
return (retVal);
}
set
{
ViewState["textid"] = value;
this.EnsureChildControls();
TellaFreindText retVal;
retVal = value;
}
}
#endregion
#region Bind
protected override void CreateChildControls()
{
req1 = new RequiredFieldValidator();
req2 = new RequiredFieldValidator();
req3 = new RequiredFieldValidator();
req4 = new RequiredFieldValidator();
reg1 = new RegularExpressionValidator();
reg2 = new RegularExpressionValidator();
vs = new ValidationSummary();
lbl_title = new Label();
txt_yourname = new TextBox();
txt_yourEmail = new TextBox();
txt_friendEmail = new TextBox();
txt_message = new TextBox();
btn_send = new Button();
btn_send.Click+=new EventHandler(btn_send_Click);
HtmlTable table = new HtmlTable();
HtmlTableRow newRow;
HtmlTableCell newCell;
table.Border = 0;
table.Style.Add("DISPLAY", "inline");
table.Style.Add("VERTICAL-ALIGN", "middle");
///1st row
newRow = new HtmlTableRow();
newCell = new HtmlTableCell();
newCell.Controls.Add(lbl_title);
newCell.ColSpan = 2;
newRow.Cells.Add(newCell);
table.Rows.Add(newRow);
///2nd row
newRow =new HtmlTableRow();
newCell = new HtmlTableCell();
newCell.Align = "right";
newCell.InnerHtml = "<strong>Your Name:</strong>";
newRow.Controls.Add(newCell);
newCell = new HtmlTableCell();
txt_yourname.ID = "txtyourName";
newCell.Controls.Add(txt_yourname);
req1.ControlToValidate = txt_yourname.ID;
req1.ErrorMessage = "Enter Your Name";
req1.SetFocusOnError = true;
req1.Display = ValidatorDisplay.None;
newCell.Controls.Add(req1);
newRow.Cells.Add(newCell);
table.Rows.Add(newRow);
//3dr row
newRow = new HtmlTableRow();
newCell = new HtmlTableCell();
newCell.Align = "right";
newCell.InnerHtml = "<strong>Your Email:</strong>";
newRow.Controls.Add(newCell);
newCell = new HtmlTableCell();
txt_yourEmail.ID = "txtyourEmail";
newCell.Controls.Add(txt_yourEmail);
req2.ControlToValidate = txt_yourEmail.ID;
req2.ErrorMessage = "Enter Your Email Address";
req2.SetFocusOnError = true;
req2.Display = ValidatorDisplay.None;
newCell.Controls.Add(req2);
reg1.ControlToValidate = txt_yourEmail.ID;
reg1.ErrorMessage = "Invalid Email Address";
reg1.ValidationExpression = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
reg1.SetFocusOnError = true;
reg1.Display = ValidatorDisplay.None;
newCell.Controls.Add(reg1);
newRow.Cells.Add(newCell);
table.Rows.Add(newRow);
//4th row
newRow = new HtmlTableRow();
newCell = new HtmlTableCell();
newCell.Align = "right";
newCell.InnerHtml = "<strong>Friend's Email:</strong>";
newRow.Controls.Add(newCell);
newCell = new HtmlTableCell();
txt_friendEmail.ID = "txtFriendEmail";
newCell.Controls.Add(txt_friendEmail);
req3.ControlToValidate = txt_friendEmail.ID;
req3.ErrorMessage = "Enter Your Freind's Email Address";
req3.SetFocusOnError = true;
req3.Display = ValidatorDisplay.None;
newCell.Controls.Add(req3);
reg2.ControlToValidate = txt_friendEmail.ID;
reg2.ErrorMessage = "Invalid Email Address";
reg2.ValidationExpression = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
reg2.SetFocusOnError = true;
reg2.Display = ValidatorDisplay.None;
newCell.Controls.Add(reg2);
newRow.Cells.Add(newCell);
table.Rows.Add(newRow);
//5th row
newRow = new HtmlTableRow();
newCell = new HtmlTableCell();
newCell.Align = "right";
newCell.InnerHtml = "<strong>Message:</strong>";
newRow.Controls.Add(newCell);
newCell = new HtmlTableCell();
txt_message.TextMode = TextBoxMode.MultiLine;
txt_message.ID = "txtMessage";
newCell.Controls.Add(txt_message);
req4.ControlToValidate = txt_message.ID;
req4.ErrorMessage = "Enter Message";
req4.SetFocusOnError = true;
req4.Display = ValidatorDisplay.None;
newCell.Controls.Add(req4);
newRow.Cells.Add(newCell);
table.Rows.Add(newRow);
//6th row
newRow = new HtmlTableRow();
newCell = new HtmlTableCell();
newCell.Align = "right";
newCell.InnerHtml = "";
newRow.Controls.Add(newCell);
newCell = new HtmlTableCell();
newCell.Controls.Add(btn_send);
vs.ShowMessageBox = true;
vs.ShowSummary = false;
newCell.Controls.Add(vs);
newRow.Cells.Add(newCell);
table.Rows.Add(newRow);
table.CellPadding = 2;
table.CellSpacing = 4;
Controls.Add(table);
this.TellaFreindText = TellaFreindText.Button;
this.Text = "Send Message";
//this.Text = "Enter your name";
}
#endregion
#region Button Event
///
/// This delegate is called when the CoolButtonMode is set to Text.
/// It's only job is to forward the event to any registered handelers that
/// are encapsulating this control, including parent composite controls, or
/// the page itself.
///
///<span> <</span>param name="sender">The sender of the event<span></</span>param>
/// <span><</span>param name="e">An EventArgs object.<span></</span>param>
public void btn_send_Click(object sender, EventArgs e)
{
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
TellaFreindText = TellaFreindText.Your_Name;
string subject = "Mail from" + this.Text;
TellaFreindText = TellaFreindText.Your_Email;
string from = this.Text;
TellaFreindText = TellaFreindText.Friend_Email;
string to = this.Text;
TellaFreindText = TellaFreindText.Message;
string body = this.Text;
System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage(from, to, subject, body);
System.Net.Mail.SmtpClient cl = new System.Net.Mail.SmtpClient("localhost");
mm.IsBodyHtml = true;
cl.Send(mm);
}
#endregion
}
}
namespace ccc.TellaFriend.Design
{
public class TellaFriendDesing :ControlDesigner
{
///
/// Returns a design view of the control as rendered by the control itself.
///
/// The HTML of the design time control.
///
#region Bind control at desing time
public override string GetDesignTimeHtml()
{
TellaFriend tf = (TellaFriend)Component;
// If there are no controls, then it's the first time through the
// designer, so set the text to the unique id. This will also
// cause EnsureChildControls() to be called in Text(), which will
// build out the rest of the control.
if (tf.Controls.Count == 0)
tf.Text = tf.UniqueID;
StringWriter sw = new StringWriter();
HtmlTextWriter tw = new HtmlTextWriter(sw);
tf.RenderBeginTag(tw);
tf.RenderControl(tw);
tf.RenderEndTag(tw);
return (sw.ToString());
}
#endregion
}
}
Friday, November 2, 2007
Tell a friend : Custom Control
Watermark Image
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Image;
public void AddWatermark(string filename, string watermarkText, Stream outputStream) {
Bitmap bitmap = Bitmap.FromFile(filename);
Font font = new Font("Arial", 20, FontStyle.Bold, GraphicsUnit.Pixel);
Color color = Color.FromArgb(10, 0, 0, 0); //Adds a black watermark with a low alpha value (almost transparent).
Point atPoint = new Point(100, 100); //The pixel point to draw the watermark at (this example puts it at 100, 100 (x, y)).
SolidBrush brush = new SolidBrush(color);
Graphics graphics = null;
try {
graphics = Graphics.FromImage(bitmap);
} catch {
Bitmap temp = bitmap;
bitmap = new Bitmap(bitmap.Width, bitmap.Height);
graphics = Graphics.FromImage(bitmap);
graphics.DrawImage(temp, new Rectangle(0, 0, bitmap.Width, bitmap.Height), 0, 0, bitmap.Width, bitmap.Height, GraphicsUnit.Pixel);
temp.Dispose();
}
graphics.DrawString(text, font, brush, atPoint);
graphics.Dispose();
bitmap.Save(outputStream);
}
To call it, just add something like this to your aspx file (assume the class is called MyImage):
string filename = Request.MapPath(Request.QueryString["filename"]);
MyImage image = new MyImage();
image.AddWatermark(filename, "Watermark Test", HttpResponse.OutputStream);
Friday, August 24, 2007
Themes
ASP.NET Themes
What are ASP.NET 2.0 Themes?
One of the most important aspects of a Web application is a consistent look and feel across the site. ASP.NET 1.x developers usually use Cascading Style Sheets (CSS) to implement a consistent look and feel. ASP.NET 2.0 themes significantly improve upon CSS because they give the ASP.NET developer the ability to define the appearance of ASP.NET server controls as well as HTML elements. ASP.NET themes can be applied to individual controls, a specific Web page, or an entire Web application. Themes use a combination of CSS files, an optional skin file, and an optional Images directory if images are needed. The skin file controls the visual appearance of ASP.NET server controls.
Where are Themes Stored?
The location where themes are stored differs based upon their scope. Themes that can be applied to any application are stored in the following folder:
C:\WINDOWS\Microsoft.NET\Framework\v2.x.xxxxx\ASP.NETClientFiles\Themes\
A theme that is specific to a particular application is stored in an App_Themes\
Note: A skin file should only modify server control properties that affect appearance.
A global theme is a theme that can be applied to any application or Web site running on the Web server. These themes are stored by default in the ASP.NETClientfiles\Themes directory that is inside of the v2.x.xxxxx directory. Alternatively, you can move the theme files into the aspnet_client/system_web/[version]/Themes/[theme_name] folder in the root of your Web site.
Application-specific themes can only be applied to the application in which the files reside. These files are stored in the App_Themes/
The Components of a Theme
A theme is made up of one or more CSS files, an optional skin file, and an optional Images folder. The CSS files can be any name you wish (i.e. default.css or theme.css, etc.) and must be in the root of the themes folder. The CSS files are used to define ordinary CSS classes and attributes for specific selectors. To apply one of the CSS classes to a page element, the CSSClass property is used.
The skin file is an XML file that contains property definitions for ASP.NET server controls. The code listed below is an example skin file.
<asp:TextBox runat="server"
BackColor="#FFC080"
BorderColor="Black"
BorderStyle="Solid"
BorderWidth="1px"
Font-Names="Tahoma, Verdana, Arial"
Font-Size="Smaller" />
<asp:Button runat="server"
BackColor="#C04000"
BorderColor="Maroon"
BorderStyle="Solid"
BorderWidth="2px"
Font-Names="Tahoma,Verdana,Arial"
Font-Size="Smaller"
ForeColor="#FFFFC0" />
Figure 1 below shows a small ASP.NET page browsed without a theme applied. Figure 2 shows the same file with a theme applied. The background color and text color are configured via a CSS file. The appearance of the button and textbox are configured using the skin file listed above.
Figure 1: No Theme
The skin file listed above defines a default skin for all TextBox controls and Button controls. That means that every TextBox control and Button control inserted on a page will take on this appearance. You can also define a skin that can be applied to specific instances of these controls using the SkinID property of the control.
The code below defines a skin for a Button control. Only Button controls with a SkinID property of goButton will take on the appearance of the skin.
<asp:Button runat="server"
BackColor="#C04000"
BorderColor="Maroon"
BorderStyle="Solid"
BorderWidth="2px"
Font-Names="Tahoma,Verdana,Arial"
Font-Size="Smaller"
ForeColor="#FFFFC0"
Text=go
SkinID=goButton
Width="95px" />
You can only have one default skin per server control type. If you require additional skins, you should use the SkinID property.
Applying Themes to Pages
A theme can be applied using any one of the following methods:
* In the
* In the @Page directive of a page
* Programmatically
Applying a Theme in the Configuration File
To apply a theme in the applications configuration file, use the following syntax:
<system.web>
<pages theme="CoolTheme" />
...
</system.web>
The theme name specified here must match the name of the themes folder. This folder can exist either in any one of the locations mentioned earlier in this course. If you attempt to apply a theme that doesn't exist, a configuration error will occur.
Applying a Theme in the Page Directive
You can also apply a theme in the @ Page directive. This method allows you to use a theme for a specific page.
To apply a theme in the @Page directive, use the following syntax:
<%@ Page Language="C#" Theme=CoolTheme CodeFile="Default.aspx.cs" ... %>
Once again, the theme specified here must match the theme folder as mentioned previously. If you attempt to apply a theme that doesn't exist, a build failure will occur. Visual Studio will also highlight the attribute and notify you that no such theme exists.
Applying a Theme Programmatically
To apply a theme programmatically, you must specify the Theme property for the page in the Page_PreInit method.
To apply a theme programmatically, use the following syntax:
Page.Theme = CoolTheme;It is necessary to apply the theme in the PreInit method due to the page lifecycle. If you apply it after that point, the pages theme will have already been applied by the runtime and a change at that point is too late in the lifecycle. If you apply a theme that doesn't exist, an HttpException occurs. When a theme is applied programmatically, a build warning will occur if any server controls have a SkinID property specified. This warning is intended to inform you that no theme is declaratively applied and it can be ignored.
Exercise 1 : Applying a Theme
In this exercise, you will apply an ASP.NET theme to a Web site.
IMPORTANT: If you are using Microsoft Word to enter information into a skin file, make sure that you are not replacing regular quotes with smart quotes. Smart quotes will cause problems with skin files.
- Create a new ASP.NET Web site.
- Right-click on the project in Solution Explorer and choose Add New Item.
- Choose Web Configuration File from the list of files and click Add.
- Right-click on the project in Solution Explorer and choose Add New Item.
- Choose Skin File and click Add.
- Click Yes when asked if youd like to place the file inside of the App_Themes folder.
- Right-click on the SkinFile folder inside of the App_Themes folder in Solution Explorer and choose Add New Item.
- Choose Style Sheet from the list of files and click Add. You now have all of the files necessary to implement your new theme. However, Visual Studio has named your themes folder SkinFile. Right-click on that folder and change the name to CoolTheme.
- Open the SkinFile.skin file and add the following code the end of the file:
<asp:TextBox runat="server"
BackColor="#FFC080"
BorderColor="Black"
BorderStyle="Solid"
BorderWidth="1px"
Font-Names="Tahoma, Verdana, Arial"
Font-Size="Smaller"
/>
<asp:Button runat="server"
BackColor="#C04000"
BorderColor="Maroon"
BorderStyle="Solid"
BorderWidth="2px"
Font-Names="Tahoma,Verdana,Arial"
Font-Size="Smaller"
ForeColor="#FFFFC0"
/>
<asp:Button runat="server"
BackColor="#C04000"
BorderColor="Maroon"
BorderStyle="Solid"
BorderWidth="2px"
Font-Names="Tahoma,Verdana,Arial"
Font-Size="Smaller"
ForeColor="#FFFFC0"
Text="go"
SkinID="goButton"
Width="95px"
/>
10. Save the SkinFile.skin file.
11. Open the StyleSheet.css.
12. Replace all of the text in it with the following:
body {
background-color: #FFDEAD;
}
- Save the StyleSheet.css file.
- Open the Default.aspx page.
- Add a TextBox control and a Button control.
- Save the page. Now browse the Default.aspx page. It should display as a normal Web form.
- Open the web.config file.
- Add the following directly underneath the opening
<system.web>
tag:
<pages theme="CoolTheme" />
19. Save the web.config file. Now browse the Default.aspx page. It should display with the theme applied.
20. If it's not already open, open the Default.aspx page in Visual Studio.
21. Select the Button.
22. Change the SkinID property to goButton. Notice that Visual Studio provides a dropdown with valid SkinID values for a Button control.
23. Save the page. Now preview the page in your browser again. The Button should now say "go" and should be wider in appearance.
Using the SkinID property, you can easily configure different skins for different instances of a particular type of server control.
The StyleSheetTheme Property
So far, we've talked only about applying themes using the Theme property. When using the Theme property, the skin file will override any declarative settings for server controls. For example, in exercise 1, you specified a SkinID of "goButton" for the Button control and that changed the Button's text to "go". You may have noticed that the Text property of the Button in the designer was set to "Button", but the theme overrode that. The theme will always override any property settings in the designer.
If you'd like to be able to override the properties defined in the theme's skin file with properties specified in the designer, you can use the StyleSheetTheme property instead of the Theme property. The StyleSheetTheme property is the same as the Theme property except that it does not override all explicit property settings like the Theme property does.
To see this in action, open the web.config file from the project in exercise 1 and change the
<pages styleSheetTheme="CoolTheme" />
Now browse the Default.aspx page and you'll see that the Button control has a Text property of "Button" again. That's because the explicit property setting in the designer is overriding the Text property set by the goButton SkinID.
Overriding Themes
A global theme can be overridden by applying a theme by the same name in the App_Themes folder of the application. However, the theme is not applied in a true override scenario. If the runtime encounters theme files in the App_Themes folder, it will apply the theme using those files and will ignore the global theme.
The StyleSheetTheme property is overridable and can be overridden in code as follows:
const String THEME_NAME = "CoolTheme";
public override string StyleSheetTheme {
get { return THEME_NAME; }
set { Page.StyleSheetTheme = THEME_NAME; }
}
Profiles
ASP.NET 2.0 represents a substantial improvement in the area of personalized Web sites. In addition to the membership features weve already covered, ASP.NET profiles, themes, and Web parts significantly enhance personalization in Web sites.
ASP.NET Profiles
ASP.NET profiles are similar to sessions. The difference is that a profile is persistent whereas a session is lost when the browser is closed. Another big difference between sessions and profiles is that profiles are strongly typed, therefore providing you with IntelliSense during the development process.
A profile is defined in either the machines configuration file or the web.config file for the application. (You cannot define a profile in a sub-folders web.config file.) The code below defines a profile to store the Web site visitors first and last name.
<profile>The default data type for a profile property is System.String. In the above example, no data type was specified. Therefore the FirstName and LastName properties are both of type String. As previously mentioned, profile properties are strongly typed. The code below adds a new property for age that is of type Int32.
<properties>
<add name="FirstName" />
<add name="LastName" />
</properties>
</profile>
<profile>
<properties>
<add name="FirstName" />
<add name="LastName" />
<add name="Age" type="Int32"/>
</properties>
</profile>
Profiles are generally used with ASP.NET Forms authentication. When used in combination with Forms authentication, each user has a separate profile associated with their user ID. However, it is also possible to allow the use of profiles in an anonymous application using the
<anonymousIdentification enabled="true" />
<profile>
<properties>
<add name="FirstName" allowAnonymous="true" />
<add name="LastName" allowAnonymous="true" />
</properties>
</profile>
When an anonymous user browses the site, ASP.NET creates an instance of ProfileCommon for the user. This profile uses a unique ID stored in a cookie on the browser to identify the user as a unique visitor. In this way, you can store profile information for users who are browsing anonymously.
Profile Groups
It is possible to group properties of profiles. By grouping properties, it is possible to simulate multiple profiles for a specific application.
The following configuration configures a FirstName and LastName property for two groups; Buyers and Prospects.
<profile>
<properties>
<group name="Buyers">
<add name="FirstName" />
<add name="Lastname" />
<add name="NumberOfPurchases" type="Int32" />
</group>
<group name="Prospects">
<add name="FirstName" />
<add name="Lastname" />
</group>
</properties>
</profile>
It is then possible to set properties on a particular group as follows:
Profile.Buyers.NumberOfPurchases += 1;
Storing Complex Objects
So far, the examples we've covered have stored simple data types in a profile. It is also possible to store complex data types in a profile by specifying the method of serialization using the serializeAs attribute as follows:<add name="PurchaseInvoice"
type="PurchaseInvoice"
serializeAs="Binary"
/>
In this case, the type is PurchaseInvoice. The PurchaseInvoice class needs to be marked as serializable and can contain any number of properties. For example, if PurchaseInvoice has a property called NumItemsPurchased, you can refer to that property in code as follows:
Profile.PurchaseInvoice.NumItemsPurchased
Profile Inheritance
It is possible to create a profile for use in multiple applications. By creating a profile class that derives from ProfileBase, you can reuse a profile in several applications by using the inherits attribute as shown below:
<profile inherits="PurchasingProfile" />
In this case, the class PurchasingProfile would look
like so:
using System;
using System.Web.Profile;
public class PurchasingProfile : ProfileBase {
private string _ProductName;
private Int32 _ProductID;
public string ProductName {
get { return _ProductName; }
set { _ProductName = value; }
}
public Int32 ProductID {
get { return _ProductID; }
set { _ProductID = value; }
}
}
Profile Providers
ASP.NET profiles use the provider model. The default provider stores the information in a SQL Server Express database in the App_Data folder of the Web application using the SqlProfileProvider provider. If the database doesn't exist, ASP.NET will automatically create it when the profile attempts to store information.
In some cases, however, you may want to develop your own profile provider. The ASP.NET profile feature enables you to easily use different providers.
You create a custom profile provider when:
- You need to store profile information in a data source, such as in a FoxPro database or in an Oracle database, that is not supported by the profile providers included with the .NET Framework.
- You need to manage profile information using a database schema that is different from the database schema used by the providers included with the .NET Framework. A common example is that you want to integrate profile information with user data in an existing SQL Server database.
Required Classes
To implement a profile provider, you create a class that inherits the System.Web.Profile.ProfileProvider abstract class. The ProfileProvider abstract class in turn inherits the System.Configuration.SettingsProvider abstract class, which inherits the System.Configuration.Provider.ProviderBase abstract class. Because of this inheritance chain, in addition to the required members of the ProfileProvider class, you must implement the required members of the SettingsProvider and ProviderBase classes.
The following tables describe the properties and methods that you must implement from the ProviderBase, SettingsProvider, and ProfileProvider abstract classes.
ProviderBase Members
Member | Description |
Initialize method | Takes as input the name of the provider instance and a NameValueCollection of configuration settings. Used to set options and property values for the provider instance, including implementation-specific values and options specified in the machine configuration or Web.config file. |
SettingsProvider Members
Member | Description |
ApplicationName property | The application name that is stored with each profile. The profile provider uses the application name to store profile information separately for each application. This enables multiple ASP.NET applications to use the same data source without a conflict if the same user name is created in different applications. Alternatively, multiple ASP.NET applications can share a profile data source by specifying the same application name. |
GetPropertyValues method | Takes as input a SettingsContext and a SettingsPropertyCollection object. The SettingsContext provides information about the user. You can use the information as a primary key to retrieve profile property information for the user. Use the SettingsContext object to get the user name and whether the user is authenticated or anonymous. The SettingsPropertyCollection contains a collection of SettingsProperty objects. Each SettingsProperty object provides the name and type of the property as well as additional information such as the default value for the property and whether the property is read-only. The GetPropertyValues method populates a SettingsPropertyValueCollection with SettingsPropertyValue objects based on the SettingsProperty objects provided as input. The values from the data source for the specified user are assigned to the PropertyValue properties for each SettingsPropertyValue object and the entire collection is returned. Calling the method also updates the LastActivityDate value for the specified user profile to the current date and time. |
SetPropertyValues method | Takes as input a SettingsContext and a SettingsPropertyValueCollection object. The SettingsContext provides information about the user. You can use the information as a primary key to retrieve profile property information for the user. Use the SettingsContext object to get the user name and whether the user is authenticated or anonymous. The SettingsPropertyValueCollection contains a collection of SettingsPropertyValue objects. Each SettingsPropertyValue object provides the name, type, and value of the property as well as additional information such as the default value for the property and whether the property is read-only. The SetPropertyValues method updates the profile property values in the data source for the specified user. Calling the method also updates the LastActivityDate and LastUpdatedDate values for the specified user profile to the current date and time. |
ProfileProvider Members
Member | Description |
DeleteProfiles method | Takes as input a string array of user names and deletes from the data source all profile information and property values for the specified names where the application name matches the ApplicationName property value. If your data source supports transactions, it is recommended that you include all delete operations in a transaction and that you roll back the transaction and throw an exception if any delete operation fails. |
DeleteProfiles method | Takes as input a collection of ProfileInfo objects and deletes from the data source all profile information and property values for each profile where the application name matches the ApplicationName property value. If your data source supports transactions, it is recommended that you include all delete operations in a transaction and roll back the transaction and throw an exception if any delete operation fails. |
DeleteInactiveProfiles method | Takes as input a ProfileAuthenticationOption value and a DateTime object and deletes from the data source all profile information and property values where the last activity date is less than or equal to the specified date and time and where the application name matches the ApplicationName property value. The ProfileAuthenticationOption parameter specifies whether only anonymous profiles, only authenticated profiles, or all profiles are to be deleted. If your data source supports transactions, it is recommended that you include all delete operations in a transaction and roll back the transaction and throw an exception if any delete operation fails. |
GetAllProfiles method | Takes as input a ProfileAuthenticationOption value, an integer that specifies the page index, an integer that specifies the page size, and a reference to an integer that will be set to the total count of profiles. Returns a ProfileInfoCollection that contains ProfileInfo objects for all profiles in the data source where the application name matches the ApplicationName property value. The ProfileAuthenticationOption parameter specifies whether only anonymous profiles, only authenticated profiles, or all profiles are to be returned. The results returned by the GetAllProfiles method are constrained by the page index and page size values. The page size value specifies the maximum number of ProfileInfo objects to return in the ProfileInfoCollection. The page index value specifies which page of results to return, where 1 identifies the first page. The parameter for total records is an out parameter (you can use ByRef in Visual Basic) that is set to the total number of profiles. For example, if the data store contains 13 profiles for the application and the page index value is 2 with a page size of 5, the ProfileInfoCollection returned contains the sixth through the tenth profiles. The total records value is set to 13 when the method returns. |
GetAllInactiveProfiles method | Takes as input a ProfileAuthenticationOption value, a DateTime object, an integer that specifies the page index, an integer that specifies the page size, and a reference to an integer that will be set to the total count of profiles. Returns a ProfileInfoCollection that contains ProfileInfo objects for all profiles in the data source where the last activity date is less than or equal to the specified DateTime and where the application name matches the ApplicationName property value. The ProfileAuthenticationOption parameter specifies whether only anonymous profiles, only authenticated profiles, or all profiles are to be returned. The results returned by the GetAllInactiveProfiles method are constrained by the page index and page size values. The page size value specifies the maximum number of ProfileInfo objects to return in the ProfileInfoCollection. The page index value specifies which page of results to return, where 1 identifies the first page. The parameter for total records is an out parameter (you can use ByRef in Visual Basic) that is set to the total number of profiles. For example, if the data store contains 13 profiles for the application and the page index value is 2 with a page size of 5, the ProfileInfoCollection returned contains the sixth through the tenth profiles. The total records value is set to 13 when the method returns. |
FindProfilesByUserName method | Takes as input a ProfileAuthenticationOption value, a string containing a user name, an integer that specifies the page index, an integer that specifies the page size, and a reference to an integer that will be set to the total count of profiles. Returns a ProfileInfoCollection that contains ProfileInfo objects for all profiles in the data source where the user name matches the specified user name and where the application name matches the ApplicationName property value. The ProfileAuthenticationOption parameter specifies whether only anonymous profiles, only authenticated profiles, or all profiles are to be returned. If your data source supports additional search capabilities, such as wildcard characters, you can provide more extensive search capabilities for user names. The results returned by the FindProfilesByUserName method are constrained by the page index and page size values. The page size value specifies the maximum number of ProfileInfo objects to return in the ProfileInfoCollection. The page index value specifies which page of results to return, where 1 identifies the first page. The parameter for total records is an out parameter (you can use ByRef in Visual Basic) that is set to the total number of profiles. For example, if the data store contains 13 profiles for the application and the page index value is 2 with a page size of 5, the ProfileInfoCollection returned contains the sixth through the tenth profiles. The total records value is set to 13 when the method returns. |
FindInactiveProfilesByUserName method | Takes as input a ProfileAuthenticationOption value, a string containing a user name, a DateTime object, an integer that specifies the page index, an integer that specifies the page size, and a reference to an integer that will be set to the total count of profiles. Returns a ProfileInfoCollection that contains ProfileInfo objects for all profiles in the data source where the user name matches the specified user name, where the last activity date is less than or equal to the specified DateTime, and where the application name matches the ApplicationName property value. The ProfileAuthenticationOption parameter specifies whether only anonymous profiles, only authenticated profiles, or all profiles are to be returned. If your data source supports additional search capabilities, such as wildcard characters, you can provide more extensive search capabilities for user names. The results returned by the FindInactiveProfilesByUserName method are constrained by the page index and page size values. The page size value specifies the maximum number of ProfileInfo objects to return in the ProfileInfoCollection. The page index value specifies which page of results to return, where 1 identifies the first page. The parameter for total records is an out parameter (you can use ByRef in Visual Basic) that is set to the total number of profiles. For example, if the data store contains 13 profiles for the application and the page index value is 2 with a page size of 5, the ProfileInfoCollection returned contains the sixth through the tenth profiles. The total records value is set to 13 when the method returns. |
GetNumberOfInActiveProfiles method | Takes as input a ProfileAuthenticationOption value and a DateTime object and returns a count of all profiles in the data source where the last activity date is less than or equal to the specified DateTime and where the application name matches the ApplicationName property value. The ProfileAuthenticationOption parameter specifies whether only anonymous profiles, only authenticated profiles, or all profiles are to be counted. |
ApplicationName
Because profile providers store profile informationseparately for each application, you must ensure that your data schema includes
the application name and that queries and updates also include the application
name. For example, the following command is used to retrieve a property value
from a database based on the user name and whether the profile is anonymous,
and ensures that the ApplicationName value
is included in the query.
SELECT Property
FROM PropertyTable
WHERE Username = 'user1'
AND IsAnonymous = False
AND ApplicationName = 'MyApplication'