Tuesday, July 28, 2009

Visual Basic 6

Visual Basic is an event driven programming language that can run on Microsoft windows environment. It is a successor of BASIC language and is visual in nature. Visual Basic was developed in early 1990s by Microsoft Corporation.Visual Basic is a visual programming language which involves a lot of graphics rather than writing numerous lines of code to illustrate the appearance, functionality, etc. of the applications interface. It is a WYSIWYG (What you see is what you get) editor.

Visual Basic provides acommon Programming platform across all MS Office applications.

Events
An event refers to the occurance of an activity. Eg: When you click a command button a set of statments are executed. Comman Button is the object and click is the event(action).

Event Procedure
An event procedure is a procedure containing code that is executed when a event occurs.

Double clicking an object will take you to the default event of an object. Here on double clicking the button you are taken to the click event.
Eg :
Private Sub btnDisplay_Click()
Print "Welcome to Visual Basic"
Print "Shalvin"
End Sub

Here the two print statements are contents of the procedure which is related to the click event.
The output is shown in the figure below.



















Properties
Properties are the attributes or characteristics of an object.Eg: Name, Caption, Font, etc. are the properties of a Label. Properties can be set either using the Properties Windows or by writing code.






Visual Basic 6 Editions

Learning EditionFor beginners. It is also known as Standard Edition. It includes all intrinsic controls.
Professional EditionIncludes all the features of Learining Edition, in addition it has activex Controls and Visual Data Tools.
Enterprise EditionThis edition is used to create distributed application in a team setting.


Enabled and Visible Properties







Enabled Property








Used to set a value that determines if the label canl respond to the events that are generated by the user. If the enabled Property is false that particular control will be inactive.












Visible Property








Determines whether the control will be visible or invisible on the screen.



















































































































Private Sub btnEnabled_Click()
Label2.Enabled = True
End Sub













Private Sub cmdVisible_Click()
Label1.Visible = False
End Sub











Result




























Variables and Data Types
Variable
Variables are named storage locations whose values can be manipulated during execution of the programme.
A variable has a name ane data type.

Data Type
Data Type refers to type of data and associated operations to identify a particular data.

Data Types can be broadly classified into :
1. Numeric Types
2. Non Numeric Types

Numeric Types
They consist of numbers.

Non numeric types
It deals with a character or set of characters, date or boolean value (true/false).

Numeric Data Types


Byte - 0 to 255
Integer - -32,767 to 32,767
long - 4 bytes
Single (decimal numbers) - 4 bytes
Double (decimal numbers) - 8 bytes

Non Numeric Data Types
String - Single character or set of characters
Date
Boolean - True of false
Variant - If data type is mentioned while declaring a variable, it is considered as variant.

Dim statment is used to define a variable.

Suppose you want to define a string memory named strName of type string.


Dim strName as string

Operators
Operators are symbols or words that trigger an action on some data.

Types of operators
Arithmetic Operators
Concatenation Operators
Comparison Operators
Logical Operators

Arithmetic Operators
Arithmetic Operators are the operators based on mathematical calculations.

+ Addition
- Sutraction
* Multiplication
/ Division
mod Reainder after division
^ Exponent

Concatenation Operators (&, +)
Concatenation operators are used to join two or three variables. If it is string data type, it will be concatenate both the values.
If it is integer data type both the values will be added.

Comparison Operators
Comparison operators are used to compare two values.

> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
= Assignment operator and equality checking operator
<> Not equal to

Logical Operators
Logical operators are used to compare two conditions.

AND
XOR
OR
LIKE NOT



Menus
Menus are a convenient and consistent way to group commands so that they become readily and easily available to the users.
To create a menu,
Tols -> Menu Editor or clicking the Menu Editor icon in the Standard Toolbar as shown in the figures below.













































Fundamentals of menu
Menu Bar
Menu Bar is a horizontal bar containing different menu options. Each menu option has sub menus.

Pull Down Menu
When you click an option on a menu bar you will get submenus under that, those menus are called pull down menus (vertical menu).

Menu Item
Each option on a menu bar is called menu item.

Sub Menu
A menu attached to a menu item is called a sub menu.

Pop up Menu
A floating menu that is displayed over a form or a control independent of the menu bar. It is also called Context menu.

Separator Bar
A bar on a menu that divides menu items into logical groups on a menu.

Shortcut Key
Key or a key combination used for invoking the command associated with a menu item.

