Friday, May 15, 2009

Simple steps for starting program

BASEDB.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;
using DataAccessLayer;
using BusinessLogic;


///
/// Summary description for BaseDB
///

namespace DataAccessLayer
{
public class BaseDB
{
///
/// This is a comman function which is used by various class files for getting dataset.
///

/// sqlcommand type object
/// Dataset which holds all the values
internal static DataSet GetDataset(SqlCommand oCommand)//Accepts sqlcommand and procedure name as parameters and makes connection with database to bring required data and returns dataset
{
using (DataSet oDataSet = new DataSet())
{
using (SqlConnection oConn = new SqlConnection(CommonClass.getConnectionPath()))
{
oCommand.Connection = oConn;
oCommand.CommandType = CommandType.StoredProcedure;
oCommand.CommandTimeout = 3600;
using (SqlDataAdapter oAdapter = new SqlDataAdapter())
{
oAdapter.SelectCommand = oCommand;
try
{
oAdapter.Fill(oDataSet);

}
catch (Exception e)
{
throw e;
}
}
}
return oDataSet;
}
}

///
/// This is a commen function used by various class files to get scalar values from databae.
///

/// sqlcommand type object
/// object
internal static object ExecuteScalar(SqlCommand oCommand)
{
object objectToRead = null;
using (SqlConnection oConn = new SqlConnection(CommonClass.getConnectionPath()))
{
if (oConn.State == ConnectionState.Closed)
{
oConn.Open();
}
oCommand.Connection = oConn;
oCommand.CommandType = CommandType.StoredProcedure;
oCommand.CommandTimeout = 3600;
try { objectToRead = oCommand.ExecuteScalar(); }
catch (Exception e) { throw e; }
}
return objectToRead;
}


///
/// Commen function shared by all the class file to execute update , delete queries and return nothing.
///

/// sqlcommand type object
internal static int ExecuteNonQuery(SqlCommand oCommand)
{
using (SqlConnection oConn = new SqlConnection(CommonClass.getConnectionPath()))
{
if (oConn.State == ConnectionState.Closed)
{
oConn.Open();
}
oCommand.Connection = oConn;
oCommand.CommandType = CommandType.StoredProcedure;
oCommand.CommandTimeout = 3600;
try { return oCommand.ExecuteNonQuery(); }
catch (Exception e) { return 0; }
}
}

///
/// Commen function shared by all the class file to execute update , delete queries
/// and return no. of rows affected, because in file we perform other operations on the base
/// of rows affected.
///

/// sqlcommand type object
///
internal static int ExecuteNonQuery_ReturnVal(SqlCommand oCommand)
{
int RowsAffected = 0;
using (SqlConnection oConn = new SqlConnection(CommonClass.getConnectionPath()))
{
if (oConn.State == ConnectionState.Closed)
{
oConn.Open();
}
oCommand.Connection = oConn;
oCommand.CommandType = CommandType.StoredProcedure;
oCommand.CommandTimeout = 3600;
try
{
RowsAffected = oCommand.ExecuteNonQuery();
return RowsAffected;
}
catch (Exception e)
{
return RowsAffected;

}
}
return RowsAffected;
}
}
}


COMMON CLASS


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;



///
/// Summary description for CommonClass
///

