Monday, December 15, 2008

Handle Large ViewState Size

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

Remove Cashing

Try this in Page Load

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:


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.
#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.
    <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

Friday, November 28, 2008

GridView color change depending on inner value

Hi all

try this example

Protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// This line will get the reference to the underlying row
DataRowView _row = (DataRowView)e.Row.DataItem;
if (_row != null)
{
// get the field value which you want to compare and
// convert to the corresponding data type
// i assume the fieldName is of int type
int _field = Convert.ToInt32(_row.Row["fieldName"]);
if (_field == 7)
e.Row.BackColor = System.Drawing.Color.Green;
else
e.Row.BackColor = System.Drawing.Color.Red;
}
}
}
Good Luck

Friday, October 31, 2008

Validate Image Size using CustomValidator Control

Try this code in server side of CustomValidator

protected void CustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
if (IsValid)
{
int maxSize = 5 * 1024 * 1024;
if (FileUpload1.PostedFile.ContentLength > maxSize)
{
args.IsValid = false;
}
}
}

Good Luck

Get Yesterday Date

Try this code:

DateTime.Now.AddDays(-1).ToString("dd-MM-yyyy");

Good Luck

Wednesday, October 29, 2008

Automatically change text to Uppercase

Try this with textbox in page Load

TextBox1.Attributes.Add("onblur", "this.value=this.value.toUpperCase();");

Good Luck

Change User Email using Membership

Try this:

Dim user As MembershipUser user = Membership.GetUser(UserName)
user.Email = TxtBxNewEmail.Text
Membership.UpdateUser(user)

-- But check for email availability:

public bool CheckEmail()
{
bool emailExsit = false;
MembershipUserCollection users = Membership.FindUsersByEmail(Email.Text);
foreach (MembershipUser user in users)
{
if (Email.Text == user.Email)
{
emailExsit = true;
break;
}
else
{
emailExsit = false;
}
}
return emailExsit;
}

Good Luck

Count Number of record in Table

Try this

public int Count_Company()
{
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand comm = new SqlCommand();
comm.CommandText = "Select count(UserName) from CompanyData"; comm.CommandType = CommandType.Text;
comm.Connection = conn;
conn.Open();
rows = int.Parse(comm.ExecuteScalar().ToString());
conn.Close();
return rows;
}

Good Luck

Show and Hide Hyperlink in LoginView according to Role of Login user

Try this:


protected void Page_Load(object sender, EventArgs e)
{
//-- show Admin Page Link in Login View for Admin user
if (Request.IsAuthenticated)
{
HyperLink lnk_Admin = (HyperLink)LoginView1.FindControl("lnk_Admin");
string userName=Membership.GetUser().UserName;
if (Roles.IsUserInRole(userName, "Admin"))
{
lnk_Admin.Visible = true;
}
else
{
lnk_Admin.Visible = false;
}
}

Good Luck

Get current page name

Try this:

public string GetCurrentPageName()
{
string sPath = System.Web.HttpContext.Current.Request.Url.AbsolutePath; System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath);
string sRet = oInfo.Name;
return sRet;
}

Good Luck

Find Control in Gridview and DataList

Try this :

//--- DataList
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item
e.Item.ItemType == ListItemType.AlternatingItem)
{
Label lbl_Desc = (Label)e.Item.FindControl("lbl_Desc");
lbl_Desc.Text = lbl_Desc.Text.Substring(0, 180).ToString() + "...";
}
}

//--- Gridview
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

//-- find control in row
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl_Type= (DropDownList)e.Row.FindControl("ddl_Type");
}

//-- find control in footer
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddl_Type = (DropDownList)e.Row.FindControl("ddl_Type");
}
}

Good Luck

Select top and last five record from Database

In Query try this:

FOR TOP 5
select top 5 * from table

//-------------------

FOR LAST 5
select top 5 * from table order by primarykey_columnname desc

Good Luck

Validate URL

Try this with Regular Expression Validator

^((htf)tp(s?)\:\/\/~//)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+/?)(\w+\.[\w]{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?

Good Luck

Validate Fileupload to accept JPG image

Use this with Regular Expression Validator

ValidationExpression="^(([a-zA-Z]:)(\\{2}\w+)\$?)(\\(\w[\w](.)*))+(\.jpg\.JPG)$"

or

ValidationExpression="^(([a-zA-Z]:)(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpg.JPG)$"

or

ValidationExpression="^.+\.(([jJ][pP][eE]?[gG])([gG][iI][fF]))$"

Good Luck

Preview Default image in Gridview

Try this Code:

protected void grdtest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Image imgCarPic = (Image)e.Row.FindControl("imgCarPic");
if (string.IsNullOrEmpty(imgCarPic.ImageUrl.ToString()))
{
imgCarPic.ImageUrl = "../images/NoImageSmall.jpg";
}
else
{
String strUploadedPicPath = Server.MapPath(imgCarPic.ImageUrl.ToString());
if (!System.IO.File.Exists(strUploadedPicPath))
{
imgCarPic.ImageUrl = "../images/NoImageSmall.jpg";
}
}
}
}

Good Luck

Prevent Multiple Login at the same time

Try this:
protected void Login1_LoggingIn(object sender, LoginCancelEventArgs e)
{
e.Cancel = Membership.GetUser(Login1.UserName).IsOnline;
}

or try this code

void Login1_LoggingIn(object sender, LoginCancelEventArgs e)
{
MembershipUser u = Membership.GetUser(Login1.UserName); Response.Write(u.IsOnline);
if (u.IsOnline)
{
Login1.FailureText = "A user with this username is already logged in."; e.Cancel = true;
}
else
{
Login1.FailureText = String.Empty;
e.Cancel = false;
}
}

ASP.NET Regular Expression for date format

In ASP.Net Many times required to Validate Date Fromat Enter in Control.in Regular Expression Following RE used to Validate Date Format.

dd/mm/yyyy Format (optional mm,optional dd)
([1-9]0[1-9][12][0-9]3[01])[- /.]([1-9]0[1-9]1[012])[- /.][0-9]{4}$

mm/dd/yyyy (optional mm,optional dd)
^([1-9]0[1-9]1[012])[- /.]([1-9]0[1-9][12][0-9]3[01])[- /.][0-9]{4}$

mm/dd/yyyy (Exact Format)
^([01]\d)/([0-3]\d)/(\d{4})$

Good Luck

Monday, August 11, 2008

Get DayNames in a given Culture

Sometimes we may need to have the day names in a week for a given culture. With ASP.NET CultureInfo class you can loop through the DateTimeFormat.DayNames and get them. Here is the example of it

using System.Globalization;
CultureInfo ci = new CultureInfo("ar-ae");
// gets the day names of arabic, arab emirates
foreach (string day in ci.DateTimeFormat.DayNames)
Response.Write(day + " ");

Depending on the culture you want, you can get the CultureInfo reference for that corresponding culture. The DateTimeFormat also provides other values like month names, first day of week etc.,

Good Luck

Preventing Duplicate Record Insertion on Page Refresh

I have found a good article on preventing the duplicate record insertion on page refresh by Terri Mortan.
Check the article here http://aspalliance.com/687

Friday, July 25, 2008

