Friday, July 22, 2011

Comma separated values in SQL Server

For comma seperated value



;WITH ctm
AS
(
SELECT id,id AS idlist ,VName [Name],0 AS [Status] FROM testTableData
WHERE fk_id = 0
UNION ALL
SELECT ct.id,tt.id AS idlist,tt.Vname [Name],1 AS [Status] FROM testTableData tt
INNER JOIN ctm AS ct ON ct.id = tt.FK_id
AND ct.[Status] = 0
)

SELECT * FROM ctm ORDER BY id,idlist,[Name]

Wednesday, June 22, 2011

Automate mail merge in C#

private void MailMerge()
{
# region local variables

Object oMissing = System.Reflection.Missing.Value;

Object oTrue = true;
Object oFalse = false;

Word.Application oWord = new Word.Application();
Word.Document oWordDoc = new Word.Document();


oWord.Visible = true;

// Word Mail Merge Template file
Object oTemplatePath = System.Windows.Forms.Application.StartupPath+ "\\Report.dot";

oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

#endregion

foreach (Word.Field myMergeField in oWordDoc.Fields)
{

iTotalFields++;
Word.Range rngFieldCode = myMergeField.Code;
String fieldText = rngFieldCode.Text;

if (fieldText.StartsWith(" MERGEFIELD"))
{
// example: MERGEFIELD Name \* MERGEFORMAT
Int32 endMerge = fieldText.IndexOf("\\");
Int32 fieldNameLength = fieldText.Length - endMerge;
String fieldName = fieldText.Substring(11, endMerge - 11); // [Name]

fieldName = fieldName.Trim();

if (fieldName == "Name")
{
myMergeField.Select();
oWord.Selection.TypeText(txt_name.Text);
}

if (fieldName == "Address")
{
myMergeField.Select();
oWord.Selection.TypeText(txt_address.Text);
}

if (fieldName == "Age")
{
myMergeField.Select();
oWord.Selection.TypeText(num_age.Text);
}

if (fieldName == "EAddress")
{
myMergeField.Select();
oWord.Selection.TypeText(txt_email.Text);
}

if (fieldName == "Company")
{
myMergeField.Select();
oWord.Selection.TypeText(txt_company.Text);
}

if (fieldName == "TelNo")
{
myMergeField.Select();
oWord.Selection.TypeText(txt_tel.Text);
}

if (fieldName == "ODetails")
{
myMergeField.Select();
oWord.Selection.TypeText(txt_odetails.Text);
}
}
}

// Open File

}

Structure of the template document

Name: «Name»
Address: «Address»
Age: «Age»
E-mail Address: «EAddress»
Company: «Company»
Telephone Number: «TelNo»
Other Details: «ODetails»

Friday, April 1, 2011

Recursive Search for Folders and Files

public ClsFolderNFileCollection GetCollectionOfRecursiveDirAndFiles(string Src, List Elements)
{
ClsFolderNFileCollection objDirAndFileCollection = new ClsFolderNFileCollection();
string[] Files;

try
{

Files = Directory.GetFileSystemEntries(Src);
foreach (string Element in Files)
{
// Sub directories

if (Directory.Exists(Element))
{
objDirAndFileCollection.FolderCollection.Add(Element);
GetCollectionOfRecursiveDirAndFiles(Element, Elements);
}

else
{
objDirAndFileCollection.FileCollection.Add(Element);
}
}


}
catch (Exception ex)
{
throw new Exception(ex.Message);
}

return objDirAndFileCollection;
}


}

// Return Class

public class ClsFolderNFileCollection
{
public List FileCollection { get; set; }
public List FolderCollection { get; set; }

}

Monday, March 28, 2011

DateTime Stamp Functions

public static string DateTimeIn24Hours()
{
return DateTime.Now.ToString("yyyyMMddHHmm");
}

public static string DateTimeWithUniqueID()
{
string guid = Guid.NewGuid().ToString();

return DateTime.Now.ToString("yyyymmdd") + guid;
}

Tuesday, March 22, 2011

General Class for FTP Functions

class FTPFunctions
{
///
/// To Make Directory on the FTP-Server
///

/// public static void MakeDir(string dirName)
{
FtpWebRequest reqFTP = null;
Stream ftpStream = null;
try
{

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + dirName));

reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(FTPSettings.UserID, FTPSettings.Password);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
if (ftpStream != null)
{
ftpStream.Close();
ftpStream.Dispose();
}
throw new Exception(ex.Message.ToString());
}
}
///
/// To Check Whether Folder exists or not on the FTP-Server
///

