Friday, March 15, 2013

TO BACKUP SQL SERVER DATABASE USING ADO.NET

Imports System.Data.SqlClient

Public Sub GenerateBackup()
 Using xCon As New SqlConnection(<<ConnectionString>>), _
            Cmd As New SqlCommand
                xCon.Open()
                Cmd.Connection = xCon
                Cmd.CommandText = "BACKUP DATABASE @dbFile TO DISK= @Target WITH FORMAT"
       
        sqlCmd.Parameters.AddWithValue("@dbFile ","<<DatabaseFile>>")
        '//<<DatabaseFile>> -- IF AN ATTACHED DATABASE FILE, SPECIFY THE FULL PATH AND FILE NAME [ie 'C:\MyDbSpace\db.mdf']
                       OTHERWISE SPECIFY THE DATABASE NAME

         sqlCmd.Parameters.AddWithValue("@Target  ","<<BackupFilePath & FileName>>")
                Cmd.ExecuteNonQuery()
                xCon.Close()
End Using

Thursday, March 14, 2013

COMBO BOX DATA BINDING


Public Sub PopulateComboBox(ByRef Combo As ComboBox, ByVal SQl As String)

        Try
            Dim DS As New DataSet
            Dim DA As New SqlClient.SqlDataAdapter
            Dim TableName As String

            TableName = Trim(Mid(SQl, InStr(SQl, " FROM ", CompareMethod.Text) + 6)) & " "
            TableName = Mid(TableName, 1, InStr(TableName, " ", CompareMethod.Text))

            Using xCon As New SqlClient.SqlConnection(conn_string)
                xCon.Open()
                DA.SelectCommand = New SqlClient.SqlCommand(SQl)
                DA.SelectCommand.Connection = xCon
                DA.Fill(DS, TableName)
                xCon.Close()
            End Using
            Combo.DataSource = DS.Tables(TableName)
            Combo.DisplayMember = DS.Tables(TableName).Columns(1).Caption
            Combo.ValueMember = DS.Tables(TableName).Columns(0).Caption
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation)
        End Try

    End Sub


Usage
PopulateComboBox(cmbProperty, "Select Id,Title,SurveyNo From Properties")

To Retrive Value from Combox
cmbProperty.SelectedValue -- to get Id
cmbProperty.SelectedItem -- to get DataRowView -
[Conversion Needed, ie CType(cmbProperty.SelectedItem,DataRowView)]


Set DataGridView Row Height

Dim xRow as DataGridViewRow = DataGridView1.Rows(DataGridView1.Rows.Add())
'//after assigning cell values use following statement
xRow.Height = xRow.GetPreferredHeight(xRow.Index, DataGridViewAutoSizeRowMode.AllCells, False)

Reset SQL Server Database Table's IDENTITY Column


DBCC CHECKIDENT (Table_1, RESEED, 1)

For More Info
http://msdn.microsoft.com/en-us/library/ms176057.aspx


Delegate - Sample -1

'// Assumes  Form-1 shows a list of records and Form2 to create a new record. The purpose of this delegate is to update the list view in Form-1 after saving the record.

FORM-1
Public Class Form1

    Private Sub AddOrUpdateRecordallbackFn(ByVal xRec As AuctionInword)
    //Arg - 'AuctionInword' user defined type
    //METHOD IMPLIMENTATION
    End Sub

   Private Sub Button1_Click()
       '// CALL FORM 2
      Dim xfm As New Form2
      '// Point the function
       xfm.AddOrUpdateAICallBack = AddressOf AddOrUpdateRecordallbackFn
       xfm.Show()
     End Sub

End Class


FORM-2
Public Class Form2
    '//Delegate to Form1 function AddOrUpdateRecordallbackFn
    Public Delegate Sub AddOrUpdateRecord(ByVal xRecord As AuctionInword)   
   
    '//variable to point the function
    Public AddOrUpdateAICallBack As AddOrUpdateRecord

Private Sub SaveRecord()
        //Save record implementation
    Dim _CurrentRecord = New <<User Type>> '//To store new record
    -----------------------
    -----------------------
       
    //After Saving, call the Form1 function 'AddOrUpdateRecordallbackFn' using delegate
    If AddOrUpdateAICallBack IsNot Nothing Then AddOrUpdateAICallBack(_CurrentRecord)
End Sub

End Class

Update a ConnectionString Stored in App.Config File

        using System.Configuration;
        public void updateConnectionString()
        {
           //create a new connection string settings
            ConnectionStringSettings cSetting = new ConnectionStringSettings();

            //connection string
            cSetting.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated Security=True;User Instance=True";
            //connection settings name in conf. file
            cSetting.Name = "WindowsFormsApplication1.Properties.Settings.conStr";
            //Provider
            cSetting.ProviderName = "MySql.Data.MySqlClient";

            //get the application conf file
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
           
            //read the connection string section
            ConnectionStringsSection connectionSettings = (ConnectionStringsSection)config.GetSection("connectionStrings");

            //remove the current conf section and add new
            connectionSettings.ConnectionStrings.Remove(cSetting);
            connectionSettings.ConnectionStrings.Add(cSetting);

            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);

            //to read and view
            //string newString = ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.conStr"].ConnectionString;
            //System.Diagnostics.Debug.Print(newString);
        }

Wednesday, March 13, 2013

Design Patterns

http://www.dofactory.com/Patterns/Patterns.aspx