Create New Account Manually

Try this

protected void Create_Click(object sender, EventArgs e)
{
MembershipCreateStatus createStatus;
MembershipUser newUser = Membership.CreateUser(Username.Text, Password.Text, Email.Text, passwordQuestion, SecurityAnswer.Text, true, out createStatus);

switch (createStatus)
{
case MembershipCreateStatus.Success:
CreateAccountResults.Text = "The user account was successfully created!";
break;

case MembershipCreateStatus.DuplicateUserName:
CreateAccountResults.Text = "There already exists a user with this username.";
break;

case MembershipCreateStatus.DuplicateEmail:
CreateAccountResults.Text = "There already exists a user with this email address.";
break;

case MembershipCreateStatus.InvalidEmail:
CreateAccountResults.Text = "There email address you provided in invalid.";
break;

case MembershipCreateStatus.InvalidAnswer:
CreateAccountResults.Text = "There security answer was invalid.";
break;

case MembershipCreateStatus.InvalidPassword:
CreateAccountResults.Text = "The password you provided is invalid. It must be seven characters long and have at least one non-alphanumeric character.";
break;

default:
CreateAccountResults.Text = "There was an unknown error; the user account was NOT created.";
break;

}
}

for more info visit
http://www.asp.net/Learn/Security/tutorial-05-cs.aspx
Good Luck

Method to Get Hijri Date

Try this method:

public static string ConvertDateString(string DATE_INS, int COND)
{
string functionReturnValue = null;
int CurrentDay;
int CurrentMonth;
int CurrentYear;
System.DateTime DateFrom;
DateFrom = Strings.Trim(DATE_INS);
CurrentDay = DateFrom.Day;
CurrentMonth = DateFrom.Month;
CurrentYear = DateFrom.Year;
if (COND == 1)
{
// من هجرى الى ميلادى
System.DateTime ConversionDate = new System.DateTime(CurrentYear, CurrentMonth, CurrentDay, new HijriCalendar());
functionReturnValue = ConversionDate;
}
else if (COND == 2)
{
CultureInfo higri_format = new CultureInfo("ar-SA"); higri_format.DateTimeFormat.Calendar = new HijriCalendar();
System.DateTime CurrentDate;
if (!Information.IsDate(DATE_INS))
{
functionReturnValue = "";
return;
// TODO: might not be correct. Was : Exit Function
}
CurrentDate = Convert.ToDateTime(DATE_INS);
functionReturnValue = CurrentDate.Date.ToString("dd/MM/yyyy", higri_format);
}
return functionReturnValue;
}
Good Luck

Login Redirection

Try this:
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");
}
}
}

Good Luck

Logout

Try this code:
protected void lnkbLogout_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut(); Session.Abandon(); HttpContext.Current.Response.Redirect("Login.aspx", true);
}

//--- another way

protected void LoginStatus1_LoggedOut(object sender, EventArgs e)
{
//FormsAuthentication.SignOut();
//Roles.DeleteCookie();
//Session.Clear();
}

Make Icon of website in URL

Hi
visit these websites
http://www.html-kit.com/favicon/
http://www.alperguc.com/blog/html-tags/how-to-add-favicon-and-create-favicon-online/
http://www.tjitjing.com/blog/2006/10/how-to-create-favicon-in-visual-studio.html

Good Luck

Saturday, May 31, 2008

Send Gridview through Email

Create aspx page and put Gridview and Bind it using SqlDataSource and add button control
to send Email with Gridview

In Code behind

using System;
using System.Data;
using System.Configuration;
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;
using System.Net.Mail;
using System.Text;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
private string GridViewToHtml(GridView gv)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(sw);
gv.RenderControl(hw);
return sb.ToString();
}
private bool SendMail(string body, string subject)
{
//string mailServerName = "SMTP.ewebbers.com";
string mailServerName = "SMTP.ewebbers.com";
MailMessage message = new MailMessage("noor3rb@hotmail.com", "y.ahmed@ewebbers.com", subject, GridViewToHtml(GridView1));

message.IsBodyHtml = true;
SmtpClient mailClient = new SmtpClient();
mailClient.Host = mailServerName;
mailClient.Send(message);
message.Dispose();
return true;
}

protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
bool x = SendMail(GridViewToHtml(GridView1), "Send Gridview");
if (x == true)
{
Response.Redirect("~/MailSent.aspx");
}
else
{
Label1.Text = "Try again";
}
}
public override void VerifyRenderingInServerForm(Control control)
{
}

}

Friday, May 30, 2008

Solve Access denied to your own ASP.NET application Problem

Every have a bad day with your ASP.NET app? Ever get the yellow screen of death with this on it:
Access to the path "'c:\inetpub\wwwroot\Car_Image " is denied.
If you go googling for the problem, you'll find a few suggestions, solutions, ideas, and rants. We had the same problem happen at our shop a few times in the same week. In fact, it got to the point where we (the users in the local Administrator group) couldn't even access the folders themselves.
After putting our proverbial minds to work, we did something fairly simple. We reclaimed ownership of the folders. You can do this in the security tab of the ASP.NET Temporary files directory.
1) Right click and select "Properties"
2) Select the "Security" tab
3) Click on the "Advanced" button
4) Select the "Owner" tab
5) Select the owner (MACHINENAME\Administrators), check the "Replace owner on subcontainers and objects" and click OK

Friday, May 23, 2008

How to Refresh Page after time

In Page_Load of page write this code :

HtmlMeta RedirectMetaTag = new HtmlMeta();
RedirectMetaTag.HttpEquiv = "Refresh";
Response.AppendHeader("Refresh", "5");

Wednesday, May 21, 2008

How to Validate CheckListBox

Create Page has CheckListBox (cbx_Application) and CustomValidator and button Control

and In Event Server_Control of Custom Validator write the following Code:

protected void User_Choice(object source, ServerValidateEventArgs args)
{
int counter = 0;
for (int i = 0; i < cbx_Application.Items.Count; i++)
{
if (cbx_Application.Items[i].Selected)
{
counter++;
}
args.IsValid = (counter == 0) ? false : true;
}

Wednesday, May 14, 2008

How to save User Name and Password (Remember Me)

Use this code:

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
CheckBox cek = (CheckBox)Login1.FindControl("RememberMe");
if (Request.Cookies["username"] == null Request.Cookies["username"].Value.ToString().Trim() == "")
{
cek.Checked = false;
}
else
{

Login1.UserName = Request.Cookies["username"].Value.ToString();
}
}
}


protected void Login1_LoggingIn(object sender, LoginCancelEventArgs e)
{
CheckBox cek = (CheckBox)Login1.FindControl("RememberMe");
if (cek.Checked == true)
{
HttpCookie cookie = new HttpCookie("username");
cookie.Value = Login1.UserName;

cookie.Expires = DateTime.Now.AddDays(1);//cookie Expires
HttpContext.Current.Response.AppendCookie(cookie);
}
else {
HttpContext.Current.Response.Cookies.Remove("username");
}
cek.Checked = false;
}


//--- another way

protected void Page_Load(object sender, EventArgs e)

