Monday 5 March 2012

SQL Connection



Connected Procedure : -

SqlConnection con = new SqlConnection("Pass the Connection String here");

SqlCommand com = new SqlCommand("select * from table3", con);

con.Open();

SqlDataReader dr = com.ExecuteReader();

GridView1.DataSource = dr;

GridView1.DataBind();

con.Close();

How to Send a Mail in Asp Dot Net



public partial class mailer : System.Web.UI.Page
{
MailMessage mailmsg;
SqlConnection con;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["admin"] == null)
{
Response.Redirect("index.aspx");
}
//if (Request.QueryString["id"] != null)
//{
//    txtToAddress.Text = Request.QueryString["id"];
//}
if(!IsPostBack)
{
String user = Session["admin"].ToString();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["name"].ConnectionString);
con.Open();
cmd = new SqlCommand("select email from registration where username='" + user + "'",con );
SqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
txtFromAddress.Text = dr.GetString(0);
}
dr.Close();
}
}
protected void btnSendmail_Click(object sender, ImageClickEventArgs e)
{
try
{
String to = txtToAddress.Text;
String from = txtFromAddress.Text;
String cc = txtCCAddress.Text;
String bcc = txtBCC.Text;
String subject = txtSubject.Text;
String body = txtMessage.Text;
mailmsg = new MailMessage();
mailmsg.From =new MailAddress( from );
mailmsg.To.Add ( new MailAddress(to));
if ((cc != null) && (cc != string.Empty))
{
mailmsg.CC.Add(new MailAddress(cc));
}
if ((bcc != null) && (bcc != string.Empty))
{
mailmsg.Bcc.Add(new MailAddress(bcc));
}
mailmsg.Subject = subject;
mailmsg.Body = body;
if (fileAttachment.HasFile)
{
mailmsg.Attachments.Add(new Attachment(fileAttachment.PostedFile.FileName));
}
// Set the format of the mail message body as HTML
mailmsg.IsBodyHtml = true;
// Set the priority of the mail message to normal
mailmsg.Priority = MailPriority.Normal;
SmtpClient smtpclient = new SmtpClient();
smtpclient.Host = ConfigurationManager.AppSettings["hostname"];
smtpclient.Send(mailmsg);
}
catch (Exception ex)
{
lblmsg.Text = "Your mail has been sent..";
}
}
}



File Handling In Asp Dot Net : Insert Into File


Protected Void InsertIntoFile()

{

if (TextBox1.Text != "" && TextBox2.Text != "" && TextBox3.Text != "" && TextBox4.Text != "")

{

FileStream fs = new FileStream(Server.MapPath("Temp/temp.txt"), FileMode.Append, FileAccess.Write);

StreamWriter sw = new StreamWriter(fs);

sw.WriteLine(TextBox1.Text);

sw.WriteLine(TextBox2.Text);

sw.WriteLine(TextBox3.Text);

sw.WriteLine(TextBox4.Text);

sw.WriteLine();

sw.Flush();

sw.Close();

fs.Close();

}

else Response.Write("Please fill all the fields.");

total = 0;

FileStream fs1 = new FileStream(Server.MapPath("Temp/temp.txt"), FileMode.Open, FileAccess.Read);

StreamReader sr = new StreamReader(fs1);

while (!sr.EndOfStream)

{

for (int i = 0; i < 5; i++)

{

sr.ReadLine();

}

total++;

}

}


Use of File upload Control in Asp Dot Net


protected void Page_Load(object sender, EventArgs e)

{

        Image1.Visible = false;

}

protected void Button_Upload_Click(object sender, EventArgs e)

{

        String str = "Pass the path wher you want to save the uploaded file

                           (For example : D:\\Visual studio\\Website\\FileUpload\\

                           Images\\)" + FileUpload1.FileName;

        FileUpload1.SaveAs(str);

        Image1.ImageUrl = "~//Images//" + FileUpload1.FileName;

        Image1.Visible = true;

}


How to get IP address by Hostname from Domain name Server in C#

This code is in c# to retrieve IP address corresponding to any hostname from Domain name server

string hostname = http://www.dotnetspider.com/;

IPAddress[] addresslist = Dns.GetHostAddresses(hostname);

foreach (IPAddress theaddress in addresslist)

{

Response.Write(theaddress.ToString());

Response.Write("NewLine");

}

in the second response we have a line brake. age is not visible so i am placing "NewLine" there.

don't forget to use

using System.Net;

Auto Complete Extender In Asp Dot Net


<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
  TargetControlID="TextBox1" ServiceMethod="GetCompletionList"
  ServicePath="AjaxLearning.asmx" MinimumPrefixLength="1"
  ShowOnlyCurrentWordInCompletionListItem="True">
</asp:AutoCompleteExtender>
Using Service File Method : (.asmx)
[WebMethod]
public string[] GetCompletionList(string prefixText)
{
SqlConnection conn = new                    SqlConnection(ConfigurationManager.ConnectionStrings["mystring"].ConnectionString);
SqlCommand com = new SqlCommand("SELECT Username FROM Table_Login WHERE Username LIKE '" + prefixText + "%'", conn);
com.CommandType = CommandType.Text;
conn.Open();
SqlDataReader reader = com.ExecuteReader();
List<string> strarr = new List<string>();
while (reader.Read())
{
strarr.Add(reader.GetString(0));
}
conn.Close();
return strarr.ToArray();
}
Using Handler : (.ashx)
public class AutocompleteData : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string firstname = context.Request.QueryString["q"];
string sql = "select top 10 Username from Table_Login where Username like '" + firstname + "%'";
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["mystring"].ConnectionString))
using (SqlCommand command = new SqlCommand(sql, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
context.Response.Write(reader.GetString(0) + Environment.NewLine);
}
}
}
}
public bool IsReusable {
get {
return false;
}
}
}


How To Use Image Map Control In Dot Net


ImageMap.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ImageMap.aspx.cs" Inherits="ImageMap" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>asp.net ImageMap: how to use</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Red">ImageMap</h2>
<asp:Label
ID="Label1"
runat="server"
Font-Size="Medium"
ForeColor="DodgerBlue"
>
</asp:Label>
<br />
<asp:ImageMap
ID="ImageMap1"
runat="server"
ImageUrl="~/Images/Doll.gif"
HotSpotMode="PostBack"
OnClick="ImageMap1_Click"
>
<asp:RectangleHotSpot
Top="0"
Bottom="360"
Left="0"
Right="180"
AlternateText="Green Doll"
PostBackValue="Green Doll"
/>
<asp:RectangleHotSpot
Top="0"
Bottom="360"
Left="181"
Right="360"
AlternateText="Pink Doll"
PostBackValue="Pink Doll"
/>
</asp:ImageMap>
</div>
</form>
</body>
</html>



ImageMap.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class ImageMap : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
Label1.Text = "Click any doll!";
ImageMap1.BorderWidth = 3;
ImageMap1.BorderStyle = BorderStyle.Double;
ImageMap1.BorderColor = System.Drawing.Color.Crimson;
}
}

protected void ImageMap1_Click(object sender, ImageMapEventArgs e)
{
Label1.Text = "You ckecked: " + e.PostBackValue;
}
}