Create Class in App_Code called BasePage.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web.UI;
class BasePage : System.Web.UI.Page
{
//Override two relevant methods that handle Loading and Saving of ViewState:
protected override object LoadPageStateFromPersistenceMedium()
{
object viewStateBag;
string m_viewState = (string)Session["ViewState"];
LosFormatter m_formatter = new LosFormatter();
try
{
viewStateBag = m_formatter.Deserialize(m_viewState);
}
catch
{
throw new HttpException("The View State is invalid.");
}
return viewStateBag;
}
protected override void SavePageStateToPersistenceMedium(object viewState)
{
MemoryStream ms = new MemoryStream();
LosFormatter m_formatter = new LosFormatter();
m_formatter.Serialize(ms, viewState);
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
viewStateString = sr.ReadToEnd();
Session["ViewState"] = viewStateString;
ms.Close();
return;
}
}
and make all pages inhrit from BasePage class
Good Luck
Monday, December 15, 2008
Remove Cashing
Try this in Page Load
Good Luck
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
Good Luck
Validate Image Size
Try this example :
<asp:CustomValidator ID="valFileSize" runat="server" ErrorMessage="The image exceeds 10 MB" onservervalidate="valFileSize_ServerValidate" Display="Dynamic" />
The method that actually performs the validation looks like this one:
protected void valFileSize_ServerValidate(object source, ServerValidateEventArgs args)
{
if (IsValid)
{
int maxSize = 5 * 1024 * 1024;
if (fileImage.PostedFile.ContentLength > maxSize)
{
args.IsValid = false;
}
}
}
and in web.config
<httpRuntime maxRequestLength="20480"/>
Good Luck
Login Redirection
Try this:
Good Luck
in Login.aspx page
public static void RequestLogin()
{
string OriginalUrl = HttpContext.Current.Request.RawUrl;
string LoginPageUrl = "~/login.aspx";
HttpContext.Current.Response.Redirect(_String.Format("{0}?ReturnUrl={1}", LoginPageUrl, OriginalUrl));
}
protected void Login1_LoggedIn(object sender, EventArgs e)
{
TextBox TextBox1 = (TextBox)Login1.FindControl("UserName");
//MembershipUser user = Membership.GetUser(TextBox1.Text);
MembershipUser user = Membership.GetUser(Login1.UserName);
if (Request.QueryString["ReturnUrl"] != null)
{
Response.Redirect(Request.QueryString["ReturnUrl"].ToString());
}
else
{
//-- check if login user in Admin role
if (Roles.IsUserInRole(TextBox1.Text, "Admin"))
{
Response.Redirect("~/Admin/Default.aspx");
}
//-- check if login user in User role
else if (Roles.IsUserInRole(TextBox1.Text, "User"))
{
Response.Redirect("~/User/Default.aspx");
}
}
}
//---------- another way----------
protected void Page_Load(object sender, EventArgs e)
{
}
protected void custlogin_Authenticate(object sender, AuthenticateEventArgs e)
{
if (Membership.ValidateUser(custlogin.UserName, custlogin.Password))
{
e.Authenticated = true;
if (Roles.IsUserInRole(custlogin.UserName, "administrator"))
{
custlogin.DestinationPageUrl = "~/CMS/CMS_Home.aspx";
FormsAuthentication.RedirectFromLoginPage(custlogin.UserName, custlogin.RememberMeSet);
}
if (Roles.IsUserInRole(custlogin.UserName, "employee"))
{
custlogin.DestinationPageUrl = "~/Employee/Employee_Home.aspx";
FormsAuthentication.RedirectFromLoginPage(custlogin.UserName, custlogin.RememberMeSet);
}
if (Roles.IsUserInRole(custlogin.UserName, "customer"))
{
custlogin.DestinationPageUrl = "~/Client/Customer_Home.aspx";
FormsAuthentication.RedirectFromLoginPage(custlogin.UserName, custlogin.RememberMeSet);
}
}
else
e.Authenticated = false;
}
Good Luck
Logout
protected void lnkbLogout_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Session.Abandon();
HttpContext.Current.Response.Redirect("Login.aspx", true);
}
//-----------Or --------------
protected void LoginStatus1_LoggedOut(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Roles.DeleteCookie();
Session.Clear();
}
Good Luck
Send an Activation Email with ASP.NET 2.0
Many sites as you've seen send out an email that contains a link to activate your account after you've filled out all requested information. This is primarily seen on Web Forum sites and other sites that require a membership. I'm going to show a quick example of how to do this using ASP.NET and sending the email via Gmail or some other SMTP server such as your hosting company's smtp server. It is assumed that you have already configured your ASPNETDB with Membership and Roles. This is just a basic email activation you can expand upon it and add other features you might want.Start by dropping a standard CreateUserWizard Control on a page. I've dropped the control on a page called Default.aspx. You can format it later with any of the available Format templates Microsoft has provided or customize it using CSS if you like.Below is the code-behind for the Default.aspx page. This code essentially grabs the Username, Password, and Email address that was entered through the CreateUserWizard Control puts the information into a StringBuilder object along with a link to the Activate.aspx page. The UserID is a Guid value that is appended to the Activate URL as a query string.Using a conditional you can select to send the emails via your Hosting Companies SMTP server, a local SMTP server, or a Gmail account.
Hope it helps and Good Luck
#define Gmail
#define SMTP
using System;
using System.Data;
using System.Configuration;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
{
StringBuilder bodyMsg = new StringBuilder();
TextBox username = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("UserName");
TextBox password = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Password");
TextBox email = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Email");
CreateUserWizard cuw = (CreateUserWizard)sender;
MembershipUser user = Membership.GetUser(cuw.UserName);
Guid userID = (Guid)user.ProviderUserKey;
bodyMsg.Append("Thank you for creating your account.\n\nPlease follow this link to activate: ");
bodyMsg.Append("<br /><br /><a href=http://yourserver/SendEmailConfirmationSample/Activate.aspx?ID=" + userID.ToString() + ">Activate Your Account</a>");
bodyMsg.Append("<br />");
bodyMsg.Append("<br />");
bodyMsg.AppendFormat("UserName: {0}", username.Text);
bodyMsg.Append("<br />");
bodyMsg.AppendFormat("Password: {0}", password.Text);
bodyMsg.Append("<br />");
bodyMsg.AppendFormat("Registered Email: {0}", email.Text);
#if SMTP
// Sending email via local or web hosts smtp server.
NetworkCredential loginInfo = new NetworkCredential("yourusername", "yourpassword");
MailMessage msg = new MailMessage();
msg.From = new MailAddress("youremailaddress");
msg.To.Add(new MailAddress(CreateUserWizard1.Email));
msg.Subject = "Account Information";
msg.Body = bodyMsg.ToString();
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtpserver", 25);
client.Credentials = loginInfo;
client.Send(msg);
#endif
#if Gmail
// Sending email via Gmail.
NetworkCredential loginInfo = new NetworkCredential("yourUsername@gmail.com", "yourGmailPassword");
MailMessage msg = new MailMessage();
msg.From = new MailAddress("mailto:yourUsername@gmail.com%22);
msg.To.Add(new MailAddress(CreateUserWizard1.Email));
msg.Subject = "Account Information";
msg.Body = bodyMsg.ToString();
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
client.Send(msg);
#endif
Response.Redirect("~/thankyoupage.aspx");
}
}
The Activate.aspx page's code behind gets the ID that was passed in the query string and uses it to link the user to the account that was created, as well as adds the user to the Power Users Role in ASPNETDB. The page then displays the Username, Date the account was created, and the Status of the user's account.using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Activate : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string userID = Request.QueryString["ID"];
Guid gd = new Guid(userID);
MembershipUser user = Membership.GetUser(gd);
user.IsApproved = true;
Roles.AddUserToRole(user.ToString(), "Power Users");
Membership.UpdateUser(user);
ActiviationNameLabel.Text = user.UserName;
ActivationCreationDateLabel.Text = user.CreationDate.ToShortDateString();
if (user.IsApproved)
{
ActivationStatusLabel.Text = "Active";
}
else
{
ActivationStatusLabel.Text = "Pending";
}
}
}
}
Hope it helps and Good Luck
Embedding an image within an email
Not to long ago I remember seeing a post on the ASP.NET forums where someone had a need to embed an image within an email that they generated from their web application. I decided to put together a short sample that does just that. Using the code I'll provide you can embed an image within your email, so that when you open the email up with in Yahoo's Webmail client or any other Web based email client the image will be displayed in-line as opposed to being sent as an attachment. This code is just a sample and can be further improved, but it should get you started. I have verified that the image is embedded in-line when sent to GMail, Yahoo, and Hotmail.
Here is the Sample's HTML.
NOTE: Make sure to add the attribute ValidateRequest="false" to the Page Directive. This is so that you can embeded HTML into your email message. Also please beware that this will also allow for XSS via Javascript.
Hope it helps
Here is the Sample's HTML.
NOTE: Make sure to add the attribute ValidateRequest="false" to the Page Directive. This is so that you can embeded HTML into your email message. Also please beware that this will also allow for XSS via Javascript.
<div>
<div>
<asp:Label ID="ToLabel" runat="server" Style="padding-left: 1.8em" Text="To:" />
<asp:TextBox ID="ToTextBox" runat="server" />
</div>
<div>
<asp:Label ID="FromLabel" runat="server" Style="padding-left: .8em" Text="From:" />
<asp:TextBox ID="FromTextBox" runat="server" />
</div>
<div>
<asp:Label ID="SubjectLabel" runat="server" Text="Subject:" />
<asp:TextBox ID="SubjectTextBox" runat="server" />
</div>
<div>
<asp:Label ID="BodyLabel" runat="server" Style="padding-left: .8em" Text="Body:" />
<asp:TextBox ID="BodyTextBox" runat="server" TextMode="MultiLine" Width="250px" Height="100px" />
<asp:Image ID="SelectedImage" runat="server" style="left: 200px; top: 200px;"
Height="100px" Width="100px" />
</div>
<div>
<br />
<asp:Button ID="SendButton" runat="server" Style="margin-left: 10em"
Text="Send" onclick="SendButton_Click" />
</div>
<div>
<br />
<div style="width: 550px; overflow: scroll; height: 100px;">
<asp:DataList ID="ImageDataList" runat="server" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4"
ForeColor="Black" GridLines="Horizontal" HorizontalAlign="Center"
RepeatDirection="Horizontal" Height="90px" Width="500px"
onitemcommand="ImageDataList_ItemCommand">
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<SelectedItemStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<ItemTemplate>
<asp:ImageButton ID="ProfileImageButton" runat="server"
ImageUrl='<%# Eval("FullName") %>' />
</ItemTemplate>
</asp:DataList>
</div>
</div>
</div>
<br />
<asp:Label ID="StatusLabel" runat="server" />
Here's the Sample's Code make sure to include the following namespaces.using System.IO;
using System.Net;
using System.Net.Mail;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
StatusLabel.Visible = false;
DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/Images"));
int total = dir.GetFiles("*.jpg").Length;
if (total > 3)
{
ImageDataList.RepeatColumns = total + 1;
}
ImageDataList.DataSource = dir.GetFiles("*.jpg");
ImageDataList.DataBind();
}
}
protected void SendButton_Click(object sender, EventArgs e)
{
NetworkCredential loginInfo = new NetworkCredential("username@gmail.com", "yourGMailPassword");
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress(Server.HtmlEncode(ToTextBox.Text)));
msg.From = new MailAddress(Server.HtmlEncode(FromTextBox.Text));
msg.Subject = Server.HtmlEncode(SubjectTextBox.Text);
msg.Body = BodyTextBox.Text;
AlternateView body = AlternateView.CreateAlternateViewFromString(msg.Subject + "<br /><br />" + msg.Body + "<br /><br /><img src=cid:profile />", null, "text/html");
try
{
LinkedResource profileImg = new LinkedResource(SelectedImage.ImageUrl);
profileImg.ContentId = "profile";
body.LinkedResources.Add(profileImg);
}
catch (ArgumentException argEx)
{
StatusLabel.Visible = true;
StatusLabel.Style.Add("color", "#CC0033");
StatusLabel.Text = "An image was not selected.";
return;
}
catch (Exception ex)
{
StatusLabel.Visible = true;
StatusLabel.Style.Add("color", "#CC0033");
StatusLabel.Text = "The following error occurred: " + "<br /><br />" + ex.Message;
}
msg.AlternateViews.Add(body);
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
try
{
client.Send(msg);
}
catch (SmtpException smtpEx)
{
StatusLabel.Visible = true;
StatusLabel.Style.Add("color", "#CC0033");
StatusLabel.Text = "The following error occurred: " + "<br /><br />" + smtpEx.Message;
}
catch (Exception ex)
{
StatusLabel.Visible = true;
StatusLabel.Style.Add("color", "#CC0033");
StatusLabel.Text = "The following error occurred: " + "<br /><br />" + ex.Message;
}
StatusLabel.Visible = true;
StatusLabel.Style.Add("color", "#009966");
StatusLabel.Text = "Email sent successfully.";
}
protected void ImageDataList_ItemCommand(object source, DataListCommandEventArgs e)
{
SelectedImage.ImageUrl = ((ImageButton)e.CommandSource).ImageUrl;
}
Hope it helps
Subscribe to:
Comments (Atom)