///
namespace BusinessLogic
{
public class CommonClass
{
public CommonClass()
{
//
// TODO: Add constructor logic here
//
}

public static string getConnectionPath()
{
return ConfigurationManager.ConnectionStrings["connStr"].ConnectionString.ToString();
}

public static string Trim( TextBox tb)
{
return tb.Text.Trim();

}

public static void AddParameter(SqlCommand cmd, string parmName, string value)
{
parmName = "@" + parmName.Trim();
cmd.Parameters.AddWithValue(parmName, value);
}

///
/// This function used for bind GridView with dataset.
///

///
///
///
public static int Bind(DataSet dst, GridView gv)
{
try
{
if (dst.Tables[0].Rows.Count > 0)
{
gv.DataSource = dst;
gv.DataBind();
return 1;
}
else
{
return 2;
}
}
catch
{
return 0;/// Error

}

}

public static string StyleforSelectedRow()
{
return "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#add8e6'";
}

///
/// Function is used for insert - between strings etc phone number
///

///
///
///
public static string PhoneString(string str, int len)
{
string retString = string.Empty;;
if (str.Length == len)
{
retString ="("+ str.Substring(0, 3) +") "+ str.Substring(3, 3) +"-"+ str.Substring(6, 4);
return retString;
}
return str;
}
///
/// This function break the email from @ when lenthh is > 25
///

public static string EMailBreak(string str, int len)
{
string retString = string.Empty; ;
if ((str.Length > len) && ( str.Contains("@")))
{

retString = str.Replace("@", "
@");
return retString;
}
return str;
}




}
}


APPLICATION PATH TO FIND WHERE APPLICATION

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;



///
/// Summary description for CommonClass
///

///
namespace BusinessLogic
{
public class CommonClass
{
public CommonClass()
{
//
// TODO: Add constructor logic here
//
}

public static string getConnectionPath()
{
return ConfigurationManager.ConnectionStrings["connStr"].ConnectionString.ToString();
}

public static string Trim( TextBox tb)
{
return tb.Text.Trim();

}

public static void AddParameter(SqlCommand cmd, string parmName, string value)
{
parmName = "@" + parmName.Trim();
cmd.Parameters.AddWithValue(parmName, value);
}

///
/// This function used for bind GridView with dataset.
///

///
///
///
public static int Bind(DataSet dst, GridView gv)
{
try
{
if (dst.Tables[0].Rows.Count > 0)
{
gv.DataSource = dst;
gv.DataBind();
return 1;
}
else
{
return 2;
}
}
catch
{
return 0;/// Error

}

}

public static string StyleforSelectedRow()
{
return "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#add8e6'";
}

///
/// Function is used for insert - between strings etc phone number
///

///
///
///
public static string PhoneString(string str, int len)
{
string retString = string.Empty;;
if (str.Length == len)
{
retString ="("+ str.Substring(0, 3) +") "+ str.Substring(3, 3) +"-"+ str.Substring(6, 4);
return retString;
}
return str;
}
///
/// This function break the email from @ when lenthh is > 25
///

public static string EMailBreak(string str, int len)
{
string retString = string.Empty; ;
if ((str.Length > len) && ( str.Contains("@")))
{

retString = str.Replace("@", "
@");
return retString;
}
return str;
}




}
}


Thanks
Helpondesk Team

Friday, May 1, 2009

user to select value from dropdown list

For validating user selection in dropdownlist we can use rangevalidator. and values of drop down must be in integer type.
syntax is follows :-
[asp:RangeValidator ID="RVddRegistrationType" runat="server" ControlToValidate="ddRegistrationType" ErrorMessage="Select registration type" Display="None"
MaximumValue="100" MinimumValue="1" Type="Integer"][/asp:RangeValidator]


Thanks
Helpondesk Team

Saturday, April 18, 2009

how to download the images / pdf / text files from a directroy.

how to download the images / pdf / text files from a directroy.

There is one simple solution to set the path of that file with hyperlink button and when user right click the file button it will show option for download. what you think that it is correct. No.

so we have to get some steps

using directoryinfo class read all the files from dwonload directroy. and create a anchor tag redirecting on dowloadin page.

On Downlaoding page.

get the file name from url of page and

using FileStream class streamed out that file.
and that streamed file passed as constructor of binary reader class
and get the downlaod of server file.

Benifit :- this approch we can hide the orignal location of files.

code is following :-

On free download page.
// using System.IO;
DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/images"));
int i = 0;
foreach (FileInfo fi in di.GetFiles())
{
HyperLink HL = new HyperLink();
HL.ID = "HyperLink" + i++;
HL.Text = fi.Name;
HL.NavigateUrl = "downloading.aspx?file=" + fi.Name;
Page.Controls.Add(HL);
Page.Controls.Add(new LiteralControl("<br/>"));
}


On freedownlaoding page
protected void Page_Load(object sender, EventArgs e)
{
string filename = Request["file"].ToString();
fileDownload(filename, Server.MapPath("~/images/"+filename));

}

private void fileDownload(string fileName, string fileUrl)
{
Response.Clear();
bool success = ResponseFile(Page.Request, Page.Response, fileName, fileUrl, 1024000);
if (!success)
Response.Write("Downloading Error!");
Response.End();
}

public bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullUrl, long _speed)
{
try
{
FileStream myFile = new FileStream(_fullUrl, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
try
{
_Response.AddHeader("Accept-Ranges", "bytes");
_Response.Buffer = false;
long fileLength = myFile.Length;
long startBytes = 0;
int pack = 10240; //10K bytes
int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
if (_Request.Headers["Range"] != null)
{
_Response.StatusCode = 206;
string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[1]);
}
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if (startBytes != 0)
{
_Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
}
_Response.AddHeader("Connection", "Keep-Alive");
_Response.ContentType = "application/octet-stream";
_Response.AddHeader("Content-Disposition", "attachment;filename="
+ HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));
br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;
for (int i = 0; i <>
{
if (_Response.IsClientConnected)
{
_Response.BinaryWrite(br.ReadBytes(pack));
Thread.Sleep(sleep);
}
else
{
i = maxCount;
}
}
}
catch
{
return false;
}
finally
{
br.Close();
myFile.Close();
}
}
catch
{
return false;
}
return true;
}


Thanks
Helpondesk Team

Wednesday, April 15, 2009

findout howmany users are currently online

Step 1 - > Create a class
namespace Utility
{
public class WebsiteVisitor
{
private string sessionId;
public string SessionId
{
get { return sessionId; }
set { sessionId = value; }
}
public string IpAddress
{
get { return ipAddress; }
set { ipAddress = value; }
}
private string ipAddress;
public string UrlReferrer
{
get { return urlReferrer; }
set { urlReferrer = value; }
}
private string urlReferrer;
public string EnterUrl
{
get { return enterUrl; }
set { enterUrl = value; }
}
private string enterUrl;
public string UserAgent
{
get { return userAgent; }
set { userAgent = value; }
}
private string userAgent;
public DateTime SessionStarted
{
get { return sessionStarted; }
set { sessionStarted = value; }
}
private DateTime sessionStarted;
public WebsiteVisitor(HttpContext context)
{
if ((context != null) && (context.Request != null) && (context.Session != null))
{
this.sessionId = context.Session.SessionID;
sessionStarted = DateTime.Now;
userAgent = string.IsNullOrEmpty(context.Request.UserAgent) ? "" : context.Request.UserAgent;
ipAddress = context.Request.UserHostAddress;
if (context.Request.UrlReferrer != null)
{
urlReferrer = string.IsNullOrEmpty(context.Request.UrlReferrer.OriginalString) ? "" : context.Request.UrlReferrer.OriginalString;
}
enterUrl = string.IsNullOrEmpty(context.Request.Url.OriginalString) ? "" : context.Request.Url.OriginalString;
}
}
}
public static class OnlineVisitorsContainer
{
public static Dictionary[string, WebsiteVisitor] Visitors = new Dictionary[string, WebsiteVisitor]();
}
}
Step 2- >
Add Global.aspx file in porject and use following name spaces
[%@ Import Namespace="System.Collections.Generic" %]
[%@ Import Namespace="Utility" %]
Use session start and session end event for global.aspx page
void Session_Start(object sender, EventArgs e)
{
Session["Start"] = DateTime.Now;
HttpContext currentContext = HttpContext.Current;
if (currentContext != null)
{
if (!OnlineVisitorsContainer.Visitors.ContainsKey(currentContext.Session.SessionID))
{
WebsiteVisitor currentVisitor = new WebsiteVisitor(currentContext);
OnlineVisitorsContainer.Visitors.Add(currentVisitor.SessionId, currentVisitor);
}
}
}
void Session_End(object sender, EventArgs e)
{
if (this.Session != null)
{
OnlineVisitorsContainer.Visitors.Remove(this.Session.SessionID);
}
}
Step 3 ->
One Third step we are able to show user informarmations
[asp:GridView ID="gvVisitors" runat="server" AutoGenerateColumns="False"
CellPadding="2" ForeColor="#333333" GridLines="Both" ]
[FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /]
[RowStyle BackColor="#EFF3FB" /]
[Columns]
[asp:TemplateField HeaderText="Session Started"]
[ItemTemplate]
[%# ((DateTime)Eval("SessionStarted")).ToString("dd/MM/yyyy HH:mm:ss") %][br /]
[/ItemTemplate]
[/asp:TemplateField]
[asp:TemplateField HeaderText="Ip"]
[ItemTemplate]
[%# Eval("IpAddress") %]
[/ItemTemplate]
[/asp:TemplateField]
[asp:TemplateField HeaderText="Other"]
[ItemTemplate]
[span style="font-size:small;"]
[%# Eval("UserAgent") %][br /]
[%# Eval("EnterUrl") %][br /]
[/span]
[asp:HyperLink ID="refurl" Text='[%# Eval("UrlReferrer") %]' Font-Size="Small"
NavigateUrl='[%# Eval("UrlReferrer") %]' runat="server" Target="_blank" /]
[/ItemTemplate]
[/asp:TemplateField]
[/Columns]
[PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /]
[SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /]
[HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /]
[EditRowStyle BackColor="#2461BF" /]
[AlternatingRowStyle BackColor="White" /]
[/asp:GridView]
Add name space on page
using Utility
if (!Page.IsPostBack)
{
if (OnlineVisitorsContainer.Visitors != null)
{
gvVisitors.DataSource = OnlineVisitorsContainer.Visitors.Values;
gvVisitors.DataBind();
}
}
Thanks
HelponDesk Team

How to wath howmany users currently on our site

Step 1 - > Create a class
namespace Utility
{
public class WebsiteVisitor
{
private string sessionId;
public string SessionId
{
get { return sessionId; }
set { sessionId = value; }
}
public string IpAddress
{
get { return ipAddress; }
set { ipAddress = value; }
}
private string ipAddress;
public string UrlReferrer
{
get { return urlReferrer; }
set { urlReferrer = value; }
}
private string urlReferrer;
public string EnterUrl
{
get { return enterUrl; }
set { enterUrl = value; }
}
private string enterUrl;
public string UserAgent
{
get { return userAgent; }
set { userAgent = value; }
}
private string userAgent;
public DateTime SessionStarted
{
get { return sessionStarted; }
set { sessionStarted = value; }
}
private DateTime sessionStarted;
public WebsiteVisitor(HttpContext context)
{
if ((context != null) && (context.Request != null) && (context.Session != null))
{
this.sessionId = context.Session.SessionID;
sessionStarted = DateTime.Now;
userAgent = string.IsNullOrEmpty(context.Request.UserAgent) ? "" : context.Request.UserAgent;
ipAddress = context.Request.UserHostAddress;
if (context.Request.UrlReferrer != null)
{
urlReferrer = string.IsNullOrEmpty(context.Request.UrlReferrer.OriginalString) ? "" : context.Request.UrlReferrer.OriginalString;
}
enterUrl = string.IsNullOrEmpty(context.Request.Url.OriginalString) ? "" : context.Request.Url.OriginalString;
}
}
}
public static class OnlineVisitorsContainer
{
public static Dictionary[string, WebsiteVisitor] Visitors = new Dictionary[string, WebsiteVisitor]();
}
}
Step 2- >
Add Global.aspx file in porject and use following name spaces
[%@ Import Namespace="System.Collections.Generic" %]
[%@ Import Namespace="Utility" %]
Use session start and session end event for global.aspx page
void Session_Start(object sender, EventArgs e)
{
Session["Start"] = DateTime.Now;
HttpContext currentContext = HttpContext.Current;
if (currentContext != null)
{
if (!OnlineVisitorsContainer.Visitors.ContainsKey(currentContext.Session.SessionID))
{
WebsiteVisitor currentVisitor = new WebsiteVisitor(currentContext);
OnlineVisitorsContainer.Visitors.Add(currentVisitor.SessionId, currentVisitor);
}
}
}
void Session_End(object sender, EventArgs e)
{
if (this.Session != null)
{
OnlineVisitorsContainer.Visitors.Remove(this.Session.SessionID);
}
}
Step 3 ->
One Third step we are able to show user informarmations
[asp:GridView ID="gvVisitors" runat="server" AutoGenerateColumns="False"
CellPadding="2" ForeColor="#333333" GridLines="Both" ]
[FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /]
[RowStyle BackColor="#EFF3FB" /]
[Columns]
[asp:TemplateField HeaderText="Session Started"]
[ItemTemplate]
[%# ((DateTime)Eval("SessionStarted")).ToString("dd/MM/yyyy HH:mm:ss") %][br /]
[/ItemTemplate]
[/asp:TemplateField]
[asp:TemplateField HeaderText="Ip"]
[ItemTemplate]
[%# Eval("IpAddress") %]
[/ItemTemplate]
[/asp:TemplateField]
[asp:TemplateField HeaderText="Other"]
[ItemTemplate]
[span style="font-size:small;"]
[%# Eval("UserAgent") %][br /]
[%# Eval("EnterUrl") %][br /]
[/span]
[asp:HyperLink ID="refurl" Text='[%# Eval("UrlReferrer") %]' Font-Size="Small"
NavigateUrl='[%# Eval("UrlReferrer") %]' runat="server" Target="_blank" /]
[/ItemTemplate]
[/asp:TemplateField]
[/Columns]
[PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /]
[SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /]
[HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /]
[EditRowStyle BackColor="#2461BF" /]
[AlternatingRowStyle BackColor="White" /]
[/asp:GridView]
Add name space on page
using Utility
if (!Page.IsPostBack)
{
if (OnlineVisitorsContainer.Visitors != null)
{
gvVisitors.DataSource = OnlineVisitorsContainer.Visitors.Values;
gvVisitors.DataBind();
}
}
Thanks
HelponDesk Team

Monday, April 13, 2009

How to find a page control in usercontrol?

Write down the following code snipps for find the control of page
in user control.

TextBox tb = new TextBox();
tb = (TextBox) this.Parent.FindControl("tb1");
tb.Text = "I m in user control 1";


Thanks
Helpondesk Team

Monday, April 6, 2009

How to use regular expression in javaScript

Hi,
Today i got a problem to validate user validation on html form.
i m strange when i face difficulty on use Regular Expression. but i got the solution
from www.javascriptkit.com/ here i explained a validation with regular expression

there are two important thing pack the validation between two forward slash.
and on the value of text box use .search(regexp) . if it is -1 that mean match is fail


[script language="JavaScript1.2"]
function checkUSPhoneFormat()
{
var USPhoneFormat=/((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}/ //regular expression defining a US format number
if (document.myform.myinput.value.search(USPhoneFormat)==-1) //if match failed
alert("Please enter a valid format")
}
[/script]

[form name="myform"]
[input type="text" name="myinput" size=15]
[input type="button" onClick="checkUSPhoneFormat()" value="check"]

[/form]

Thanks
HelpOnDesk

How to load css and javascript file runtime

Hi
In following function we demostrate that how to load css and javascirpt at runtime.


function loadjscssfile(filename, filetype){
if (filetype=="js"){ //if filename is a external JavaScript file
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
}
else if (filetype=="css"){ //if filename is an external CSS file
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}

loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file


myscript.js" source:

var petname="Spotty"
alert("Pet Name: " + petname)

"mystyle.css" source:

#demotable td{
background-color: lightyellow;
}

#demotable b{
color: blue;
}


This code is taken from

http://javascriptkit.com/cutpastejava.shtml

Thanks
Help on desk

Friday, April 3, 2009

Typed DataSet

Typed DataSet :-
Typed DataSets have all the functionality of DataSets, Typed DataSets directly inherit from the

DataSet classes. Some additional code generated by .NET Framework tools gives all the additional benefits of

Typed DataSets. Furthermore, you can access table and columns by name instead of having to use collection-based

methods with DataSets

-> Typed DataSets check types at compile time it also konwn as This is known as type-safe access
-> automatically complete lines while typing rather the describe each time column name.
Hi how to use Typed Data set
/ * 1-> add new item set dataset. give a name to it delete which coneection is provide by default with it.
* 2-> right click on dataset and add a new table.
* 3-> right click on table and add column which will filled by code.
* 4-> code snipp is bellow.
* note the column name of select command and dataset.xss shuld be same
*/
SqlConnection cn = new SqlConnection(@"Data Source=xxxxxx\VER2005;Initial Catalog=PUBS;Persist Security Info=True;User ID=xxx;Password=xxxx");
SqlCommand cmd = new SqlCommand("SELECT bookRecord.* FROM bookRecord", cn); SqlDataAdapter da = new SqlDataAdapter(cmd);
dsProducts tds = new dsProducts();
da.Fill(tds, tds.Tables[0].TableName);

foreach (DataRow oOrderRow in tds.DataTable1.Rows )
{ Response.Write ("BookID = " + oOrderRow["bookid"].ToString()); }
string ss = tds.DataTable1.Rows[0]["bookid"].ToString();

string ss2 = t ds.DataTable1.Rows[1]["bookid"].ToString();

Thanks
HelpOnDesck Team

how to set default button dynamically in page.

There are many way to sortout this problem.
like wrapup each seprate panel and set the defaultbutton property on panel.or set the WebForm_FireDefaultButton onclick event of text box.But i like mostand prefer to keep this in practice is call javaScript function of for setdefault button this is aplicabe on firefox,IE,Safari id did not tyr it for netscape but i belive it will run. this function is
function clickButton(e, buttonid)
{ var evt = e ? e : window.event;
var bt = document.getElementById(buttonid);
if (bt)
{
if (evt.keyCode == 13)

{
bt.click();
return false;
}
}
}
we can implement it as follws
TextBox1.Attributes.Add("onkeypress", "return clickButton(event,'" + Button2.ClientID + "')"); TextBox2.Attributes.Add("onkeypress", "return clickButton(event,'" + Button3.ClientID + "')"); TextBox3.Attributes.Add("onkeypress", "return clickButton(event,'" + Button4.ClientID + "')"); TextBox4.Attributes.Add("onkeypress", "return clickButton(event,'" + Button5.ClientID + "')");

Thanks
HelponDesk Team

Thursday, April 2, 2009

How to change css dynamicaly without using javaScript

How to change css dynamicaly without using javaScript

[html]
[head]
[title]Change CSS Class[/title]
[style type="text/css"]
.ClassOut
{
background-color: black;
color: white;
font-weight: bold;
}

.ClassOver
{
background-color: white;
color: black;
font-weight: bold;
border: 1px solid black;
}
[/style]
[/head]
[body]
[p class="ClassOut" onmouseover="this.className='ClassOver';"
onmouseout="this.className='ClassOut';"]
Hi, I am a paragraph with text. If you hover your mouse
over me, my color changes . This is done by setting the
className CSS property.
[/p]
[/body]
[/html]

Thanks
HeelpOnDesk Team

How to create a table with fixed header

How to create a table with fixed header



[table style="width: 300px" cellpadding="0" cellspacing="0"]
[tr]
[td]Column 1[/td]
[td]Column 2[/td]
[/tr]
[/table]

[div style="overflow: auto;height: 100px; width: 320px;"]
[table style="width: 300px;" cellpadding="0" cellspacing="0"]
[tr]
[td]Value 1[/td]
[td]Value 2[/td]
[/tr]
[tr]
[td]Value 1[/td]
[td]Value 2[/td]
[/tr]
[tr]
[td]Value 1[/td]
[td]Value 2[/td]
[/tr]
[tr]
[td]Value 1[/td]
[td]Value 2[/td]
[/tr]
[tr]
[td]Value 1[/td]
[td]Value 2[/td]
[/tr]
[tr]
[td]Value 1[/td]
[td]Value 2[/td]
[/tr]
[/table]
[/div]

Thanks
Helpondesk team

How to Embed Video Player in ASPX page

we can very easily embed the media player on web page
sample code is follows
I read it form following link

http://alistapart.com/articles/byebyeembed


[object type="video/x-ms-wmv"
data="movie.wmv" width="320" height="260"]
[param name="src" value="movie.wmv" /]
[param name="autostart" value="true" /]
[param name="controller" value="true" /]
[/object]

Thanks
Publish Post

HelpOnDesk Team

sending email with attachment using Attachment Class

For sending email with attachment we usally upload file on server and after sending the email delete it from sever. but .net 2.0 interdues new class Attachment which provide us a eazy way with IO.Stream and filename. this class has a constructor that allows you to pass an IO.Stream and a file name. Conveniently, the FileUpload control has a FileContent property that returns the uploaded file as an IO.Stream. All that's left to do is to

get the file name from the uploaded file using Path.GetFileName and you're good to go.


private void functionSendMailWithAttachment(FileUpload FileUpload1)
{

if (FileUpload1.HasFile)
{
string toAddress = "reciver@gmail.com";
string fromAddress = "admin@helpondesk.com";
string mailServer = "smtp.server.com";

MailMessage myMailMessage = new MailMessage();

myMailMessage.To.Add(toAddress);
myMailMessage.From = new MailAddress(fromAddress);
myMailMessage.Subject = "Never :) ";


string fileName = FileUpload1.PostedFile.FileName;
Attachment myAttachment = new Attachment(FileUpload1.FileContent, fileName);
myMailMessage.Attachments.Add(myAttachment);

SmtpClient mySmtpClient = new SmtpClient(mailServer);
//if you want to send mail from local host.
/// SmtpClient smtpClientho = new SmtpClient("localhost");


mySmtpClient.Send(myMailMessage);
}


}

Add fileupload control on aspx page.

[asp:FileUpload ID="FileUpload1" runat="server" /]

namespace
using System.Net.Mail;

Thanks
Helpondesk Team

Friday, March 27, 2009

Cursor for get all the table name in database

This cursor is used for get all the table name form database.
and we can simply add the sql commands in this cursor. as
I shown in Print Statement.

Declare @t varchar (1024)
Declare tbl_cur cursor for
select TABLE_NAME from INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' order by TABLE_NAME
OPEN tbl_cur
FETCH NEXT from tbl_cur INTO @t
WHILE @@FETCH_STATUS = 0
BEGIN
-- print ('sp_rename '+ @t +','+@t+'Notused')
print ('select * from '+ @t )
print 'GO'
FETCH NEXT from tbl_cur INTO @t
END
CLOSE tbl_cur
DEALLOCATE tbl_Cur

Thanks
HELPONDESK TEAM

Thursday, March 19, 2009

steps to set minimum and maxumum length of passwerd

Hi
This is simple steps to set minimum and maxumum length of passwerd.


Step 1) For Req. filed

[asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="txtpassword" Display="None"
ErrorMessage="Your password is a required field."][/asp:RequiredFieldValidator]

Step 2) For set Min n Max length of password.


[asp:RegularExpressionValidator ID="RegularExpressionValidator7" runat="server"
ControlToValidate="txtpassword" Display="None"
ErrorMessage="password shuld be 6-32 characters" ValidationExpression="\w{6,}"][/asp:RegularExpressionValidator]


Thanks
Helpondesk Team

Saturday, March 14, 2009

funcition for calculating distacne from langitude and latetude.

private double distance(double lat1, double lon1, double lat2, double lon2, string unit)
{
double totalDistance;
double theta, dist;
theta = lon1 - lon2;
dist = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * Math.Cos(deg2rad(theta));
dist = acos(dist);
dist = rad2deg(dist);
totalDistance = dist * 60 * 1.1515;
if (unit == "K")
{
totalDistance = totalDistance * 1.609344;
return totalDistance;
}
else if (unit == "N")
{
totalDistance = totalDistance * 0.8684;

return totalDistance;

}
else
{
return 0.00;
}


}

private double acos(double rad)
{
if (Math.Abs(rad) != 1)
{
return pi / 2 - Math.Atan(rad / Math.Sqrt(1 - rad * rad));

}
else if (rad == -1)
{
return pi;
}
else
{
return 0.00;

}



}

private double deg2rad(double Deg)
{
return Convert.ToDouble(Deg * pi / 180);
}

private double rad2deg(double Rad)
{
return Convert.ToDouble(Rad * 180 / pi);
}

Friday, March 13, 2009

Delete Duplicate Records -- Without having Primary key

-----------Delete Duplicate Records ---------------------------
-------- Without having Primary key ---------------------------
CREATE TABLE [SalesHistory]
( [Product] [varchar](10) NULL,
[SaleDate] [datetime] NULL,
[SalePrice] [money] NULL )
GO
INSERT INTO SalesHistory(Product, SaleDate, SalePrice)
SELECT 'Computer','1919-03-18 00:00:00.000',1008.00
UNION ALL
SELECT 'BigScreen','1927-03-18 00:00:00.000',91.00
UNION ALL
SELECT 'PoolTable','1927-04-01 00:00:00.000',139.00
UNION ALL
SELECT 'Computer','1919-03-18 00:00:00.000',1008.00
UNION ALL
SELECT 'BigScreen','1927-03-18 00:00:00.000',91.00
UNION ALL
SELECT 'PoolTable','1927-04-01 00:00:00.000',139.00





set rowcount 1
select 'start'
while @@rowcount > 0
begin

delete a from SalesHistory a
where
(
select count(*) from saleshistory b

where a.product = b.product and a.saledate = b.saledate and a.SalePrice = b.SalePrice)>1
end

set rowcount 0

select product,saledate, SalePrice from SalesHistory

Thursday, March 12, 2009

Whats new in ASP.NET 3.5

Whats new in ASP.NET 3.5
Some important featues which are introduce in with framework 3.5
ASP.NET AJAX
In ASP.NET 2.0, ASP.NET AJAX was used as an extension to it. You had to download the extensions and install it. However in ASP.NET 3.5, ASP.NET AJAX is integrated into the .NET Framework, thereby making the process of building cool user interfaces easier and intuitive.
The integration between webparts and the update panel is much smoother. Another noticeable feature is that you can now add ASP.NET AJAX Control Extenders to the toolbox in VS2008. Even though this is an IDE specific feature, however I feel it deserves a mention over here for developers, who had to add extenders using source view earlier. It is also worth noting that Windows Communication Foundation (WCF) now supports JSON along with other standard protocols like SOAP, RSS and POX.
New Controls
The ListView and DataPager are new controls added along with a new datasource control called the LinqDataSource.
ListView
The ListView control is quiet flexible and contains features of the Gridview, Datagrid, Repeater and similar list controls available in ASP.NET 2.0. It provides the ability to insert, delete, page (using Data Pager), sort and edit data. However one feature of the ListView control that stands apart, is that it gives you a great amount of flexibility over the markup generated. So you have a complete control on how the data is to be displayed. You can now render your data without using thetag. You also get a rich set of templates with the ListView control.
DataPager
DataPager provides paging support to the ListView control. The best advantage is that you need not have to keep it ‘tied’ with the control on which the paging is being done. You can keep it anywhere on the page.
DataPager gives you a consistent way of paging with the controls that support it. Currently only ListView supports it as it implements the IPageableItemContainer. However support is likely to be added to other List controls as well.
LINQ
LINQ (Language Integrated Query) adds native data querying capability to C# and VB.NET along with the compiler and Intellisense support. LINQ is a component of .NET 3.5. LINQ defines operators that allow you to code your query in a consistent manner over databases, objects and XML. The ASP.NET LinqDataSource control allows you to use LINQ to filter, order and group data before binding to the List controls.
ASP.NET Merge Tool
ASP.NET 3.5 includes a new merge tool (aspnet_merge.exe). This tool lets you combine and manage assemblies created by aspnet_compiler.exe. This tool was available earlier as an add-on.
New Assemblies
The new assemblies that would be of use to ASP.NET 3.5 developers are as follows:
System.Core.dll - Includes the implementation for LINQ to Objects
System.Data.Linq.dll - Includes the implementation for LINQ to SQL
System.Xml.Linq.dll - Includes the implementation for LINQ to XML
System.Data.DataSetExtensions.dll - Includes the implementation for LINQ to DataSet
System.Web.Extensions.dll: Includes the implementation for ASP.NET AJAX (new enhancements added) and new web controls as explained earlier.
Some other important points for move to asp.net 3.5
ASP.NET 3.5 provides better support to IIS7. IIS7 and ASP.NET 3.5 modules and handlers support unified configuration.
You can have multiple versions of ASP.NET on the same machine.
For those who are wondering what happened to ASP.NET 3.0, well there isn’t anything called ASP.NET 3.0.
VS 2002 worked with ASP.NET 1.0, VS 2003 worked with ASP.NET 1.1, and VS 2005 worked with ASP.NET 2.0. However VS 2008 supports multi-targeting, i.e it works with ASP.NET 2.0, and ASP.NET 3.5.
Intellisense with javaScript for rapid developement.
Addin system p2p base class Active directory Anonymous types with static type inference Paging support for ADO.NET ADO.NET synchronization API to synchronize local caches and server side datastores Asynchronous network I/O API Support for HTTP pipelining and syndication feeds. New System.CodeDom namespace.

Tuesday, February 24, 2009

Useful Link

You will find very UseFul Link Here http://mattberseth.com
http://www.sqlmgmt.com/

How to Get Location Of any Control using Sys.UI.DomElement.getLocation class in Javascript

Hi
Today I want to share a small but very good javascript that is used to get the Location of any control by using the Control using Sys.UI.DomElement.getLocation Class..



Step 1:)
Write the HTML of any control , here suppose we are using the Button .
< id="Btn" text ="FindLocation" onclientclick= "return findLoc(this);" runat="server">

Step 2:)

Write the javascript like below...

function findLoc(ctrlBtn)
{
var location = Sys.UI.DomElement.getLocation(ctrlBtn);
alert(location.x);
alert(location.y);
alert(ctrlBtn.offsetWidth);
alert(ctrlBtn.offsetHeight)
return false;
}

Thanks:
Sanjeev Kumar

Monday, February 16, 2009

Simple Way to Use Cascading DropdownList

How to Use the Cascading Dropdown ? When You need Such type of requirment.Then Please follow the following Steps then You will find that it's very sipmle.
Step 1.) Adding Webservice to bind the Drop DownLIst
A.) Go to Website -> Add New Item ->Choose WebService ->Rename it as you want
(For Example here we have Taken the name of WebService "CascadingDataService.asmx")
B.) Write the CascadingDataService.cs code in App_Code folder as Given Below:-
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
///
/// Summary description for CascadingDataService
///

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class CascadingDataService : System.Web.Services.WebService
{
string conString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
public CascadingDataService()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownCountries(string knownCategoryValues, string category)
{
SqlConnection sqlConn = new SqlConnection(conString);
sqlConn.Open();
SqlCommand sqlSelect = new SqlCommand("select * from country order by rowid ", sqlConn);
sqlSelect.CommandType = System.Data.CommandType.Text;
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlSelect);
DataSet myDataset = new DataSet();
sqlAdapter.Fill(myDataset);
sqlConn.Close();
List cascadingValues = new List();
foreach (DataRow dRow in myDataset.Tables[0].Rows)
{
string categoryID = dRow["ID"].ToString();
string categoryName = dRow["CountryName"].ToString();
cascadingValues.Add(new AjaxControlToolkit.CascadingDropDownNameValue(categoryName, categoryID));
}
return cascadingValues.ToArray();
}
[WebMethod]
public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownStates(string knownCategoryValues, string category)
{
int categoryID;
StringDictionary categoryValues = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
categoryID = Convert.ToInt32(categoryValues["category"]);
SqlConnection sqlConn = new SqlConnection(conString);
sqlConn.Open();
SqlCommand sqlSelect = new SqlCommand("select * from state where CountryID = @categoryID", sqlConn);
sqlSelect.CommandType = System.Data.CommandType.Text;
sqlSelect.Parameters.Add("@categoryID", SqlDbType.Int).Value = categoryID;
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlSelect);
DataSet myDataset = new DataSet();
sqlAdapter.Fill(myDataset);
sqlConn.Close();
List cascadingValues = new List();
foreach (DataRow dRow in myDataset.Tables[0].Rows)
{
string SubcategoryID = dRow["Id"].ToString();
string SubcategoryName = dRow["StateName"].ToString();
cascadingValues.Add(new AjaxControlToolkit.CascadingDropDownNameValue(SubcategoryName, SubcategoryID));
}
return cascadingValues.ToArray();
}
}


