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;

}

Tuesday, March 23, 2010

Recursive_Files_Search_In_CSharp

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Trans829115.BLL
{
///
/// RecursiveFilesSearch from FolderPath/DrivePath
///

///


public class RecursiveFilesSearch
{

static private List FilesFound = new List(); // DirectSearch(Global)

///
///
///

///
public RecursiveFilesSearch()
{

}

private string PaddAsDirectoryPath(string path)
{
if(string.IsNullOrEmpty(path)) return string.Empty;


if(path.Substring((path.Length-2))!="\\")
return path+"\\";

return string.Empty;

}


public enum EnumSourceFilesType
{
CS_Files,
VB_Files
}
///
/// Get All the files in the respective Folder/Drive
///

///
///
///
public List GetAllFileNames(string SourceDir, bool blnIsFileValidator)
{
if(!Directory.Exists(SourceDir))
{
throw new Exception(string.Format("{0} - is not exists - Please define valid Source Path", SourceDir ));
return null;
}

SourceDir = PaddAsDirectoryPath(SourceDir);

List files = new List();

DirectoryInfo di = new DirectoryInfo(SourceDir);

DirectoryInfo[] dirs = di.GetDirectories();

foreach (DirectoryInfo diNext in dirs)
{
files.AddRange(DirSearch(diNext.FullName, "*.*", blnIsFileValidator));
}

return files;

}

///
/// Specific search on SearchType
///

///
///
///

public List GetSelectedFileNames(string SourceDir, EnumSourceFilesType enumSourceType, bool blnIsFileValidator)
{
if(!Directory.Exists(SourceDir))
{
throw new Exception(string.Format("{0} - is not exists - Please define valid Source Path", SourceDir ));
return null;
}

string searchPattern = "*.*"; // Default

switch(enumSourceType)
{
case EnumSourceFilesType.CS_Files:
searchPattern = "*.cs";
break;
case EnumSourceFilesType.VB_Files:
searchPattern = "*.vb";
break;
}

SourceDir = PaddAsDirectoryPath(SourceDir);

List files = new List();

DirectoryInfo di = new DirectoryInfo(SourceDir);

DirectoryInfo[] dirs = di.GetDirectories();

foreach (DirectoryInfo diNext in dirs)
{
files.AddRange(DirSearch(diNext.FullName, searchPattern, blnIsFileValidator));
}

return files;

}



private List DirSearch(string sDir, string SearchPattern)
{

try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, SearchPattern))
{
FilesFound.Add(f);
}
DirSearch(d,SearchPattern);
}

return FilesFound;
}
catch (System.Exception excpt)
{
throw new Exception(excpt.Message);
}
}

///
/// Option to apply FileValidator method
///

///
///
///
///
private List DirSearch(string sDir, string SearchPattern, bool blnIsFileValidator)
{

try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, SearchPattern))
{
if(blnIsFileValidator)
{
if(ValidateFile(f))
FilesFound.Add(f);
}
else
FilesFound.Add(f);
}
DirSearch(d, SearchPattern, blnIsFileValidator);
}

return FilesFound;
}
catch (System.Exception excpt)
{
return FilesFound; // Intermediate results to pass on
throw new Exception(excpt.Message);
}
}
///
/// check Is File is Valid for Copying
///

///
///
private bool ValidateFile(string file)
{
file = Path.GetFileName(file);
if(string.IsNullOrEmpty(file)) return false;

if(file.Equals("Program.cs")) return false;

if(file.Equals("Program.vb")) return false;

if(file.Contains("Designer.cs")) return false;

if(file.Contains("Designer.vb")) return false;

if(file.Equals("AssemblyInfo.cs")) return false;

if(file.Equals("AssemblyInfo.vb")) return false;

return true;
}
}
}

Thursday, February 25, 2010

Appling Linq on ADO.net

// Marking sql-like queries on datatable with linq