/// /// /// /// ///
public static bool FtpDirectoryExists(string OurDir, string FTPDir, string FTPUser, string FTPPassword)
{
bool IsExists = true;
try
{
FtpWebRequest request;

// Create FtpWebRequest object from the Uri provided
if (!FTPDir.Contains("ftp://"))
{
request = (FtpWebRequest)FtpWebRequest.Create
(new Uri("ftp://" + FTPDir));
}
else
{
request = (FtpWebRequest)FtpWebRequest.Create
(new Uri(FTPDir));
}

// request = (FtpWebRequest)WebRequest.Create(FTPDir);
request.Credentials = new NetworkCredential(FTPUser, FTPPassword);
request.Method = WebRequestMethods.Ftp.PrintWorkingDirectory;

FtpWebResponse response = (FtpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
IsExists = false;
}
return IsExists;
}

///
/// Upload file on the FTP-Server
///

/// /// /// /// ///
public static bool ftpfile(string inputfilepath, string ftpfilepath, string strFTPUser, string strFTPPwd)
{

try
{

FileInfo fileInf = new FileInfo(inputfilepath);

FtpWebRequest ftp;

// Create FtpWebRequest object from the Uri provided
if (!ftpfilepath.Contains("ftp://"))
{
ftp = (FtpWebRequest)FtpWebRequest.Create
(new Uri("ftp://" + ftpfilepath + "/" + fileInf.Name));
}
else
{
ftp = (FtpWebRequest)FtpWebRequest.Create
(new Uri(ftpfilepath + "/" + fileInf.Name));
}

ftp.Credentials = new NetworkCredential(strFTPUser, strFTPPwd);

ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fs = File.OpenRead(inputfilepath);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = ftp.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();

return true;

}
catch (Exception ex)
{
// WriteLog("Unable to upload zip file: '"+strFilename+"' - Excep: " + ex.Message);
return false;
}
}

///
/// Get MetaData of the FTP-File
///

/// /// /// /// /// ///
public static FTPFileMetaData GetMetaDataFTPFile(string ftpServerIP, string ftpUserID, string ftpPassword, string strFolderName, string strFileName)
{
FTPFileMetaData metaData = new FTPFileMetaData();
FtpWebRequest reqFTP;


long fileSize = 0;

if (!ftpServerIP.Contains("ftp://"))
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" +
ftpServerIP + "/" + strFolderName + "/" + strFileName));
}
else
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP +
"/" + strFolderName + "/" + strFileName));
}
reqFTP.Method = WebRequestMethods.Ftp.GetDateTimestamp;
reqFTP.UseBinary = true;
reqFTP.KeepAlive = false;
reqFTP.Credentials = new NetworkCredential(ftpUserID,
ftpPassword);
FtpWebResponse response;
try
{
response = (FtpWebResponse)reqFTP.GetResponse();

DateTime lastModified = response.LastModified;

metaData.FileName = strFileName;
metaData.ModifiedTime = lastModified;
Stream ftpStream = response.GetResponseStream();
fileSize = response.ContentLength;
metaData.FileLength = fileSize;
metaData.FileLength = GetFTPFileSize(ftpServerIP, ftpUserID, ftpPassword, strFolderName, strFileName);

return metaData;
}
catch (Exception ex)
{
// BLayer.WriteLog("Error in FTPModule for MetaData " + ex.ToString() + "-" + DateTime.Now);
return metaData;
}
}

///
/// Delete file from the FTP-Server
///

/// /// /// /// /// ///
public static bool DeleteFileFromFTPServer(string ftpServerIP, string ftpUserID, string ftpPassword, string strFolderName, string strFileName)
{



FtpWebRequest request;

try
{

if (!ftpServerIP.Contains("ftp://"))
{
request = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" +
ftpServerIP + "/" + strFolderName + "/" + strFileName));
}
else
{
request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP +
"/" + strFolderName + "/" + strFileName));
}

request.Credentials = new NetworkCredential(ftpUserID,
ftpPassword);
request.Method = WebRequestMethods.Ftp.DeleteFile;

FtpWebResponse response = (FtpWebResponse)request.GetResponse();

response.Close();
return true;
}
catch (Exception ex)
{
return false;
}

}

///
/// Get File-Size
///

/// /// /// /// /// ///
public static long GetFTPFileSize(string ftpServerIP, string ftpUserID, string ftpPassword, string strFolderName, string strFileName)
{
FtpWebRequest reqFTP;
long fileSize = 0;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + strFolderName + "/" + strFileName));
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
reqFTP.UseBinary = true;
reqFTP.KeepAlive = false;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
fileSize = response.ContentLength;

ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
// BLayer.WriteLog("Error in FTPModule for FileSize " + ex.ToString() + "-" + DateTime.Now);
}
return fileSize;
}

///
/// Download file from the FTP-Server
///

/// /// /// /// /// /// ///

public static bool DownloadFileFromFTPServer(string ftpServerIP, string ftpUserID, string ftpPassword, string strFolderName, string strFileName, string DestFolder)
{
FtpWebRequest reqFTP;

if (!ftpServerIP.Contains("ftp://"))
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" +
ftpServerIP + "/" + strFolderName + "/" + strFileName));


}
else
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP +
"/" + strFolderName + "/" + strFileName));



}

reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.KeepAlive = false;
reqFTP.Credentials = new NetworkCredential(ftpUserID,
ftpPassword);
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);
Directory.CreateDirectory(DestFolder);

FileStream outputStream = new FileStream(DestFolder +
Path.DirectorySeparatorChar + strFileName, FileMode.Create);

try
{

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

ftpStream.Close();
outputStream.Close();
response.Close();

return true;
}
catch (Exception ex)
{
string errMsg = "There is problem in downloading file from: " + DestFolder + "\\" + strFileName;
errMsg = errMsg + ": " + ex.Message.ToString();

return false;
}
}

///
/// Get File-listing from the FTP-Server
///

/// /// /// /// ///
public static List GetFTPFileList(string ftpServerIP, string ftpUserID, string ftpPassword, string strFolderName)
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
FtpWebRequest reqFTP;
List FTPFiles = new List();
try
{
if (!ftpServerIP.Contains("ftp://"))
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" +
ftpServerIP + "/" + strFolderName));
}
else
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP +
"/" + strFolderName));
}
reqFTP.UseBinary = true;
reqFTP.KeepAlive = false;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
//MessageBox.Show(reader.ReadToEnd());
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf('\n'), 1);
reader.Close();
response.Close();
//MessageBox.Show(response.StatusDescription);
downloadFiles = result.ToString().Split('\n');