Assigning Access Key
Access keys allow the user to open a menu by pressing the alt key and typing a designated letter. To assign an access key, select the menu item and set the caption as & immediately infront of the letter which is the starting letter of the corresponding menu item.

Creating a Calculator





































Dim i, j, res As Integer
Private Sub btnAdd_Click()
Assign
res = i + j
lblResult.Caption = res
End Sub
Private Sub Assign()
i = Val(txtInt1.Text)
j = Val(txtInt2.Text)
End Sub
Private Sub btnDivide_Click()
On Error GoTo Err
Assign
res = i / j
lblResult.Caption = res
Err:
If Err.Number = 11 Then
MsgBox "Cannot divide a number with 0"
txtInt2.Text = ""
txtInt2.SetFocus
End If
If Err.Number = 6 Then
MsgBox "Input not in correct format"
End If
End Sub



Database Connectivity with ADO

ActiveX Data Object (ADO) is the preferred database connectivity option for VB 6. Inorder to work with ADO you have to set a reference to Microsoft ActiveX DataObject 2.x Library by going to Project, Add Reference Dialog.









Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset

Private Sub Form_Load()
Set cnn = New ADODB.Connection
cnn.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Initial Catalog=Northwind"

Set rs = cnn.Execute("select * from Categories")

While Not rs.EOF
List1.AddItem (rs("CategoryName"))
rs.MoveNext

Wend

End Sub



Related Blog
VB.Net : The Console Way

Saturday, July 25, 2009

BackgroundWorker Component

BackgroundWorker Component can be used in situations where long running operations is likely to affect the responsiveness of the UI.

Here I am writing a method within an intention to simulate a delay using Thread Sleep. If I am directly calling the method from button click, the UI will freeze till the operation is complete.
Instead I am using DoWork event of BackgroundWorker Component in conjunction with RunWorkerAsync method.




















using System.Threading
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int arg = (int)e.Argument;
e.Result = Add(arg);
}

private int Add(int ct)
{
int o, j;
o = 0;
j = 1;
int sum = 0;
for(int i = 0 ;i < ct; i++)
{
sum += o + j;
o = j;
j = sum;
Thread.Sleep(1000);
}

return sum;
}

private void btnAdd_Click(object sender, EventArgs e)
{
//int sum = Add(4);
//MessageBox.Show(sum.ToString());
int arg = 4;
backgroundWorker1.RunWorkerAsync(arg);
}

private void btnBlog_Click(object sender, EventArgs e)
{
MessageBox.Show("ShalvinPD.blogspot.com");
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show(e.Result.ToString());
}

Saturday, July 4, 2009

Windows Communication Framework (WCF) Introduction

Windows Communication Framework in the Application Programming Interface in .Net 3.x for building Service Oriented Applications.

Create a new project by select WCF Service Application in the New Project Dialog.




















The project comprises of an Interface and a Class File.

















In the interface add Operation Contracts.



















Implement the interface in the Class Service1.cs.




public string Blog()
{
return "ShalvinPD.blogspot.com";
}

public int Add(int i, int j)
{
return i + j;
}







Now run the application.






Consuming the Service

We can consume a WCF service from any UI technologies say Windows Forms, Web Forms, WPF etc.
Go to Project, Add Service Reference.
In the Address copy paste the url from WCF Test Page. Give an appropriate name in the Namespace TextBox.






















Now your are ready to use the service just like consuming a dll.


Shalvin.Service1Client sc = new Shalvin.Service1Client();

private void btnBlog_Click(object sender, EventArgs e)
{
MessageBox.Show(sc.Blog());
}

private void button1_Click(object sender, EventArgs e)
{
int intSum = sc.Add(456, 345);
MessageBox.Show(intSum.ToString());
}









WCFwithout Interface

It is possible to create WCF service without an associated interface file.

[ServiceContract]
public class Service
{
[OperationContract]
public string Blog()
{
    return "ShalvinPD.blogspot.com";
}
[OperationContract]
public int Add(int i, int j)
{
    return i + j;
}
[OperationContract]
public List<string> Students()
{
    List<string> glsStudents = new List<string> { "Shalvin P D", "Praseed Pai", "Mathew K J", "Ashok Shenoy" };
    return glsStudents;
}
}


Silverlight Enabled WCF Service service for example comes without Interface.

Friday, July 3, 2009

