August 31, 2004

Understanding the difference between COM, DCOM and Service

August 28, 2004

Multi-select ASP.NET datagrid

How to extend ASP.NET datagrid for multi-selection of data rows?

Clcik the joint link to know how it works.

August 27, 2004

Rotating Is Fun

Linked article describes the creation of a simple "content rotator" in ASP.NET

Web Site Operations in ASP.NET 2.0

Discusses how ASP.NET 2.0, Internet Information Services 6.0, and the Microsoft .NET Framework 2.0 make deploying, configuring, monitoring, and maintaining Web applications easier than ever before. Gives an overview of how to perform IT operations with ASP.NET 2.0 and IIS 6.0.

August 26, 2004

Export Report Utility

public static bool ExportReport(ReportDocument crReportDocument, string ExpType,string ExportPath, string filename)
{
//creating full report file name for example if the filename was "MyReport1"
//and ExpType was "pdf", full file name will be "MyReport1.pdf"
filename = filename + "." + ExpType;

//creating storage directory if not exists
if (!Directory.Exists(ExportPath))
Directory.CreateDirectory(ExportPath);

//creating new instance representing disk file destination options such as filename, export type etc.
DiskFileDestinationOptions crDiskFileDestinationOptions = new DiskFileDestinationOptions();
ExportOptions crExportOptions = crReportDocument.ExportOptions;


switch(ExpType)
{
case "rtf":
{
//setting disk file name
crDiskFileDestinationOptions.DiskFileName = ExportPath + filename;
//setting destination type in our case disk file
crExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
//setuing export format type
crExportOptions.ExportFormatType = ExportFormatType.RichText;
//setting previously defined destination opions to our input report document
crExportOptions.DestinationOptions = crDiskFileDestinationOptions;
break;
}
//NOTE following code is similar to previous, so I want comment it again
case "pdf":
{
crDiskFileDestinationOptions.DiskFileName = ExportPath + filename;
crExportOptions.DestinationOptions = crDiskFileDestinationOptions;
crExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
crExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
break;
}
case "doc":
{
crDiskFileDestinationOptions.DiskFileName = ExportPath + filename;
crExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
crExportOptions.ExportFormatType = ExportFormatType.WordForWindows;
crExportOptions.DestinationOptions = crDiskFileDestinationOptions;
break;
}
case "xls":
{
crDiskFileDestinationOptions.DiskFileName = ExportPath + filename;
crExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
crExportOptions.ExportFormatType = ExportFormatType.Excel;
crExportOptions.DestinationOptions = crDiskFileDestinationOptions;
break;
}
case "rpt":
{
crDiskFileDestinationOptions.DiskFileName = ExportPath + filename;
crExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
crExportOptions.ExportFormatType = ExportFormatType.CrystalReport;
crExportOptions.DestinationOptions = crDiskFileDestinationOptions;
break;
}
case "htm":
{
HTMLFormatOptions HTML40Formatopts = new HTMLFormatOptions();
crExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
crExportOptions.ExportFormatType = ExportFormatType.HTML40;
HTML40Formatopts.HTMLBaseFolderName = ExportPath + filename;
HTML40Formatopts.HTMLFileName = "HTML40.html";
HTML40Formatopts.HTMLEnableSeparatedPages = true;
HTML40Formatopts.HTMLHasPageNavigator = true;
HTML40Formatopts.FirstPageNumber = 1;
HTML40Formatopts.LastPageNumber = 3;
crExportOptions.FormatOptions = HTML40Formatopts;
break;
}

}
try
{
//trying to export input report document, and if success returns true
crReportDocument.Export();
return true;
}
catch (Exception e)
{
throw e;
}
}

///


/// Export report to byte array
///

/// ReportDocument
/// CrystalDecisions.Shared.ExportFormatType
/// byte array representing current report
public static byte[] ExportReportToStream(ReportDocument crReportDocument,ExportFormatType exptype)
{//this code exports input report document into stream, and returns array of bytes

Stream st;
st = crReportDocument.ExportToStream(exptype);

byte[] arr = new byte[st.Length];
st.Read(arr,0,(int) st.Length);

return arr;

}

///
/// Export report to string
///

/// ReportDocument
/// byte unicode string representing current report
public static string ExportReportToString(ReportDocument crReportDocument)
{
Stream st;
st = crReportDocument.ExportToStream(ExportFormatType.PortableDocFormat);

byte[] arr = new byte[st.Length];
st.Read(arr,0,(int) st.Length);

string rep = new UnicodeEncoding().GetString(arr);

return rep;
}

Introduction to .NET Assemblies - Beginner

You must have heard the word assembly many times in .NET documentation. In this article I will share some thing about .NET assemblies.

How to display an assembly in "Add References"

When you are developing a class library, you may want Visual Studio .NET to list your library in the Add Reference dialog box on the .NET tab without the user having to browse for it.
.NET Classes used :

This issue is not resolved if you install your assembly to the Global Assembly Cache (GAC), because the Add Reference dialog box is path-based and does not enumerate the components from the GAC.

To display your assembly in the Add Reference dialog box, you can add a registry key, such as the following, which points to the location of the assembly
[HKEY_CURRENT_USER\SOFTWARE\Microsoft\.NETFramework\AssemblyFolders\MyAssemblies]@="C:\\MyAssemblies"