{

if (Request.Cookies["MyCookie"] != null)

{

TextBox pass = (TextBox)Login1.FindControl("Password"); pass.Attributes.Add("value", Request.Cookies["MyCookie"]["password"]); Login1.UserName = Request.Cookies["MyCookie"]["username"];

}

}

protected void Login1_LoggedIn(object sender, EventArgs e)

{

HttpCookie cookie1 = new HttpCookie("MyCookie");

cookie1.Values.Add("username", Login1.UserName);

cookie1.Values.Add("password", Login1.Password);

cookie1.Expires = DateTime.Now.AddDays(1);//cookie Expires HttpContext.Current.Response.AppendCookie(cookie1);

}

Sunday, May 11, 2008

Send Multiple Email at the Same time (create Newsletter)

We want to create a newsletter where user enter his full name and his email which send him email of a deaily news in website
In other word this is a way to send email to multiple user at the same time

-- First :- create database called (Database) has table named (Person_Data) has the following fields:
Id --> (int , Primary key , Identity)
FullName --> nnarchar(50)
Email --> nnarchar(50)

-- Second :- craete website has the following pages
1) AddPerson.aspx
2) DataSaved.aspx
3) SendEmail.aspx
4) EmailSend.aspx

--**AddPerson.aspx :-
add two Textbox (txt_Full , txt_Email) and two RequiredFieldValidator control and button (Save)

--** AddPerson.aspx.cs
using System;
using System.Data;
using System.Configuration;
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;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
public int add_Person(string Name, string Email)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data_ConnectionString"].ConnectionString);
string quey = "INSERT INTO [Person_Data] ([FullName], [Email]) VALUES (@FullName, @Email)";
SqlCommand comm = new SqlCommand();
comm.CommandText = quey;
comm.CommandType = CommandType.Text;
comm.Connection = conn;
comm.Parameters.Add("@FullName",SqlDbType.NVarChar,50).Value=Name;
comm.Parameters.Add("@Email", SqlDbType.NVarChar, 50).Value = Email;
conn.Open();
int x = comm.ExecuteNonQuery();
conn.Close();
return x;
}

protected void Page_Load(object sender, EventArgs e)
{
}

protected void Button1_Click(object sender, EventArgs e)
{
int y = add_Person(txt_Full.Text, txt_Email.Text);
if (y > 0)
{
Response.Redirect("~/DataSaved.aspx");
}
else
{
ClientScript.RegisterStartupScript(Type.GetType("System.String"), "messagebox", "");
}
}
}

--** SendEmail.aspx
add Gridview and SQLDataSource control to select all data in Gridview1

--** SendEmail.aspx.cs

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;
using System.Data.SqlClient;
using System.Web.Mail;

public partial class SendEmail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}

//-- send Email button
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data_ConnectionString"].ConnectionString);
string query = "SELECT Email FROM [Person_Data]";
SqlCommand comm = new SqlCommand();
comm.CommandText = query;
comm.Connection = conn;
comm.CommandType = CommandType.Text;
SqlDataReader dr;
//--- Send Email ----
string Email = "yasser021@gmail.com";
string EmailPassword = "XXXXX";
string subject = "NewsLetter";
string body = "You are applied in newsletter";
//----
try
{
conn.Open();
dr = comm.ExecuteReader(CommandBehavior.CloseConnection);
string To="";
while (dr.Read())
{
To = dr["Email"].ToString();
//--
bool s = MailSender.SendEmail(Email, EmailPassword, To, subject, body, MailFormat.Html, "");
//if (s == true)
//{
// Response.Redirect("~/EmailSend.aspx");
//}
//else
//{
// ClientScript.RegisterStartupScript(Type.GetType("System.String"), "messagebox", "");
//}
}
dr.Close();
}
catch (Exception ex)
{
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
}

Don't forget i create a class called MailSender.cs
that used to send Email

Copyright Method

Create Website and add Default.aspx page and in it add lable (lblCopyright)

and in Default.aspx.cs

public string DynamicCopyright(string YearSiteCreated)
{
string DynamicCopyrightYear;
//Is the current year equal to the year the site was created?
if (DateTime.Now.Year.ToString() != YearSiteCreated)
{
//If not then concatenate year created and current year
DynamicCopyrightYear = YearSiteCreated + "-" + DateTime.Now.Year.ToString();
}
else
{
DynamicCopyrightYear = YearSiteCreated;
}
string Copyright = "Copyright © " + DynamicCopyrightYear + ". All rights reserved.";
return Copyright;
}

protected void Page_Load(object sender, System.EventArgs e)
{
lblCopyright.Text = DynamicCopyright(2006);
//Use the created year as parameter
}

Prevent Copy from Textbox to another

create a website and add Default.aspx page and in it add two Textbox
now we want to prevent copy from Textbox1 to Textbox2

First thing use this Javascript code:

function noCopyMouse(e)
{
var isRight = (e.button) ? (e.button == 2) : (e.which == 3);
if(isRight)
{
alert('You are prompted to type this twice for a reason!');
return false;
} return true;
}
function noCopyKey(e)
{
var forbiddenKeys = new Array('c','x','v');
var keyCode = (e.keyCode) ? e.keyCode : e.which;
var isCtrl;
if(window.event)
isCtrl = e.ctrlKey
else
isCtrl = (window.Event) ? ((e.modifiers & Event.CTRL_MASK) == Event.CTRL_MASK) : false;
if(isCtrl)
{
for(i = 0; i < forbiddenKeys.length; i++)
{
if(forbiddenKeys[i] == String.fromCharCode(keyCode).toLowerCase())
{
alert('You are prompted to type this twice for a reason!');
return false;
}
}
}
return true;
}

and in Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Textbox1.Attributes.Add("onmousedown", "return noCopyMouse(event);") Textbox1.Attributes.Add("onkeydown", "return noCopyKey(event);")
}
}

Prevent Right Click on my WebSitePage

Using this Javascript code :-

document.onmousedown=disableclick;status="Right Click Disabled";
Function disableclick(e)
{
if(event.button==2)
{
alert(status);
return false;
}
}

and to use it in page between body tag we write :
oncontextmenu="return false"

SQL Server 2005 Express Data Transfer

Since there is no mechanism to transfer data from one DB to another in Free SQL Server 2005 Management Studio Express I thought to write a simple utility to do this.

It’s so simple that you can use with only MS Sql Server and transfer data from one table at a time.

The utility is using ADO.Net SqlBulkCopy class to achieve the functionality.

Steps to transfer the data from one DB to another

1) Enter DB connection information of both Source DB and Destination DB.
2) Click Connect
If there is no error in the connection details it will establish connections to both server and list all the tables in both Db in bottom combo boxes.
3) Choose the source table from left side combo box and designation table from right side combo box.
4) Click Transfer.


Notes :-
1) Work only with Sql server.
2) Tested only in Sql server 2005.
3) Both source table and destination table should be similar.

Friday, April 25, 2008

Export Gridview to Word file

create new website and add Default page and in it add Gridview and button control
We will use Northwind database


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;
using System.Data.SqlClient;

public partial class ExportToWord : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = BindData();
GridView1.DataBind();
}
}

private string ConnectionString
{

get { return @"Data Source=YASER\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True"; }

}



