Saturday, May 28, 2011

(3) Winapp-‘how to read values from your application’s properties.

In this post I will talk briefly about ‘how to read values from your application’s properties‘, I mean resources and settings like images, icons and connection string.

Step 1 Create new windows application ‘language does not matter C# or VB’

Step 2 Adding images in your resources: in solution explorer right-click on your application name >> then >> Properties >> then >> on your left hand click Resources >> then >> click Images >> then >> from the next icon ‘Add Resource’ choose ‘Add Existing Files ..’.

Step 3 Adding connection string in your application setting: like step 2 but here you will click on ‘Setting’ on your left hand, it is the second button bellow ‘Resources’ >> then >> you will see control like DataGrid, write what name you want to call your connection string, we can call it ‘con_Northwind’, from type select (Connection string), then on value field the wizard will help you to configure your connection easily.

Step 4 save your change and be ready for coding.

by the way I will give you the code in simple example that will help you to know how to read those values, on form1 load event write the following code, by the way code will change [icon form], [text form] and picture I have dragged from toolbox, and I will give it its Image by code.

VB code:
Me.Icon = My.Resources.heart
Me.PictureBox1.Image = My.Resources.cartoon_police
Me.Text = My.Settings.con_Northwing.ToString()

C# code:
this.Icon = CSharp_WinApp.Properties.Resources.heart;
pictureBox1.Image = CSharp_WinApp.Properties.Resources.cartoon_police;
this.Text = Properties.Settings.Default.con_Northwind.ToString();

Notes :
1- you can add pictures as many as you want.
2- You can choose icon, audio file or any type of files you want to use in your application.

I hope it was simple and clear enough for you.

Thursday, May 26, 2011

(2) WinApp-How to backup & restore your sql database by code

In this post I will create 2 voids, one we will use to create a backup for our sql server database, and the other void we will use to restore the backup, our database name is ‘Northwind’.

C# Code:

//add these classes to your project

using System.Data.SqlClient;

using System.IO;

VB Code:

Imports System.IO

Imports System.Data.SqlClient

C# Code:

//backup datebase, to use ità createBackup(“databasename”)

private void createBackup(string dbName)

