Tuesday, 22 October 2013

Single Instance Application VB.NET

'How to check / Allow only one instance of Application is Running.

Imports System.Diagnostics
Module mdlMain

    Public Sub main()
        Application.EnableVisualStyles()
        Dim tempProcess As Process
        tempProcess = checkInstance()
        If tempProcess Is Nothing Then
            Application.Run(New Form1)
        Else
            MessageBox.Show("Application is already running")
        End If
    End Sub

    'Return Value : Returns the Process if the exe
    'is already running or else returns nothing
    Public Function checkInstance() As Process
        Dim cProcess As Process = Process.GetCurrentProcess()
        Dim aProcesses() As Process = Process.GetProcessesByName(cProcess.ProcessName)
        'loop through all the processes that are currently running on the
        'system that have the same name
        For Each process As Process In aProcesses
            'Ignore the currently running process
            If process.Id <> cProcess.Id Then
                'Check if the process is running using the same EXE as this one
                If Reflection.Assembly.GetExecutingAssembly().Location = cProcess.MainModule.FileName Then
                    'if so return to the calling function with the instance of the process
                    Return process
                End If
            End If
        Next
        'if nothing was found then this is the only instance, so return null
        Return Nothing
    End Function


End Module

Tuesday, 3 September 2013

Sending SMS Via PC (VB6)

(VB sms application with source code. Mobile/USB connection. AT command for sending SMS.)
Private Sub cmdSend_Click()
 With MSComm1
        .CommPort = Val(Trim(txtPortNo))
        .Settings = "9600,N,8,1"
        .Handshaking = comRTS
        .RTSEnable = True
        .DTREnable = True
        .RThreshold = 1
        .SThreshold = 1
        .InputMode = comInputModeText
        .InputLen = 0
        .PortOpen = True 'must be the last
End With
' Send an 'AT' command to the phone
MSComm1.Output = "AT" & vbCrLf
Sleep 500
MSComm1.Output = "AT+CMGF=1" & vbCrLf           'Set Modem always in Text Mode...
Sleep 500
MSComm1.Output = "AT+CMGS=" & Chr(34) & TxtNumber.Text & Chr(34) & vbCrLf
Sleep 1000
MSComm1.Output = TxtMessage.Text & Chr(26)
Sleep 2000

Dim Result As String
Result = MSComm1.Input

If MSComm1.PortOpen = True Then
MSComm1.PortOpen = False
End If

    MsgBox "Message Send" & Result

End Sub

Wednesday, 31 July 2013

How to use ControlParameter in asp.net

Example: Country-->State-->City selection in asp.net


Asp.net Page Source:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        #form1
        {    height: 283px;
            width: 218px; }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <asp:SqlDataSource ID="SqldataSourceCountry" runat="server" 
        ConnectionString="<%$ ConnectionStrings:TestDBConnectionString %>" 
        SelectCommand="SELECT [countryID], [countryName] FROM [tblCountry] ORDER BY [countryName]">
    </asp:SqlDataSource>
    <asp:SqlDataSource ID="SqlDataSourceState" runat="server" 
        ConnectionString="<%$ ConnectionStrings:TestDBConnectionString %>" 
        SelectCommand="SELECT [stateID], [stateName] FROM [tblState] WHERE ([countryID] = @countryID) ORDER BY [stateName]">
        <SelectParameters>
            <asp:ControlParameter ControlID="cmbCountry" DefaultValue="0" Name="countryID" 
                PropertyName="SelectedValue" Type="Int32" />
        </SelectParameters>
    </asp:SqlDataSource>
    <asp:SqlDataSource ID="SqlDataSourceCity" runat="server" 
        ConnectionString="<%$ ConnectionStrings:TestDBConnectionString %>" 
        SelectCommand="SELECT [cityId], [cityName] FROM [tblCity] WHERE ([stateID] = @stateID) ORDER BY [cityName]">
        <SelectParameters>
            <asp:ControlParameter ControlID="cmbStates" DefaultValue="0" Name="stateID" 
                PropertyName="SelectedValue" Type="Int32" />
        </SelectParameters>
    </asp:SqlDataSource>
    <br />Select Country:<br>
    <asp:DropDownList ID="cmbCountry" runat="server" 
        DataSourceID="SqldataSourceCountry" DataTextField="countryName" 
        DataValueField="countryID" Height="18px" Width="169px" AutoPostBack="True">
    </asp:DropDownList>
    <br />
    <br />Select State:<br />
    <asp:DropDownList ID="cmbStates" runat="server" 
        DataSourceID="SqlDataSourceState" DataTextField="stateName" 
        DataValueField="stateID" Height="50px" Width="163px" AutoPostBack="True">
    </asp:DropDownList>
    <br />
    <br />Select City <br />
    <asp:DropDownList ID="cmbCity" runat="server" Height="33px" Width="167px" 
        DataSourceID="SqlDataSourceCity" DataTextField="cityName" 
        DataValueField="cityId">
    </asp:DropDownList>

    </form>
