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