Tuesday, January 29, 2008

Mouse Events in JavaScript

//WRITE THESE FUNCTIONS IN JAVASCRIPT ...

function sname_focus()

{

if( window.document.all.sendmsg.SenderName.style.fontStyle == "italic")

{

window.document.all.sendmsg.SenderName.value = "";

window.document.all.sendmsg.SenderName.style.fontStyle = "normal";

}

}

function sname_blur()

{

if( window.document.all.sendmsg.SenderName.value == "")

{

window.document.all.sendmsg.SenderName.value = "Name of Contact";

window.document.all.sendmsg.SenderName.style.fontStyle = "italic";

}

}

function scompany_focus()

{

if( window.document.all.sendmsg.SenderCompany.style.fontStyle == "italic")

{

window.document.all.sendmsg.SenderCompany.value = "";

window.document.all.sendmsg.SenderCompany.style.fontStyle = "normal";

}

}

function scompany_blur()

{

if( window.document.all.sendmsg.SenderCompany.value == "")

{

window.document.all.sendmsg.SenderCompany.value = "Company Name";

window.document.all.sendmsg.SenderCompany.style.fontStyle = "italic";

}

}

function semail_focus()

{

if( window.document.all.sendmsg.SenderEmail.style.fontStyle == "italic")

{

window.document.all.sendmsg.SenderEmail.value = "";

window.document.all.sendmsg.SenderEmail.style.fontStyle = "normal";

}

}

function semail_blur()

{

if( window.document.all.sendmsg.SenderEmail.value == "")

{

window.document.all.sendmsg.SenderEmail.value = "Email Address";

window.document.all.sendmsg.SenderEmail.style.fontStyle = "italic";

}

}

function sphone_focus()

{

if( window.document.all.sendmsg.SenderPhone.style.fontStyle == "italic")

{

window.document.all.sendmsg.SenderPhone.value = "";

window.document.all.sendmsg.SenderPhone.style.fontStyle = "normal";

}

}

function sphone_blur()

{

if( window.document.all.sendmsg.SenderPhone.value == "")

{

window.document.all.sendmsg.SenderPhone.value = "Phone Number";

window.document.all.sendmsg.SenderPhone.style.fontStyle = "italic";

}

}

function smessage_focus()

{

if( window.document.all.sendmsg.SenderMessage.style.fontStyle == "italic")

{

window.document.all.sendmsg.SenderMessage.value = "";

window.document.all.sendmsg.SenderMessage.style.fontStyle = "normal";

}

}

function smessage_blur()

{

if( window.document.all.sendmsg.SenderMessage.value == "")

{

window.document.all.sendmsg.SenderMessage.value = "Message to Send";

window.document.all.sendmsg.SenderMessage.style.fontStyle = "italic";

}

}

function setboxstyles()

{

window.document.all.sendmsg.SenderName.style.fontStyle = "italic";

window.document.all.sendmsg.SenderCompany.style.fontStyle = "italic";

window.document.all.sendmsg.SenderEmail.style.fontStyle = "italic";

window.document.all.sendmsg.SenderPhone.style.fontStyle = "italic";

window.document.all.sendmsg.SenderMessage.style.fontStyle = "italic";

}


========================================================
//If you want to toggle the textbox values, if the mouse is clickes in it ...

input name="SenderName" type="text" value="Name of Contact" id="SenderName" onFocus="sname_focus()" onBlur="sname_blur()" class=contactsendmsg style="font-style:italic" />

// If you want to make a mouse-over events on buttons, etc ...

td width=90 valign=middle align=center style="cursor:pointer" onclick="window.location=('aboutus.htm')" id=aboutdiv class=mainmenutd onmouseover="changelayer_color('aboutdiv','maincolorover');" onmouseout="changelayer_color('aboutdiv','maincolorout');"><font class=mainmenutext>About Usfont>td>


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Monday, January 28, 2008