</body>
</html>


SQL Queries:
Create Country/State/City Tables as follows
CREATE TABLE [dbo].[tblCountry](
[countryID] [int] IDENTITY(1,1) NOT NULL,
[countryName] [varchar](50) NOT NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[tblState](
[stateID] [int] IDENTITY(1,1) NOT NULL,
[stateName] [varchar](50) NOT NULL,
[countryID] [int] NOT NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[tblCity](
[cityId] [int] IDENTITY(1,1) NOT NULL,
[cityName] [varchar](50) NOT NULL,
[stateID] [int] NOT NULL
) ON [PRIMARY]
Insert Data into tblCountry/State/City Tables


Friday, 26 July 2013

SQL Database Backup Restore Utility
VB.NET Code

















Code :
    'Database resourecs
    Dim con As SqlConnection
    Dim cmd As SqlCommand
    Shared conn As New SqlConnection

#Region "DATABASE BACKUP"
    Public Function DatabaseBackup(ByVal ToDisk As String) As Boolean
        Try
            con = New SqlConnection(APPCONSTRING)
            cmd = New SqlCommand("backup database " & SQL_DBNAME & " to disk='" & ToDisk & ".bak'", con)
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
            'MsgBox("Database Backup Successfull")
        Catch ex As SqlException
            MsgBox("SQlServer Exception :" & ex.Message)
            Dim frm As New FrmApplicationSettings
            frm.ShowDialog()
            Return False
        Catch ex As Exception
            MsgBox("Exception :" & ex.Message)
            Dim frm As New FrmApplicationSettings
            frm.ShowDialog()
            Return False
        Finally
            If Not (con Is Nothing) Then con.Dispose()
            con = Nothing
            If Not (cmd Is Nothing) Then cmd.Dispose()
        End Try
        Return True
    End Function
#End Region

#Region "DATABASE RESTORE"
    Public Function DatabaseRestore(ByVal FromDisk As String) As Boolean
        Try
            MsgBox(FromDisk)

            Dim sqlstr As String = "RESTORE DATABASE " & SQL_DBNAME & " " _
            & "FROM DISK='" & FromDisk & "'" _
            & " WITH RECOVERY"

            MsgBox(sqlstr)

            Dim CONSTR = "Persist Security Info=False;User ID=" & SQL_USER_ID & ";pwd=" & SQL_PASSWORD & ";Initial Catalog=master;Data Source=" & SQL_SERVER_NAME
            con = New SqlConnection(CONSTR)
            cmd = New SqlCommand(sqlstr, con)
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
            MsgBox("Database restore Successfull", MsgBoxStyle.Information, MSG_TITLE)
        Catch ex As SqlException
            MsgBox("SQlServer Exception :" & ex.Message, MsgBoxStyle.Critical, MSG_TITLE)
            Return False
        Catch ex As Exception
            MsgBox("Exception :" & ex.Message, MsgBoxStyle.Critical, MSG_TITLE)
            Return False
        Finally
            If Not (con Is Nothing) Then con.Dispose()
            con = Nothing
            If Not (cmd Is Nothing) Then cmd.Dispose()
            cmd = Nothing
        End Try
        Return True
    End Function
#End Region

Thursday, 18 April 2013

String Fuction to put given Charactor for given lenth of String

 Hello,
          Can you need to print a string as Given bello..
           dim str as String= "----------------------------------------------------"

There is another flexible way to print this line..

USING VB :
           String(Length,CharString)
eg.
        str= String(50,"-")


USING .NET
strDup : Returns a string or object consisting of the specified character repeated the specified number of times.
        str= Strings.StrDup(Length,"-")
eg.
       str=Strings.StrDup(50,"-")

Hope this will help you...
Regards,
Ganesh S. Chatraband.


Wednesday, 6 March 2013


Solution of error 9003- sql server 2000 –Database Suspect

1. Create Database with exact name and mdf-ldf files

2. Stop MSSQLSERVER service, replace created mdf file with original one

3. Start MSSQLSERVER service, the database will be in Suspend mode

4. From Query Analyzer (QA) execute script

use master

go

sp_configure 'allow updates', 1

reconfigure with override

go

5. From QA execute script

update sysdatabases set status= 32768 where name = '<db_name>'

6. Restart MSSQLSERVER service, the database will be in Emergency mode

7. Rebuild Log. From QA execute script

DBCC REBUILD_LOG('<db_name>', '<full name to new log file>')

 You got a message - Warning: The log for database '<db_name>' has been rebuilt.


8. From QA execute script

Use master

go

sp_configure 'allow updates', 0

Go

9. Clear from Enterprise Manager on database properties options tab Restrict 
access checkbox

It works..

Regards,
Ganesh Chatraband.

Sunday, 3 February 2013

Visual Basics MS Access database Connection Example

First Create a Access 2000 Database "Test.mdb"

Ganesh S Chtraband
Add caption














Create a Visual Basic Form Design 
1) Add ADODC component and bulid connection to "Test.mdb"
2) Add datagrid and Set Property DataSource =ADODC
3) Add Command Button


