private DataSet BindData()
{
// make the query
string query = "SELECT * FROM Categories";
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "Categories");
return ds;

}

protected void Button1_Click(object sender, EventArgs e)
{

Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.word";

System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();

}

public override void VerifyRenderingInServerForm(Control control)
{

}


}

Export Gridview to Exel file

create new website and add Default page and in it add Gridview and button

In Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
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;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = BindData();
GridView1.DataBind();
}
}

private string ConnectionString
{

get { return @"Data Source=YASER\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True"; }

}

private DataSet BindData()
{
// make the query
string query = "SELECT * FROM Products";
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "Products");
return ds;

}

protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();

Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");

Response.Charset = "";

// If you want the option to open the Excel file without saving than

// comment out the line below

// Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.ContentType = "application/vnd.xls";

System.IO.StringWriter stringWrite = new System.IO.StringWriter();

System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);

GridView1.RenderControl(htmlWrite);

Response.Write(stringWrite.ToString());

Response.End();

}

public override void VerifyRenderingInServerForm(Control control)
{

// Confirms that an HtmlForm control is rendered for the
//specified ASP.NET server control at run time.

}
}

Get List and Number of Online users

First create website and add Registe , Login and WhoIsOnline page in website

In OnlineUser page add lable (lblSessionCount) and Gridview (OnlineUserList) control which is bound to
(UserName (BoundField), IsOnline (CheckBoxField) , Email (BoundField) )


Im WhoIsOnLine.aspx.cs page add

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 WhoIsOnLine : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//if (!IsPostBack)
//{
MembershipUserCollection OnlineUsers = new MembershipUserCollection();
MembershipUserCollection AllUsers = new MembershipUserCollection();
AllUsers = Membership.GetAllUsers();

foreach (MembershipUser user in AllUsers)
{
if (user.IsOnline)
{
OnlineUsers.Add(user);

}
}
int OnlineUserCount = OnlineUsers.Count;

lblSessionCount.Text = OnlineUserCount.ToString();
OnlineUserList.DataSource = OnlineUsers;
OnlineUserList.DataBind();
//}
}
}

Send Email (using System.Web.Mail)

First create new website project and add two pages :-
SendEmail.aspx and EmailSent.aspx

and in the page SendEmail.aspx add three TextBox (txtFrom , txtSubject , txtMessage)
and add button (btn_Send) and Lable control
and Required Validator for txtFrom , txtSubject


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;
using System.Web.Mail;

public partial class SendEmail : System.Web.UI.Page
{
string strMailOrTel;

protected void Page_Load(object sender, EventArgs e)
{

}
private bool SendMail()
{
try
{
string strTo = "y.ahmed@ewebbers.com";
string strFrom = txtFrom.Text;
string strBody = txtMessage.Text ;
string strSubject = txtSubject.Text ;
SmtpMail.SmtpServer = ("SMTP.ewebbers.com");
SmtpMail.Send(strFrom, strTo, strSubject, strBody);

return true;
}
catch (Exception ex)
{
return false;
}
}

protected void btn_Send_Click(object sender, EventArgs e)
{
bool TrueOrFalse = SendMail();
if ((TrueOrFalse == true))
{
Response.Redirect("~/MailSent.aspx");
}
else
{
Label1.Text = "Try again";
}

}


}

Send Email with attachment (using System.Web.Mail)

First create new website project and add two pages :-
SendEmail.aspx and EmailSent.aspx

and in the page SendEmail.aspx add three TextBox (txtFrom , txtSubject , txtMessage)
and add button (btn_Send) and Lable control
and Required Validator for txtFrom , txtSubject and Fileupload control


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;
using System.Web.Mail;
using System.IO;


public partial class SendEmail : System.Web.UI.Page
{
string strPath;

protected void Page_Load(object sender, EventArgs e)
{

}

private bool SendMail()
{
try
{

/* Create a new blank MailMessage */
MailMessage mailMessage = new MailMessage();

mailMessage.From = txtTo.Text;

mailMessage.To = "y.ahmed@ewebbers.com";

mailMessage.Subject = txtSubject.Text ;

msgMail.Body = txtMessage.Text ;

/* We use the following variables to keep track of
attachments and after we can delete them */

string attach1 = null;

/*strFileName has a attachment file name for attachment process. */

string strFileName = null;

if (FileUpload1.PostedFile != null)
{
/* Get a reference to PostedFile object */
HttpPostedFile attFile = FileUpload1.PostedFile;

/* Get size of the file */
int attachFileLength = attFile.ContentLength;

/* Make sure the size of the file is > 0 */
if (attachFileLength > 0)
{
/* Get the file name */
strFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);

/* Save the file on the server */
FileUpload1.PostedFile.SaveAs(Server.MapPath(strFileName));

/* Create the email attachment with the uploaded file */
MailAttachment attach = new MailAttachment(Server.MapPath(strFileName));

/* Attach the newly created email attachment */
mailMessage.Attachments.Add(attach);

/* Store the attach filename so we can delete it later */
attach1 = strFileName;
}

/* Set the SMTP server and send the email with attachment */
SmtpMail.SmtpServer = ("SMTP.ewebbers.com");

SmtpMail.Send(mailMessage);

/* Delete the attachements if any */
if (attach1 != null)
{
File.Delete(Server.MapPath(attach1));
}
}

return true;
}
catch (Exception ex)
{
return false;
}
}

protected void btn_Send_Click(object sender, EventArgs e)
{
bool TrueOrFalse = SendMail();

if ((TrueOrFalse == true))
{
Response.Redirect("~/MailSent.aspx");
}
else
{
Label1.Text = "Try again";
}
}
}

Monday, April 14, 2008

Highlight Gridview Row when checbox is checked

First thing create Database (Company) with Table (Employee)
which has fields (Id,Name)

Second enter data in Database

Now create new website


In Default.aspx add Gridview and in Gridview add Template field
and in ItemTemplate add checkbox(cbxId)

and in Default.aspx.cs

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;
using System.Text;

public partial class SelectGridview : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

//-- for Highlight
if ((e.Row.RowType == DataControlRowType.DataRow))
{
StringBuilder script = new StringBuilder();
script.Append("if (this.checked) {");
script.Append("document.getElementById('");
script.Append(e.Row.ClientID);
script.Append("').style.backgroundColor='Blue';");
script.Append("} else {");
script.Append("document.getElementById('");
script.Append(e.Row.ClientID);
script.Append("').style.backgroundColor='';");
script.Append("}");
((CheckBox)e.Row.FindControl("cbxId")).Attributes.Add("onclick", script.ToString());

}

}
}

Send Email Using (System.Net.Mail)

First create new website project and add two pages :-
SendEmail.aspx and EmailSent.aspx

and in the page SendEmail.aspx add three TextBox (txtFrom , txtSubject , txtMessage)
and add button (Send) and Lable control
and Required Validator for txtFrom , txtSubject and also add CustomValidator control for txtMessage as we want the characters in txtMessage not more than 50 characters



In SendEmail.aspx.cs

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;
using System.Net.Mail;