foreach (string s in downloadFiles)
{
FTPFileMetaData data = GetMetaDataFTPFile(ftpServerIP, ftpUserID, ftpPassword, strFolderName, s);

// Here we requires only file name

FTPFiles.Add(data.FileName);


}

return FTPFiles;
}
catch (Exception ex)
{

return FTPFiles;
}
}

///
/// Get Folder List from the FTP-Server
///

/// /// /// /// ///
public static List GetDirectoryListingFromFTPServer(string ftpServerIP, string ftpUserID, string ftpPassword, string strFolderName)
{

FtpWebRequest request;

StringBuilder result = new StringBuilder();
List directories = new List();

try
{

if (!ftpServerIP.Contains("ftp://"))
{
request = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" +
ftpServerIP + "/" + strFolderName));
}
else
{
request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP +
"/" + strFolderName));
}


request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential(ftpUserID,
ftpPassword);


FtpWebResponse response = (FtpWebResponse)
request.GetResponse();

Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string line = reader.ReadLine();
while (line != null)
{
// Filtering folder names from the ListingString
if (line.StartsWith("drw-") && !(line.EndsWith(".")))
{
if (line.Contains(":"))
{
result.Append(line.Substring(line.LastIndexOf(":") + 4));
result.Append("\n");
}
}
line = reader.ReadLine();
}


directories.AddRange(result.ToString().Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries));


reader.Close();
response.Close();

return directories;
}
catch (WebException e)
{
return directories;
}
}

///
/// Check Existence of the File on FTP-Server
///

/// /// /// ///
public bool IsFileExistsFTPServerURI(string fullFtpFilepath, string userName,string passWord)
{

bool exists = true;

var request =

(FtpWebRequest)WebRequest.Create(fullFtpFilepath);

request.Credentials =

new NetworkCredential(userName, passWord);

request.Method =

WebRequestMethods.Ftp.GetDateTimestamp;

try
{

FtpWebResponse response =

(FtpWebResponse)request.GetResponse();

}

catch (WebException ex)
{

FtpWebResponse response = (FtpWebResponse)ex.Response;

if (response.StatusCode ==

FtpStatusCode.ActionNotTakenFileUnavailable)
{

exists = false; //File does not exist

}

}

return exists;

}


}

Friday, March 4, 2011

Data Table Export to Excel with XSLT

Util Class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Threading;
using System.Data;
using System.Xml.Xsl;
using System.Web;
using System.Xml.XPath;

