This blog is moved to
http://amalhashim.wordpress.com

Sunday, May 31, 2009

Achieved a great milestone in MSDN forums

Monday, May 25, 2009

Single Instance application using C#

Single instance application.

We can use two ways to solve this problem.
1. Using Mutex
2. Using Process list and checking for the any other running instance

Option1

static void Main() {
bool running;
System.Threading.Mutex mutex = new System.Threading.Mutex(true, "applicationName", out running);
if(!running) {
MessageBox.Show("Another instance is already running.");
return;
}
Application.Run(new Form1());
GC.KeepAlive(mutex);
}

Option2

static void Main() {
bool flag;
Process curr = Process.GetCurrentProcess();
Process[] procs = Process.GetProcessesByName(curr.ProcessName);
foreach (Process p in procs) {
if ((p.Id != curr.Id) && (p.MainModule.FileName == curr.MainModule.FileName)) {
flag = true;
break;
}
}

if(flag) {
MessageBox.Show("Application already running");
return;
}

Application.Run(new Form1());
}

Friday, May 22, 2009

Linq and C# - Part 2

Linq queries with Restriction Operators

1=>


Prints each element of an input integer array whose value is less than 5.

int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0);

var lowNums = from n in numbers
where n < 5 select n;

foreach(var x in lowNums) {
Console.WriteLine(x);
}

2=>

class Product {
string ProducName { get; set; }
int Units { get; set; }
int Price { get; set; }
}

Listing of all products that are out of stock.

// Fill products

var soldOutProducts = from p in products
where p.Units == 0
select p;

foreach(var pr in soldOutProducts) {
Console.WriteLine(pr.Name);
}

3=>

Lists all expensive items in stock.

var expensiveInStockProducts =
from p in products
where p.Units > 0 && p.Price > 3

foreach (var product in expensiveInStockProducts) {
Console.WriteLine(product.Name);
}

4=>

This sample uses an indexed Where clause to print the name of each number, from 0-9, where the length of the number's name is shorter than its value. In this case, the code is passing a lamda expression which is converted to the appropriate delegate type. The body of the lamda expression tests whether the length of the string is less than its index in the array.

string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };

var shortDigits = digits.Where((digit, index) => digit.Length < index);

Console.WriteLine("Short digits:");
foreach (var d in shortDigits) {
Console.WriteLine("The word {0} is shorter than its value.", d);
}

Get Path where the Executable is running from in C#

Option#1
string path1 = System.Windows.Forms.Application.ExecutablePath;

Option#2
String path2 = System.Reflection.Assembly.GetExecutingAssembly().Location;

Database Backup/Restore using C#

Add a reference of SQLDMO Object



// The application object for getting server list
SQLDMO.Application sqlApp = new SQLDMO.ApplicationClass();
//NameList variable for server name collection
SQLDMO.NameList sqlServers = null;
//get all available SQL Servers
sqlServers = sqlApp.ListAvailableSQLServers();
List servers = new List();
for (int i = 0; i < sqlServers.Count; i++)
{
object srv = sqlServers.Item(i + 1);
if (srv != null)
{
servers.Add(srv);
}
}

/// Connecting
SQLDMO.SQLServer srv = new SQLDMO.SQLServerClass();
srv.Connect(stringServer, userName, password);

/// Getting All databases
List databases = new List();
foreach (SQLDMO.Database db in srv.Databases)
{
if (db.Name != null)
databases.Add(db.Name);
}

///Backup
//create an instance of a server class
SQLDMO._SQLServer srv = new SQLDMO.SQLServerClass();
//connect to the server
srv.Connect(stringServer, userName, password);
//create a backup class instance
SQLDMO.Backup bak = new SQLDMO.BackupClass();
//set the backup device = files property ( easy way )
bak.Devices = bak.Files;
//set the files property to the File Name text box
bak.Files = "filepath";
//set the database to the chosen database
bak.Database = "databasetobackup";
//perform the backup
bak.SQLBackup(srv);


///Restore
//create an instance of a server class
SQLDMO._SQLServer srv = new SQLDMO.SQLServerClass();
//connect to the server
srv.Connect(stringServer, userName, password);
//create a restore class instance
SQLDMO.Restore res = new SQLDMO.RestoreClass();
//set the backup device = files property ( easy way )
res.Devices = res.Files;
//set the files property to the File Name text box
res.Files = "filepath";
//set the database to the chosen database
res.Database = "database";
// Restore the database
res.ReplaceDatabase = true;
res.SQLRestore(srv);

Thursday, May 21, 2009

Linq and C# - Part 1

Linq => Language Integrated Query

3 Parts of Linq Query

1. Obtain data source
2. Create the query
3. Execute the query