Automatic Redirection To Index.aspx After 5 Seconds

Place this line of code on page load ...

<META HTTP-EQUIV="Refresh" CONTENT="5; URL=Index.aspx"/>


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Toggle DIV Visibility In .aspx File

<DIV style="CURSOR: hand; COLOR: blue" onclick="ShowHideImageUploader()">

<span style="font-family: Arial; font-weight:bold">Open Insertion span>DIV>


===================================================

function ShowHideImageUploader()

{

if(document.getElementById('tblyes').style.display=='none')

{

document.getElementById('tblyes').style.display='block';

}

else

{

document.getElementById('tblyes').style.display='none';

}

}


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Friday, January 25, 2008

Alerting A Multiline Text In ASP.Net 2.0

script type="text/javascript">
function disp_alert()
{
alert("First line" + '\n' + "second line");
}


input onclick="disp_alert()" value="Display alert box" type="button"

=================================================================

Code for ".cs" file ...

string str_msg = "Thank you for your feedback.\\n We will be reverting back to you soon.";

ClientScript.RegisterStartupScript (this.GetType(), "script", "script language = 'javascript'> alert('" + str_msg + "'); ");


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Inserting Values in Parent Page from a Pop-Up Wndow

function parent_location()

{

var firstname ,lastname ;

//store value in variables using getelementbyid

firstname = document.getElementById("txtFname").value;

lastname = document.getElementById("txtLname").value;

//value send in parent form

window.opener.document.getElementById( "ctl00_ContentPlaceHolder1_TextBox_FName").value = firstname;

window.opener.document.getElementById( "ctl00_ContentPlaceHolder1_TextBox_LName").value = lastname;

//closing the PopUp window

window.close();

}


=================================================

Add this Code on Page_Load ...

Button2.Attributes.Add("onclick", "javascript:return parent_location()");


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Opening A New Window

<a style="text-align:right" href="#" onclick="window.open ('../DisplayImage.aspx?Id= <%#DataBinder.Eval(Container.DataItem,"Photo_Id")%> ', null, 'height=700, width=700, status=yes, toolbar=no, menubar=no, location=no, scrollbars=1') ">

-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Setting Some Value of a Control in Master Page

((Label)this.Master.FindControl("Label_Heading")).Text = "Hello !";



-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Displaying Alert Without Postback

ClientScript.RegisterStartupScript( this.GetType(), "script", "script language="'javascript'"> alert('This is the alert message !'); " );



-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Creating An XML File in ASP.Net 2.0

//function for creting mapdat file in particular location

void CreateMapDataXML(int city,int selectedindx)

{

//declare variable

//string path;

SqlConnection sqlcon = new SqlConnection( System.Configuration.ConfigurationManager.AppSettings ["Con"]);

SqlCommand sqlcmd;

try

{

sqlcon.Open();

sqlcmd = new SqlCommand("proc_bankmarker", sqlcon);

sqlcmd.CommandType = CommandType.StoredProcedure;

sqlcmd.Parameters.AddWithValue("@cityid", city);

sqlcmd.Parameters.AddWithValue("@index", selectedindx);

SqlDataAdapter sqladp = new SqlDataAdapter(sqlcmd);

DataSet ds = new DataSet();

ds.Clear();

sqladp.Fill(ds);

//function for genral

if (city >= 0 && selectedindx >= 0)

{

//map server data file from mapdata folder

path = Server.MapPath("..") + @"\MapData\MapData_" + selectedindx + city +".xml";

}

XmlTextWriter writer = new XmlTextWriter(path, System.Text.Encoding.UTF8);

writer.WriteStartDocument();

writer.WriteStartElement("Banks");

for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)

{

writer.WriteStartElement("Bank");

writer.WriteAttributeString("Name", ds.Tables[0].Rows[i]["bank_name"].ToString());

writer.WriteAttributeString("Contact", ds.Tables[0].Rows[i]["Contact_No"].ToString());

writer.WriteAttributeString("lat", ds.Tables[0].Rows[i]["lat"].ToString());

writer.WriteAttributeString("lng", ds.Tables[0].Rows[i]["lng"].ToString());

writer.WriteAttributeString("address", ds.Tables[0].Rows[i]["address"].ToString());

writer.WriteAttributeString("BankOrATM", ds.Tables[0].Rows[i]["bankoratm"].ToString());

writer.WriteEndElement();

}

writer.WriteEndElement();

writer.WriteEndDocument();

writer.Close();

}