namespace Auditor_Apps
{
class DataSetToExcelUtil
{


private string appType;
private HttpResponse response;

private void CreateStylesheet(XmlTextWriter writer, string[] sHeaders, string[] sFileds, ExportFormat FormatType)
{
try
{
string ns = "http://www.w3.org/1999/XSL/Transform";
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement("xsl", "stylesheet", ns);
writer.WriteAttributeString("version", "1.0");
writer.WriteStartElement("xsl:output");
writer.WriteAttributeString("method", "text");
writer.WriteAttributeString("version", "4.0");
writer.WriteEndElement();
writer.WriteStartElement("xsl:template");
writer.WriteAttributeString("match", "/");
for (int i = 0; i < sHeaders.Length; i++) { writer.WriteString("\""); writer.WriteStartElement("xsl:value-of"); writer.WriteAttributeString("select", "'" + sHeaders[i] + "'"); writer.WriteEndElement(); writer.WriteString("\""); if (i != (sFileds.Length - 1)) { writer.WriteString((FormatType == ExportFormat.CSV) ? "," : "\t"); } } writer.WriteStartElement("xsl:for-each"); writer.WriteAttributeString("select", "Export/Values"); writer.WriteString("\r\n"); for (int j = 0; j < sFileds.Length; j++) { writer.WriteString("\""); writer.WriteStartElement("xsl:value-of"); writer.WriteAttributeString("select", sFileds[j]); writer.WriteEndElement(); writer.WriteString("\""); if (j != (sFileds.Length - 1)) { writer.WriteString((FormatType == ExportFormat.CSV) ? "," : "\t"); } } writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); } catch (Exception exception) { throw exception; } } public enum ExportFormat { CSV = 1, Excel = 2 } public enum AppType { WEB = 1, Winform = 2 } public void ExportDetails(DataTable DetailsTable, ExportFormat FormatType, AppType appType, string FileName) { try { if (DetailsTable.Rows.Count == 0) { throw new Exception("There are no details to export."); } DataSet dsExport = new DataSet("Export"); DataTable table = DetailsTable.Copy(); table.TableName = "Values"; dsExport.Tables.Add(table); string[] sHeaders = new string[table.Columns.Count]; string[] sFileds = new string[table.Columns.Count]; for (int i = 0; i < table.Columns.Count; i++) { sHeaders[i] = table.Columns[i].ColumnName; sFileds[i] = this.ReplaceSpclChars(table.Columns[i].ColumnName); } if (appType == AppType.WEB) { this.Export_with_XSLT_Web(dsExport, sHeaders, sFileds, FormatType, FileName); } else if (appType == AppType.Winform) { this.Export_with_XSLT_Windows(dsExport, sHeaders, sFileds, FormatType, FileName); } } catch (Exception exception) { throw exception; } } private void Export_with_XSLT_Web(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName) { try { this.response.Clear(); this.response.Buffer = true; if (FormatType == ExportFormat.CSV) { this.response.ContentType = "text/csv"; this.response.AppendHeader("content-disposition", "attachment; filename=" + FileName); } else { this.response.ContentType = "application/vnd.ms-excel"; this.response.AppendHeader("content-disposition", "attachment; filename=" + FileName); } MemoryStream w = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(w, Encoding.UTF8); this.CreateStylesheet(writer, sHeaders, sFileds, FormatType); writer.Flush(); w.Seek(0L, SeekOrigin.Begin); XmlDataDocument document = new XmlDataDocument(dsExport); XslTransform transform = new XslTransform(); transform.Load(new XmlTextReader(w), null, null); StringWriter writer2 = new StringWriter(); transform.Transform((IXPathNavigable)document, null, (TextWriter)writer2, null); this.response.Write(writer2.ToString()); writer2.Close(); writer.Close(); w.Close(); this.response.End(); } catch (ThreadAbortException exception) { string message = exception.Message; } catch (Exception exception2) { throw exception2; } } public void ExportDetails(DataTable DetailsTable, int[] ColumnList, ExportFormat FormatType, AppType appType, string FileName) { try { if (DetailsTable.Rows.Count == 0) { throw new Exception("There are no details to export"); } DataSet dsExport = new DataSet("Export"); DataTable table = DetailsTable.Copy(); table.TableName = "Values"; dsExport.Tables.Add(table); if (ColumnList.Length > table.Columns.Count)
{
throw new Exception("ExportColumn List should not exceed Total Columns");
}
string[] sHeaders = new string[ColumnList.Length];
string[] sFileds = new string[ColumnList.Length];
for (int i = 0; i < ColumnList.Length; i++) { if ((ColumnList[i] < 0) || (ColumnList[i] >= table.Columns.Count))
{
throw new Exception("ExportColumn Number should not exceed Total Columns Range");
}
sHeaders[i] = table.Columns[ColumnList[i]].ColumnName;
sFileds[i] = this.ReplaceSpclChars(table.Columns[ColumnList[i]].ColumnName);
}
if (appType == AppType.WEB)
{
this.Export_with_XSLT_Web(dsExport, sHeaders, sFileds, FormatType, FileName);
}
else if (appType == AppType.Winform)
{
this.Export_with_XSLT_Windows(dsExport, sHeaders, sFileds, FormatType, FileName);
}
}
catch (Exception exception)
{
throw exception;
}
}
private void Export_with_XSLT_Windows(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName)
{
try
{
MemoryStream w = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(w, Encoding.UTF8);
this.CreateStylesheet(writer, sHeaders, sFileds, FormatType);
writer.Flush();
w.Seek(0L, SeekOrigin.Begin);
XmlDataDocument document = new XmlDataDocument(dsExport);
XslTransform transform = new XslTransform();
transform.Load(new XmlTextReader(w), null, null);
StringWriter writer2 = new StringWriter();
transform.Transform((IXPathNavigable)document, null, (TextWriter)writer2, null);
StreamWriter writer3 = new StreamWriter(FileName);
writer3.WriteLine(writer2.ToString());
writer3.Close();
writer2.Close();
writer.Close();
w.Close();
}
catch (Exception exception)
{
throw exception;
}
}



private string ReplaceSpclChars(string fieldName)
{
fieldName = fieldName.Replace(" ", "_x0020_");
fieldName = fieldName.Replace("%", "_x0025_");
fieldName = fieldName.Replace("#", "_x0023_");
fieldName = fieldName.Replace("&", "_x0026_");
fieldName = fieldName.Replace("/", "_x002F_");
return fieldName;
}



}
}



Implementation code:

DataSetToExcelUtil ObjUtil = new DataSetToExcelUtil();

ObjUtil.ExportDetails(dt, DataSetToExcelUtil.ExportFormat.Excel, DataSetToExcelUtil.AppType.Winform, ExcelPath);

Thursday, March 3, 2011

Get ASCII in C#

public static string GetASCIIValue(string strValue)
{
return Encoding.ASCII.GetString(
Encoding.Convert(
Encoding.UTF8,
Encoding.GetEncoding(
Encoding.ASCII.EncodingName,
new EncoderReplacementFallback(string.Empty),
new DecoderExceptionFallback()
),
Encoding.UTF8.GetBytes(strValue)
)
);

}



string s1 = FinancialMIS_Apps.StringManipulation.GetASCIIValue("Expression");
string s2 = FinancialMIS_Apps.StringManipulation.GetASCIIValue("Räksmörgås");

Monday, February 7, 2011

How to write custom formatted excel in C# from dataTable

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Export_Excel = RKLib.ExportData;
using System.IO;
using MyExcel = Microsoft.Office.Interop.Excel;