--where MyAssemblies is the name of the folder in which the assemblies reside.

NOTE: You can create the this registry entry under the HKEY_LOCAL_MACHINE hive. This will change the setting for all of the users on the system. If you create this registry entry under HKEY_CURRENT_USER, this entry will affect the setting for only the current user.

Restart Visual Studio .NET after you have added the key.

MORE INFO:

Microsoft recommends that you not install your assemblies to the GAC, unless you want to share your assemblies with other applications running on that system.

Installing an Assembly in GAC (Global Assembly Cache)

To share assemblies within an ASP.NET web application they are required to be placed within the \bin directory, but in order to share them through different applications existing on the same web server it is required to install them into the Global Assembly Cache (GAC). This article will provide guidance to you in the process of adding an assembly to the GAC.

URL Rewriting with ASP.NET

Demonstrates the use of regular expression-based URL Rewriting, similar to mod_rewrite with ASP.NET

.NET Framework Glossary

This glossary provides definitions for key .NET Framework terminology.

August 23, 2004

Cross-Page request in ASP.Net 2.0

A full discriptive article on how cross-page request can be handled and how it owrks.

ASP.Net 2.0 Client Callbacks, makes remote scripting easier.

A full description on what is Client-side Callback, and how it works with code sample. Click on the link have a nice journey on Client Callbacks. :)

FTP Factory class in C#

/*
FTPFactory.cs
Better view with tab space=4

Written by Jaimon Mathew (jaimonmathew@rediffmail.com)
Rolander,Dan (Dan.Rolander@marriott.com) has modified the download
method to cope with file name with path information. He also
provided the XML comments so that the library provides Intellisense
descriptions.
*/

using System;
using System.Net;
using System.IO;
using System.Text;
using System.Net.Sockets;