Write following Code on Command1 click

Private Sub Command1_Click()

  'Define the three objects that we need,
  '   A Connection Object - connects to our data source
  '   A Command Object - defines what data to get from the data source
  '   A RecordSet Object - stores the data we get from our data source

  Dim con As New ADODB.Connection
  Dim cmd As New ADODB.Command
  Dim res As New ADODB.Recordset


  'Defines the connection string for the Connection.  Here we have used fields
  'Provider, Data Source and Mode to assign values to the properties
  ' conConnection.Provider and conConnection.Mode

  con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
      App.Path & "\" & "test.mdb;Mode=Read|Write"


  'Define the location of the cursor engine, in this case we are opening an Access database
  'and adUseClient is our only choice.

  con.CursorLocation = adUseClient


  'Opens our connection using the password "Admin" to access the database.  If there was no password
  'protection on the database this field could be left out.

  con.Open


  'Defines our command object

  ' .ActiveConnection tells the command to use our newly created command object.
  ' .CommandText tells the command how to get the data, in this case the command
  '              will evaluate the text as an SQL string and we will return all
  '              records from a table called tabTestTable
  ' .CommandType tells the command to evaluate the .CommandText property as an SQL string.

  With cmd
    .ActiveConnection = con
    .CommandText = "SELECT * FROM Table1;"
    .CommandType = adCmdText
  End With

  'Defines our RecordSet object.

  '  .CursorType sets a static cursor, the only choice for a client side cursor
  '  .CursorLocation sets a client side cursor, the only choice for an Access database
  '  .LockType sets an optimistic lock type
  '  .Open executes the cmdCommand object against the data source and stores the
  '        returned records in our RecordSet object.

  With res
    .CursorType = adOpenStatic
    .CursorLocation = adUseClient
    .LockType = adLockOptimistic
    .Open cmd
  End With

  'Firstly test to see if any records have been returned, if some have been returned then
  'the .EOF property of the RecordSet will be false, if none have been returned then the
  'property will be true.

  If res.EOF = False Then

    'Move to the first record

    res.MoveFirst

    'Lets move through the records one at a time until we reach the last record
    'and print out the values of each field

    Do

      'Access the field values using the fields collection and print them to a message box.
      'In this case I do not know what you might call the columns in your database so this
      'is the safest way to do it.  If I did know the names of the columns in your table
      'and they were called "Column1" and "Column2" I could reference their values using:

      '  res!Column1
      '  res!Column2


      MsgBox "Record " & res.AbsolutePosition & " " & _
          res.Fields(0).Name & "=" & res.Fields(0) & " " & _
          res.Fields(1).Name & "=" & res.Fields(1)

      'Move to the next record

      res.MoveNext
    Loop Until res.EOF = True

    'Add a new record

    With res
      .AddNew
            .Fields(1) = "New"
                  .Fields(2) = "Record"
      .Update
    End With

    'Move back to the first record and delete it

    res.MoveFirst
    'To Delete Record
    'res.Delete
   
    res.Update


    'Close the recordset

    res.Close
  Else
    MsgBox "No records were returned using the query " & cmd.CommandText
  End If

  'Close the connection

  con.Close

  'Release your variable references

  Set con = Nothing
  Set cmd = Nothing
  Set res = Nothing