public class FormattedMISReports
{
public static string ExportDataTableToExcel(DataTable dtSource, string ExcelPath, bool blnFirstSheet, string sheetName, int sheetIndex)
{
MyExcel.Application oXL;
MyExcel.Workbook oWB;
MyExcel.Worksheet oSheet;
MyExcel.Range oRange;

List CustomIndex = new List();
CustomIndex.Add(14);
CustomIndex.Add(40);
CustomIndex.Add(41);
CustomIndex.Add(88);
CustomIndex.Add(89);
CustomIndex.Add(90);
CustomIndex.Add(91);
CustomIndex.Add(96);

List NonHypen = new List();
NonHypen.Add(92);
NonHypen.Add(93);
NonHypen.Add(94);
NonHypen.Add(95);

try
{

// Start Excel and get Application object.
oXL = new MyExcel.Application();

// Set some properties
oXL.DisplayAlerts = false;
oXL.Visible = true;

if (blnFirstSheet)
{
// Get a new workbook.
oWB = oXL.Workbooks.Add(Type.Missing);

// Adding extra sheets in the workbook
oWB.Sheets.Add(Type.Missing, oWB.Worksheets[oWB.Worksheets.Count], 7, Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);

// Activating first sheet in the workbook
oSheet = (MyExcel.Worksheet)oWB.Worksheets[sheetIndex];

oSheet.Activate();

oSheet.Name = sheetName;
}
else
{
// opening existing excel file
oWB = oXL.Workbooks.Open(ExcelPath, 0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", false, false, 0, true, 0, 0);

// Activating first sheet in the workbook
oSheet = (MyExcel.Worksheet)oWB.Worksheets[sheetIndex];

oSheet.Activate();

oSheet.Name = sheetName;
}



// Header Text
oSheet.Cells[1, 1] = "IDS Infotech Ltd.";
oSheet.Cells[2, 1] = "Department: " +sheetName + "";
oSheet.get_Range("A1", "B2").Font.Bold = true;
oSheet.get_Range("A1", "B2").Font.Color = System.Drawing.ColorTranslator.ToWin32(System.Drawing.Color.DarkBlue);



// Process the DataTable into the Excel
DataTable dt = dtSource;

int startIndex = 5;
int rowCount = 5;
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
// Add the header the first time through
if (rowCount == (startIndex+1))
{
oSheet.Cells[startIndex, i] = dt.Columns[i - 1].ColumnName;
}

// coversion for the zero values
if ((Convert.ToString(dr[i - 1]) == "0.00" || Convert.ToString(dr[i - 1]) == string.Empty) && !NonHypen.Contains(rowCount))
oSheet.Cells[rowCount, i] = "-";
else
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();


// Custom Formatting

// Resize the columns
oRange = oSheet.get_Range(oSheet.Cells[1, 1],
oSheet.Cells[rowCount, dt.Columns.Count + 1]); // Additional column for the aggregate-sum
oRange.EntireColumn.AutoFit();

oRange.Borders.LineStyle = MyExcel.XlLineStyle.xlContinuous;
oRange.Borders.Color = System.Drawing.ColorTranslator.ToWin32(System.Drawing.Color.LightSteelBlue);



oSheet.get_Range(oSheet.Cells[startIndex, 1], oSheet.Cells[1, dt.Columns.Count]).Font.Bold = true;
oSheet.get_Range(oSheet.Cells[1, 1], oSheet.Cells[1, dt.Columns.Count]).Font.Italic = true;
oSheet.get_Range(oSheet.Cells[1, 1], oSheet.Cells[1, dt.Columns.Count]).Font.Size = 11;

oSheet.get_Range(oSheet.Cells[rowCount, dt.Columns.Count], oSheet.Cells[rowCount, dt.Columns.Count]).HorizontalAlignment = MyExcel.XlHAlign.xlHAlignCenter;

if (CustomIndex.Contains(rowCount))
{
oSheet.get_Range(oSheet.Cells[rowCount, 1], oSheet.Cells[rowCount, dt.Columns.Count]).Font.Bold = true;
oSheet.get_Range(oSheet.Cells[rowCount, 1], oSheet.Cells[rowCount, dt.Columns.Count]).Font.Italic = true;
oSheet.get_Range(oSheet.Cells[rowCount, 1], oSheet.Cells[rowCount, dt.Columns.Count]).Font.Size = 11;
oSheet.get_Range(oSheet.Cells[rowCount, 1], oSheet.Cells[rowCount, dt.Columns.Count]).Font.Color = System.Drawing.ColorTranslator.ToWin32(System.Drawing.Color.DarkBlue);
oSheet.get_Range(oSheet.Cells[rowCount, dt.Columns.Count], oSheet.Cells[rowCount, dt.Columns.Count]).HorizontalAlignment = MyExcel.XlHAlign.xlHAlignCenter;
oSheet.get_Range(oSheet.Cells[rowCount, 1], oSheet.Cells[rowCount, i]).Borders.LineStyle = MyExcel.XlLineStyle.xlDouble;
}

// End of Custom Formatting

}
}



// array for the excel column heads
string[] array = { "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ", "BA", "BB", "BC", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BK", "BL", "BM", "BN", "BO", "BP", "BQ", "BR", "BS", "BT", "BU", "BV", "BW", "BX", "BY", "BZ" };
int iArrayIndex = 0;

// Applying formulae
for (int i = 2; i < dt.Columns.Count + 2; i++)
{

// Total_Revenue_A
oSheet.get_Range(oSheet.Cells[14, i], oSheet.Cells[14, i]).Formula = "=sum(" + array[iArrayIndex] + "7:" + array[iArrayIndex] + "13)";

// Total_Employ_Cost_B
oSheet.get_Range(oSheet.Cells[40, i], oSheet.Cells[40, i]).Formula = "=sum(" + array[iArrayIndex] + "15:" + array[iArrayIndex] + "39)";

// PerCentage_Employ_Cost_Per_Revenue
oSheet.get_Range(oSheet.Cells[41, i], oSheet.Cells[41, i]).Formula = "=(" + array[iArrayIndex] + "40/" + array[iArrayIndex] + "14)";
oSheet.get_Range(oSheet.Cells[41, i], oSheet.Cells[41, i]).NumberFormat = "##.##%";

// Total_Establis_OtherCost_C
oSheet.get_Range(oSheet.Cells[88, i], oSheet.Cells[88, i]).Formula = "=sum(" + array[iArrayIndex] + "42:" + array[iArrayIndex] + "87)";

// Total_Cost_D_SumOf_B_Plus_C

oSheet.get_Range(oSheet.Cells[89, i], oSheet.Cells[89, i]).Formula = "=(" + array[iArrayIndex] + "88+" + array[iArrayIndex] + "40)";

// Gross_Profit_EBIT
oSheet.get_Range(oSheet.Cells[90, i], oSheet.Cells[90, i]).Formula = "=(" + array[iArrayIndex] + "14-" + array[iArrayIndex] + "89)";

// Gross_Profit_EBIT without CSG cost
oSheet.get_Range(oSheet.Cells[91, i], oSheet.Cells[91, i]).Formula = "=(" + array[iArrayIndex] + "40+" + array[iArrayIndex] + "90+" + array[iArrayIndex] + "88)";

// Netprofit
oSheet.get_Range(oSheet.Cells[96, i], oSheet.Cells[96, i]).Formula = "=(" + array[iArrayIndex] + "14-" + array[iArrayIndex] + "89-" + array[iArrayIndex] + "92-" + array[iArrayIndex] + "93-" + array[iArrayIndex] + "94-" + array[iArrayIndex] + "95)";

if(iArrayIndex < dt.Columns.Count)
iArrayIndex++;
}

// Aggregate Column
for (int k = 7; k <= 97; k++)
{
oSheet.get_Range(oSheet.Cells[k, (dt.Columns.Count + 1)], oSheet.Cells[k, (dt.Columns.Count + 1)]).Formula = "=sum(B" + k + ":"+array[(dt.Columns.Count-2)]+ k + ")";

}

// Set-Header/Column Settings

oSheet.get_Range(oSheet.Cells[5, (dt.Columns.Count + 1)], oSheet.Cells[5, (dt.Columns.Count + 1)]).Value2 = "Total";
oSheet.get_Range(oSheet.Cells[5, (dt.Columns.Count + 1)], oSheet.Cells[97, (dt.Columns.Count + 1)]).Interior.Color = System.Drawing.ColorTranslator.ToWin32(System.Drawing.Color.LightSteelBlue);
oSheet.get_Range(oSheet.Cells[5, (dt.Columns.Count + 1)], oSheet.Cells[97, (dt.Columns.Count + 1)]).Borders.LineStyle = MyExcel.XlLineStyle.xlDouble;
oSheet.get_Range(oSheet.Cells[5, (dt.Columns.Count + 1)], oSheet.Cells[97, (dt.Columns.Count + 1)]).Borders.Color = System.Drawing.ColorTranslator.ToWin32(System.Drawing.Color.LightSteelBlue);
oSheet.get_Range(oSheet.Cells[5, (dt.Columns.Count + 1)], oSheet.Cells[97, (dt.Columns.Count + 1)]).Font.Bold = true;

// Header-Line

oSheet.get_Range(oSheet.Cells[5, 1], oSheet.Cells[5, (dt.Columns.Count + 1)]).Borders.LineStyle = MyExcel.XlLineStyle.xlDouble;


// Report Footer

MyExcel.Range FooterColumn = oSheet.get_Range(oSheet.Cells[100, 1], oSheet.Cells[100, 1]);
FooterColumn.Font.Bold = true;
FooterColumn.Font.Italic = true;
FooterColumn.Font.Color = System.Drawing.ColorTranslator.ToWin32(System.Drawing.Color.DarkBlue);
FooterColumn.Value2 = "Report Generated by MIS_Finance - " + DateTime.Now.ToShortDateString();


// Text-Alignment

oSheet.get_Range(oSheet.Cells[5, 2], oSheet.Cells[96, (dt.Columns.Count + 1)]).HorizontalAlignment = MyExcel.XlHAlign.xlHAlignCenter;


// Save the sheet and close
oSheet = null;
oRange = null;


if (blnFirstSheet)
{
oWB.SaveAs(ExcelPath, MyExcel.XlFileFormat.xlWorkbookNormal,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
MyExcel.XlSaveAsAccessMode.xlExclusive,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
}

else
{
oWB.Save();
}

oWB.Close(Type.Missing, Type.Missing, Type.Missing);
oWB = null;
oXL.Quit();

// No-Errors
return string.Empty;
}
catch (Exception ex)
{
MessageBox.Show("Invalid Operation : \n" + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
DataLayer.ExecuteExcepLogProcedure(ex.ToString());
return "Error " + ex.Message;
}
finally
{

// Clean up
// NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

}
}
}

Thursday, February 3, 2011

DES encryption in C#

const string DESKey = "AQWSEDRF";
const string DESIV = "HGFEDCBA";

public static string DESDecrypt(string stringToDecrypt)
{
byte[] key;
byte[] IV;
byte[] inputByteArray;
key = Convert2ByteArray(DESKey);
IV = Convert2ByteArray(DESIV);
int len = stringToDecrypt.Length;
inputByteArray = Convert.FromBase64String(stringToDecrypt);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
try
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
Encoding encoding = Encoding.UTF8;
return encoding.GetString(ms.ToArray());
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
ms.Close();
cs.Close();
}
}

public static string DESEncrypt(string stringToEncrypt)
{
byte[] key;
byte[] IV;
byte[] inputByteArray;
key = Convert2ByteArray(DESKey);
IV = Convert2ByteArray(DESIV);
inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
try
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
ms.Close();
cs.Close();
}
}