namespace Common
{
///


/// This class provides the functionality for FTP Server connection
/// and related functions.
///

public class FTPFactory
{
private string remoteHost,remotePath,remoteUser,remotePass,mes;
private int remotePort,bytes;
private Socket clientSocket;

private int retValue;
private Boolean debug;
private Boolean logined;
private string reply;

private static int BLOCK_SIZE = 512;

Byte[] buffer = new Byte[BLOCK_SIZE];
Encoding ASCII = Encoding.ASCII;

///
/// Default constuctor for FTP Factory class
///

public FTPFactory()
{
remoteHost = "localhost";
remotePath = ".";
remoteUser = null;
remotePass = null;
remotePort = 21;
debug = false;
logined = false;
}

///
/// Sets the name of the FTP server to connect to
///

/// Remote host Name
public void setRemoteHost(string remoteHost)
{
this.remoteHost = remoteHost;
}

///
/// Returns the name of the current FTP server
///

/// Host Name
public string getRemoteHost()
{
return remoteHost;
}

///
/// Sets the port number to use for FTP.
///

/// Port number
public void setRemotePort(int remotePort)
{
this.remotePort = remotePort;
}

///
/// Returns the current port number.
///

/// Current port number
public int getRemotePort()
{
return remotePort;
}

///
/// Sets the remote directory path.
///

/// The remote directory path
public void setRemotePath(string remotePath)
{
this.remotePath = remotePath;
}

///
/// Return the current remote directory path.
///

/// The current remote directory path.
public string getRemotePath()
{
return remotePath;
}

///
/// Sets the user name to use for logging into the remote server.
///

/// Username
public void setRemoteUser(string remoteUser)
{
this.remoteUser = remoteUser;
}

///
/// Sets the password to user for logging into the remote server.
///

/// Password
public void setRemotePass(string remotePass)
{
this.remotePass = remotePass;
}

///
/// Returns a string array containing the remote directory's file list.
///

/// Mask to be used for filteration
/// List of files in string array format
public string[] getFileList(string mask)
{
if(!logined)
{
login();
}

Socket cSocket = createDataSocket();

sendCommand("NLST " + mask);

if(!(retValue == 150 || retValue == 125))
{
throw new IOException(reply.Substring(4));
}

mes = "";

while(true)
{
int bytes = cSocket.Receive(buffer, buffer.Length, 0);
mes += ASCII.GetString(buffer, 0, bytes);

if(bytes < buffer.Length)
{
break;
}
}

char[] seperator = {'\n'};
string[] mess = mes.Split(seperator);

cSocket.Close();

readReply();

if(retValue != 226)
{
throw new IOException(reply.Substring(4));
}
return mess;
}

///
/// Returns the size of a file.
///

/// Name of the file for which the size is required
/// size in long format
public long getFileSize(string fileName)
{
if(!logined)
{
login();
}

sendCommand("SIZE " + fileName);
long size=0;

if(retValue == 213)
{
size = Int64.Parse(reply.Substring(4));
}
else
{
throw new IOException(reply.Substring(4));
}

return size;
}

///
/// Login to the remote server.
///

public void login()
{
clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(Dns.Resolve(remoteHost).AddressList[0], remotePort);

try
{
clientSocket.Connect(ep);
}
catch(Exception)
{
throw new IOException("Couldn't connect to remote server");
}

readReply();
if(retValue != 220)
{
close();
throw new IOException(reply.Substring(4));
}
if(debug)
Console.WriteLine("USER "+remoteUser);

sendCommand("USER "+remoteUser);

if( !(retValue == 331 || retValue == 230) )
{
cleanup();
throw new IOException(reply.Substring(4));
}

if( retValue != 230 )
{
if(debug)
Console.WriteLine("PASS xxx");

sendCommand("PASS "+remotePass);
if( !(retValue == 230 || retValue == 202) )
{
cleanup();
throw new IOException(reply.Substring(4));
}
}

logined = true;
Console.WriteLine("Connected to "+remoteHost);

chdir(remotePath);
}

///
/// Sets the mode for file transfer
///

/// Value of the Mode, if the value of mode is true, set binary mode for downloads, else set Ascii mode.
public void setBinaryMode(Boolean mode)
{
if(mode)
{
sendCommand("TYPE I");
}
else
{
sendCommand("TYPE A");
}
if (retValue != 200)
{
throw new IOException(reply.Substring(4));
}
}

///
/// Download a file to the Assembly's local directory, keeping the same file name.
///

/// File to be downlaoded
public void download(string remFileName)
{
download(remFileName,"",false);
}

///
/// Download a remote file to the Assembly's local directory,
/// keeping the same file name, and set the resume flag.
///

/// File to be downlaoded
/// Flag to set if the resume is managed or not
public void download(string remFileName,Boolean resume)
{
download(remFileName,"",resume);
}

///
/// Download a remote file to a local file name which can include
/// a path. The local file name will be created or overwritten,
/// but the path must exist.
///

/// File to be downlaoded
/// Local file name
public void download(string remFileName,string locFileName)
{
download(remFileName,locFileName,false);
}

///
/// Download a remote file to a local file name which can include
/// a path, and set the resume flag. The local file name will be
/// created or overwritten, but the path must exist.
///

/// File to be downlaoded
/// Local file name
/// Flag stating if it is required to set the resume
public void download(string remFileName,string locFileName,Boolean resume)
{
if(!logined)
{
login();
}

setBinaryMode(true);

Console.WriteLine("Downloading file "+remFileName+" from "+remoteHost + "/"+remotePath);

if (locFileName.Equals(""))
{
locFileName = remFileName;
}

if(!File.Exists(locFileName))
{
Stream st = File.Create(locFileName);
st.Close();
}

FileStream output = new FileStream(locFileName,FileMode.Open);

Socket cSocket = createDataSocket();

long offset = 0;

if(resume)
{

offset = output.Length;

if(offset > 0 )
{
sendCommand("REST "+offset);
if(retValue != 350)
{
//throw new IOException(reply.Substring(4));
//Some servers may not support resuming.
offset = 0;
}
}

if(offset > 0)
{
if(debug)
{
Console.WriteLine("seeking to " + offset);
}
long npos = output.Seek(offset,SeekOrigin.Begin);
Console.WriteLine("new pos="+npos);
}
}

sendCommand("RETR " + remFileName);

if(!(retValue == 150 || retValue == 125))
{
throw new IOException(reply.Substring(4));
}

while(true)
{
bytes = cSocket.Receive(buffer, buffer.Length, 0);
output.Write(buffer,0,bytes);

if(bytes <= 0)
{
break;
}
}

output.Close();
if (cSocket.Connected)
{
cSocket.Close();
}

Console.WriteLine("");

readReply();

if( !(retValue == 226 || retValue == 250) )
{
throw new IOException(reply.Substring(4));
}
}

///
/// Uploads a file
///

/// File name to be uplaoded
public void upload(string fileName)
{
upload(fileName,false);
}

///
/// Upload a file and set the resume flag.
///

/// File name to be uplaoded
/// Flag to set if the operation needs the resume functionality
public void upload(string fileName,Boolean resume)
{
if(!logined)
{
login();
}

Socket cSocket = createDataSocket();
long offset=0;

if(resume)
{
try
{
setBinaryMode(true);
offset = getFileSize(fileName);
}
catch(Exception)
{
offset = 0;
}
}

if(offset > 0 )
{
sendCommand("REST " + offset);
if(retValue != 350)
{
//throw new IOException(reply.Substring(4));
//Remote server may not support resuming.
offset = 0;
}
}

sendCommand("STOR "+Path.GetFileName(fileName));

if( !(retValue == 125 || retValue == 150) )
{
throw new IOException(reply.Substring(4));
}

// open input stream to read source file
FileStream input = new FileStream(fileName,FileMode.Open);

if(offset != 0)
{
if(debug)
{
Console.WriteLine("seeking to " + offset);
}
input.Seek(offset,SeekOrigin.Begin);
}

Console.WriteLine("Uploading file "+fileName+" to "+remotePath);

while ((bytes = input.Read(buffer,0,buffer.Length)) > 0)
{
cSocket.Send(buffer, bytes, 0);
}
input.Close();

Console.WriteLine("");

if (cSocket.Connected)
{
cSocket.Close();
}

readReply();
if( !(retValue == 226 || retValue == 250) )
{
throw new IOException(reply.Substring(4));
}
}

///
/// Deletes a file from the remote FTP server.
///

/// File name to be deleted
public void deleteRemoteFile(string fileName)
{

if(!logined)
{
login();
}

sendCommand("DELE "+fileName);

if(retValue != 250)
{
throw new IOException(reply.Substring(4));
}
}

///
/// Renames a file on the remote FTP server.
///

/// Old File Name
/// New File Name
public void renameRemoteFile(string oldFileName,string newFileName)
{
if(!logined)
{
login();
}

sendCommand("RNFR "+oldFileName);

if(retValue != 350)
{
throw new IOException(reply.Substring(4));
}

// known problem
// rnto will not take care of existing file.
// i.e. It will overwrite if newFileName exist
sendCommand("RNTO "+newFileName);
if(retValue != 250)
{
throw new IOException(reply.Substring(4));
}
}

///
/// Creates a directory on the remote FTP server.
///

/// Name of the directory
public void mkdir(string dirName)
{
if(!logined)
{
login();
}

sendCommand("MKD "+dirName);

if(retValue != 250)
{
throw new IOException(reply.Substring(4));
}
}

///
/// Deletes a directory on the remote FTP server.
///

/// Removes the directory
public void rmdir(string dirName)
{
if(!logined)
{
login();
}

sendCommand("RMD "+dirName);

if(retValue != 250)
{
throw new IOException(reply.Substring(4));
}
}

///
/// Change the current working directory on the remote FTP server.
///

/// New directory Name
public void chdir(string dirName)
{
if(dirName.Equals("."))
{
return;
}

if(!logined)
{
login();
}

sendCommand("CWD "+dirName);

if(retValue != 250)
{
throw new IOException(reply.Substring(4));
}

this.remotePath = dirName;

Console.WriteLine("Current directory is "+remotePath);
}

///
/// Close the FTP connection.
///

public void close()
{
if( clientSocket != null )
{
sendCommand("QUIT");
}
cleanup();
Console.WriteLine("Closing...");
}

///
/// Set debug mode.
///

///
public void setDebug(Boolean debug)
{
this.debug = debug;
}

// Reads a reply from the server
private void readReply()
{
mes = "";
reply = readLine();
retValue = Int32.Parse(reply.Substring(0,3));
}

// Clean up the socket connections
private void cleanup()
{
if(clientSocket!=null)
{
clientSocket.Close();
clientSocket = null;
}
logined = false;
}

// Read line
private string readLine()
{
while(true)
{
bytes = clientSocket.Receive(buffer, buffer.Length, 0);
mes += ASCII.GetString(buffer, 0, bytes);
if(bytes < buffer.Length)
{
break;
}
}

char[] seperator = {'\n'};
string[] mess = mes.Split(seperator);

if(mes.Length > 2)
{
mes = mess[mess.Length-2];
}
else
{
mes = mess[0];
}

if(!mes.Substring(3,1).Equals(" "))
{
return readLine();
}

if(debug)
{
for(int k=0;k < mess.Length-1;k++)
{
Console.WriteLine(mess[k]);
}
}
return mes;
}

private void sendCommand(String command)
{
Byte[] cmdBytes = Encoding.ASCII.GetBytes((command+"\r\n").ToCharArray());
clientSocket.Send(cmdBytes, cmdBytes.Length, 0);
readReply();
}

private Socket createDataSocket()
{
sendCommand("PASV");

if(retValue != 227)
{
throw new IOException(reply.Substring(4));
}

int index1 = reply.IndexOf('(');
int index2 = reply.IndexOf(')');
string ipData = reply.Substring(index1+1,index2-index1-1);
int[] parts = new int[6];

int len = ipData.Length;
int partCount = 0;
string buf="";

for (int i = 0; i < len && partCount <= 6; i++)
{
char ch = Char.Parse(ipData.Substring(i,1));
if (Char.IsDigit(ch))
buf+=ch;
else if (ch != ',')
{
throw new IOException("Malformed PASV reply: " + reply);
}

if (ch == ',' || i+1 == len)
{
try
{
parts[partCount++] = Int32.Parse(buf);
buf="";
}
catch (Exception)
{
throw new IOException("Malformed PASV reply: " + reply);
}
}
}

string ipAddress = parts[0] + "."+ parts[1]+ "." + parts[2] + "." + parts[3];

int port = (parts[4] << 8) + parts[5];

Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(Dns.Resolve(ipAddress).AddressList[0], port);

try
{
s.Connect(ep);
}
catch(Exception)
{
throw new IOException("Can't connect to remote server");
}
return s;
}
}
}