public partial class Default2 : System.Web.UI.Page
{
private bool SendMail(string from, string body,string subject)
{
//string mailServerName = "SMTP.ewebbers.com";
string mailServerName = "SMTP.ewebbers.com";
MailMessage message = new MailMessage(from, "y.ahmed@ewebbers.com",subject, body);
SmtpClient mailClient = new SmtpClient();
mailClient.Host = mailServerName;
mailClient.Send(message);
message.Dispose();

return true;
}

protected void Page_Load(object sender, EventArgs e)
{

}

protected void btn_Send_Click(object sender, EventArgs e)
{
bool x=SendMail(txtFrom.Text, txtMessage.Text,txtSubject.Text);
if (x == true)
{
Response.Redirect("~/MailSent.aspx");
}
else
{
Label1.Text = "Try again";
}
}

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
if (txtMessage.Text.Length > 50)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}

}
}


Note:- we can use javascript with CustomValidator to ensure that user not enter more than 50 characters in txtMessage
so we will add Javascript code in SendEmail.aspx page

// function ValidateComments(sender, args)
// {
// if (args.Value.length > 50)
// args.IsValid = false;
// else
// args.IsValid = true;
// }


and in property of CustomValidator control set ClientValidationFunction="ValidateComments"

Friday, April 4, 2008

Delete Checked in Gridview

First thing create Database (Company) with Table (Employee)
which has fields (Id,Name)

Second enter data in Database

Now create new website

in Default.aspx

write the following javascript code

//function SelectAll(id)
// {
// var frm = document.forms[0];
//
// for (i=0;i < frm.elements.length;i++)
// {
// if (frm.elements[i].type == "checkbox")
// {
// frm.elements[i].checked = document.getElementById(id).checked;
//
// }
// }
//
// }

and add Gridview and button (Delete)and lable (lblMsg)
and in Gridview add Template field and In HeaderTemplate add checkbox (cbxAll) and in ItemTemplate checkbox (cbxId)

and in Default.aspx.cs

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.Header))
{
//adding an attribut for onclick event on the check box in the hearder and passing the ClientID of the Select All checkbox
((CheckBox)e.Row.FindControl("cbxAll")).Attributes.Add("onclick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("cbxAll")).ClientID + "')");
}
}

protected void btn_Delete_Click(object sender, EventArgs e)
{
try
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkbox = (CheckBox)row.FindControl("cbxId");

if (checkbox.Checked == true)
{
// method to delete by Id

lblMsg.Text = "Selected deleted";
GridView1.DataBind();


}

}
}
catch (Exception ex)
{
lblMsg.Text = ex.Message.ToString();
}
}

Monday, March 31, 2008

Move Item from Listbox to another using Javascript

Create new Website and in Default.aspx add two Listbox (ListBox1 , ListBox2) and add items in Listbox1 and add two buttons (<< ,>>) with Id's
(btnMoveLeft,btnMoveRight)

The Javascript code will be:

//function fnMoveItems(lstbxFrom,lstbxTo)
//{
// var varFromBox = document.all(lstbxFrom);
// var varToBox = document.all(lstbxTo);
// if ((varFromBox != null) && (varToBox != null))
// {
// if(varFromBox.length < 1)
// {
// alert('There are no items in the source ListBox');
// return false;
// }
// if(varFromBox.options.selectedIndex == -1)
// when no Item is selected the index will be -1
// {
// alert('Please select an Item to move');
// return false;
// }
// while ( varFromBox.options.selectedIndex >= 0 )
// {
// Create a new instance of ListItem
// var newOption = new Option();
// newOption.text = varFromBox.options[varFromBox.options.selectedIndex].text;
// newOption.value = varFromBox.options[varFromBox.options.selectedIndex].value;
//Append the item in Target Listbox
// varToBox.options[varToBox.length] = newOption;
//Remove the item from Source Listbox
// varFromBox.remove(varFromBox.options.selectedIndex);
// }
// }
// return false;
//}


and in Default.aspx.cs

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 Default3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
btnMoveRight.Attributes.Add("onclick", "return fnMoveItems('ListBox1','ListBox2')");
btnMoveLeft.Attributes.Add("onclick", "return fnMoveItems('ListBox2','ListBox1')");

}


}

Move item from Listbox to another (2)

Create new Website and in Default.aspx add two Listbox (lstEmployees , lstSelectedEmployees) and in lstEmployees Listbox add items and add four buttons (<< ,>>,<,>) with Id's
(btn_AddAll,btn_RemoveAll,btn_Add,btn_Remove)

and in Default.aspx.cs

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 Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void btn_Add_Click(object sender, EventArgs e)
{
if (lstEmployees.SelectedIndex > -1)
{
//Gets the value of items in list.

string _value = lstEmployees.SelectedItem.Value;
// Gets the Text of items in the list.
string _text = lstEmployees.SelectedItem.Text;
//create a list item
ListItem item = new ListItem();
//Assign the values to list item
item.Text = _text;
item.Value = _value;
//Add the list item to the selected list of employees

lstSelectedEmployees.Items.Add(item);
//Remove the details from employee list

lstEmployees.Items.Remove(item);

}
}

protected void btn_Remove_Click(object sender, EventArgs e)
{
if (lstSelectedEmployees.SelectedIndex > -1)
{
//Gets the value of items in list.
string _value = lstSelectedEmployees.SelectedItem.Value;
//Gets the Text of items in the list.
string _text = lstSelectedEmployees.SelectedItem.Text;
//create a list item
ListItem item = new ListItem();
item.Text = _text;
//Assign the values to list item
item.Value = _value;
//Remove from the selected list
lstSelectedEmployees.Items.Remove(item);
//Add in the Employee list
lstEmployees.Items.Add(item);
}

}

protected void btn_AddAll_Click(object sender, EventArgs e)
{
int _count = lstEmployees.Items.Count;
if (_count != 0)
{
for (int i = 0; i < _count; i++)
{
ListItem item = new ListItem();
item.Text = lstEmployees.Items[i].Text;
item.Value = lstEmployees.Items[i].Value;
//Add the item to selected employee list
lstSelectedEmployees.Items.Add(item);
}

}

//clear employee list
lstEmployees.Items.Clear();


}

protected void btn_RemoveAll_Click(object sender, EventArgs e)
{
int _count = lstSelectedEmployees.Items.Count;
if (_count != 0)
{
for (int i = 0; i < _count; i++)
{
ListItem item = new ListItem();
item.Text = lstSelectedEmployees.Items[i].Text;
item.Value = lstSelectedEmployees.Items[i].Value;
lstEmployees.Items.Add(item);
}
}
//clear the items
lstSelectedEmployees.Items.Clear();
}
}

Moving Item from listbox to another (1)

Create new Website and in Default.aspx add two Listbox (lstEmployees , lstSelectedEmployees) and add six buttons (<< ,>>,<,>,^,v) with Id's
(btnremoveall,btnaddall,btnremoveitem,btnadditem,btnColmoveup,btnColmovedown)