static byte[] Convert2ByteArray(string strInput)
{
int intCounter; char[] arrChar;
arrChar = strInput.ToCharArray();
byte[] arrByte = new byte[arrChar.Length];
for (intCounter = 0; intCounter < arrByte.Length; intCounter++)
arrByte[intCounter] = Convert.ToByte(arrChar[intCounter]);
return arrByte;
}

Zip File or Folder in C#

using ICSharpCode.SharpZipLib.Zip;
using System.IO;

ZipOutputStream zos = null;
protected void Button1_Click(object sender, EventArgs e)
{
string[] pathCollection = new string[2];
PathCellction[0] = "c:\\folder1";
PathCellction[1] = "c:\\folder2";
StartZip(pathCollection, "filename");
}

protected void StartZip(string[] pathCollection, string strFileName)
{
MemoryStream ms;
Response.ContentType = "application/octet-stream";
strFileName = HttpUtility.UrlEncode(strFileName).Replace('+', ' ');
Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName + ".zip");
ms = new MemoryStream();
zos = new ZipOutputStream(ms);
addZipEntry(pathCollection);
ms.Close();
zos.Finish();
zos.Close();
Response.Clear();
Response.BinaryWrite(ms.ToArray());
Response.End();
}

protected void addZipEntry(string[] pathCollection)
{
for (int i = 0; i < pathCollection.Length; i++)
{
string strPath = pathCollection[i];
addZipEntry(strPath, strPath.LastIndexOf("\\") + 1);
}
}