catch (Exception ex)

{

Response.Write(ex.ToString());

}

}



-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Generate META Tags Dynamically in ASP.Net 2.0 ...

This method should be called on Page_Load() ...

//Dynamically Generates the META tags consecutively for page ...

private void GenerateMetatags()

{

try

{

string str_country;

//If the there is no selected country OR the user clicks on select, then the default country that is set in Title is India ...

if (DropDownList_Country.SelectedItem == null || DropDownList_Country.SelectedItem.Text == "Select")

{

str_country = "India";

}

else

{

str_country = DropDownList_Country.SelectedItem.Text;

}

HtmlMeta hmKeyWords = new HtmlMeta();

HtmlHead head = (HtmlHead)Page.Header;

hmKeyWords.Name = "Keywords";

hmKeyWords.Content = "Home Loans - in " + str_country + ";

head.Controls.Add(hmKeyWords);

HtmlMeta hmDescription = new HtmlMeta();

hmDescription.Name = "Description";

hmDescription.Content = "Your Description ... about the site.";

head.Controls.Add(hmDescription);

HtmlTitle ht = new HtmlTitle();

ht.Text = "Home Loans in " + str_country + "";

head.Controls.Add(ht);

HtmlMeta httpequiv = new HtmlMeta();

httpequiv.HttpEquiv = "Content-Type";

httpequiv.Content = "text/html; charset=iso-8859-1";

head.Controls.Add(httpequiv);

}

catch (Exception ex)

{

Response.Write(ex.ToString());

}

}



-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Binding GridView Controls By Database

<%@ Register Assembly="MagicAjax" Namespace="MagicAjax.UI.Controls" TagPrefix="ajax" %>



<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White"

BorderColor="White" BorderStyle="Ridge" BorderWidth="3px" CellPadding="3" CellSpacing="1" OnRowCommand="GridView1_RowCommand" OnRowCreated="GridView1_RowCreated"

GridLines="None" Style="position: static" AllowPaging="True" AllowSorting="True" OnPageIndexChanging="GridView1_PageIndexChanging" OnSelectedIndexChanging="GridView1_SelectedIndexChanging" OnSorting="GridView1_Sorting">

<FooterStyle BackColor="#C6C3C6" ForeColor="Black" />

<Columns>

<asp:TemplateField HeaderText="Bank ATM Locations">

<ItemTemplate>

<asp:Label ID="Label_Bank" runat="server" Font-Names="Arial" Font-Size="8pt" Style="position: static"

Text='<%# Eval("Branch_Name") %>' Visible="False">asp:Label><ajax:AjaxPanel ID="AjaxPanel1" runat="server">

<asp:LinkButton ID="LinkButton_Location" runat="server" Style="position: static" Text='<%# Eval("Branch_Name") %>'>asp:LinkButton>ajax:AjaxPanel>

<asp:Label ID="Label_Latitude" runat="server"

Style="position: static" Visible="False" Text='<%# Eval("LatiTude") %>'>asp:Label> <asp:Label ID="Label_Longitude"

runat="server" Style="position: static" Visible="False" Text='<%# Eval("Longitude") %>'>asp:Label>

ItemTemplate>

asp:TemplateField>

<asp:TemplateField HeaderText="Bank ATM Address">

<ItemStyle HorizontalAlign="Center" />

<HeaderStyle HorizontalAlign="Center" />

<ItemTemplate>