and in Default.aspx.cs

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 _Default : System.Web.UI.Page
{
#region Methods
private void MoveUp(ListBox lstBox)
{
int iIndex, iCount, iOffset, iInsertAt, iIndexSelectedMarker = -1;
string lItemData, lItemval;
try
{

// Get the count of items in the list control
iCount = lstBox.Items.Count;

// Set the base loop index and the increment/decrement value based on the direction the item are being moved (up or down).
iIndex = 0;
iOffset = -1;

// Loop through all of the items in the list.
while (iIndex < iCount)
{
// Check if this item is selected.
if (lstBox.SelectedIndex > 0)
{
// Get the item data for this item
lItemval = lstBox.SelectedItem.Value.ToString();
lItemData = lstBox.SelectedItem.Text.ToString();
iIndexSelectedMarker = lstBox.SelectedIndex;

// Don't move selected items past other selected items
if (-1 != iIndexSelectedMarker)
{
for (int iIndex2 = 0; iIndex2 < iCount; ++iIndex2)
{
// Find the index of this item in enabled list
if (lItemval == lstBox.Items[iIndex2].Value.ToString())
{
// Remove the item from its current position
lstBox.Items.RemoveAt(iIndex2);

// Reinsert the item in the array one space higher than its previous position
iInsertAt = (iIndex2 + iOffset) < 0 ? 0 : iIndex2 + iOffset;
ListItem li = new ListItem(lItemData, lItemval);
lstBox.Items.Insert(iInsertAt, li);
break;
}
}
}
}
// If this item wasn't selected save the index so we can check it later so we don't move past the any selected items.
else if (-1 == iIndexSelectedMarker)
{
iIndexSelectedMarker = iIndex;
break;

}

iIndex = iIndex + 1;
}

if (iIndexSelectedMarker == 0)
lstBox.SelectedIndex = iIndexSelectedMarker;
else
lstBox.SelectedIndex = iIndexSelectedMarker - 1;
}
catch (Exception expException)
{
Response.Write(expException.Message);
}

}

private void MoveDown(ListBox lstBox)
{
try
{
int iIndex, iCount, iOffset, iInsertAt, iIndexSelectedMarker = -1;
string lItemData;
string lItemval;


// Get the count of items in the list control
iCount = lstBox.Items.Count;

// Set the base loop index and the increment/decrement value based on the direction the item are being moved (up or down).
iIndex = iCount - 1;
iOffset = 1;

// Loop through all of the items in the list.
while (iIndex >= 0)
{
// Check if this item is selected.
if (lstBox.SelectedIndex >= 0)
{
// Get the item data for this item
lItemData = lstBox.SelectedItem.Text.ToString();
lItemval = lstBox.SelectedItem.Value.ToString();
iIndexSelectedMarker = lstBox.SelectedIndex;

// Don't move selected items past other selected items
if (-1 != iIndexSelectedMarker)
{
for (int iIndex2 = 0; iIndex2 < iCount - 1; ++iIndex2)
{
// Find the index of this item in enabled list
if (lItemval == lstBox.Items[iIndex2].Value.ToString())
{
// Remove the item from its current position

lstBox.Items.RemoveAt(iIndex2);

// Reinsert the item in the array one space higher than its previous position
iInsertAt = (iIndex2 + iOffset) < 0 ? 0 : iIndex2 + iOffset;
ListItem li = new ListItem(lItemData, lItemval);
lstBox.Items.Insert(iInsertAt, li);
break;

}
}
}
}
iIndex = iIndex - 1;
}
if (iIndexSelectedMarker == lstBox.Items.Count - 1)
lstBox.SelectedIndex = iIndexSelectedMarker;
else
lstBox.SelectedIndex = iIndexSelectedMarker + 1;
}
catch (Exception expException)
{
Response.Write(expException.Message);
}
}

private void AddRemoveAll(ListBox aSource, ListBox aTarget)
{

try
{

foreach (ListItem item in aSource.Items)
{
aTarget.Items.Add(item);
}
aSource.Items.Clear();

}
catch (Exception expException)
{
Response.Write(expException.Message);
}

}

private void AddRemoveItem(ListBox aSource, ListBox aTarget)
{

ListItemCollection licCollection;

try
{

licCollection = new ListItemCollection();
for (int intCount = 0; intCount < aSource.Items.Count; intCount++)
{
if (aSource.Items[intCount].Selected == true)
licCollection.Add(aSource.Items[intCount]);
}

for (int intCount = 0; intCount < licCollection.Count; intCount++)
{
aSource.Items.Remove(licCollection[intCount]);
aTarget.Items.Add(licCollection[intCount]);
}

}
catch (Exception expException)
{
Response.Write(expException.Message);
}
finally
{
licCollection = null;
}

}
#endregion

protected void Page_Load(object sender, EventArgs e)
{

}

protected void btnaddall_Click(object sender, EventArgs e)
{
AddRemoveAll(lstEmployees, lstSelectedEmployees);
}

protected void btnadditem_Click(object sender, EventArgs e)
{
AddRemoveItem(lstEmployees, lstSelectedEmployees);
}

protected void btnremoveitem_Click(object sender, EventArgs e)
{
AddRemoveItem(lstSelectedEmployees, lstEmployees);
}

protected void btnremoveall_Click(object sender, EventArgs e)
{
AddRemoveAll(lstSelectedEmployees, lstEmployees);
}

protected void btnColmoveup_Click(object sender, EventArgs e)
{
MoveUp(lstSelectedEmployees);
}

protected void btnColmovedwn_Click(object sender, EventArgs e)
{
MoveDown(lstSelectedEmployees);
}
}

Copyright Method

Create new web project and in Default.asp add lable (Id=lblCopyright)

and in Default.aspx.cs

public string DynamicCopyright(string YearSiteCreated)
{
string DynamicCopyrightYear;
//Is the current year equal to the year the site was created?
if (DateTime.Now.Year.ToString() != YearSiteCreated)
{
//If not then concatenate year created and current year
DynamicCopyrightYear = YearSiteCreated + "-" + DateTime.Now.Year.ToString();
}
else
{
DynamicCopyrightYear = YearSiteCreated;
}

string Copyright = "Copyright © " + DynamicCopyrightYear + ". All rights reserved.";
return Copyright;
}

protected void Page_Load(object sender, System.EventArgs e)
{
lblCopyright.Text = DynamicCopyright(2006);
//Use the created year as parameter
}

Method to Encrypt and Decrypt

Create new Project and in add new class in App_Code name it Encryption

using System;
using System.Data;
using System.Configuration;
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;
using System.Security.Cryptography;
using System.Xml;
using System.Text;
using System.IO;


public class Encryption
{
public string Decrypt(string stringToDecrypt)
{
stringToDecrypt = stringToDecrypt.Replace(" ", "+");
string sEncryptionKey = "01234567890123456789";
byte[] key = { };
byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 };
byte[] inputByteArray = new byte[stringToDecrypt.Length];
try
{
key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(stringToDecrypt);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
Encoding encoding = Encoding.UTF8;
return encoding.GetString(ms.ToArray());
}
catch (System.Exception ex)
{
return (string.Empty);
}
}


public string Encrypt(string stringToEncrypt)
{
string sEncryptionKey = "01234567890123456789";
byte[] key = { };
byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 };
byte[] inputByteArray; //Convert.ToByte(stringToEncrypt.Length)

try
{
key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch
{
return (string.Empty);
}
}

}

Friday, March 28, 2008

How to move item from ListBox to another