End Sub

All the Best...

Thursday, 31 January 2013

Steps to generate the setup files of any vb.NET project.

Steps to generate the setup files of any vb.NET project.
•Open your project
•Now move the cursor to file----->add Project------->New Project
•then add project dialog box appears
•now select Setup and deployment project types and setup project from templates and mention the name in name text box and the location in location text box, now click ok button
•now in solution explorer right click on setup option then add------>file (if you have used any extra file e.g. databases or image file or dll file).
•add all of these files files
•repeat the prevous two steps untill you have added all of the extra file to the current setup.
•now again right click on setup in solution explorer then click on add---->project output.
•now add project group box appears. here configuration should be (Active) for primary ouputs. now click on ok button.
•now right click on setup option in solution explorer again and click on Build (Now wait and observe the progress inoutput window).
•time taken to build depend upon how heavy your project is?
•now go to the location that you have mentioned in new project dialog box box.
•now open setup folder then release then open setup.exe.
•now installation starts observe the location where this project is going to be installed.
•after intallling it go to the lcation where this project is installed now execute the exe file. (Your project is installed successfully and running, enjoy this feature of deployment and setup with VB.NET to)
All the Best,
Ganesh S. Chatraband.

Client Server Database Connection Testing Using universal data link (.udl) file

Client Server Database Connection Testing Using universal data link (.udl) file
Step 1 : On Sever computer install SQL Server and MSDE (MicroSoft Desktop Engine) and  create a   database.
Step 2 : On client Computer Install only MSDE.
Step 3 : On client Computer Open Notepad and Save as "Test.udl" Universal Data link file format.
To configure a universal data link (.udl) file
  1. Double-click the universal data link (.udl) file. The Data Link Properties dialog box opens, displaying the following tabs: Provider, Connection, Advanced, and All. Choose Next to navigate from tab to tab.
  2. On the Provider tab, select a database provider. Select "Microsoft OLE DB provider for SQL Server"
  3. On the Connection tab, either select SQL Server Name From drop-down list or Enter Manually. Here Choose SQL Sever Name installed on Server. If you have provided Security then Enter User Name And Password. Then It shows available database on Server. Select Database Name created on Server.
  4. Click on Test Connection. If Test Connection Successful it means you can access database on Server to that client system. 
  5. Choose OK to save the connection string to the Universal Data Link (.udl) file.
Note : IF Test connection fails then Please check following causes.
1) Open services by typing "services.msc" on Sever Computer Run Window.
    Check SQL Server Browser It requires Automatic and Started.
2) Check LAN connection.
IMP : You can get Connection String by Using universal data link (.udl) file to use in programming by Opening "Test.udl" file into Notepad.

Hope this will help you,
Feedback me at
chatrabandg@gmail.com.