Monday, August 3, 2009

Uploading files to FTP using .NET

public void Upload(string filename, string host, string username, string password)
{
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + host + "/" + fileInf.Name;
FtpWebRequest reqFTP = default(FtpWebRequest);

// Create FtpWebRequest object from the Uri provided
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + host + "/" + fileInf.Name));

// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(username, password);

// By default KeepAlive is true, where the control connection is not closed
// after a command is executed.
reqFTP.KeepAlive = false;

// Specify the command to be executed.
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

// Specify the data transfer type.
reqFTP.UseBinary = true;

// Notify the server about the size of the uploaded file
reqFTP.ContentLength = fileInf.Length;

// The buffer size is set to 2kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen = 0;

// Opens a file stream (System.IO.FileStream) to read the file to be uploaded
FileStream fs = fileInf.OpenRead();

try
{
// Stream to which the file to be upload is written
Stream strm = reqFTP.GetRequestStream();

// Read from the file stream 2kb at a time
contentLen = fs.Read(buff, 0, buffLength);

// Till Stream content ends
while (contentLen != 0)
{
// Write Content from the file stream to the FTP Upload Stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}

// Close the file stream and the Request Stream
strm.Close();
fs.Close();


}

catch (Exception ex)
{
MessageBox.Show(ex.Message, "Upload Error");
}
}

Use the above function with appropriate values

Downloading files from FTP using .NET

public void Download(string filePath, string fileName, string host, string username, string password)
{
FtpWebRequest reqFTP;

try
{
//filePath: The full path where the file is to be created.
//fileName: Name of the file to be createdNeed not name on
// the FTP server. name name()
FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + host + "/" + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(username, password);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];

readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}

ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}


Call this above function with appropriate parameter values

Converting hours to TimeSpan in .NET

double hour=3.5;
TimeSpan time = new TimeSpan(hour*TimeSpan.TicksPerHour);

Wednesday, July 15, 2009

Multiple line in C# .NET

string str = @" hello..
This is a
multi line content";

Sending Mail in .NET 2.0

try
{

System.Net.Mail.MailMessage obj = new System.Net.Mail.MailMessage();

String message =@ "Hello
";

// for sending html contents
obj.IsBodyHtml = true;

obj.BodyEncoding = System.Text.Encoding.UTF8;
obj.Subject = txtNature.Text ;
obj.From = new System.Net.Mail.MailAddress("From Address");
obj.To.Add("To Address")
obj.Body = message;

System.Net.Mail.SmtpClient cli = new System.Net.Mail.SmtpClient();
cli.Host = "host IP or host address";//can give localhost
cli.Send(obj);

}
catch (Exception ex)
{
}

Friday, March 20, 2009

Detect SHIFT, ALT, CTRL & character key example

Write these inside a script tag

document.onkeydown = KeyDownHandler;

document.onkeyup = KeyUpHandler;



var CTRL = false;

var SHIFT = false;

var ALT = false;

var CHAR_CODE = -1;



function KeyDownHandler(e)

{

var x = '';

if (document.all)

{

var evnt = window.event;

x = evnt.keyCode;

}

else

{

x = e.keyCode;

}

DetectKeys(x, true);

ShowReport();

}



function KeyUpHandler(e)

{

var x = '';

if (document.all)

{

var evnt = window.event;

x = evnt.keyCode;

}

else

{

x = e.keyCode;

}

DetectKeys(x, false);

ShowReport();

}



function DetectKeys(KeyCode, IsKeyDown)

{

if (KeyCode == '16')

{

SHIFT = IsKeyDown;

}

else if (KeyCode == '17')

{

CTRL = IsKeyDown;

}

else if (KeyCode == '18')

{

ALT = IsKeyDown;

}

else

{

if(IsKeyDown)

CHAR_CODE = KeyCode;

else

CHAR_CODE = -1;

}

}



function ShowReport()

{

var TBReport = document.getElementById("tbReport");
//tbReport is textbox control with id=tbReport

var DIVCtrl = document.getElementById("IsCtrl");

var DIVShift = document.getElementById("IsShift");

var DIVAlt = document.getElementById("IsAlt");

var DIVChar = document.getElementById("IsChar");



document.title = 'SHIFT: ' + SHIFT + ', CTRL: ' + CTRL + ', ALT: ' + ALT + ', Char code is: ' + CHAR_CODE;

TBReport.value = document.title;



if(SHIFT)

DIVShift.style.visibility = "visible";

else

DIVShift.style.visibility = "hidden";



if(ALT)

DIVAlt.style.visibility = "visible";

else

DIVAlt.style.visibility = "hidden";



if(CTRL)

DIVCtrl.style.visibility = "visible";

else

DIVCtrl.style.visibility = "hidden";

}