{

//connection string (with master database) I read it from application properties

SqlConnection _conMasterDatabase = new SqlConnection(Properties.Settings.Default.con_dbMaster);

try

{

if (MessageBox.Show("Are you sure of this operation?", "Attention; please", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)

{

SqlCommand _cmd = new SqlCommand();

_cmd.Connection = _conMasterDatabase;

//creating object from Save-file-dialog to save the backup file

SaveFileDialog _saveFile = new SaveFileDialog();

_saveFile.AddExtension = true;

_saveFile.DefaultExt = "bak";

_saveFile.Title = "Please; rename the backup file.";

_saveFile.Filter = "backup files (*.bak)|*.bak|All files (*.*)|*.*";

_saveFile.FilterIndex = 1;

if (_saveFile.ShowDialog() == DialogResult.OK)

{

//dynamic command text, dbName refers to my database name I want to create a backup from

_cmd.CommandText = "backup database " + dbName.ToString() + " to disk = '" + _saveFile.FileName + "'";

if (_conMasterDatabase.State == ConnectionState.Closed)

{

_conMasterDatabase.Open();

}

try

{

_cmd.ExecuteNonQuery();

MessageBox.Show("Operation succeeded; Please re-open your application if you want to use it now.", "Congratulation!");

}

catch (Exception exx)

{

MessageBox.Show(string.Format("{0} , {1}{2}", exx.Message.ToString(), "\n", "Operation did not succeed."), "Error");

}

}

}

}

catch (Exception ex)

{

MessageBox.Show(ex.Message.ToString(), "Error");

}

finally

{

if (_conMasterDatabase.State == ConnectionState.Open)

{

_conMasterDatabase.Close();

}

}

}

VB Code:

'create backup file, you can use it like this [createBackup("Northwind")]

Private Sub createBackup(ByVal dbName As String)

Dim conMasterdb As New SqlConnection(My.Settings.con_dbMaster.ToString())

If MessageBox.Show("Are you sure of this operation?", "Attention; please", MessageBoxButtons.OKCancel) = Windows.Forms.DialogResult.OK Then

Dim savefile As New SaveFileDialog()

savefile.AddExtension = True

savefile.DefaultExt = "bak"

savefile.Title = "Please; rename the backup file."

savefile.Filter = "backup files (*.bak)|*.bak|All files (*.*)|*.*"

savefile.FilterIndex = 1

If savefile.ShowDialog() = Windows.Forms.DialogResult.OK Then

Dim cmd As New SqlCommand("backup database " + dbName.ToString() + " to disk = '" + savefile.FileName + "'", conMasterdb)

If conMasterdb.State = ConnectionState.Closed Then

conMasterdb.Open()

End If

Try

cmd.ExecuteNonQuery()

MessageBox.Show("Operation succeeded; Please re-open your application if you want to use it now.", "Congratulation!")

Catch ex As Exception

MessageBox.Show(ex.Message.ToString() & vbCrLf & "Operation did not succeed." & "Error")

Finally

If conMasterdb.State = ConnectionState.Open Then

conMasterdb.Close()

End If

End Try

End If

End If

End Sub

C# Code:

//restore database, you can call it easily restoreBackup(“databasename”)

private void restoreBackup(string dbName)

{

//connection string (with master database) I read it from application properties

SqlConnection _conMasterDatabase = new SqlConnection(Properties.Settings.Default.con_dbMaster);

try

{

//create object from open-file-dialog to select a backup file which I want to restore

OpenFileDialog _ofDialog = new OpenFileDialog();

_ofDialog.AddExtension = true;

_ofDialog.DefaultExt = "bak";

_ofDialog.Title = "Select backup file to restore";

_ofDialog.Filter = "backup files (*.bak)|*.bak|All files (*.*)|*.*";

_ofDialog.FilterIndex = 1;

if (_ofDialog.ShowDialog() == DialogResult.OK)

{

if (_conMasterDatabase.State == ConnectionState.Closed)

{

_conMasterDatabase.Open();

}

string _bakFilePath = _ofDialog.FileName;

SqlCommand _cmd = new SqlCommand(string.Format("alter database {0} set single_user with rollback immediate;exec sp_dboption {1} ,'offline' ,'TRUE';restore database {2} from disk = '{3}' with REPLACE", dbName.ToString(), dbName.ToString(), dbName.ToString(), _bakFilePath), _conMasterDatabase);

_cmd.ExecuteNonQuery();

MessageBox.Show("Operation succeeded,Please re-open the application.", "Attention!");

}

}

catch (Exception exx)

{

MessageBox.Show(string.Format("{0} , {1}{2}", exx.Message.ToString(), "\n", "Operation did not succeed."), "Error");

}

finally

{

if (_conMasterDatabase.State == ConnectionState.Open)

{

_conMasterDatabase.Close();

}

}

}

VB Code:

'restore backup, you can use it like this [restoreBackup("Northwind")]

Private Sub restoreBackup(ByVal dbName As String)

Dim conMasterdb As New SqlConnection(My.Settings.con_dbMaster.ToString())

Dim ofDialog As New OpenFileDialog()

ofDialog.AddExtension = True

ofDialog.DefaultExt = "bak"

ofDialog.Title = "Select backup file to restore"

ofDialog.Filter = "backup files (*.bak)|*.bak|All files (*.*)|*.*"

ofDialog.FilterIndex = 1

If ofDialog.ShowDialog() = DialogResult.OK Then

Dim bakFilePath As String = ofDialog.FileName

If conMasterdb.State = ConnectionState.Closed Then

conMasterdb.Open()

End If

Dim cmd As New SqlCommand(String.Format("alter database {0} set single_user with rollback immediate;exec sp_dboption {1} ,'offline' ,'TRUE';restore database {2} from disk = '{3}' with REPLACE", dbName.ToString(), dbName.ToString(), dbName.ToString(), bakFilePath), conMasterdb)

Try

cmd.ExecuteNonQuery()

MessageBox.Show("Operation succeeded,Please re-open the application.", "Congratulation!")

Catch ex As Exception

MessageBox.Show(ex.Message.ToString() & vbCrLf & "Operation did not succeed." & "Error")

Finally

If conMasterdb.State = ConnectionState.Open Then

conMasterdb.Close()

End If

End Try

End If

End Sub

(1) Shortcuts for some programming idioms

CLR: Common Language Run-time [the main stage to translate .net codes]

CTS: Common Type System [class – interface – structure – enumeration - delegates]

CLS: Common Language Specification

MSIL: Microsoft Intermediate Language

IDE: Integrated Development Environment

DFD: Data Flow Diagram

UML: Unified Modeling Language

ERD: Entity Relationship Diagram

DML: Data Manipulation Language (insert – update – delete)

DDL: Data definition Language (drop – alter – select)