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.