<asp:Label ID="Label_ROIfl" runat="server" Style="position: static" Text='<%# Eval("Address") %>'>asp:Label>

ItemTemplate>

asp:TemplateField>

Columns>

<RowStyle BackColor="#DEDFDE" Font-Size="8pt" ForeColor="Black" />

<SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />

<PagerStyle BackColor="#C6C3C6" Font-Overline="False" ForeColor="Black" />

<HeaderStyle BackColor="#004040" Font-Bold="True" Font-Size="8pt" ForeColor="#E7E7FF"

Wrap="False" />

asp:GridView>

=========================================================

Now Add This Code in ".cs" file in some event ...

//Fill the DataList dynamically on user's choice of banks ...

private void FillGridView(string SelectedBankIds)

{

string str = "SELECT Bank_Name, Website FROM Bank_List WHERE (Bank_Id IN (" + SelectedBankIds + "))";

// DataSet dt = new DataSet();

DataTable dt = new DataTable();

SqlDataAdapter da = new SqlDataAdapter(str, sqlcon);

da.Fill(dt);

if (dt.Rows.Count == 0)

{

// Remove contraints so an empty row can be added...

dt.Constraints.Clear();

foreach (DataColumn dc in dt.Columns)

dc.AllowDBNull = true;

// Add a blank row to the dataset...

dt.Columns[0].AllowDBNull = true;

dt.Rows.Add(dt.NewRow());

// Bind the DataSet to the GridView...

GridView1.Visible = true;

GridView1.DataSource = dt;

GridView1.DataBind();

// Get the number of columns to know what the Column Span should be...

int columnCount = GridView1.Rows[0].Cells.Count;

// Call the clear method to clear out any controls that you use in the columns. I use a dropdown list in one of the column so this was necessary....

GridView1.Rows[0].Cells.Clear();

GridView1.Rows[0].Cells.Add(new TableCell());

GridView1.Rows[0].Cells[0].ColumnSpan = columnCount;

GridView1.Rows[0].Cells[0].Text ="No Bank Selected!";

}

else

{

//Clear the databinding ...

GridView1.DataSource = null;

GridView1.DataBind();

//Rebind with the database ...

GridView1.DataSource = dt;

GridView1.DataBind();

}

}


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Delete Selected Rows in GridView in ASP.Net 2.0

protected void Button_DelProp_Click(object sender, EventArgs e)

{

Select_CheckBox();

if (_newId == "")

{

ClientScript.RegisterStartupScript( this.GetType(), "script", "");

}

else

{

string strcmd = "DELETE FROM Registered_Properties WHERE (Property_Id IN (" + _newId + ") )";

SqlCommand cmd = new SqlCommand(strcmd, con);

con.Open();

cmd.ExecuteNonQuery();

con.Close();

Response.Redirect(Session["Page"].ToString());

}

}

private void Select_CheckBox()