EnumerableRowCollection query =
from employee in employees.AsEnumerable()
where employee.Field("salary") > 20
orderby employee.Field("salary")
select employee;
foreach (DataRow emp in query)
{
Response.Write(emp.Field("LastName") + ": ");
Response.Write(emp.Field("salary") + "
");
}

Tuesday, February 16, 2010

Editable DatagridView linked with database

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 System.Data.OracleClient;

namespace Trans829115.PL
{
public partial class frmUpdateDBViaDataGridView : Form
{
# region Private variables

private OracleConnection objcon;
private OracleCommand objcmd;
private OracleDataAdapter objadapter;
private OracleCommandBuilder objbuilder;
private DataSet objdataset;
private DataTable userTable;
private bool mAllowInsert;
private bool mAllowDelete;
private bool IsModifications = false;
ToolTip errorToolTip = new ToolTip();


#endregion

public frmUpdateDBViaDataGridView()
{
InitializeComponent();

// In Form control definition



objcon = new OracleConnection(BLL.QuerySet.ConString);
objcmd= new OracleCommand(BLL.QuerySet.TestQuery, objcon);
objadapter = new OracleDataAdapter(objcmd);
objbuilder = new OracleCommandBuilder(objadapter);
objdataset = new DataSet();
objadapter.Fill(objdataset);
userTable = objdataset.Tables[0];

userDataGridView.AllowUserToAddRows = true;
userDataGridView.AllowUserToDeleteRows = true;
btnDelete.Enabled = true;

}

private void btnDelete_Click(object sender, EventArgs e)
{
DeleteSelectedData();
}

private void frmUpdateDBViaDataGridView_Load(object sender, EventArgs e)
{
# region datagridveiw events/delegates

userDataGridView.CellBeginEdit+=new DataGridViewCellCancelEventHandler(userDataGridView_CellBeginEdit);
userDataGridView.CellEndEdit+=new DataGridViewCellEventHandler(userDataGridView_CellEndEdit);

userDataGridView.CellValidating+=new DataGridViewCellValidatingEventHandler(userDataGridView_CellValidating);
userDataGridView.CellValidated+=new DataGridViewCellEventHandler(userDataGridView_CellValidated);


userDataGridView.SelectionChanged+=new EventHandler(userDataGridView_SelectionChanged);
userDataGridView.CellEnter+=new DataGridViewCellEventHandler(userDataGridView_CellEnter);
userDataGridView.CellLeave+=new DataGridViewCellEventHandler(userDataGridView_CellLeave);




#endregion

# region custom datagridview settings

userDataGridView.MultiSelect = false;
userDataGridView.EditMode = DataGridViewEditMode.EditOnEnter;


#endregion
userDataGridView.DataSource = userTable.DefaultView;
lblRowCount.Text = "Number of records: " + userTable.Rows.Count.ToString();
userDataGridView.AllowUserToResizeColumns = true;
if (userTable.Rows.Count == 0)
{
btnDelete.Enabled = false;
btnUpdate.Enabled = false;
}

}

private void DeleteSelectedData()
{
if (MessageBox.Show("Do you really want to delete the selected record(s)?",
"Delete records", MessageBoxButtons.YesNo,
MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2, 0, false)
== DialogResult.Yes)
{
try
{

int cnt = userDataGridView.SelectedRows.Count;
for (int i = 0; i < cnt; i++)
{
if (this.userDataGridView.SelectedRows.Count > 0 &&
this.userDataGridView.SelectedRows[0].Index !=
this.userDataGridView.Rows.Count - 1)
{
this.userDataGridView.Rows.RemoveAt(
this.userDataGridView.SelectedRows[0].Index);
}
}

if(objdataset.HasChanges())
{
DataTable changes = objdataset.Tables[0].GetChanges();

if (changes != null)


objadapter.Update(changes);
objdataset.Tables[0].AcceptChanges();


}

}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{

}
}
if (userTable.Rows.Count == 0)
{
btnUpdate.Enabled = false;
if (mAllowDelete) btnDelete.Enabled = false;
}
IsModifications = true;
}

private void UpdateModifiedData()
{
try
{
objcon.Open();
objadapter.UpdateCommand = objbuilder.GetUpdateCommand();
objadapter.Update(userTable);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
objcon.Close();
}
}


private void btnUpdate_Click(object sender, EventArgs e)
{
UpdateModifiedData();
}

private void frmUpdateDBViaDataGridView_FormClosing(object sender, FormClosingEventArgs e)
{
if (IsModifications)
if (MessageBox.Show("Do you want to save changes?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2, 0, false) == DialogResult.Yes)
UpdateModifiedData();

}

private void userDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
//if (IsModifications)
// if (MessageBox.Show("Do you want to save changes?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2, 0, false) == DialogResult.Yes)
// UpdateModifiedData();

}

private void userDataGridView_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete) DeleteSelectedData();
e.Handled = true; // Cancel
}

#region events

public void userDataGridView_SelectionChanged(object sender, EventArgs e)
{
//if(userDataGridView.SelectedRows.Count > 0)
//{
// DataGridViewCellStyle style = new DataGridViewCellStyle();

// style.Font = new Font(userDataGridView.Font, FontStyle.Bold);

// style.ForeColor = System.Drawing.Color.DarkBlue;


// userDataGridView.SelectedRows[0].DefaultCellStyle = style;

//}
//else
//{
// // Deformat cells
//}
}

public void userDataGridView_CellEnter(object sender, DataGridViewCellEventArgs e)
{
//Font underLineFont = new Font(userDataGridView.Font, FontStyle.Underline);
//userDataGridView[e.ColumnIndex, e.RowIndex].Style.ForeColor = Color.OrangeRed;
//userDataGridView[e.ColumnIndex, e.RowIndex].Style.Font = underLineFont;
}

public void userDataGridView_CellLeave(object sender, DataGridViewCellEventArgs e)
{
//Font BoldFont = new Font(userDataGridView.Font, FontStyle.Bold);
//userDataGridView[e.ColumnIndex, e.RowIndex].Style.ForeColor = Color.Black;
//userDataGridView[e.ColumnIndex, e.RowIndex].Style.Font = BoldFont;
}
public void userDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{

if(((DataGridView)sender).CurrentCell.ColumnIndex==1)
{

// CurrentCell.EditedFormattedValue is key otherwise currentCell.Value will not work
if(((DataGridView)sender).CurrentCell.EditedFormattedValue.ToString().Length < 5)
{
((DataGridView)sender).CurrentRow.Cells[0].ErrorText = "Text Length could not be less than five";
e.Cancel = true;

}
else
{
((DataGridView)sender).CurrentRow.Cells[0].ErrorText = string.Empty;
}
}

}

public void userDataGridView_CellValidated(object sender, DataGridViewCellEventArgs e)
{

}


public void userDataGridView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
// restrict column i.e. primary key to get edit
if(((DataGridView)sender).CurrentCell.ColumnIndex==0)
{
e.Cancel = true;
}

// Changing font for the Editing cells
if(((DataGridView)sender).CurrentCell.ColumnIndex!=0)
{
((DataGridView)sender).CurrentCell.Style.ForeColor = Color.OrangeRed;
((DataGridView)sender).CurrentCell.Style.Font= new Font("Arial", 10F,FontStyle.Bold);
((DataGridView)sender).CurrentCell.Style.BackColor = Color.LightGray;
((DataGridView)sender).CurrentCell.Style.SelectionForeColor = Color.Yellow;

}
}

public void userDataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
// De-formattting the font for the Editing cells
if(((DataGridView)sender).CurrentCell.ColumnIndex!=0)
{
((DataGridView)sender).CurrentCell.Style.ForeColor = Color.Black;
((DataGridView)sender).CurrentCell.Style.Font= new Font("Arial", 8F, FontStyle.Bold);
((DataGridView)sender).CurrentCell.Style.BackColor = Color.White;
((DataGridView)sender).CurrentCell.Style.SelectionForeColor = Color.DarkBlue;



}
}

#endregion

}
}

Monday, February 8, 2010

Convert Text into Title Case/Sentance Case

public static string ConvertTextIntoSentanceCase(string strValue)
{
if(string.IsNullOrEmpty(strValue)) return string.Empty;


return new System.Globalization.CultureInfo("en").TextInfo.ToTitleCase(strValue.ToLower());


}
 
Locations of visitors to this page