Create new page and add two ListBox (lstEmployees ,lstSelectedEmployees) and in lstEmployees ListBox add items and the other one don't
also add four buttons (btn_Add , btn_Remove ,btn_AddAll ,btn_RemoveAll)

In Default.aspx.cs

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 Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void btn_Add_Click(object sender, EventArgs e)
{
if (lstEmployees.SelectedIndex > -1)
{
string _value = lstEmployees.SelectedItem.Value; //Gets the value of items in list.
string _text = lstEmployees.SelectedItem.Text; // Gets the Text of items in the list.
ListItem item = new ListItem(); //create a list item
item.Text = _text; //Assign the values to list item
item.Value = _value;
lstSelectedEmployees.Items.Add(item); //Add the list item to the selected list of employees
lstEmployees.Items.Remove(item); //Remove the details from employee list


}
}

protected void btn_Remove_Click(object sender, EventArgs e)
{
if (lstSelectedEmployees.SelectedIndex > -1)
{
string _value = lstSelectedEmployees.SelectedItem.Value; //Gets the value of items in list.
string _text = lstSelectedEmployees.SelectedItem.Text; // Gets the Text of items in the list.
ListItem item = new ListItem(); //create a list item
item.Text = _text; //Assign the values to list item
item.Value = _value;
lstSelectedEmployees.Items.Remove(item); //Remove from the selected list
lstEmployees.Items.Add(item); //Add in the Employee list

}

}

protected void btn_AddAll_Click(object sender, EventArgs e)
{
int _count = lstEmployees.Items.Count;
if (_count != 0)
{
for (int i = 0; i < _count; i++)
{
ListItem item = new ListItem();
item.Text = lstEmployees.Items[i].Text;
item.Value = lstEmployees.Items[i].Value;
//Add the item to selected employee list
lstSelectedEmployees.Items.Add(item);
}

}

//clear employee list
lstEmployees.Items.Clear();


}

protected void btn_RemoveAll_Click(object sender, EventArgs e)
{
int _count = lstSelectedEmployees.Items.Count;
if (_count != 0)
{
for (int i = 0; i < _count; i++)
{
ListItem item = new ListItem();
item.Text = lstSelectedEmployees.Items[i].Text;
item.Value = lstSelectedEmployees.Items[i].Value;
lstEmployees.Items.Add(item);
}
}

lstSelectedEmployees.Items.Clear();//clear the items
}
}

Question for Dot Net Interview (Part 7):

--* What is Data Binding?
Data binding is a way used to connect values from a collection of data (e.g. DataSet) to the controls on a web form.

--* Describe the difference between inline and code behind.
1)Inline code is written along side the HTML in a page.
2)Code-behind is code written in a separate file and referenced by the .aspx page


--* What is the transport protocol you use to call a Web service?
SOAP (Simple Object Access Protocol) is the preferred protocol.

--* What is database replicaion
Replication is the process of copying/moving data between databases on the same or different servers

--* What are the different types of replication?
1) Transactional
2) Snapshot
3) Merge


--* What is the difference among “dropping a table”, “truncating a table” and “deleting all records” from a table.

* Dropping : (Table structure + Data are deleted), Invalidates the dependent objects ,Drops the indexes
* Truncating: (Data alone deleted), Performs an automatic commit, Faster than delete
* Delete : (Data alone deleted), Doesn’t perform automatic commit


--* BulkCopy is a tool used to copy huge amount of data from tables

--* Types of Trigger:
Inserted and Deleted.


--* What is SQL Profiler?
SQL Profiler is a graphical tool that allows system administrators to monitor events in an instance of Microsoft SQL Server


--* What is User Defined Functions?
User-Defined Functions allow to define its own T-SQL functions that can accept 0 or more parameters
and return a single scalar data value or a table data type

Question for Dot Net Interview (Part 6):

--* What is the difference between Dataset.clone() and Dataset.copy()?
1) Dataset.clone() --> Copy only structure (Returns a DataSet with the same structure (tables andrelationships) but no data.)
2) Dataset.copy() --> Copy Structure & Data Both (Returns an exact duplicate of the DataSet, with the same set of tables, relationships, and data.)

--* What is the difference between autopostback and ispostback?
1) Autopostback - Property of the control
2) IsPostback - Property of the Page class

--* What is the difference between ExcuteQuery and ExcuteNonQuery ?
1) ExcuteQuery used with select statement
2) ExcuteNonQuery used with insert ,update ,delete statement
3) ExcuteNonQuery return number of row affected
4) ExcuteQuery return one or more row of data

--* What is Tracing :
Trace in ASP.Net is nothing but to trace error and It will also give some details of the error, so that the user can easily debug the code.

--* Types of Tracing :
1) Application Level Tracing
2) Page Level Tracing

--* Different types of style sheets:
1) External
2) Inline

--* Viewstate : stores the state of controls in HTML hidden fields.

--* Can we run asp.net apllication without WEB.CONFIG file?
YES , Because all the configuration settings will be available under MACHINE.CONFIG file

--* Session state is global to your entire application for the current user. Session state can be lost in several ways:
1) If the user closes and restarts the browser.
2) If the user accesses the same page through a different browser window, although the session will still exist if a web page is accessed through the original browser window. Browsers differ on how they handle this situation.
3) If the session times out because of inactivity. By default, a session times out after 20 idle minutes.
4) If the programmer ends the session by calling Session.Abandon().

--* A transactionis:- a set of operations that must either succeed or fail as a unit. The goal of a transaction is to ensure that data is always in a valid

--* Types of Data Source in the.NET Framework:
1) SqlDataSource: This data source allows you to connect to any data source that has an ADO.NET data provider
2) ObjectDataSource: This data source allows you to connect to a custom data access class
3) XmlDataSource : This data source allows you to connect to an XML file
4) SiteMapDataSource: This data source allows you to connect to the Web.Sitemap file that describes the navigational structure of your website

--* Types of ADO.Net Data Provider:
1) System.Data.SqlClient
2) System.Data.OracleClient
3) System.Data.OleDb
4) System.Data.Odbc

--* What are types of sub queries :
1) Single row subquery
2) Multiple row subquery
3) Multiple column subquery

--* What command do we use to rename a Database sp_renamedb ‘oldname’ , ‘newname’

--* What is the command that we use to install IIS after you installed ASP.NET aspnet_regsql -i

--* What is the purpose of @@Identety:
Returns the last identity value inserted as a result of the last INSERT or SELECT INTO statement.

--* Describe the difference between inline code and code behind.
1) Inline code written along side the html in a page.
2) Code-behind is code written in seprate file and refrenced by .aspx in page.

--* What is the difference between System.Array.CopyTo and System.Array.Clone in .NET?
1) The Clone() method returns a new array object containing all the elements in the original array.
2) The CopyTo() method copies the elements into another existing array.

--* What is Encapsulation?
Encapsulation - is the ability of an object to hide its data and methods from the rest of the world. It is one of the fundamental principles of OOPs

--* Who is a protected class-level variable available to?
It is available to any sub-class (a class inheriting this class).

--* Describe the accessibility modifier “protected internal”.
It is available to classes that are within the same assembly and derived from the specified base class

--* What’s the difference between the Debug class and Trace class?
1) Use Debug class for debug builds,
2) use Trace class for both debug and release builds