{

string Id = "";

for (int i = 0; i <>

{

bool chkSelect = (((CheckBox) GridView1.Rows[i].FindControl ("Chkselect")).Checked);

if (chkSelect)

{

Label lblPId = new Label();

lblPId = (Label)GridView1.Rows[i].FindControl("Label_PId");

Id += "," + lblPId.Text.ToString();

}

}

_newId = Id.Trim(',');

}

-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Creating A Unique Registration Code in ASP.Net 2.0

public string RegistrationCode()

{

string str = System.Guid.NewGuid().ToString();

str = str.Replace("-", "");

return str;

}



-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Uploading Images in ASP.Net 2.0

string DefaultImageName = System.IO.Path.GetExtension ( System.IO.Path.GetFileName( FileUpload_CompanyLogo.FileName));


string DefaultImagePath = Server.MapPath(".") + "/Agent_Logos/"+ Session["SellerID"] +"_Logo"+ DefaultImageName;

SaveAgentLogo(DefaultImagePath);



//Method to save the agent logo ...

private void SaveAgentLogo(string DefaultImagePath)

{

// Create and store the default image and its thumbnail.

FileUpload_CompanyLogo.PostedFile.SaveAs(DefaultImagePath);

string fileName = System.IO.Path.GetFileName(DefaultImagePath);

string strThumbnailPath = Server.MapPath(".") + @"/Agent_Logos/Thumbnails/" + fileName;

ThumbImage.C_Thumbnails(50, DefaultImagePath, strThumbnailPath);

}


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Syntax for Connection String in Web.Config

<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">

<connectionStrings>
<
add name= "Con" connectionString= "Server=.; initial catalog=my_database_in; uid=sa; pwd=sa" />

connectionStrings>

======================================================
Now Add the Code Line Below in the ".aspx.cs" file at class level

using System.Data.SqlClient;

protected SqlConnection con = new SqlConnection( System.Configuration.ConfigurationManager.AppSettings ["CON"] );




-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Calculate distance between two points on Google Maps

public double CalculateDistance(double Lat1, double Long1, double Lat2, double Long2)
{
double dDistance = Double.MinValue;
double dLat1InRad = Lat1 * (Math.PI / 180.0);
double dLong1InRad = Long1 * (Math.PI / 180.0);
double dLat2InRad = Lat2 * (Math.PI / 180.0);
double dLong2InRad = Long2 * (Math.PI / 180.0);

double dLongitude = dLong2InRad - dLong1InRad;
double dLatitude = dLat2InRad - dLat1InRad;

// Intermediate result a.
double a = Math.Pow(Math.Sin(dLatitude / 2.0), 2.0) +
Math.Cos(dLat1InRad) * Math.Cos(dLat2InRad) *
Math.Pow(Math.Sin(dLongitude / 2.0), 2.0);

// Intermediate result c (great circle distance in Radians).
double c = 2.0 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1.0 - a));

// Distance.
// const Double kEarthRadiusMiles = 3956.0;
const Double kEarthRadiusKms = 6376.5;
dDistance = kEarthRadiusKms * c;

return(dDistance);
}


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Sending E-Mails in ASP.Net

using System.Net.Mail;

public void SendPageErrorMailToAdmin(string ErrorPageName, string ExceptionMessage)
{

string _to = System.Configuration.ConfigurationManager.AppSettings ["SiteMasterEmail"];
string _from = System.Configuration.ConfigurationManager.AppSettings ["AdminEmail"];
//string _to = System.Configuration.ConfigurationManager.AppSettings ["ContactEmail"];


MailAddress from = new MailAddress( _from, "My Website Admin");
MailAddress to = new MailAddress( _to, "My SiteMaster");
MailMessage msg = new MailMessage( from, to);

msg.Body = "Dear SiteMaster, An Exception Has Been Found !" + Environment.NewLine;
msg.Body += "=============================================" + Environment.NewLine;
msg.Body += Environment.NewLine;

//=====Testing Lines, Not To Be Included in the Main Site.
//msg.Body += "//=====Testing Line, Not To Be Included in the Main Site." + Environment.NewLine;
//msg.Body += "(From " + _from + " To " + _to + ")" + Environment.NewLine;


msg.Body += Environment.NewLine;
msg.Body += "ExceptionPage : " + ErrorPageName + "." + Environment.NewLine;
msg.Body += Environment.NewLine;
msg.Body += Environment.NewLine;
msg.Body += "Exception : " + Environment.NewLine;
msg.Body += ExceptionMessage + ".";
msg.Body += Environment.NewLine;
msg.Body += Environment.NewLine;
msg.Body += Environment.NewLine;
msg.Body += "Needs To Be Corrected Immediately." + Environment.NewLine;
msg.Body += "Thanks" + Environment.NewLine;

msg.BodyEncoding = System.Text.Encoding.UTF8;
msg.Subject = "An Exception on " + ErrorPageName + " page.";
msg.Priority = MailPriority.High;
SmtpClient smtpObj = new SmtpClient("127.0.0.1");
smtpObj.Send(msg);
}


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Thursday, January 24, 2008