Step 2.) HTML page where we want to use the Cascading DropDown List :

Country : < id="ddlCountry" runat="server">
< id="CascadingDropDown1" runat="server" category="category" targetcontrolid="ddlCountry" prompttext="--Select Country--" loadingtext="Loading countries..." servicepath="CascadingDataService.asmx" servicemethod="GetDropDownCountries"> < /ajaxToolkit:CascadingDropDown >
State : < id="ddlState" runat="server">
< id="CascadingDropDown2" runat="server" category="subcategory" targetcontrolid="ddlState" parentcontrolid="ddlCountry" prompttext="--Select State--" loadingtext="Loading states..." servicepath="CascadingDataService.asmx" servicemethod="GetDropDownProducts">
< /ajaxToolkit:CascadingDropDown >

By following the Steps described above can make easy to use the Cascading DropDown List.

Thanks:
Sanjeev Kumar

Tuesday, February 10, 2009

popup window which Show on full screen regardless of system resulation

Hi
Today we have to open a popup window which will show on fulll screen. and we can not set the resolution for it b'cz diff sys may have diff resolution we use screen.avilwidth and height peroperty) more detais are bellow :-

window.open("Default5.aspx",null,"fullscreen=yes,status=yes,toolbar=no,menuba
r=no,location=no");
window.resizeTo(screen.availWidth,screen.availHeight);testwindow.moveTo(0,0);//The code positions the popup on the top left corner
of the screen.


// fullscreen=yes it will show as window like when we press F11 button
Some genral features of popup window is shows in following ttable :-
status The status bar at the bottom of the window. toolbar The standard browser toolbar, with buttons such as Back and Forward. location The Location entry field where you enter the URL. menubar The menu bar of the window directories The standard browser directory buttons, such as What's New and
What's Cool resizable Allow/Disallow the user to resize the window. scrollbars Enable the scrollbars if the document is bigger than the window height Specifies the height of the window in pixels. (example: height='350') width Specifies the width of the window in pixels.

Thanks

Mahesh K. Sharma

Friday, February 6, 2009

Fire Item Command on DataList when CheckBox is Clicked

Hi
Today i am wondering to get a problem, when i fired a checkbox (postback enabled) will not wire up the item command on data list. and when i replace checkbox with button it works. 0) then i got a wise solution that keep a button in datalist and explicty genrate its click event when check box is clicked. for this i put code in item databound event of datalist.


