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

Friday, May 22, 2009

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);

}