How to restore a database programmatically in c#?

June 2, 2009

SQL Stored Procedure: Under master database

Create  procedure RestoreDatabase(@BackupFile varchar(500),@TestDB varchar(100),@RestoreFile varchar(500))

as

DECLARE @query varchar(2000)

DECLARE @DataFile varchar(2000)

SET @DataFile = @RestoreFile + ‘.mdf’

 

DECLARE @LogFile varchar(2000)

SET @LogFile = @RestoreFile + ‘.ldf’

IF EXISTS(SELECT * FROM sysdatabases WHERE name = @TestDB)

BEGIN

    SET @query = ‘DROP DATABASE ‘ + @TestDB

    EXEC (@query)

END

RESTORE HEADERONLY FROM DISK = @BackupFile

DECLARE @File int

SET @File = @@ROWCOUNT

DECLARE @Data varchar(500)

DECLARE @Log varchar(500)

SET @query = ‘RESTORE FILELISTONLY FROM DISK = ‘ + QUOTENAME(@BackupFile , ””)

CREATE TABLE #restoretemp

(

 LogicalName varchar(500),

 PhysicalName varchar(500),

 type varchar(10),

 FilegroupName varchar(200),

 size int,

 maxsize bigint

)

INSERT #restoretemp EXEC (@query)

SELECT @Data = LogicalName FROM #restoretemp WHERE type = ‘D’

SELECT @Log = LogicalName FROM #restoretemp WHERE type = ‘L’

PRINT @Data

PRINT @Log

TRUNCATE TABLE #restoretemp

DROP TABLE #restoretemp

IF @File > 0

BEGIN

    SET @query = ‘RESTORE DATABASE ‘ + @TestDB + ‘ FROM DISK = ‘ + QUOTENAME(@BackupFile, ””) +

        ‘ WITH MOVE ‘ + QUOTENAME(@Data, ””) + ‘ TO ‘ + QUOTENAME(@DataFile, ””) + ‘, MOVE ‘ +

        QUOTENAME(@Log, ””) + ‘ TO ‘ + QUOTENAME(@LogFile, ””) + ‘, FILE = ‘ + CONVERT(varchar, @File)

    EXEC (@query)

END

C# code

private void btnBrowse_Click(object sender, EventArgs e)

{

      openFileDialog1.ShowDialog();

      txtBackupFile.Text = openFileDialog1.FileName.ToString();

}

 

private void btnOK_Click(object sender, EventArgs e)

{

  SqlCommand cmd = new SqlCommand(“RestoreDatabase”, Connection);

  cmd.CommandType = CommandType.StoredProcedure;

  cmd.Parameters.Add(new SqlParameter(“@BackupFile”, txtBackupFile.Text));

  cmd.Parameters.Add(new SqlParameter(“@TestDB”, txtDatabaseName.Text));

  string RestoreFile=”c:\\”+txtDatabaseName.Text;

  cmd.Parameters.Add(new SqlParameter(“@RestoreFile”, RestoreFile));

 

  try

  {

      Connection.Open();

      cmd.ExecuteNonQuery();

      Connection.Close();

      MessageBox.Show(“Database Imported Succesfully”, “SUCCESS”);

  }

  catch (Exception ex)

  {

      MessageBox.Show(ex.ToString());

  }

}

Udhaya

How to create a database backup programmatically in c#?

June 2, 2009

SQL Stored Procedure:

Create  procedure BackupDatabase(@Location varchar(300))

as

Backup Database PACB to DISK = @Location

C# code:

private void btnBrowse_Click(object sender, EventArgs e)

{

     folderBrowserDialog1.ShowDialog();

    txtFileName.Text = folderBrowserDialog1.SelectedPath.ToString()+”\\DatabaseBackup.bak”;

}

 

private void btnOk_Click(object sender, EventArgs e)

{

   SqlCommand cmd = new SqlCommand(“BackupDatabase”, Connection);

   cmd.CommandType = CommandType.StoredProcedure;

   cmd.Parameters.Add(new SqlParameter(“@Location”, txtFileName.Text));

   try

   {

      Connection.Open();

      cmd.ExecuteNonQuery();

      Connection.Close();

      MessageBox.Show(“Database Backup Completed Succesfully”,”SUCCESS”);

  }

  catch (Exception ex)

  {

      MessageBox.Show(ex.ToString());

  }

}