// Find controls : -
CheckBox chk1 = (CheckBox)(e.Item.FindControl("chk1"));
Button Button1 = (Button)(e.Item.FindControl("Button1"));
// Add javasCript on onClick event to check box which call click evetnt of button. and after it
// Item command will fire

chk1.Attributes.Add("OnClick",
"javascript:document.getElementById('" + Button1.ClientID + "').click()");

Thansk
HelpOnDesk Team

Wednesday, February 4, 2009

javascript function for generate unique random number

I created a javascript function for generate unique random number. for this function i take object of date and call funciton of getTime() which return milliseconds since 970/01/01 and i also add some random numeric value between 0 to 999 from make it Random.

code snips is as

[script language="javascript"]

function UniqRanDomNumber()

{

var d = new Date();

var randomnumber = Math.floor(Math.random()*1001);

var randomnumber = d.getTime() + randomnumber;

//alert(randomnumber.toString().length);

//alert(randomnumber.toString().substring(6,13)); // If we want to remove right side number whihc are prefixed

document.getElementById("lbl").innerHTML = randomnumber;

return false;

}


[/script]

lbl is id of label where we want to show the uniq random nubmer.


Thanks
HelpOnDesk Team

Tuesday, February 3, 2009

Genrate non Repetitive Random Number.