POP Client in C#

/*
POPClient class provides some methods to connect to a POP server and work with the emails.
Some functionality is implemented using public methods.
Open - Open Connection to the POP server, Login and Get Status
Close - QUIT and close the streams
Login - Login to the POP mail account
GetStatus - Retrieves the status of the account (Number of mails and total size of the mails (returned as a long array of two elements, first being the message count). It also initialises the member variables that are accessible through properties MessageCount and TotalSize
GetList - Returns ArrayList that has long elements representing the size of each mail
GetHeader - Accepts a message number as argument (starting from 1 and not 0) and returns Hashtable with some common header elements, and entire header as string. e.g. MESSAGEID_FIELD, FROM_FIELD, HEADER_FIELD, etc.
GetMessage - Retrieves given message
DeleteMessage - Deletes given message from the POP server

In addition, there are two generic methods to send other commands to the server.
[b]SendCommand(POPCommands)[/b]
It sends given command to the server without any arguments
[b]SendCommand(POPCommands, string)[/b]
It sends given command to the server with given arguments (a string with blank separated arguments)

These two methods will not raise an exception in case the server returns an error message.

Server returns '[b]+OK[/b]' followed by the result data in case the command is successful.
The result can be of two types, multi-line and single-line.
Multi-line results end with a line having only one character '.', these results do not have any data in the first line (+OK)
e.g. For command "LIST" the result would be

[code]+OK
1 1451
2 10359
.[/code]

An example of single-line result.
For command "STAT":
[code]+OK 2 11810[/code]

All the possible commands are defined in the [b]POPCommands[/b] enum.

[b]multilineCommands[/b] Hashtable stores all the commands that return multi-line result.

In case of an error, the server returns message with prefix "-ERR", e.g.
-ERR not that many messages
(returned if "LIST n" command is given and there are less than n mails in account)
*/