protected void addZipEntry(string strPath, int baseIndex)
{
DirectoryInfo di = new DirectoryInfo(strPath);
foreach (DirectoryInfo item in di.GetDirectories())
{
addZipEntry(item.FullName, baseIndex);
}
foreach (FileInfo item in di.GetFiles())
{
FileStream fs = File.OpenRead(item.FullName);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string strEntryName = item.FullName.Remove(0, baseIndex);
ZipEntry entry = new ZipEntry(strEntryName);
zos.PutNextEntry(entry);
zos.Write(buffer, 0, buffer.Length);
fs.Close();
}
}

Friday, September 17, 2010

Copy complete folder with respective folder hierarchy to another location

public class FileSystem{
// Copy directory structure recursively

public static void copyDirectory(string Src,string Dst){
String[] Files;

if(Dst[Dst.Length-1]!=Path.DirectorySeparatorChar)
Dst+=Path.DirectorySeparatorChar;
if(!Directory.Exists(Dst)) Directory.CreateDirectory(Dst);
Files=Directory.GetFileSystemEntries(Src);
foreach(string Element in Files){
// Sub directories

if(Directory.Exists(Element))
copyDirectory(Element,Dst+Path.GetFileName(Element));
// Files in directory

else
File.Copy(Element,Dst+Path.GetFileName(Element),true);
}
}

}

Thursday, September 2, 2010

How to write XML File from the Object Collection

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

public partial class WriteProductXMLFile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
WriteProducts("9955");
}
}

public System.Collections.IEnumerable CreateProducts()
{
List products = new List();


products.Add(Product.Create("1", "AAAA"));
products.Add(Product.Create("2", "BBBB"));
products.Add(Product.Create("3", "JJJJJ"));
products.Add(Product.Create("4", "AAAKKKA"));
products.Add(Product.Create("5", "YYYYY"));
products.Add(Product.Create("6", "PPPPP"));
products.Add(Product.Create("7", "MMMMM"));
products.Add(Product.Create("8", "TTTTT"));


return products;

}


protected void WriteProducts(string CustomerID)
{

System.Collections.IEnumerable products = CreateProducts();

string FileName = "Products_" + CustomerID+".xml";

string FilePath = Server.MapPath(FileName);

if (System.IO.File.Exists(FilePath))
{
System.IO.File.Delete(FilePath);
}

XmlTextWriter XmlWriter = new XmlTextWriter(FilePath, null);

XmlWriter.WriteStartDocument();
XmlWriter.WriteComment("Product XML.");
XmlWriter.WriteStartElement("Products of Customer: ID");

foreach (Product prod in products)
{

XmlWriter.WriteStartElement("Product");
XmlWriter.WriteElementString("ProductID", prod.ProductID);
XmlWriter.WriteElementString("ProductImage", prod.ProductImage);
XmlWriter.WriteEndElement();
}


XmlWriter.WriteEndDocument();
XmlWriter.Flush();
XmlWriter.Close();

}


# region Internal Class


public class Product
{
public static Product Create(string productID,
string productImage)
{
Product product = new Product();

product.ProductID = productID;
product.ProductImage = productImage;

return product;
}

private string _productID;

public string ProductID
{
get { return _productID; }
set { _productID = value; }
}

private string _Image;
public string ProductImage
{
get { return _Image; }
set { _Image = value; }
}

}

#endregion



}

Wednesday, August 25, 2010

Extract SubString From Delimitered Chars

public string ExtractSubStringFromDelimiterChar(string strValue, char Char1, char Char2)
{
if (string.IsNullOrEmpty(strValue)) {
return strValue;

} else {
Int16 iStart = strValue.IndexOf(Char1);
Int16 iEnd = strValue.LastIndexOf(Char2);

if ((iStart >= 0 & iEnd > iStart)) {
return strValue.Substring(iStart + 1, (iEnd) - (iStart + 1));
} else {
return strValue;


}
}

}


VB.Net

Public Function ExtractSubStringFromDelimiterChar(ByVal strValue As String, ByVal Char1 As Char, ByVal Char2 As Char) As String
If String.IsNullOrEmpty(strValue) Then
Return strValue
Else

Dim iStart As Int16 = strValue.IndexOf(Char1)
Dim iEnd As Int16 = strValue.LastIndexOf(Char2)

If (iStart >= 0 And iEnd > iStart) Then
Return strValue.Substring(iStart + 1, (iEnd) - (iStart + 1))
Else
Return strValue


End If
End If

End Function

Extract SubString From the Delimitered String