static void Main()
{
// The Three Parts of a LINQ Query:
// 1. Data source.
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

// 2. Query creation.
// numQuery is an IEnumerable
var numQuery =
from num in numbers
where (num % 2) == 0
select num;

// 3. Query execution.
foreach (int num in numQuery)
{
Console.Write("{0,1} ", num);
}
}

DataSource


In LINQ the execution of the query is distinct from the query itself;in other words you have not retrieved any data just by creating a query variable.

The datasource must support IEnumerable interface.

Query

The query expression contains three clauses: from, where and select. The from clause specifies the data source, the where clause applies the filter, and the select clause specifies the type of the returned elements.

Execution

the query variable itself only stores the query commands. The actual execution of the query is deferred until you iterate over the query variable in a foreach statement. This concept is referred to as deferred execution.

Forcing Immediate Execution : Queries that perform aggregation functions over a range of source elements must first iterate over those elements. Examples of such queries are Count, Max, Average, and First. These execute without an explicit foreach statement because the query itself must use foreach in order to return a result.

Saturday, May 16, 2009

Move Folders Accross Drives or Volumes using C#

public void MoveDirectory(string strSourceDir,string strDestDir,bool bDelSource)
{
if (Directory.Exists(strSourceDir))
{
if (Directory.GetDirectoryRoot(strSou­ rceDir) == Directory.GetDirectoryRoot(strDest­ Dir))
{
Directory.Move(strSourceDir, strDestDir);
}
else
{
try
{
CopyDirectory(new DirectoryInfo(strSourceDir),new DirectoryInfo(strDestDir));
if (bDelSource)Directory.Delete(strSo­ urceDir, true);
}
catch (Exception subEx)
{
throw subEx;
}
}
}
}

private void CopyDirectory(DirectoryInfo diSourceDir,DirectoryInfo diDestDir)
{
if (!diDestDir.Exists)diDestDir.Create();­
FileInfo[] fiSrcFiles = diSourceDir.GetFiles();
foreach (FileInfo fiSrcFile in fiSrcFiles)
{
fiSrcFile.CopyTo(Path.Combine(diDe­ stDir.FullName, fiSrcFile.Name));
}
DirectoryInfo[] diSrcDirectories = diSourceDir.GetDirectories();
foreach (DirectoryInfo diSrcDirectory in diSrcDirectories)
{
CopyDirectory(diSrcDirectory, new DirectoryInfo(Path.Combine(diDestD­ ir.FullName, diSrcDirectory.Name)));
}
}

List All Active IP Address in a Network using C#

using System.Net.NetWorkInformation;

IPGlobalProperties network = IPGlobalProperties. GetIPGlobalProperties();
TcpConnectionInformation[] connections = network. GetActiveTcpConnections();

Friday, May 15, 2009

Command Prompt History

In command prompt we can use the command doskey /history

Another cool feature is in command window just press f7


Sorting DropDownList Using Linq

C#
protected void btnSortNames_Click(object sender, EventArgs e)
{
cboNames.DataSource = cboNames.Items.Cast<ListItem>()
.OrderByDescending(o => o.Text)
.ToList();
cboNames.DataBind();
}
protected void btnSortAscending_Click(object sender, EventArgs e)
{
cboNames.DataSource = cboNames.Items.Cast<ListItem>()
.OrderBy(o => o.Text)
.ToList();
cboNames.DataBind();
}


VB.NET


Protected Sub btnSortNames_Click(ByVal sender As Object, ByVal e As EventArgs)
cboNames.DataSource = cboNames.Items.Cast(Of ListItem)().OrderByDescending(Function(o) o.Text).ToList()
cboNames.DataBind()
End Sub
Protected Sub btnSortAscending_Click(ByVal sender As Object, ByVal e As EventArgs)
cboNames.DataSource = cboNames.Items.Cast(Of ListItem)().OrderBy(Function(o) o.Text).ToList()
cboNames.DataBind()
End Sub

Monday, May 11, 2009

Runtime app.config modification

static void Main(string[] args)
{
UpdateAppSettings("abc", "value1000");
ConfigurationManager.RefreshSection("appsettings");
Console.WriteLine(ConfigurationManager.AppSettings["abc"]);
}

static void UpdateAppSettings(String KeyName, String KeyValue)
{
XmlDocument XmlDoc = new XmlDocument();

XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

foreach(XmlElement xElement in XmlDoc.DocumentElement)
{
if(xElement.Name == "appSettings")
{
foreach(XmlNode xNode in xElement.ChildNodes)
{
if(xNode.Attributes[0].Value == KeyName)
{
xNode.Attributes[1].Value = KeyValue;
}
}
}

}

XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

}