using System;
using System.Collections;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;

namespace Common
{
///


/// Summary description for POPClient.
///

public class POPClient
{
public enum POPCommands
{
USER,
PASS,
QUIT,
STAT,
LIST,
RETR,
DELE,
NOOP,
LAST,
RSET,
TOP,
//RPOP,
}
public const string CRLF = "\r\n";
public const string MESSAGEID_FIELD = "messageid";
public const string FROM_FIELD = "from";
public const string FROMEMAIL_FIELD = "fromemail";
public const string REPLYTO_FIELD = "replyto";
public const string REPLYTOEMAIL_FIELD = "replytoemail";
public const string TO_FIELD = "to";
public const string CC_FIELD = "cc";
public const string SUBJECT_FIELD = "subject";
public const string HEADER_FIELD = "header";
public const int RECEIVETIMEOUT = 20000;

public static Hashtable multilineCommands;

static POPClient()
{
multilineCommands = new Hashtable();
multilineCommands.Add(POPCommands.LIST,true);
multilineCommands.Add(POPCommands.RETR,false);
multilineCommands.Add(POPCommands.TOP,false);
}

private bool isopen;
private string serveraddress;
private int port;
private string username;
private string password;

private string connresponse;
private long msgcount;
private long totalsize;

public bool IsOpen
{
get { return isopen; }
}

public string ServerAddress
{
get { return serveraddress; }
set { serveraddress = value; }
}

public int Port
{
get { return port; }
set { port = value; }
}

public string UserName
{
get { return username; }
set { username = value; }
}

public string Password
{
get { return password; }
set { password = value; }
}

public string ConnectionResponse
{
get { return connresponse; }
}

public long MessageCount
{
get { return msgcount; }
}

public long TotalSize
{
get { return totalsize; }
}

private TcpClient server;
private NetworkStream writer;
private StreamReader reader;

public POPClient()
{
port = 110;
isopen = false;
}

protected void Dispose( bool disposing )
{
if( disposing )
{
Close();
}
}

public void Open()
{
Close();
server = new TcpClient(serveraddress,port);
server.ReceiveTimeout = RECEIVETIMEOUT;
writer = server.GetStream();
reader = new StreamReader(server.GetStream());
connresponse = reader.ReadLine();
isopen = true;
Login();
GetStatus();
}

public void Close()
{
try
{
SendCommand(POPCommands.QUIT);
}
catch{}
try
{
if(null != writer) writer.Close();
}
catch{}
finally
{
writer = null;
}
try
{
if(null != reader) reader.Close();
}
catch{}
finally
{
reader = null;
}
isopen = false;
}

public string SendCommand(POPCommands pCmd)
{
return SendCommand(pCmd, null);
}

public string SendCommand(POPCommands pCmd, string args)
{
if(!isopen) throw new Exception("Invalid State");
string response = null;
if(null != writer)
{
string cmd = pCmd.ToString() + " " + args + CRLF;
byte[] data = Encoding.ASCII.GetBytes(cmd.ToCharArray());
writer.Write(data,0,data.Length);

response = reader.ReadLine();
if(multilineCommands.ContainsKey(pCmd))
{
bool withoutArgsOnly = (bool)multilineCommands[pCmd];
if(!withoutArgsOnly || null == args || 0 == args.Trim().Length)
{
string tresp = null;
do
{
tresp = reader.ReadLine();
response += CRLF + tresp;
}while("." != tresp);
}
}
}
return response;
}

private void ValidateResponse(string cmd, string response)
{
if('-' == response[0])
{
throw new Exception(cmd + ":" + response.Substring(4).Trim());
}
}

public void Login()
{
string response = SendCommand(POPCommands.USER, username);
ValidateResponse(POPCommands.USER.ToString(),response);
if(null != password && password.Length > 0)
{
response = SendCommand(POPCommands.PASS, password);
ValidateResponse(POPCommands.PASS.ToString(),response);
}
}

public long[] GetStatus()
{
string response = SendCommand(POPCommands.STAT);
ValidateResponse(POPCommands.STAT.ToString(),response);
string[] rparts = response.Substring(3).Trim().Split(new char[] {' '});
long[] lary = new long[2];
msgcount = lary[0] = Int64.Parse(rparts[0].Trim());
totalsize = lary[1] = Int64.Parse(rparts[1].Trim());
return lary;
}

public ArrayList GetList()
{
string response = SendCommand(POPCommands.LIST);
ValidateResponse(POPCommands.LIST.ToString(),response);
string[] rlines = response.Split(new char[] {'\n'});
ArrayList aList = new ArrayList();
for(int i = 1;i < rlines.Length-1;i++)
{
string[] sdata = rlines[i].Trim().Split(new char[] {' '});
aList.Add(Int64.Parse(sdata[1]));
}
return aList;
}

///
/// MAtches the Regular expression and returns the groups
///

/// Regular Express
/// Source string to be processed
/// Collection of Groups yield from teh source string
public static GroupCollection MatchRegexAndGetGroups(string regexp,string source)
{
Regex r = new Regex(regexp,RegexOptions.IgnoreCase);
Match m = r.Match(source);
GroupCollection gc = null;
if(m.Success) gc = m.Groups;
return gc;
}

///
/// MAtches the Regular expression and returns the groups, and return
/// value of specific Group
///

/// Regular Express
/// Source string to be processed
/// group id to be returned
/// String containing the value of the specific indexed group
public static string MatchRegexAndGetGroup(string regexp,string source,int group)
{
GroupCollection gc = MatchRegexAndGetGroups(regexp,source);
string result = null;
if(null != gc && group <= gc.Count)
result = gc[group-1].Value;
return result;
}

public Hashtable GetHeader(int msg)
{
string response = SendCommand(POPCommands.TOP,msg + " 0");
ValidateResponse(POPCommands.TOP.ToString(),response);
Hashtable ht = new Hashtable();
ht.Add(HEADER_FIELD,response);
ht.Add(MESSAGEID_FIELD,MatchRegexAndGetGroup("\\r\\nMessage-ID:[\\s]*<([^>]*)>",
response,2));
string fromEmail = MatchRegexAndGetGroup("\\r\\nFrom:[\\s]*([^\\r\\n]*)",response,2);
ht.Add(FROM_FIELD,fromEmail);
Regex r = new Regex(@"([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)");
Match m = r.Match(fromEmail);
if(m.Success) fromEmail = m.Value;
ht.Add(FROMEMAIL_FIELD,fromEmail);
string replyto = MatchRegexAndGetGroup("\\r\\nReply-To:[\\s]*([^\\r\\n]*)",
response,2);
if(null == replyto)
{
ht.Add(REPLYTO_FIELD,fromEmail);
ht.Add(REPLYTOEMAIL_FIELD,fromEmail);
}
else
{
ht.Add(REPLYTO_FIELD,replyto);
m = r.Match(replyto);
if(m.Success) replyto = m.Value;
ht.Add(REPLYTOEMAIL_FIELD,replyto);
}
ht.Add(TO_FIELD,MatchRegexAndGetGroup("\\r\\nTo:[\\s]*([^\\r\\n]*)",
response,2));
ht.Add(CC_FIELD,MatchRegexAndGetGroup("\\r\\nCC:[\\s]*([^\\r\\n]*)",
response,2));
ht.Add(SUBJECT_FIELD,MatchRegexAndGetGroup("\\r\\nSubject:[\\s]*([^\\r\\n]*)",
response,2));
return ht;
}

public string GetMessage(int msg)
{
string response = SendCommand(POPCommands.RETR,msg.ToString());
ValidateResponse(POPCommands.RETR.ToString(),response);
return response;
}

public string DeleteMessage(int msg)
{
string response = SendCommand(POPCommands.DELE,msg.ToString());
ValidateResponse(POPCommands.DELE.ToString(), response);
return response;
}
}
}