How to use Repeater Control

One of important goals of any application development process is making data presentation richer. ASP.NET 2.0 provides many server controls which render data in different rich formats and styles.

For example, DataGrid control is suitable in many scenarios where you wish to display data in a grid like representation for easy understanding. Similarly, if the situation demands for rendering list like data, you can consider using of DataLists and Repeater server controls.

Repeater control is a container control which is template based with no basic rendering of its own. This way, you define layout for the Repeater control by creating different templates based on your needs. You can create different kinds of lists using Repeater control including Table, Comma-separated list and XML formatted list.

Repeater Control Templates

Repeater controls provides different kinds of templates which helps in determining the layout of control's content. Templates generate markup which determine final layout of content.

Repeater control is an iterative control in the sense it loops each record in the DataSource and renders the specified template (ItemTemplate) for each record in the DataSource collection. In addition, before and after processing the data items, the Repeater emits some markup for the header and the footer of the resulting structure

Repeater control supports five templates which are as follows:

  • ItemTemplate

  • AlternatingItemTemplate

  • HeaderTemplate

  • FooterTemplate

  • SeparatorTemplate

ItemTemplate: ItemTemplate defines how the each item is rendered from data source collection.

AlternatingItemTemplate: AlternatingItemTemplates define the markup for each Item but for AlternatingItems in DataSource collection like different background color and styles.

HeaderTemplate: HeaderTemplate will emit markup for Header element for DataSource collection

FooterTemplate: FooterTemplate will emit markup for footer element for DataSource collection

SeparatorTemplate: SeparatorTemplate will determine separator element which separates each Item in Item collection. Usually, SeparateTemplate will be
html element or


html element.

DataBinding in Repeater Control

Like any other Data Bound control, Repeater control supports DataSource property which allows you to bind any valid DataSource like sqlDataSource, XML file or any datasets which implements ICollection, IEnumerable or IListSource Interfaces.

The data in DataSource is bound to Repeater using its DataBind Method. Once the data is bound, the format of each data item is defined by a template like ItemTemplate.

Adding Repeater server control to ASP.NET page


Add any Data Source control to the page such as sqlDataSource or AccessDataSource. Configure Data Source control such that you specify connection information and perform query.

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address], [City], [Region], [PostalCode] FROM [Customers]">asp:SqlDataSource>

Drag and Drop Repeater control from Data section of the Toolbox onto the page.

<asp:Repeater ID="Repeater1" DataSourceID="SqlDataSource1" runat="server" asp:Repeater>

Set the DataSourceID property of Repeater Control to newly configured sqlDataSource control as shown above.

Add an element into the page as a child of the Repeater control. The Repeater control must contain at least an ItemTemplate that in turn contains data-bound controls in order for the control to render at run time.

Embed HTML markup and Web server controls or HTML server controls to the ItemTemplate to render data at run time

Bind the child controls to data from the query using the Eval data-binding function.

Following example shows how to use Repeater control to display data in a HTML table.

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<HeaderTemplate>
<table border="1" cellpadding="5" cellspacing="2">
<tr bgcolor="gray">
<td><b>CompanyNameb>
td>
<td><b>Cityb>td>
tr>
HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%#DataBinder.Eval(Container.DataItem, "CompanyName")%>
td>
<td>
<%#DataBinder.Eval(Container.DataItem, "City")%>
td>
tr>
ItemTemplate>
<AlternatingItemTemplate >
<tr bgcolor="aqua" >
<td>
<%#DataBinder.Eval(Container.DataItem, "CompanyName")%>
td>
<td>
<%#DataBinder.Eval(Container.DataItem, "City")%>
td>
tr>
AlternatingItemTemplate>
<FooterTemplate>
table>
FooterTemplate>
asp:Repeater>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address], [City], [Region], [PostalCode] FROM [Customers]">asp:SqlDataSource>


Repeater Control in action

The Databinder.Eval method uses reflection to parse and evaluate a data-binding expression against an object at run time; in this case the object is our Repeater. So this line of code:

<%#DataBinder.Eval(Container.DataItem, "CompanyName")%>

It will render the contents of the "CompanyName" field for each row in the DataSource Collection.