public string ExtractSubStringFromDelimiterString(string strValue, string s1, string s2)
{
if (string.IsNullOrEmpty(strValue)) {
return strValue;

} else {
Int16 iStart = strValue.IndexOf(s1);
Int16 iEnd = strValue.LastIndexOf(s2);

if ((iStart >= 0 & iEnd > iStart)) {
return strValue.Substring(iStart + 1, (iEnd) - (iStart + 1));
} else {
return strValue;


}
}

}


VB.Net

Public Function ExtractSubStringFromDelimiterString(ByVal strValue As String, ByVal s1 As String, ByVal s2 As String) As String
If String.IsNullOrEmpty(strValue) Then
Return strValue
Else

Dim iStart As Int16 = strValue.IndexOf(s1)
Dim iEnd As Int16 = strValue.LastIndexOf(s2)

If (iStart >= 0 And iEnd > iStart) Then
Return strValue.Substring(iStart + 1, (iEnd) - (iStart + 1))
Else
Return strValue


End If
End If

End Function

Tuesday, August 24, 2010

Get File Attributes of File residing on FTP Server

private static FTPFileMetaData GetMetaDataFTPFile(string ftpServerIP, string ftpUserID, string ftpPassword, string strFolderName, string strFileName)
{
FTPFileMetaData metaData = new FTPFileMetaData();
FtpWebRequest reqFTP;


long fileSize = 0;

if (!ftpServerIP.Contains("ftp://"))
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" +
ftpServerIP + "/" + strFolderName + "/" + strFileName));
}
else
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP +
"/" + strFolderName + "/" + strFileName));
}
reqFTP.Method = WebRequestMethods.Ftp.GetDateTimestamp;
reqFTP.UseBinary = true;
reqFTP.KeepAlive = false;
reqFTP.Credentials = new NetworkCredential(ftpUserID,
ftpPassword);
FtpWebResponse response;
try
{
response = (FtpWebResponse)reqFTP.GetResponse();

DateTime lastModified = response.LastModified;

metaData.FileName = strFileName;
metaData.ModifiedTime = lastModified;
Stream ftpStream = response.GetResponseStream();
fileSize = response.ContentLength;
metaData.FileLength = fileSize;
metaData.FileLength = GetFTPFileSize(ftpServerIP, ftpUserID, ftpPassword, strFolderName, strFileName);

return metaData;
}
catch(Exception ex)
{
BAL.WriteLog("Error in FTPModule for MetaData " + ex.ToString() + "-" + DateTime.Now);
return metaData;
}
}

Get the File List of Files on FTP Server

public static FTPFileMetaData GetFTPFileList(string ftpServerIP, string ftpUserID, string ftpPassword, string strFolderName, string FileName)
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
FtpWebRequest reqFTP;
FTPFileMetaData metaDataOfReFile = new FTPFileMetaData();
try
{
if (!ftpServerIP.Contains("ftp://"))
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" +
ftpServerIP + "/" + strFolderName + "/" + FileName));
}
else
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP +
"/" + strFolderName + "/" + FileName ));
}
reqFTP.UseBinary = true;
reqFTP.KeepAlive = false;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
//MessageBox.Show(reader.ReadToEnd());
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf('\n'), 1);
reader.Close();
response.Close();
//MessageBox.Show(response.StatusDescription);
downloadFiles = result.ToString().Split('\n');


foreach (string s in downloadFiles)
{
metaDataOfReFile = GetMetaDataFTPFile(ftpServerIP, ftpUserID, ftpPassword, strFolderName, s);


#if (Diagnostics)

BAL.WriteTrackLog("Fetching meta data of FTP File in Re-DownloadMode - '" + s + "'" + " " + DateTime.Now);

#endif
}

return metaDataOfReFile;
}
catch (Exception ex)
{
BAL.WriteLog("Error in FTPModule for FTPList for ReDownload" + ex.ToString() + "-" + DateTime.Now);
return metaDataOfReFile;
}
}

Get the File Size of File residing on FTP Server

private static long GetFTPFileSize(string ftpServerIP, string ftpUserID, string ftpPassword, string strFolderName, string strFileName)
{
FtpWebRequest reqFTP;
long fileSize = 0;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + strFolderName + "/" + strFileName));
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
reqFTP.UseBinary = true;
reqFTP.KeepAlive = false;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
fileSize = response.ContentLength;

ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
BAL.WriteLog("Error in FTPModule for FileSize " + ex.ToString() + "-" + DateTime.Now);
}
return fileSize;
}


}

Wednesday, August 18, 2010

Filter DataTable with Select method of DataTable

Private Function GetRowsByBlockIdFilter(ByVal dt As DataTable, ByVal blockId As String) As DataTable

Dim table As DataTable = dt.Copy()
dt.Rows.Clear()

Dim expression As String
expression = "blockId='" + blockId.Trim() + "' "
Dim foundRows() As DataRow

' Use the Select method to find all rows matching the filter.
foundRows = table.Select(expression)

Dim i As Integer
' Print column 0 of each returned row.
For i = 0 To foundRows.GetUpperBound(0)
dt.ImportRow(foundRows(i))

Next i

Return dt
End Function

Tuesday, August 17, 2010

Remove Cache in ASP.net

For Each de As DictionaryEntry In HttpContext.Current.Cache

HttpContext.Current.Cache.Remove(DirectCast(de.Key, String))

Next

Saturday, May 8, 2010

How to get the ContentType of the File

private string GetContentType(string fileName)

{

string contentType = "application/octetstream";

string ext = System.IO.Path.GetExtension(fileName).ToLower();

Microsoft.Win32.RegistryKey registryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);

if (registryKey != null && registryKey.GetValue("Content Type") != null)

contentType = registryKey.GetValue("Content Type").ToString();

return contentType;

}
 
Locations of visitors to this page