HI,
Today I have to generate Non Repetitive random number. means a number may me 1234 but not 1224 means no same digit repeat on same number.

javascritp function is as follows :_

function generateRandomNumber(n)
{

if( n > 10)
{
alert('Please Enter 2 to 10');
return false;
}
var randomNo;
var finalArray=new Array();
while(finalArray.length < n)
{
randomNo = Math.floor(Math.random()*10);
if(finalArray.join('').indexOf(randomNo,0) == -1)
{
finalArray[finalArray.length] = randomNo;
}
}
document.getElementById("lbl").innerHTML = finalArray.join('');
return false;
}


Where lbl is id of label where we have to show the random number.

Thanks
Help OnDesk Team

Non Re

Some Important Interview Questions..

Hi ..

After a long long time I am here to post some interview questions on ASP.NET,
I hope that it will help you,


What is framework.
what is CLR? When its role comes?
What is connection pooling and object pooling? Difference
what is Authentication & authorization? types of authentication
what is customerror tag in web.config, its use
what is value type & ref type & where they are store.
what is assesmbly? types...
types of data control.
diff between server.transfer, server.execute & response.redirect
what is session management & types and diff?
how many column in datagrid and what r?
diff between datagrid, datalist, repeator ?
what are events of datagrid and sequence of execution?
what is Exception handling?
what is dataset, datareader, diff?
how many tables can be in dataset?
how to create COM+ in .net?
How to use com component in .net?
What is diff between metadata and menifest
What is http Handler?
What is serialization and its type?
What is uddi , soap , wsdl
What are the files required for deployment of the website?
what are different ways of debugging?
How can we debug an application if we do not have visual studio?
diff between web control , user control and custom control?
When to use remoting and when to use web service?
difference between interface and abstract classes?
From which class thus the web form is derived and what is its
heriarchy?
What is appsettings in web.config?
How we can use the com components in teh asp.net?
What is difference between UDF and stored procedures?
How we get values from stored procedure in asp.net code?
What is the purpose of abstract class?
What is diff between remoting and web service?
How many types of join are there in sql server?
What are different ways of authentication in .Net?
How the sessions are mantained in asp.net?
How we can transfer application from asp to asp.net?
what to do if i want that Class a can not be inherited?

1) What are ISAPI Filters?
2) What is process model in machine.config file?
3) Difference between inetinfo,aspnet_isapi.dll,aspnet_wp.
4) What are Composite controls in .Net ? How do u create them?
5) How can .Net assemblies be decompiled? What are the possible ways to prevent it?
6) Permission Settings in .Net
7) Difference between Http handlers & Http Modules.
8) Custom Configuration section of Web.Config?
9 Explain .Net remoting & its various communication channels
10) What are service oriented components?
11) Explain Serialization & various serialization formatters in .net
12) What is Event Bubbling?
13) How we can use the com components in the asp.net?

What is view state, session object ,cache object ,application object.
What is scope of view state, session object ,cache object ,application object.
Difference between cache object and application object.
Difference between interface and abstract class
What is data relation and write code that
What is trigger and types
Write code for abstract class, interface and define property in interface
Write query for second highest salary
If I use view state and go to second page and redirect to first page then view state maintain or not
On datagrid if I place button then what events will fire
If place datagrid inside another datagrid then what events will fire


Thank Guyes
HelpOnDesk Team

Monday, February 2, 2009

Calculate shipping charge with pay pal

Calculate shipping charge with pay pal

1) With Buy Now button
In this button we can add shipping cost with hidden filed named as shipping and set value of shipping cost. So is is fixed for that item. Sample code for this

[form id="Form2" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post"]

[input type="hidden" name="cmd" value="_ext-enter"]
[input type="hidden" name="redirect_cmd" value="_xclick"]
[input type="hidden" name="business" value="mca.mk_1233320111_biz@gmail.com"]
[input type="hidden" name="item_name" value="T-Shirt"]
[input type="hidden" name="amount" value="75.00"]

[input type="hidden" name="shipping" value="15.00"]

[input type="hidden" name="currency_code" value="USD"]
[input type="hidden" name="return" value="http://localhost/HTMLPAYPAL/Default2.aspx"]
[input type="hidden" name="cancel_return" value="http://localhost/HTMLPAYPAL/Default.aspx"]

[input type="submit" value="Buy Now" ]

[/form]

2) Two or more itmes clubed in on buy now button
In this button we add two different items under one click of buttons and set different different values of amount and shipping cost
using hidden value of shipping_x. means shipping_1 for first item and shipping_2 for second item and so on.

Sample code fro this is as follows :-

[form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post"]
[input type="hidden" name="cmd" value="_cart"]
[input type="hidden" name="upload" value="1"]
[input type="hidden" name="business" value="mca.mk_1233244379_biz@gmail.com"]
[input type="hidden" name="item_name_1" value="Pink glaf 1"]
[input type="hidden" name="amount_1" value="1.00"]
[input type="hidden" name="shipping_1" value="5.00" ]

[input type="hidden" name="item_name_2" value="IGreen glaf 2"]
[input type="hidden" name="amount_2" value="2.00"]
[input type="hidden" name="shipping_2" value="3.00" ]
[input type="submit" value="PayNow"]
[/form]



3) With Add to Cart button
In this button we add items in paypal shopping cart the shipment cost will override from value of shipping hiddn filed but when we increase quantity in cart and click on update button on paypal shopping the shipping cost will increase from the value of hidden fleld shipping2.