Udhaya

How to change form size depending on screen resolution?

June 1, 2009

Suppose the screen resolution in which you design the form is 1024*768 then

Rectangle r = Screen.GetBounds(this);

this.Location = new Point(0, 0);

this.Size = r.Size;

double PercWidthChng = (r.Width – 1024);

PercWidthChng /= 1024;

double PercHeightChng = (r.Height – 768);

PercHeightChng /= 768;

 

foreach (Control c in this.Controls)

{

   double NewWidth = c.Width + (c.Width * PercWidthChng);

   double NewHeight = c.Height + (c.Height * PercHeightChng);

   double NewX = c.Location.X + (c.Location.X * PercWidthChng);

   double NewY = c.Location.Y + (c.Location.Y * PercHeightChng);

   double fontsize = c.Font.Size + (c.Font.Size * PercHeightChng);

   c.Width = (int)Math.Floor(NewWidth);

   c.Height = (int)Math.Floor(NewHeight);

   c.Location = new Point((int)NewX, (int)NewY);

   c.Font = new Font(c.Font.FontFamily, (int)fontsize, c.Font.Style);

}

Udhaya

How to close all forms except the active form in c#?

May 30, 2009

//In the main form

 private void MainMenu_Load(object sender, EventArgs e)

{

       this.IsMdiContainer = true;

}

//In the call to other forms

private void employeeDetailsToolStripMenuItem_Click(object sender, EventArgs e)

{

       try

      {

            this.ActiveMdiChild.Close();

      }

      catch

      {

      }

      EmployeeDetails obj = new EmployeeDetails();

      obj.MdiParent = this;

      obj.Show();

}

Udhaya

Pisquare

How to get MAC Address of a system in c#?

May 28, 2009

namespace: using System.Management;

string id=” “;

ManagementObjectSearcher query = null;

ManagementObjectCollection queryCollection = null;

 

      try

      {

               query = new ManagementObjectSearcher(“SELECT * FROM                                  Win32_NetworkAdapterConfiguration”);

            queryCollection = query.Get();

            foreach (ManagementObject mo in queryCollection)

            {

              if (mo[“MacAddress”] != null)

              {

                 id = mo[“MacAddress”].ToString();

                 MessageBox.Show(id);

              }

            }

      }

      catch (Exception ex)

      {

            MessageBox.Show(ex.Source);

            MessageBox.Show(ex.Message);

      }

Udhaya

Pisquare

How to add a new Row to Dataset at runtime?

May 27, 2009

Adding a new datarow to dataset

DateTable dt = new DataTable();

DataRow DRow = dt.NewRow();

 DRow[0] = “First Column of New Row”;

dt.Rows.Add(DRow);    //Dset.Tables[“TableName”]. Add(DRow);

Udhaya

Pisquare

How to add a new Column to Dataset at runtime?

May 27, 2009

Adding a new datacolumn to dataset

DateTable dt = new DataTable();

DataColumn DC = new DataColumn();

 DC.DataType = Type.GetType(“System.String”);

DC.ColumnName = “EmpName”;

dt.Columns.Add(DC);   //Dset.Tables[“EmpTable”]. Columns.Add(DC);  for DataSet

Udhaya

Pisquare

How to change font color at runtime in c#?

May 27, 2009

First drag and place colorDialog from toolbox into the form and in the event

label1.ForeColor = Color.Red;

Udhaya

Pisquare

How to select distinct records from a dataset using c#?

May 23, 2009

DSet.Tables[0].DefaultView.ToTable(

true, “ColumnName”);

Udhaya

How to read data from a text file in c#?

May 18, 2009

string filePath = @”c:\Sample.txt”;

string line,SNo=” “;

if (File.Exists(filePath))

{

StreamReader file = null;

try

{

file = new StreamReader(filePath);

while ((line = file.ReadLine()) != null)

{

Console.WriteLine(line);

//SNo = line.Substring(0,3);

}

}

finally

{

if (file != null)

file.Close();

}

}

Udhaya