Post an ASP.NET form with JavaScript

Introduction
One of the biggest changes from ASP to ASP.NET is the postback process. By design, ASP.NET pages post form data back to themselves for processing. For most situations, this is an acceptable process. But if a page must post form data to another site or another ASP.NET page, this is impractical. The current ASP.NET postback process supports lots of ways to manage this process.

Use Server.Transfer() to send posted fields to another page. This has the unfortunate side effect of not changing the user's URL.
Pass the items on a querystring, bundling them manually and using Response.Redirect() to send the new querystring to another page. The querystring has both security and length issues.
Pass the items on a post. Create a custom function to read the current items and send them via an HTTP post.
Use an HTML form instead of a web form. Remove the runat="server" attribute from the Form tag. Unfortunately, the validator controls can no longer be used, and that is the main reason I decided to use a JavaScript solution.
Use a simple JavaScript function to alter the page behavior on the client.
I am going to describe a technique using a simple client-side JavaScript. The advantage of this is that it is quick and simple, especially for developers just starting out with ASP.NET or for simple applications. Additionally, when migrating ASP applications to ASP.NET, this little technique can help reduce migration time by allowing you to keep, the ASP page-to-page posting behavior. The one downside is that users can choose to operate their browser without JavaScript, thus negating this technique. If this is a serious concern for you, look into the third option listed above.