Sample code for this is as follows :-

[form target="paypal" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post"]
[input type="hidden" name="cmd" value="_cart"]
[input type="hidden" name="business" value="mca.mk_1233320111_biz@gmail.com"]
[input type="hidden" name="item_name" value="woolen Cap 1"]
[input type="hidden" name="item_number" value="WC1"]
[input type="hidden" name="currency_code" value="USD"]
[input type="hidden" name="amount" value="9.00"]

[input type="hidden" name="shipping" value="2.00"]
[input type="hidden" name="shipping2" value="1.00"]

[input type="hidden" name="return" value="http://localhost/HTMLPAYPAL/Default2.aspx"]
[input type="hidden" name="cancel_return" value="http://localhost/HTMLPAYPAL/Default.aspx"]



[input type="image" src="https://www.paypal.com/en_US/i/btn/x-click-but22.gif" border="0" name="submit" alt="Make payments with PayPal - it's fast, free and secure!"]
[input type="hidden" name="add" value="1"]
[/form]

if we [input type="hidden" name="shipping2" value="1.00"] set value of sipping2 is 0.00 then shipping cost will not increase for each additional item .

Thanks
HelpOnDesk Team

Friday, January 30, 2009

How to Integrate paypal with HTML

How to Integrate paypal with HTML

Paypal is very common payment gate way and mostly used in HTML ,PHP,.NET web sites for sub mit payment to vendor.


Now I am explain steps of integrating in Paypal in our application.

Suppose we have a page where we set the item and price and other inforamation in html hidden fields.
General structure of page is as follows.


[form id="Form1" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post"]
[input type="hidden" name="cmd" value="_xclick"] [input type="hidden" name="business" value="mca.mk_1233244379_biz@gmail.com"]
[input type="hidden" name="item_name" value="Item1"]
[input type="hidden" name="amount" value="100.00"]
[input type="hidden" name="currency_code" value="USD"]
[input type="hidden" name="return" value="http://localhost/eStoreFrontCS/Default2.aspx"]
[input type="hidden" name="cancel_return" value="http://localhost/eStoreFrontCS/Default.aspx"]
[asp:Label id="Label2" style="Z-INDEX: 101; LEFT: 784px; POSITION: absolute; TOP: 8px" runat="server"
ForeColor="White" BackColor="#C04000" Font-Bold="True" Width="20045px"]Loading payment process.....[/asp:Label]
[asp:Label id="Label3" style="Z-INDEX: 102; LEFT: 16px; POSITION: absolute; TOP: 8px" runat="server"
Font-Bold="True"]Wait ...[/asp:Label]
[/form]

In action tag we give the url of sandbox. This is starting step with paypal. Open the paypal.com

1)https://developer.paypal.com/ -] Signup now
2)after it you will recive a message “ Sandbox Signup Complete”
3)Check Email account which u specify in signup process. And click link for confermation.
4)Open paypal site with given link.
5)Choose option “Create a preconfigured buyer or seller account.” under TEST ACCOUNT tab.
6)Create a Buyer Account (Use to represent your customer's experience) must open “ Show Advanced Options “ link and give starting balance amout as 5000 USD or as your requirement. In Add note section copypaste the password so u can check it any time in test account secton.
7)Create a Seller Account (Use to represent yourself as the merchant) and also provide sum banalce under “ Show Advanced Options “ In Add note section copypaste the password so u can check it any time in test account secton.
8)Now the work with paypal site is over. Now come on your HTML page. And copy paste all code under form tag.
9)And after it put this script which submit page when it will load
10)[script language="JavaScript"]Form1.submit()[/script]
11) and now this will redirect u on this link https://www.sandbox.paypal.com/us/cgi-bin/webscr? With querystring.
12)Now in “ LOG IN TO PAYPAL “ frame put details of Buyer Account which u created for above code the details ar e as follows mca.mk_1233244323_per@gmail.com / pwd is testpwdtestpwd
13)enter pwd testpwdtestpwd
14) now confermation screen will come
15) Click on pay now button. And u wil get thanks msg window.
16)Now we have to check the effects on murchent and buyer account. So opent sandbox account.
17) Buyer account is debit form 100 USD
18)And murchant account is Credit by 96.8 USD.
Hope with above steps u can get basic idea of paypal account.

Thanks
HelpOnDesk Team

Friday, January 9, 2009

Retrive CSV from DATABASE

HI
Aprox in every project we need to send mail to all registred user then we can retrive emailAddress
in CSV format and form frontend we can fetch all values from for loop and send these emails to user
in single database cycle.

Basic example of this type SP is as follows :-


create proc SelectEmailAddressInCSV
as
set nocount on
DECLARE @xyz VARCHAR(100)
declare @abc varchar(100)

set @abc=''

declare selemail cursor for

select email from dataadi

open selemail
fetch NEXT from selemail into @xyz
WHILE @@Fetch_status = 0
begin


set @abc= @abc+ @xyz+','

FETCH NEXT FROM selemail INTO @xyz
END
print @abc
CLOSE selemail
DEALLOCATE selemail


Table of dataadi is as follows

