string filePath = General.GetUserDirectory(hidUserID.Value);
//Create the query to be sent to the database
string _strWhere = "where iduser = '" + hidUserID.Value + "' and location like '%" + hidFileOrFolderName.Value + "%'";
DataSet ds = new DataSet();
//Fill the dataset with the rows to be manipulated
ds = FileFolderDB.GetMultipleRows(_strWhere);
//Save the dataset in the session for the rollback operations if the database update fails
Session["DataTableBackUp"] = ds;
try
{
//Check if dataset 'ds' has any tables in it
if (ds.Tables.Count > 0)
{
#region Loop through the data set and perform database update operations
//Loop through the first table in dataset 'ds'
for (int j = 0; ds.Tables[0].Rows.Count > 0 && j < ds.Tables[0].Rows.Count; j++)
{
//Assign values from the Table
string FolderLocation = ds.Tables[0].Rows[j]["location"].ToString();
string _strFolderID = ds.Tables[0].Rows[j]["idFileFolder"].ToString();
string _strUserID = ds.Tables[0].Rows[j]["idUser"].ToString();
string _isFolder = ds.Tables[0].Rows[j]["IsDirectory"].ToString();
string _filename = ds.Tables[0].Rows[j]["Name"].ToString();
//Check if the folderlocation has any match with the compare string
//Build first compare string with complete path of the selected folder location
string _strCompareString = hidFolder.Value;
//Escape any metacharacters in the string for absolute pattern match
_strCompareString = Regex.Escape(_strCompareString);
//Finally build our custom compare string to detect a specific pattern
_strCompareString = _strCompareString + ".";
// Check if the file/folder path matches with our compare string
if (Regex.IsMatch(FolderLocation, _strCompareString))
{
//Create another compare string to detect all the files and folder within the selected folder
string _strCompareString2 = hidFolder.Value + hidFileOrFolderName.Value;
_strCompareString2 = Regex.Escape(_strCompareString2);
_strCompareString2 = _strCompareString2 + ".";
//Build the replace string which has the full path of folder renamed
string _strReplaceString = hidFolder.Value + txtRenameFolder.Text.Trim();
//Split the path after the selected folder name
string[] split = Regex.Split(FolderLocation, _strCompareString2);
//Attach the full path of new folder along with above retrieved content of string
string temp = _strReplaceString + @"\" + split[1].ToString();
//Create an object of file folder for database insertion
FileFolder ff = new FileFolder();
//Set the attributes of filefolder
ff.UserID = Convert.ToInt64(_strUserID);
ff.ID = Convert.ToInt64(_strFolderID);
ff.Location = temp;
//Checksum calculation only for description purpose
if (_isFolder == "False")
{
string checksum = General.CalculateFileCheckSum( filePath+ ff.Location + _filename);
}
Database db = new Database();
// Finally update the file/folder details with new attributes
FileFolderDB.renameFolder(db, ff);
}
}
#endregion
}
}
catch (Exception ex)
{
//When an exception occurs rollback the database to the state it was before
RollbackRenameUpdate(ds);
//Finally log the error
General.ExceptionOccured(ex);
}
Tuesday, November 30, 2010
Tuesday, November 23, 2010
How to create a persistent cookie?
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class RememberMe : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["UserName"] != null && Request.Cookies["PassWord"] != null)
{
txtUsername.Text = Request.Cookies["UserName"].Value;
txtPassword.Text = Request.Cookies["PassWord"].Value;
}
else
{
HttpBrowserCapabilities objBrowsCap;
objBrowsCap = Request.Browser;
if (objBrowsCap.Cookies)
{
lblMessage.Text = "Cookies Enabled";
}
else
{
lblMessage.Text = "Cookies Disabled";
}
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
HttpCookie UserNameCookie = new HttpCookie("UserName", txtUsername.Text.ToString());
HttpCookie PasswordCookie = new HttpCookie("PassWord", txtPassword.Text.ToString());
UserNameCookie.Expires = System.DateTime.Now.AddDays(1);
PasswordCookie.Expires = System.DateTime.Now.AddDays(1);
Response.Cookies.Add(UserNameCookie);
Response.Cookies.Add(PasswordCookie);
lblMessage.Text = "You have logged in successfully";
}
}
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class RememberMe : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["UserName"] != null && Request.Cookies["PassWord"] != null)
{
txtUsername.Text = Request.Cookies["UserName"].Value;
txtPassword.Text = Request.Cookies["PassWord"].Value;
}
else
{
HttpBrowserCapabilities objBrowsCap;
objBrowsCap = Request.Browser;
if (objBrowsCap.Cookies)
{
lblMessage.Text = "Cookies Enabled";
}
else
{
lblMessage.Text = "Cookies Disabled";
}
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
HttpCookie UserNameCookie = new HttpCookie("UserName", txtUsername.Text.ToString());
HttpCookie PasswordCookie = new HttpCookie("PassWord", txtPassword.Text.ToString());
UserNameCookie.Expires = System.DateTime.Now.AddDays(1);
PasswordCookie.Expires = System.DateTime.Now.AddDays(1);
Response.Cookies.Add(UserNameCookie);
Response.Cookies.Add(PasswordCookie);
lblMessage.Text = "You have logged in successfully";
}
}
Monday, November 15, 2010
File system watcher syncs to a private folder
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileUploader
{
class Program
{
static void Main(string[] args)
{
Run();
}
public static void Run()
{
FileSystemWatcher Watcher = new FileSystemWatcher(Environment.GetEnvironmentVariable("USERPROFILE"));
Watcher.Path = @"E:\Sameer";
Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
Watcher.Filter = "*.txt";
Watcher.Created += new FileSystemEventHandler(Watcher_Created);
Watcher.Changed += new FileSystemEventHandler(Watcher_Changed);
Watcher.Renamed += new RenamedEventHandler(Watcher_Renamed);
Watcher.Deleted += new FileSystemEventHandler(Watcher_Deleted);
Watcher.EnableRaisingEvents = true;
Console.ReadKey();
}
static void Watcher_Created(object sender, FileSystemEventArgs e)
{
try
{
string fileName = System.IO.Path.GetFileName(e.FullPath);
Console.WriteLine("File : " + e.FullPath + " Change Type is : " + e.ChangeType);
System.IO.File.Copy(e.FullPath, @"C:\Users\sameer\Documents\Visual Studio 2008\Projects\FileUploader\FileUploader\Uploaded Docs\" + fileName , true);
}
catch(Exception ex)
{
Console.WriteLine("Problem occured");
}
}
static void Watcher_Deleted(object sender, FileSystemEventArgs e)
{
Console.WriteLine("File : " + e.FullPath + " Change Type is : " + e.ChangeType);
}
static void Watcher_Renamed(object sender, RenamedEventArgs e)
{
try
{
Console.WriteLine("File : " + e.FullPath + " Change Type is : " + e.ChangeType);
string fileName = System.IO.Path.GetFileName(e.FullPath);
System.IO.File.Move(@"C:\Users\sameer\Documents\Visual Studio 2008\Projects\FileUploader\FileUploader\Uploaded Docs\" + e.OldName, @"C:\Users\sameer\Documents\Visual Studio 2008\Projects\FileUploader\FileUploader\Uploaded Docs\" + fileName);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
static void Watcher_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine("File : " + e.FullPath + " Change Type is : " + e.ChangeType);
try
{
string fileName = System.IO.Path.GetFileName(e.FullPath);
Console.WriteLine("File : " + e.FullPath + " Change Type is : " + e.ChangeType);
System.IO.File.Copy(e.FullPath, @"C:\Users\sameer\Documents\Visual Studio 2008\Projects\FileUploader\FileUploader\Uploaded Docs\" + fileName ,true );
}
catch (Exception ex)
{
Console.WriteLine("Problem occured" + ex.ToString());
}
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileUploader
{
class Program
{
static void Main(string[] args)
{
Run();
}
public static void Run()
{
FileSystemWatcher Watcher = new FileSystemWatcher(Environment.GetEnvironmentVariable("USERPROFILE"));
Watcher.Path = @"E:\Sameer";
Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
Watcher.Filter = "*.txt";
Watcher.Created += new FileSystemEventHandler(Watcher_Created);
Watcher.Changed += new FileSystemEventHandler(Watcher_Changed);
Watcher.Renamed += new RenamedEventHandler(Watcher_Renamed);
Watcher.Deleted += new FileSystemEventHandler(Watcher_Deleted);
Watcher.EnableRaisingEvents = true;
Console.ReadKey();
}
static void Watcher_Created(object sender, FileSystemEventArgs e)
{
try
{
string fileName = System.IO.Path.GetFileName(e.FullPath);
Console.WriteLine("File : " + e.FullPath + " Change Type is : " + e.ChangeType);
System.IO.File.Copy(e.FullPath, @"C:\Users\sameer\Documents\Visual Studio 2008\Projects\FileUploader\FileUploader\Uploaded Docs\" + fileName , true);
}
catch(Exception ex)
{
Console.WriteLine("Problem occured");
}
}
static void Watcher_Deleted(object sender, FileSystemEventArgs e)
{
Console.WriteLine("File : " + e.FullPath + " Change Type is : " + e.ChangeType);
}
static void Watcher_Renamed(object sender, RenamedEventArgs e)
{
try
{
Console.WriteLine("File : " + e.FullPath + " Change Type is : " + e.ChangeType);
string fileName = System.IO.Path.GetFileName(e.FullPath);
System.IO.File.Move(@"C:\Users\sameer\Documents\Visual Studio 2008\Projects\FileUploader\FileUploader\Uploaded Docs\" + e.OldName, @"C:\Users\sameer\Documents\Visual Studio 2008\Projects\FileUploader\FileUploader\Uploaded Docs\" + fileName);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
static void Watcher_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine("File : " + e.FullPath + " Change Type is : " + e.ChangeType);
try
{
string fileName = System.IO.Path.GetFileName(e.FullPath);
Console.WriteLine("File : " + e.FullPath + " Change Type is : " + e.ChangeType);
System.IO.File.Copy(e.FullPath, @"C:\Users\sameer\Documents\Visual Studio 2008\Projects\FileUploader\FileUploader\Uploaded Docs\" + fileName ,true );
}
catch (Exception ex)
{
Console.WriteLine("Problem occured" + ex.ToString());
}
}
}
}
Decrypt a string using a specific given key
public static string Decrypt(string strEncrypted)
{
try
{
TripleDESCryptoServiceProvider objDESCrypto = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();
byte[] byteHash, byteBuff;
string strTempKey = _key;
byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
objHashMD5 = null;
objDESCrypto.Key = byteHash;
objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB
byteBuff = Convert.FromBase64String(strEncrypted);
string strDecrypted = ASCIIEncoding.ASCII.GetString(objDESCrypto.CreateDecryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
objDESCrypto = null;
return strDecrypted;
}
catch (Exception ex)
{
General.ExceptionOccured(ex);
return "";
}
}
{
try
{
TripleDESCryptoServiceProvider objDESCrypto = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();
byte[] byteHash, byteBuff;
string strTempKey = _key;
byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
objHashMD5 = null;
objDESCrypto.Key = byteHash;
objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB
byteBuff = Convert.FromBase64String(strEncrypted);
string strDecrypted = ASCIIEncoding.ASCII.GetString(objDESCrypto.CreateDecryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
objDESCrypto = null;
return strDecrypted;
}
catch (Exception ex)
{
General.ExceptionOccured(ex);
return "";
}
}
Encrypt a string using a given key?
public static string Encrypt(string strToEncrypt)
{
try
{
TripleDESCryptoServiceProvider objDESCrypto = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();
byte[] byteHash, byteBuff;
string strTempKey = "Sameer";
byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
objHashMD5 = null;
objDESCrypto.Key = byteHash;
objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB
byteBuff = ASCIIEncoding.ASCII.GetBytes(strToEncrypt);
return Convert.ToBase64String(objDESCrypto.CreateEncryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
}
catch (Exception ex)
{
General.ExceptionOccured(ex);
return "";
}
}
{
try
{
TripleDESCryptoServiceProvider objDESCrypto = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();
byte[] byteHash, byteBuff;
string strTempKey = "Sameer";
byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
objHashMD5 = null;
objDESCrypto.Key = byteHash;
objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB
byteBuff = ASCIIEncoding.ASCII.GetBytes(strToEncrypt);
return Convert.ToBase64String(objDESCrypto.CreateEncryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
}
catch (Exception ex)
{
General.ExceptionOccured(ex);
return "";
}
}
Sunday, November 14, 2010
How to log errors to a Log file everytime an exceptions occurs?
string folder = AppDomain.CurrentDomain.BaseDirectory + GetAppSetting("LogFileDirectory") + "\\";
CreateDirectory(folder);
Exception objErr = ex;
StringBuilder err = new StringBuilder();
string eol = Environment.NewLine;
err.Append("Error Time: ").Append(DateTime.Now.Hour).Append(":").Append(DateTime.Now.Minute).Append(eol);
err.Append("Error Message: ").Append(objErr.Message).Append("\nStack Trace:\n").Append(objErr.StackTrace);
err.Append("\n**********************************************************************\n");
if (Convert.ToBoolean(GetAppSetting("SendErrorMail")))
{
//Send mail to support when error occured
string email = GetAppSetting("SupportEmail");
Email.SendEmail(err.ToString(), email, "", email, "", "Error Message");
}
string sErrorTime = DateTime.Now.ToString("dd-MM-yy");
StreamWriter sw = new StreamWriter(folder + sErrorTime + ".txt", true);
sw.WriteLine(err);
sw.Flush();
sw.Close();
CreateDirectory(folder);
Exception objErr = ex;
StringBuilder err = new StringBuilder();
string eol = Environment.NewLine;
err.Append("Error Time: ").Append(DateTime.Now.Hour).Append(":").Append(DateTime.Now.Minute).Append(eol);
err.Append("Error Message: ").Append(objErr.Message).Append("\nStack Trace:\n").Append(objErr.StackTrace);
err.Append("\n**********************************************************************\n");
if (Convert.ToBoolean(GetAppSetting("SendErrorMail")))
{
//Send mail to support when error occured
string email = GetAppSetting("SupportEmail");
Email.SendEmail(err.ToString(), email, "", email, "", "Error Message");
}
string sErrorTime = DateTime.Now.ToString("dd-MM-yy");
StreamWriter sw = new StreamWriter(folder + sErrorTime + ".txt", true);
sw.WriteLine(err);
sw.Flush();
sw.Close();
Subscribe to:
Posts (Atom)