Wednesday, February 4, 2009

Preventing multiple instance of an application

Hi,

.Net framework's System.Threading namespace provides Mutex class which is a synchronization primitive that can also be used for interprocess synchronization. Using this mutex object we can also control running of multiple instances of a same application. Here is the sample code to do that. The code should be wriiten on the starting point of the application obviously for a windows or console application it would be the Main() function.

static class Program
{
///
/// The main entry point for the application.
///

[STAThread]
static void Main()
{
bool instanceCountOne = false;
using (Mutex mtex = new Mutex(true, "MyRunningApp", out instanceCountOne))
{
if (instanceCountOne)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
mtex.ReleaseMutex();
}
else
{
MessageBox.Show("An application instance is already running");
}
}
}
}


Note: Replace the application name with your corresponding application name. Include the namespace System.Threading.

Happy coding...


Thursday, January 22, 2009

Finding Start and End Dates of Previous Week

private void GetDates(ref System.DateTime stDate, ref System.DateTime endDate)
{
double offset = 0;
switch (System.DateTime.Today.DayOfWeek)
{
case DayOfWeek.Monday:
offset = 0;
break;
case DayOfWeek.Tuesday:
offset = -1;
break;
case DayOfWeek.Wednesday:
offset = -2;
break;
case DayOfWeek.Thursday:
offset = -3;
break;
case DayOfWeek.Friday:
offset = -4;
break;
case DayOfWeek.Saturday:
offset = -5;
break;
case DayOfWeek.Sunday:
offset = -6;
break;
}
endDate = System.DateTime.Today.AddDays(offset);
stDate = System.DateTime.Today.AddDays(-7 + offset);
}
courtesy : http://www.knowdotnet.com/articles/getpreviousmonday.html

Monday, January 19, 2009

Import from excel to datatable

private void btnImport_Click(object sender, EventArgs e)
{
OpenFileDialog openfileDialog1 = new OpenFileDialog();
openfileDialog1.Filter = "Excel files only (*.xls)|";
if (openfileDialog1.ShowDialog() == DialogResult.OK)
{
string FNExtn = Path.GetFileName(openfileDialog1.FileName);

string FN = Path.GetExtension(openfileDialog1.FileName);
string SaveLocation = Path.GetFullPath(openfileDialog1.FileName);
if (FN == ".xls")
{
sExcelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + SaveLocation + "; Extended Properties=\"Excel 8.0;IMEX=1;\"";
Import_sample(FNExtn);

}
else if (FN == ".xlsx")
{
sExcelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + SaveLocation + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";

Import_sample(FNExtn);

}
else if (FN != "xls" || FN != "xlsx")
{

//Alert message "Please Select an Excel File to import!"
}

}
}



private void Import_sample(string FNE)
{
DataSet myDataSet = new DataSet();
DataTable dtFile = new DataTable();
try
{
//You must use the $ after the object you reference in the spreadsheet
OleDbConnection excelConnection = new OleDbConnection(sExcelConnectionString);
excelConnection.Open();

DataTable dtSheetName = new DataTable();

dtSheetName = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = "";
foreach (DataRow row in dtSheetName.Rows)
{
string strSheetTableName = row["TABLE_NAME"].ToString(); //dtSheetName.Rows[0]["TABLE_NAME"].ToString();
if (strSheetTableName.Length > 1)
SheetName = strSheetTableName.Substring(0, strSheetTableName.Length - 1).Replace("$", "").Replace("'", "");

OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [" + SheetName + "$]", sExcelConnectionString);
myCommand.Fill(myDataSet, "Import");

if (myDataSet.Tables["Import"].Rows.Count > 0 && SheetName == "Sheet1")
{

dtFile = myDataSet.Tables["Import"]; // All the records are filled in a datatable - dtFile

string sheet1col1 = dtFile.Columns[0].ColumnName.ToString().Trim().Replace(":", "");
string sheet1col2 = dtFile.Columns[1].ColumnName.ToString().Trim().Replace(":", "");

if (sheet1col1.Trim() == "Name" && sheet1col2.Trim() == "Type") // (SheetName == sheet)
{


}


}
}
}
catch (Exception)
{
throw;
}
}


Thursday, January 15, 2009

Custom Active Directory user authentication

This function helps to authenticate user in active directory. Can use provide windows authentication in a form authentication websites too.

DNS Name format: "LDAP://DNSName"

private bool ValidateUser(string dnsname,string username,string password)
{
try
{
DirectoryEntry entry = new DirectoryEntry(dnsname, username, password);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
SearchResultCollection results;
mySearcher.Filter = "cn";
results = mySearcher.FindAll();
if (results == null)
{
lblError.Text = "Invalid User";
return false;
}
else
{
lblError.Text = "User Found";
return true;
}
}
catch
{
lblError.Text = "Invalid User";
return false;
}
}

File Size Formatting in C#

Have you ever wanted to display the size of the file in bytes, kilo bytes or mega bytes, here is a simple code snippet to do that.


private string FormatSize (double fileSize)
{
if (fileSize < 1024)
return String.Format(”{0:N0} B”, fileSize);
else if (fileSize < 1024*1024)
return String.Format(”{0:N2} KB”, fileSize/1024);
else
return String.Format(”{0:N2} MB”, fileSize/(1024*1024));
}


[Posted By Yenkay]