--* Explain the differences between public, protected, private and internal.
1) Public: Allows class, methods, fields to be accessible from anywhere i.e. within and outside an assembly.
2) Private: When applied to field and method allows to be accessible within a class.3) Protected: Similar to private but can be accessed by members of derived class also.
4) Internal: They are public within the assembly i.e. they can be accessed by anyone within an assembly but outside assembly they are not visible.

--* List the event handlers that can be included in Global.asax?
1) Application start and end event handlers
2) Session start and end event handlers
3) Per-request event handlers
4) Non-deterministic event handlers

--* What’s a strong name?
A strong name includes: the name of the assembly, version number, culture identity, and a public key token.

--* What is constructor.
Constructor is a method in the class which has the same name as the class It initialises the member attributes whenever an instance of the class is created.

--* What is difference between CHAR and VARCHAR:
1) CHAR pads blank spaces to the maximum length.
2) VARCHAR2 does not pad blank spaces.
3) For CHAR the maximum length is 255 and 2000 for VARCHAR

--* What are the four types of events ?
1. System Events.
2. Control Events
3. User Events
4. Other Events

--* How many Global.asax files can an Application have?
Only one Global.asax file and it’s placed in the virtual directory’s root

--* What is a session?
A user accessing an application is known as a session.

--* Different between Local and Global Variable:
1) A variable is global if it is declared outside of the main program block and not within a function
2) A variable is local if it is declared between the function declaration
3) Global variables are visible and available to all statements in a setup script that follow its declaration
4) Local variables are visible and available only within the function where they are declared.

--* Difference Between EXE and DLL file :
1) Exe is the Application
2) DLL is the Component
3) Exe can execute on its own
4) DLL Can not execute on its own
5) EXE can run independently
6) DLL will run within an Exe
7) EXE is an out-process file
8) DLL is an in-process file

--* Difference between Strong and Weak type
1) Strong type: Checking the types of variables at compile time
2) Weak type: Checking the types of variables at run time.

--* Difference between Function and Stored Procedure:
1) Function returns only one Value
2) Stored Procedure can return many value or not return
3) Functions Must return a value, procedures doesn't need to
4) Functions can be used within a Stored Procedure but stored procedures cannot be used within a function

--* How to kill session?
use session.abandont method

--* What are the different types of cookies
1) Persistent Cookies.
2) Non Persistent CookiesPersistent cookies are those which is storing in cookies folder in hard disk.Non persistent cookies is created on memory, inside the browser process. When we close the browser, that memory region will collect by Operating system, and the cookie will also deleted.

--* Write the HTML for a hyperlink that will send mail when the user clicks the link.
Send mail

Monday, January 21, 2008

Send Email using ASP.Net














Create a web page

and in Default.aspx.cs add the following code:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Mail;
namespace Email
{
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label lblFrom;
protected System.Web.UI.WebControls.Label lblCC;
protected System.Web.UI.WebControls.TextBox txtFrom;
protected System.Web.UI.WebControls.TextBox txtCC;
protected System.Web.UI.WebControls.TextBox txtTo;
protected System.Web.UI.WebControls.Label lblTo;
protected System.Web.UI.WebControls.Label lblEmailService;
protected System.Web.UI.WebControls.TextBox txtBCC;
protected System.Web.UI.WebControls.Label lblBCC;
protected System.Web.UI.WebControls.Label lblSubject;
protected System.Web.UI.WebControls.TextBox txtSubject;
protected System.Web.UI.WebControls.Label lblMessage;
protected System.Web.UI.WebControls.TextBox txtMessage;
protected System.Web.UI.WebControls.Button btnSend;
protected System.Web.UI.HtmlControls.HtmlInputFile FileBrowse;
protected System.Web.UI.WebControls.Label lblAttachment;
protected System.Web.UI.WebControls.RadioButton rbtnAttach;
protected System.Web.UI.WebControls.RadioButton rbtnDetachment;
protected System.Web.UI.WebControls.Button btnCancel;
public string strAttachment;

private void Page_Load(object sender, System.EventArgs e)
{
lblMessage.Text="";
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent()
{
this.rbtnDetachment.CheckedChanged +=
new System.EventHandler(this.rbtnDetachment_CheckedChanged);
this.btnCancel.Click +=
new System.EventHandler(this.btnCancel_Click);
this.btnSend.Click +=
new System.EventHandler(this.btnSend_Click);
this.rbtnAttach.CheckedChanged +=
new System.EventHandler(this.rbtnAttach_CheckedChanged);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion


//Method for sending the email
//***************************************************************
private void SendMail()
{
try
{
//Creating the Mail Message object.
MailMessage Email=new MailMessage();

//Storing the To value in the object reference.
Email.To=txtTo.Text;

//Storing the From value in the object reference.
Email.From=txtFrom.Text;

//Storing the CC value in the object reference.
Email.Cc=txtCC.Text;

//Storing the BCC value in the object reference.
Email.Bcc=txtBCC.Text;

//Storing the Subject value in the object reference.
Email.Subject=txtSubject.Text;

//Specifies the email body.
Email.Body=txtMessage.Text;

//Setting priority to the mail as high,low,or normal
Email.Priority=MailPriority.High;

//Formatting the mail as html or text.
Email.BodyFormat=MailFormat.Text;

//Checking whether the attachment is needed or not.
if(rbtnAttach.Checked)
{
//Adding attachment to the mail.
Email.Attachments.Add(
new MailAttachment(FileBrowse.Value));
}

//specifying the real SMTP Mail Server.
SmtpMail.SmtpServer.Insert(0,"127.0.0.1");
SmtpMail.Send(Email);//Sending the mail.

//calling the reset method to erase all the data
//after sending the mail.
Reset();
lblMessage.ForeColor=Color.Navy;

//User information after submission.
lblMessage.Text=
"*Your email has been sent successfully-Thank You";
}
//Catching Exception
catch(Exception exc)
{
Reset();
lblMessage.Text="Send error:"+exc.ToString();
lblMessage.ForeColor=Color.Red;
}
}

//Method to reset the text fields.
//***********************************************************
private void Reset()
{
//Seeking for the controls in the active webform.
Control myForm=Page.FindControl("Form1");

//Iterating each control.
foreach(Control ctl in myForm.Controls)
{
//Checking whether it is a text
//box and clear when it is a textbox.
if(ctl.GetType().ToString().Equals(
"System.Web.UI.WebControls.TextBox"))

((TextBox)ctl).Text="";
}
}

//Event fires for sending the mail.
//***********************************************************
private void btnSend_Click(object sender, System.EventArgs e)
{
SendMail();
}

//Event for cancelling the mail.
//***********************************************************
private void btnCancel_Click(object sender, System.EventArgs e)
{
Reset();
}

//Event for enabling or disabling the File browser.
//************************************************************
private void rbtnAttach_CheckedChanged(object sender,
System.EventArgs e)
{
FileBrowse.Disabled=false;
}

//Event for enabling or disabling the File browser.
//************************************************************
private void rbtnDetachment_CheckedChanged(object sender,
System.EventArgs e)
{
FileBrowse.Disabled=true;
}
//*************************************************************
}
}