PrintDocument and PrintPreview Components and Builing a Reporting Tool

PrintDocument Class defines an object that sends output to a printer used in Windows Forms Application.
First create a Graphics object which essentialy is a drawing surface using the PrintEvenArgs object which is an argument of PrintDocument's PrintPage event.

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Graphics g = e.Graphics;
g.DrawString("Shalvin", Font, Brushes.Blue, 50, 50);
g.DrawLine(Pens.Red, 70, 70, 150, 70);

g.DrawRectangle(Pens.Purple, 100, 100, 105, 105);

g.DrawEllipse(Pens.Peru, 125, 125, 130, 130);

g.DrawPie(Pens.PeachPuff, 150, 150, 200, 200, 0, 90);
g.DrawPie(Pens.PaleGreen, 150, 150, 200, 200, 90, 45);
g.DrawPie(Pens.Orange, 150, 150, 200, 200, 135, 135);
g.FillPie(Brushes.AntiqueWhite, 150, 150, 200, 200, 270, 90);

g.FillRectangle(Brushes.Beige, 300, 300, 325, 325);
}

private void Form1_Load(object sender, EventArgs e)
{
printPreviewDialog1.Document = printDocument1;
}

private void btnPrint_Click(object sender, EventArgs e)
{
printPreviewDialog1.ShowDialog();
}





















Reporting Tool
Application development is rarely DrawLine or DrawEllipse. Let's see how to develop a reporting tool with PrintDocument class.

using System.Data.SqlClient;

SqlConnection cnn;
SqlCommand cmd;
SqlDataReader dr;

private void Form1_Load(object sender, EventArgs e)
{
cnn = new SqlConnection("Integrated Security=sspi;Initial Catalog=Northwind");
cnn.Open();
cmd = new SqlCommand("select * from Categories", cnn);
dr = cmd.ExecuteReader();
printPreviewDialog1.Document = printDocument1;
}


private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Graphics g = e.Graphics;
g.DrawString("Category Id \t\t Category Name \t\t Description", Font, Brushes.Black, 50, 50 );
g.DrawString("___________ \t\t _____________ \t\t ___________", Font, Brushes.Black, 50, 55);
//g.DrawLine(Pens.DarkSlateBlue,50,65,600,65);
int y = 70;
while (dr.Read())
{
g.DrawString(dr["CategoryId"].ToString()+"\t\t\t"+ dr["CategoryName"].ToString()+ "\t\t" + dr["Description"].ToString(), Font,Brushes.Black, 60, y );
y += 20;
}
}


Monday, June 29, 2009

Win32 Api Calls from C#

Here I am demonstrating opening and closing the CD Rom Drive using the win32 api with c#.
This was one of my favourite progam in VB era and so I thought of migrating it to C#.
mciSendString encapsulates the Media Control Interface developed by Microsoft and IBM for controlling the peripherals connected to Windows.

It's better to encapsulate the Win32 api inside a class library. So from the Windows Forms Application add a class library.

using System.Runtime.InteropServices;

namespace OpenCDWindow
{
class OpenCDDoor
{
[DllImport("winmm.dll", EntryPoint = "mciSendStringA")]
public static extern void mciSendStringA(string lpstrCommand,
string lpstrReturnString, long uReturnLength, long hwndCallback);
}
}


Back in the windows forms you can call the win32 api that you have declared in the class.

string rt = "";
private void btnOpen_Click(object sender, EventArgs e)
{
OpenCDDoor.mciSendStringA("set CDAudio door open", rt, 127, 0);
}
private void btnClose_Click(object sender, EventArgs e)
{
OpenCDDoor.mciSendStringA("set CDAudio door closed", rt, 127, 0);
}


VB 6
Module
Public Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As Long, ByVal hwndCallback As Long) As Long

Form
Private Sub CmdClose_Click()
mciSendString "set CDAudio door closed", returnstring, 1, 0
End Sub

Private Sub CmdOpen_Click()
mciSendString "set CDAudio door open", returnstring, 1, 0
End Sub

AnimateWindow Win32 Api
Now we will take up a slightly more complex api which takes a few constatnts.
The AnimateWindow function enables you to produce special effects.
using System.Runtime.InteropServices;

const uint AW_HOR_NEGATIVE = 2;
const uint AW_VER_POSITIVE = 4;
const uint AW_HIDE = 0x10000;