Background
There are two problems to overcome when using JavaScript to change the posting behavior of ASP.NET. The first problem is the self-postback. JavaScript allows the action attribute of the HTML Form tag to be changed on the client. It is the content of the post that causes ASP.NET to have the most serious problems. When an ASP.NET page receives a post, it checks for a field called __VIEWSTATE (that's 2 underscore symbols) in the post. ASP.NET is using this field for many reasons, most outside the scope of this article. But, one thing the __VIEWSTATE field does contain is internal validation for ASP.NET. If you simply post the __VIEWSTATE field to a different ASP.NET page, than the page that filled the __VIEWSTATE field, ASP.NET will throw an exception:

"The viewstate is invalid for this page and might be corrupted."
If we attempt to remove the data from the __VIEWSTATE field prior to a post with JavaScript, the same exception is thrown.

So, in order to post to another ASP.NET page, the __VIEWSTATE field cannot be passed to the next ASP.NET page. JavaScript allows us to rename the __VIEWSTATE field and change the action attribute of the form tag.

Using the code
In the HTML portion of our ASP.NET page, we need to include the JavaScript function, NoPostBack. It could reside in a separate file, but is included here in the page for simplicity.

--- JS Starts here ---
function noPostBack(sNewFormAction)
{
document.forms[0].action = sNewFormAction;
document.forms[0].__VIEWSTATE.name = 'NOVIEWSTATE';
}
--- JS Ends here ---

The first line sets the form's action attribute to a new location that is passed to the function. The second line renames the __VIEWSTATE field. It can be called anything other than it's original name or the name of your other form items. If you are trying to save bandwidth, you could also set the value of the __VIEWSTATE field to "". In the ASP.NET Page_Load function, only one line of code is necessary:

private void Page_Load(object sender, System.EventArgs e)
{
Submit.Attributes.Add("onclick", "noPostBack('secondform.aspx');");
}
This adds an onclick attribute to the Submit button, and in this attribute we are specifying the new page or location for the post. When the button is clicked, it calls the JavaScript function before the form post occurs, changing the default location from the page itself to somewhere else.

If the data is posted to another ASP.NET form, simply handle the form items using Request.Form syntax:

private void Page_Load(object sender, System.EventArgs e)
{
Result.Text = Request.Form["SomeText"].ToString();
}

How to Create a Default 'Enter' Button ?

How to Create a Default 'Enter' Button ?
===============================================
Imagine you've created an ASP.NET Web page with a search button. The user taps a phrase into a text box and presses Enter. On most regular Web pages (think: Google), the form would be submitted and the results returned. In other words, the search button is automatically "clicked" for you.

However on an ASP.NET Web page, pressing Enter resubmits the form to the server, but actually does nothing... which is pretty useless, really.

So, how do you set a default button to be clicked when the user presses Enter? Simply add the following line to your page's Load event, replacing "btnSearch" with the name of your button. It uses a hidden Page method called RegisterHiddenField and works splendidly:

Page.RegisterHiddenField("__EVENTTARGET", "btnSearch")
Wonders of the Little-Known SmartNavigation Property
Smart Navigation is a little-known Internet Explorer feature that enables the individual controls on your Web forms to maintain focus between post backs, plus allows you to suppress that "flicker" that occurs as you load the new page.

August 21, 2004

How to Open Save File Dialog

You must have given download file permissions in many or any applications. But it's getting problem because Doc/PDF/Txt files are opening in IE itself and user need to press save dialog from there.

Here is the tag that opens save file dialog to download file. Assume "testfile.txt" is getting download, so code will be :

Reponse.AppendHeader("content-disposition", "attachment; filename=testfile.txt");

This code will open a dialog box to save.

Web Deploy

Need a cool and yet simple tool to deploy web files. Here it is : WebDeploy. Try with it it's really simple and yet effective.

August 16, 2004

August 13, 2004

Database Normalization Basics

100139 - ACC: Database Normalization Basics

SQL Locator Class Object

Here is the Class Object for SQL Locator : it gives string array of SQL Server/MSDE located nearby.

///


/// SQL Locator Class Object
///

public class SqlLocator
{
[DllImport("odbc32.dll")]
private static extern short SQLAllocHandle(short hType, IntPtr inputHandle, out IntPtr outputHandle);
[DllImport("odbc32.dll")]
private static extern short SQLSetEnvAttr(IntPtr henv, int attribute, IntPtr valuePtr, int strLength);
[DllImport("odbc32.dll")]
private static extern short SQLFreeHandle(short hType, IntPtr handle);
[DllImport("odbc32.dll",CharSet=CharSet.Ansi)]
private static extern short SQLBrowseConnect(IntPtr hconn, StringBuilder inString,
short inStringLength, StringBuilder outString, short outStringLength,
out short outLengthNeeded);

private const short SQL_HANDLE_ENV = 1;
private const short SQL_HANDLE_DBC = 2;
private const int SQL_ATTR_ODBC_VERSION = 200;
private const int SQL_OV_ODBC3 = 3;
private const short SQL_SUCCESS = 0;

private const short SQL_NEED_DATA = 99;
private const short DEFAULT_RESULT_SIZE = 1024;
private const string SQL_DRIVER_STR = "DRIVER=SQL SERVER";

private SqlLocator(){}

public static string[] GetServers()
{
string[] retval = null;
string txt = string.Empty;
IntPtr henv = IntPtr.Zero;
IntPtr hconn = IntPtr.Zero;
StringBuilder inString = new StringBuilder(SQL_DRIVER_STR);
StringBuilder outString = new StringBuilder(DEFAULT_RESULT_SIZE);
short inStringLength = (short) inString.Length;
short lenNeeded = 0;

try
{
if (SQL_SUCCESS == SQLAllocHandle(SQL_HANDLE_ENV, henv, out henv))
{
if (SQL_SUCCESS == SQLSetEnvAttr(henv,SQL_ATTR_ODBC_VERSION,(IntPtr)SQL_OV_ODBC3,0))
{
if (SQL_SUCCESS == SQLAllocHandle(SQL_HANDLE_DBC, henv, out hconn))
{
if (SQL_NEED_DATA == SQLBrowseConnect(hconn, inString, inStringLength, outString,
DEFAULT_RESULT_SIZE, out lenNeeded))
{
if (DEFAULT_RESULT_SIZE < lenNeeded)
{
outString.Capacity = lenNeeded;
if (SQL_NEED_DATA != SQLBrowseConnect(hconn, inString, inStringLength, outString,
lenNeeded,out lenNeeded))
{
throw new ApplicationException("Unabled to aquire SQL Servers from ODBC driver.");
}
}
txt = outString.ToString();
int start = txt.IndexOf("{") + 1;
int len = txt.IndexOf("}") - start;
if ((start > 0) && (len > 0))
{
txt = txt.Substring(start,len);
}
else
{
txt = string.Empty;
}
}
}
}
}
}
catch (Exception ex)
{
//Throw away any error if we are not in debug mode
//#if (DEBUG)
// MessageBox.Show(ex.Message,"Acquire SQL Servier List Error");
//#endif
txt = string.Empty;
}
finally
{
if (hconn != IntPtr.Zero)
{
SQLFreeHandle(SQL_HANDLE_DBC,hconn);
}
if (henv != IntPtr.Zero)
{
SQLFreeHandle(SQL_HANDLE_ENV,hconn);
}
}

if (txt.Length > 0)
{
retval = txt.Split(",".ToCharArray());
}

return retval;
}
}

Oracle Data Provider for .NET

Oracle Data Provider for .NET

August 12, 2004

Need PageBreak in HTML??

Just put this wherever you want a page break:
<

p style="PAGE-BREAK-BEFORE: always" /

>
You won't see it on screen, but you will see it in the prinout. Bewarethough, it may only work in IE.

Web.Config : define File Download parameters

Web.Config : define File Download parameters

Response.WriteFile Cannot Download a Large File

812406 - PRB: Response.WriteFile Cannot Download a Large File

How to prevent files to be served by IIS??

815152 - HOW TO: Use ASP.NET to Protect File Types

August 04, 2004

Don’t like the URL? Change It

Dynamic
URL generation is handy for redirections. Here are some tips for best practices
when using the RewritePath method


Many
web sites serve dynamically generated pages—pages that of course don’t yet
exist at the time the application is deployed. For example, a web site that
offers daily news will easily reference pages using a fixed URL and a
progressive ID in the query string as follows: view.aspx?ID=1023.


However,
similar-looking URLs don’t necessarily all point to the same physical page,
view.aspx. In some cases, the displayed URL is dynamically mapped to a real
ASPX page with a different name.


Can
you change the URL of the requested page on the fly? If you ask this question
to a sample of ASP.NET developers, the average answer is Maybe, resulting from
a balanced set of Yes and No.


Can
you redirect the browser to show another page? If you ask this question,
instead, the answer is a resounding Yes. In both cases, you change the URL of
the originally requested page and actually force the browser to display a
different page. However, URL change and classic redirect work in two radically
different ways.


Changing
the URL is an operation that is technically known as “URL rewriting.” It takes
place during the request processing and determines the overwriting of the
originally requested URL. The ASP.NET HTTP context object has a method named
RewritePath
defined as follows:


public void RewritePath(string path)


The
RewritePath method issues a call
to an internal method defined by the HttpRequest
object. This method accesses some private fields on the
Request
object and rewrites the target URL of the request.
As a result, the displayed page is the one you set through
RewritePath
; the page shown in the address bar remains the
originally requested one. The change of the final URL takes place on the server
and, more importantly, within the context of the same call.


This
fact represents the biggest difference with the classic browser redirection.
When you call Response.Redirect,
in fact, the browser receives an HTTP 302 status code and reiterates the
request addressing a different URL.


All
in all, RewritePath is more
efficient than classic redirection because it doesn’t require a second call to
the browser. However, RewritePath
should be used carefully and mainly from within the global.asax file. If you
use RewritePath in the context of
a postback event, you might experience some viewstate troubles. The following
code shows how to rewrite the URL of a request to point to a different page:


protected void Application_BeginRequest(Object sender, EventArgs e)


{


   HttpContext context = HttpContext.Current;


   context.RewritePath("next.aspx");


}


The
code is an excerpt from a web application’s global.asax class file.


It
is worth noticing that RewritePath
is used internally to ASP.NET to implement the cookieless session feature. When
cookieless sessions are configured, each request embodies a fake URL that
includes the session ID. For the successful execution of the request, that fake
URL must be replaced with a real one and possibly without performance
penalties. That’s where HttpContext.RewritePath
fits in.