CREATE TABLE [dbo].[dataadi](
[ID] [int] NOT NULL,
[FirstName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[LastName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Email] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
CONSTRAINT [PK_dataadi] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]


So Run this script and modified as your need


simppily we can add these three lines

DECLARE @values varchar(150), @delimiter char
SET @delimiter = ','
SELECT @values = COALESCE(@values + @delimiter, '') + u_name FROM tblsplit
SELECT @values AS [List of Emails]

Thanks
HelpOnDesk Team

Template for SP geting values one by one from CSV (Comma Seprated Values)

HI,
Many time we need to update many records in database. for example if we using select all check boxes for delete or update the reocrds then we can save the selected id corespondit to selected check boxes and then pass all vlues in dataset as the form of CSV and the with the help of following SP we can get values one by one and
fire the query.
Template for SP to get values one by one from CSV. suppy two inputs first the csv and then charter which i used for seprate the values



create proc [ufn_CountChar] ( @pInput VARCHAR(1000), @pSearchChar CHAR(1) )
as
BEGIN

/*DECLARE @vInputLength INT*/
DECLARE @vIndex INT
DECLARE @vCount INT
DECLARE @s varchar(2)
DECLARE @str varchar(10)
declare @SubStr varchar(1000)

set @SubStr=''
SET @vCount = 0
SET @vIndex = 1
/*SET @vInputLength = LEN(@pInput)*/
set @str=''

WHILE @vIndex <= len(@pInput)
BEGIN
IF SUBSTRING(@pInput, @vIndex, 1) = @pSearchChar
BEGIN
SET @vCount = @vCount + 1
set @SubStr = substring(@pInput,len(@SubStr),len( @str))
select 'update insert delete query with this value - ' + @str
set @str=''
END
else
BEGIN
set @s=SUBSTRING(@pInput,@vindex,1)
set @str=@str+@s
print ' i m in else part'+ space(3)+ @str
if( @vIndex = len(@pInput))
begin
select 'update insert delete query with this value - ' + @str
end

END
SET @vIndex = @vIndex + 1

END

--select @str


END
GO

--ufn_CountChar 'afd,hghg,hgjgh',','

uplaoding an image and creating Thumbnail of same image according to heigth and width

Hi
in this article we create a class for uplaoding an image and creating
Thumbnail of same image according to heigth and width of orignal image
means if we uplaod a landscapte image then its thumbnail will genrate as
landscape if image is as potrate its thumbnail will genrate as portrare.


call this function

thumbnail oANB = new thumbnail();
oANB.CreateThumb(FileUpload1, @"Images\", @"Images\Thumbnail\");
oANB.CreateThumb(FileUpload1, @"Images\");


create a class with following code.


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.Diagnostics;
using Microsoft.Win32;
using PAB.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

public class thumbnail
{

public string UploadImage(string filename, string filetype, string str_folder_name_main, string str_folder_name_small,

FileUpload fileupload1, int width, int heigh)
{

if (fileupload1.PostedFile.ContentType == "image/pjpeg" || fileupload1.PostedFile.ContentType == "image/jpeg" ||

fileupload1.PostedFile.ContentType == "image/bmp" || fileupload1.PostedFile.ContentType == "image/gif")
{

string typ = fileupload1.PostedFile.ContentType;

fileupload1.PostedFile.SaveAs( HttpContext.Current.Server.MapPath( str_folder_name_main + filename + filetype));

if (str_folder_name_small.CompareTo(string.Empty) != 0)
{

CreateThumbnail(HttpContext.Current.Server.MapPath(str_folder_name_main + filename + filetype), width, heigh,

HttpContext.Current.Server.MapPath(str_folder_name_small + filename + filetype), 25, 25);
}

return "1";
}
else
{
return "0";
}
}

public string CreateThumbnail(string lcFilename, int lnWidth, int lnHeight, string OutputFilename, int hightPercent, int

widthPercent)
{
try
{
System.Drawing.Bitmap bmpOut = null;
Bitmap loBMP = new Bitmap(lcFilename);
ImageFormat loFormat = loBMP.RawFormat;
System.Drawing.Imaging.EncoderParameters Params = new System.Drawing.Imaging.EncoderParameters(1);
Params.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
decimal lnRatio;
int thumbnamilHigth = Convert.ToInt32((loBMP.Height * hightPercent) / 100);
int thumbnamilWidth = Convert.ToInt32((loBMP.Width * widthPercent) / 100);

bmpOut = new Bitmap(thumbnamilHigth, thumbnamilWidth);

Graphics g = Graphics.FromImage(bmpOut);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.White, 0, 0, thumbnamilHigth, thumbnamilWidth);
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half;

g.DrawImage(loBMP, 0, 0, thumbnamilHigth, thumbnamilWidth);
loBMP.Dispose();

bmpOut.Save(OutputFilename, ImageFormat.Jpeg);
bmpOut.Dispose();

return OutputFilename;
}
catch(Exception Ex)
{
return Ex.Message.ToString();

}


}

public bool checkImageType(HtmlInputFile FileUpload1)
{
if (FileUpload1.PostedFile.ContentType == "image/pjpeg" || FileUpload1.PostedFile.ContentType == "image/jpeg" ||

FileUpload1.PostedFile.ContentType == "image/bmp" || FileUpload1.PostedFile.ContentType == "image/gif")
{
return true;
}
else
{
return false;
}
}

public string CreateThumb(FileUpload fileUpload, string actIm, string tmbIm)
{
try
{
string filename = string.Empty;
string imagename = string.Empty;

string imgtype = string.Empty;
thumbnail thumb = new thumbnail();
filename = fileUpload.PostedFile.FileName;

imagename = filename.Substring(filename.LastIndexOf("\\") + 1, (filename.LastIndexOf(".") - 1) -

(filename.LastIndexOf("\\")));
imagename = imagename + DateTime.Now.Ticks.ToString() + GenrateRandomIamgeName(3);
imgtype = filename.Substring(filename.LastIndexOf("."));

if (thumb.UploadImage(imagename, imgtype, actIm, tmbIm, fileUpload, 95, 143).Equals("1"))
{
return imagename + imgtype;
}
else
{
return "";
}
}
catch
{
return "";
}


}

public string CreateThumb(FileUpload fileUpload, string actIm)
{
try
{
string tmbIm = string.Empty;
string filename = string.Empty;
string imagename = string.Empty;

string imgtype = string.Empty;
thumbnail thumb = new thumbnail();
filename = fileUpload.PostedFile.FileName;

imagename = filename.Substring(filename.LastIndexOf("\\") + 1, (filename.LastIndexOf(".") - 1) -

(filename.LastIndexOf("\\")));
imagename = imagename + DateTime.Now.Ticks.ToString() + GenrateRandomIamgeName(3);
imgtype = filename.Substring(filename.LastIndexOf("."));

if (thumb.UploadImage(imagename, imgtype, actIm, tmbIm, fileUpload, 95, 143).Equals("1"))
{
return imagename + imgtype;
}
else
{
return "";
}
}
catch
{
return "";
}


}



public string GenrateRandomIamgeName(int Length)
{
string listOfCharacter = "abcdefghijkmnopqrstuvwxyz0123456789";
Random randNum = new Random();
char[] chars = new char[Length];
int allCharacterCount = listOfCharacter.Length;

for (int i = 0; i < Length; i++)
{
chars[i] = listOfCharacter[(int)((listOfCharacter.Length) * randNum.NextDouble())];
}

return new string(chars);
}


}


Thanks
HelpOnDesk Team

Tuesday, January 6, 2009

session expire problem.

Hi,

In many application we want to live session aprox 2 - 10 Hrs. If we set session time out 10 Hrs then it is extra overload of server.
If we want to live one page then we can apply following idea for solve this problem. just do something with client browser.
so called javaScript for replace image on client borowser. this way session wil never expire on specefic page.or do work with iframes reload.

Second Idea to remove this idea is :-

1)Always create cookie when u add any records in session and write cookie
when session is null after time out in that condition read values from
cookie. in this way u find values after session time out.


In javaScript section:-


[script language="javascript" type="text/javascript"]

function AlwaysLive(imgName) {
myImg = document.getElementById(imgName);
if (myImg) myImg.src = myImg.src.replace(/\?.*$/, '?' + Math.random());
}
window.setInterval("AlwaysLive('imgReload')", 100000); //100 seconds


[/script]



HTML:
[img id="imgReload" width="1" height="1" src="images/close_btn.gif?" alt="" /]

you must save the ? with image extension.

Thanks
HelpOnDesk Team

USE of GENRIC CLASSES

-------------USE GENRIC CLASSES-----------------
Mny friedns ask me how to use Genric in our application, and what is genric.
so second question is on your part what is genric. i m giving two simple but
quite important example of genric which suerly make u understand how to use
genric.

Generic Type
Generics introduce a flexibility that combines type safety with the ability to avoid committing
to a type at design time.
What
Generics enable class, delegate, interface, and struct types, and methods to be created with
type parameters that are placeholder types, which can be substituted when the type is known.
Where
Generics are commonly used in data structures—for example, collections and arrays, or in
passing method parameters.
 
Why
Generics overcome the overhead issues of casting and boxing between types, which adversely
affects performance.
How
Generics are specified within a pair of delimiters ("<" and ">") placed after the respective type
or method name. When the type is known, it is substituted for the generic placeholder, as the
following code snippet illustrates. Note that the method
GenericMethod is declared as generic,
as is its parameter. In the Main function, we vary the types of the method.
using System;
using System.Collections.Generic;
using System.Text;
namespace ModelT
{
public class ModelTGenerics
{
public static void GenericMethod(T arg)
{
Console.WriteLine("Calling Model T generic method, " + arg.GetType());
}
public static void Main()
{
//Call the generic method passing different types:
GenericMethod("Hallo Generics");
GenericMethod(16.75);
}
}
}
 
The Standard: Generic Type
The standard acknowledges the use of generics to reduce overhead and increase type
flexibility while retaining the protection of type safety.


In First example we pass two different type in single genric class.
In second example we get data with help of genric class.

First Example :-

add new page in ur test application and paste following code

protected void Page_Load(object sender, EventArgs e)
{
//create a string version of our generic class
Col mystring = new Col();
//set the value
mystring.Val = "hello";

//output that value
Response.Write("Value :- " + mystring.Val+"
");


//output the value's type
Response.Write("Type :- " + mystring.Val.GetType() + "
");

//create another instance of our generic class, using a different type
Col myint = new Col();
//load the value
myint.Val = 5;
//output the value
Response.Write("Value :- "+ myint.Val + "
");
//output the value's type
Response.Write("Type :- " + myint.Val.GetType() + "
");

}
public class Col
{
T t;
public T Val { get { return t; } set { t = value; } }
}



There are a few things to notice. The class name "Col" is our first indication that this Type is generic, specifically the

brackets containing the Type placeholder. This Type placeholder "T" is used to show that if we need to refer to the actual

Type that is going to be used when we write this class, we will represent it as "T". Notice on the next line the variable

declaration "T t;" creates a member variable with the type of T, or the generic Type which we will specify later during

construction of the class (it will actually get inserted by the Common Language Runtime (CLR) automatically for us). The

final item in the class is the public property. Again, notice that we are using the Type placeholder "T" to represent that

generic type for the type of that property. Also notice that we can freely use the private variable "t" within the class.

This example is form
and there is more example for genric on this page.

Second Example :-

In this example we get data with help of genric class

Step 1.
caeate a simple class as following.

using System;

///
/// Summary description for UserInfo
///

public class UserInfo
{
private string _userName = string.Empty;
private string _password = string.Empty;


public UserInfo(string userName, string password)
{
this._userName = userName;
this._password = password;
}

public string UserName
{
get
{
return _userName;
}
}

public string Password
{
get
{
return _password;
}
}
}

Step 2.

create genric class which uses its type as a above class

using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Collections;
using System.Data.SqlClient;

///
/// Summary description for genricList
///

public class genricList
{
public genricList()
{

}
public System.Collections.Generic.IList fillIlist()
{
string st = ConfigurationManager.ConnectionStrings[0].ToString();
IList userinfos = new List();
string connectionString = ConfigurationManager.ConnectionStrings["PUBSConnectionString"].ToString();
string queryString = "SELECT * FROM GenricLogin";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = queryString;

try
{
connection.Open();

SqlDataReader reader = command.ExecuteReader();

while (reader.Read())
{
UserInfo info = new UserInfo(reader[0].ToString(),reader[1].ToString());
userinfos.Add(info);

}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

return userinfos;
}
}

table structure

CREATE TABLE GenricLogin (username varchar(20), password varchar(20))

Insert some values in table

Insert into GenricLogin (username,password)

select 'aaaaa','111111'
union all
select 'bb','222222222'
union all
select 'ccc','33333333'


Step 3

now call this funciton on page and bind your dataGrid with genric

genricList objgenricList = new genricList();
dg.DataSource = objgenricList.fillIlist();
dg.DataBind();


with same way we can add as much classes as we required for bind different tables.


Thanks
HelpOnDesk Team

Monday, January 5, 2009

if session is expire then redirec user like yahoo email

This code is redirect user on page where we show that is current session expired
and relogin login so on defautl button NavigateUrl="~/Admin/Login.aspx" Text="Click here to Login again" becz it is on preRender event so first it will execte

protected void Page_PreRender(object sender, EventArgs e)
{
HttpContext.Current.Response.AppendHeader("Refresh", Convert.ToString(((HttpContext.Current.Session.Timeout * 60) - 5)) + "; Url=Default.aspx");

}

Thanks
HelpOnDesk Team

Genrate Random Password

Hi,

This fucntion is used for Genrate Password.

pass length of password for example GenrateRandomPassword(8);

for better result we can add timeTick for select integer or we can call to time this fuction recurlsivle
and then get substring portion for final password.

in my earlier post i also upload a dataBAse storeprocedure for caseSenstive password.

public static string GenrateRandomPassword(int PasswordLength)
{
string listOfCharacter = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789#$&@-";
Random randNum = new Random();
char[] chars = new char[PasswordLength];
int allCharacterCount = listOfCharacter.Length;

for (int i = 0; i < PasswordLength; i++)
{
chars[i] = listOfCharacter[(int)((listOfCharacter.Length) * randNum.NextDouble())];
}

return new string(chars);
}

Thanks
HelpOnDeskTeam

Print a file without open it but this code work only when we select websete as a filesystem :(

//this code alow print a document without open it. and this code allow pdf / txt/ //doc etc. but works only on filesystem website
/*System.Diagnostics.ProcessStartInfo PrintingProcess = new System.Diagnostics.ProcessStartInfo();
PrintingProcess.Verb = "print";
PrintingProcess.WindowStyle = ProcessWindowStyle.Hidden;
PrintingProcess.FileName = "c:/M.txt";//path for the file
PrintingProcess.UseShellExecute = true;
System.Diagnostics.Process.Start(PrintingProcess); */


The following code automaticaly close its print window un comment last three lines

Process PrintingProcess = new Process();
PrintingProcess.StartInfo.CreateNoWindow = false;
PrintingProcess.StartInfo.Verb = "print";
PrintingProcess.StartInfo.FileName = @"C:\m.txt";
PrintingProcess.Start();
//PrintingProcess.WaitForExit(10000);
//PrintingProcess.CloseMainWindow();
//PrintingProcess.Close();

Thanks
HelponDesk Team

Friday, January 2, 2009

Insert or Update Template for data base stored procedure

Create PROC InsertUpdatetemplate
-- This proc is used for insert or update records
-- it is simple sp with roll back transaction
-- so we have to just upload this format
(


)


as


IF (exists(SELECT * FROM tablename WHERE condition))
BEGIN
--Update
BEGIN TRY
BEGIN TRAN

UPDATE qery

COMMIT TRAN
RETURN 1
END TRY
BEGIN CATCH
ROLLBACK TRAN
SELECT ERROR_NUMBER()[ERROR NUMBER],ERROR_LINE()[ERROR IN LINE],ERROR_PROCEDURE()[ERROR IN PROCEDURE],ERROR_MESSAGE()[ERROR

MESSAGE]
RETURN 0
END CATCH



END
ELSE
BEGIN
-- Insert

BEGIN TRY
BEGIN TRAN

insert query

COMMIT TRAN
RETURN 1
END TRY
BEGIN CATCH
ROLLBACK TRAN
SELECT ERROR_NUMBER()[ERROR NUMBER],ERROR_LINE()[ERROR IN LINE],ERROR_PROCEDURE()[ERROR IN PROCEDURE],ERROR_MESSAGE()[ERROR

MESSAGE]
RETURN 0
END CATCH



END

do not print 'PRINT BUTTON ' on printed copy page

Steps .

1. Create a CSS
like
.print
{
dsplay:none;
}

2. Apply that CSS on those control which u dont want to print while printing

3. Add the refernce of style sheet file. in this case u have to set the media="print"

[link rel="stylesheet" type="text/css" href="Retailer/CSS/StyleSheet2.css" media="print"

/]

Thanks
HelpOnDesk Team

Why should I switch to CDOSYS when my current CDONTS code works great? send mail from cdosys and cdonts

Some time our emails bounce from SMTP SERVER. when i analysis the problem i got three way to send mail. with free SMTP SERVER like gmail. etc server OR USING CDOSYS OR CDONTS. BUT the question: "Why should I switch to CDOSYS when my current CDONTS code works great?". Let me give a few reasons:

* CDONTS has been deprecated in IIS5 and is completely removed from Windows Server 2003, and even Windows XP. Yes, it is

possible to install on Windows Server 2003 but with the performance improvements and other enhancements, there should be no

need to do so.
* CDOSYS carries less overhead than CDONTS.
* HTML functionality is much improved with automatic generation of the TextBody by just setting the HTMLBody property.
* There are some new properties and methods that should have been included with CDONTS but weren't.

in my earlier post i already explain the code of send mail via gmail server so now we will focus on.

USE CDONTS.DLL


STEP 1) AS WE DESCRIBED ABOVE THAT CDONTS.DLL ARE NO MORE OVER IN WINDOW FOLDER SO CONFIGURE IT WHITH THIS WAY

Start + Run, regsvr32 c:\cdonts.dll
OR
Start + Run + cmd,
in command type and run

]regsvr32 [path for dll]

now add refference of cdonts.dll

CDONTS.NewMail mailsend1 = new CDONTS.NewMail();

string From = "helpondesk@blogspot.com";
string Subject = "xxxxxxxxxxxxxxxxxxxxxx";
string Body = "[html][body][table border=0 cellpading=0 cellspacing=0][tr][td]hi from

cdonts[/td][/tr][/table][/body][/html]";
string To = "helpondesk@blogspot.com";
mailsend1.BodyFormat = 0;
mailsend1.MailFormat = 0;
mailsend1.Importance = Convert.ToInt32(CDONTS.CdoImportance.CdoHigh);
mailsend1.Send(From, To, Subject, Body, 1);

how to implement second dll CDOSYS

we can also configure cdosys dll with same way as codonts.dll

using System.Web.Mail;

MailMessage eMail = new MailMessage();
eMail.To = "helpondesk@blogspot.com";

eMail.Subject = " 2222222222";
eMail.Body = "[html][table][tr][td]HI THIS MAIL FROM CDOSYS SO HOW ARE YOU[/td][/tr][/table]";
// Smtp configuration
eMail.From = "helpondesk@blogspot.com";
eMail.Fields.Add(CDO.CdoConfiguration.cdoSMTPAuthenticate, "1");
eMail.Fields.Add(CDO.CdoConfiguration.cdoSendUserName, "helpondesk@blogspot.com");
eMail.Fields.Add(CDO.CdoConfiguration.cdoSendPassword, "mypwd");
SmtpMail.SmtpServer = "smpt.domain.com";
eMail.BodyFormat = MailFormat.Html;
SmtpMail.Send(eMail);


Thanks
HelpOnDesk Team

Thursday, January 1, 2009

Using PayPal Pro With ASP.Net application

Hi Everybody..
"How to use PayPal Pro Method in Asp.Net 2.0 web Application", this is topic for today which, I want to add as my latest post .I hope all of you are well aware of this.Yet I am adding this for quick reference.
You can also take an idea from HERE .
You have to add the following code in your page and modified it as per your need...


protected void Page_Load(object sender, EventArgs e)
{
// Do Your Other Task Here...
UpdatePaymentStatus();
}
protected void UpdatePaymentStatus()
{
#region Paypal Return
try
{
string status = GetSuccessStatus();
if (status != null && status != string.Empty)
{
if (status.Contains("success"))
{
// Do Your DatBase related things ag save the transaction details in DB
// for eg: userID ,Unit Price,And Total Amount or anyother thing as needed
}
if (status.Contains("failed"))
{
// do as per your Logic
}
}
}
catch (Exception Ex)
{
Session["errorMessage"] = Ex.Message.ToString();
//Response.Redirect("index.aspx");
}
#endregion
}
protected void ImgPayMent_Click(object sender, ImageClickEventArgs e)
{
amount = Convert.ToDouble(lblPrice.Text);
string redirect = "";

//redirect += "https://www.paypal.com/cgi-bin/webscr";
redirect += "https://www.sandbox.paypal.com/cgi-bin/webscr";
redirect += "?cmd=_xclick";
redirect += "&business=books._1235082065_biz@gmail.com ";
//Where abc@youdomain.com is Merchant account ID
redirect += "&item_name=" + "My Testing Purpose";
redirect += "&item_number=1";
redirect += "&amount=" + String.Format("{0:0.00} ", amount);// This is amount Double Type
redirect += "&currency_code=USD";
redirect += "&no_shipping=1";
redirect += "&no_note=1";
redirect += "&return=http://HomeUrlOfSite/Purchase.aspx/success/";
redirect += "&cancel_return=http://HomeUrlOfSite/Purchase.aspx/failed/"
Response.Redirect(redirect);
}
protected string GetSuccessStatus()
{
if (Request.PathInfo.Length == 0)
return "";
else if (Request.PathInfo.Contains("success"))
return "success";
else if (Request.PathInfo.Contains("failed"))
return "failed";
return "";
}
}

Thanks:...
Sanjeev Kumar
HelpOnDesk Team