[DllImport("User32.dll")]
static extern bool AnimateWindow(IntPtr hWnd, UInt32 time, UInt32 flags);

private void btnAnimate_Click(object sender, EventArgs e)
{
AnimateWindow(this.Handle, 1000, AW_VER_POSITIVE AW_HOR_NEGATIVE AW_HIDE);
}

WPF Treeview

TreeView is used for displaying hierarchical data. Individual items in a treeview is called TreeViewItem. Here I am declaratively creating a TreeView.




Output





Constructing a treeview with code
private void Window_Loaded(object sender, RoutedEventArgs e)
{
TreeViewItem tvwIndia = new TreeViewItem();
tvwIndia.Header = "India";

treeView1.Items.Add(tvwIndia);

TreeViewItem tvwKerala = new TreeViewItem();
tvwKerala.Header = "Kerala";
tvwIndia.Items.Add(tvwKerala);

TreeViewItem tvwKochi = new TreeViewItem();
tvwKochi.Header = "Kochi";
tvwKerala.Items.Add(tvwKochi);
}


Wednesday, May 20, 2009

WPF Transforms

Transforms allow you to alter the shape of an element.

Here I am using RotateTransform to Rotate the button 45 degrees and SkewTransform to Skew the button.











Output

Tuesday, May 19, 2009

WPF Databinding

Using Silverlight 3 / WPF Databinding any property can be bound to any other property of source using declarative syntax thereby reduce coding drastically.

Here I am binding the Text Property of TextBox to the Value property of Slider.

ElementName property is used to specify the element to use as binding source.

Path is used to specify the source property of binding source.



 <Slider x:Name="slider1" HorizontalAlignment="Left" Height="70" Margin="163,96,0,0" VerticalAlignment="Top" Width="256"/>  
 <TextBox x:Name="textBox"  
      Text="{Binding ElementName=slider1, Path=Value}"  
      HorizontalAlignment="Left" Height="54" Margin="179,225,0,0" TextWrapping="Wrap"   
      VerticalAlignment="Top" Width="185"/>  



Two way Databinding
In the previous example what we saw was One way databinding, ie. as you scroll the slider the value property is reflected in the textbox. But the user can't type a value into textbox and expect the value of slider to get updated.
This is possible by setting the Mode to TwoWay.

Mode=TwoWay.




For Silverlight 3 use TextBlock control instead of TextBox.

We can bind to any Dependency property in the like manner


<Button 
    Margin="5" Content="Click to Toggle" 
    IsEnabled="{Binding IsChecked, Mode=OneWay, 
    ElementName=EnableButton}" />
<CheckBox 
    x:Name="EnableButton" IsChecked="true" 
    Margin="5" Content="Enable Button" />

In this code we are binding the IsEnabled property of Button to the IsChecked propety of CheckBox.

ItemSource Binding
Lets see how to fill a ComboBox with the Font Names and on selecting an item from  the ComboBox the Label's Font is changed.
<ComboBox x:Name="comboBox" HorizontalAlignment="Left" VerticalAlignment="Top" Width="259" Margin="102,59,0,0" Height="29"
                  ItemsSource="{x:Static Fonts.SystemFontFamilies}" />
<Label Content="Shalvin P D" HorizontalAlignment="Left" VerticalAlignment="Top" RenderTransformOrigin="3.931,6.865" Margin="102,139,0,0" FontFamily="{Binding SelectedItem, ElementName=comboBox}"/>




Binding to a Class

It is possible to bind a control's property to a property of a class. I am going to create a class with a boolean property which denotes the enabled property. Based on the value of the property we are going to set the Enabled property of the class.

class EnabledCheck
{
   public bool IsButtonEnabled { get; set; }
   public EnabledCheck()
   {
      IsButtonEnabled = true;
   }
}

<Window x:Class="WpfDataBindingEg.ButtonClass"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfDataBindingEg"
        Title="ButtonClass" Height="300" Width="300">
    <Window.Resources>
        <local:EnabledCheck x:Key="ButtonState"/>
    </Window.Resources>
    <Grid>
        <Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="58,67,0,0" IsEnabled="{Binding IsButtonEnabled, Source={StaticResource ButtonState}}"/>

    </Grid>
</Window>

Related blogs
Silverlight 3, WPF Positioning with ZIndex
Silverlight 3/Wpf : Adding Controls Dynamicallys
Silverlight 3/WPF Templates