Binding the Header of GridView even if there is no result in datatable

//Fill the GridView dynamically ...
private void FillGridView(string Ids)
{
string str = "SQL Query";

DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(str, sqlcon);
da.Fill(dt);

if (dt.Rows.Count == 0)
{
// Remove contraints so an empty row can be added...
dt.Constraints.Clear();
foreach (DataColumn dc in dt.Columns)
dc.AllowDBNull = true;

// Add a blank row to the dataset...
dt.Columns[0].AllowDBNull = true;
dt.Rows.Add(dt.NewRow());

// Bind the DataSet to the GridView...
GridView1.Visible = true;
GridView1.DataSource = dt;
GridView1.DataBind();

// Get the number of columns to know what the Column Span should be...
int columnCount = GridView1.Rows[0].Cells.Count;

// Call the clear method to clear out any controls that you use in the columns. I use a dropdown list in one of the column so this was necessary....
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columnCount;
GridView1.Rows[0].Cells[0].Text ="Nothing Selected!";
}
else
{
//Clear the databinding ...
GridView1.DataSource = null;
GridView1.DataBind();

//Rebind with the database ...
GridView1.DataSource = dt;
GridView1.DataBind();
}

}

-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Tuesday, January 22, 2008

Upload Videos in ASP.Net

protected void btnUpload_Click(object sender, EventArgs e)

{

string Venu = Request.QueryString["Venu"];

if (!( UVideo.PostedFile.ContentType == "video/x-ms-wmv" || UVideo.PostedFile.ContentType == "video/mpg" || UVideo.PostedFile.ContentType == "video/mpeg" || UVideo.PostedFile.ContentType == "video/divx" || UVideo.PostedFile.ContentType == "video/div" || UVideo.PostedFile.ContentType == "video/tix" || UVideo.PostedFile.ContentType == "video/mp4" || UVideo.PostedFile.ContentType == "video/qt" || UVideo.PostedFile.ContentType == "video/mov" || UVideo.PostedFile.ContentType == "video/avi" || UVideo.PostedFile.ContentType == "video/mp3" || UVideo.PostedFile.ContentType == "video/mpa" || UVideo.PostedFile.ContentType == "video/mpe" || UVideo.PostedFile.ContentType == "video/mp2" || UVideo.PostedFile.ContentType == "video/m1v" ))

{

pnlRight.Visible = false;

pnlWrong.Visible = true;

lblError.Text = "Video Extension Not Match";

return;

}

string file = System.IO.Path.GetFileName( System.IO.Path.GetExtension( UVideo.PostedFile.FileName ));

string loc = Server.MapPath("..")+ @"\"+ Venu + @"\Videos\" + ViewState["Id"].ToString() + file;

UVideo.PostedFile.SaveAs(loc);

SqlConnection sqlcon;

SqlCommand sqlcmd;

sqlcon = new SqlConnection ( System.Configuration.ConfigurationManager.AppSettings ["ConStr"] );

try

{

sqlcon.Open();

sqlcmd = new SqlCommand("updt_Video", sqlcon);

sqlcmd.CommandType = CommandType.StoredProcedure;

sqlcmd.Parameters.AddWithValue("@Vid", ViewState["Id"]);

sqlcmd.Parameters.AddWithValue("@VTitle", txtTitle.Text);

sqlcmd.Parameters.AddWithValue("@VPath", ViewState["Id"] + file);

sqlcmd.ExecuteNonQuery();

sqlcon.Close();

pnlRight.Visible = true;

pnlWrong.Visible = false;

lblRight.Text = "Video Uploaded Sucessfully";

}

catch (Exception ex)

{

sqlcon.Close();

Response.Write(ex.ToString());

}

finally

{

sqlcon.Close();

}

}



-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript