Tuesday, July 28, 2009

Oracle Connectivity from C# Windows Forms

Inserting Values from Front End

System.Data.OleDb namespace contains classes required for interacting with any RDBMS including Oracle.

OleDbConnection class is used for establishing a live session between front end and back end. In this example we are connecting to Oracle with scott as username, tiger as password and hostname is Shalvin.

using System.Data.OleDb;



OleDbConnection cnn;
OleDbCommand cmd;
private void Form1_Load(object sender, EventArgs e)
{
cnn = new OleDbConnection("provider=msdaora.1;user id=scott;password=tiger;Data Source=Cargomar");
cnn.Open();
}
private void btnInsert_Click(object sender, EventArgs e)
{
cmd = new OleDbCommand("insert into Categories values (5, 'Mouse', 'Computer Mouse')", cnn);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Saved");
}




Filling TextBox based on Selection from ComboBox

A common programming task is obtaining the details of a record based on a selection. Here Initially I am filling a combo box with Category Names. Based on a selection from Combo Box the the details of the Category will be displayed on the text boxes.










using System.Data.OleDb;

OleDbConnection cnn;
OleDbDataAdapter da;
DataSet ds = new DataSet();

bool b = false;

OleDbCommand cmd;
OleDbDataReader dr;

private void Form1_Load(object sender, EventArgs e)
{
cnn = new OleDbConnection("Provider=msdaora;Data Source=Cargomar;user id=scott;password=tiger");

cnn.Open();
da = new OleDbDataAdapter("select * from Categories", cnn);
da.Fill(ds, "Cat");
cboCategoryName.DataSource = ds.Tables["Cat"];
cboCategoryName.DisplayMember = "CategoryName";
cboCategoryName.ValueMember = "CategoryId";
b = true;
}

private void cboCategoryName_SelectedIndexChanged(object sender, EventArgs e)
{
if (b)
{
cmd = new OleDbCommand("select * from Categories where categoryId = " + cboCategoryName.SelectedValue, cnn);
dr = cmd.ExecuteReader();
while (dr.Read())
{
txtCategoryId.Text = dr["CategoryId"].ToString();
txtDescription.Text = dr["Description"].ToString();
}
}

Deleting Record
private void btnDelete_Click(object sender, EventArgs e)
{
cmd = new OleDbCommand("delete from Categories where CategoryId = " + cboCategoryName.SelectedValue, cnn);
cmd.ExecuteReader();
MessageBox.Show("Record Deleted");
}

Editing Record

private void btnEdit_Click(object sender, EventArgs e)
{
txtCategoryId.Enabled = false;
cmd = new OleDbCommand("Update Categories set Description = '" + txtDescription.Text + "' where CategoryId = " + cboCategoryName.SelectedValue, cnn);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Edited successfully");
}

VB.Net

Imports System.Data.SqlClient

Dim cnn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As New DataSet

Dim b As Boolean = False
Dim cmd As SqlCommand
Dim dr As SqlDataReader

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cnn = New SqlConnection("Integrated Security=sspi;Initial Catalog=Northwind")
cnn.Open()
da = New SqlDataAdapter("select * from Categories", cnn)
da.Fill(ds, "Cat")
cboCategories.DataSource = ds.Tables("Cat")
cboCategories.DisplayMember = "CategoryName"


cboCategories.ValueMember = "CategoryId"

b = True
End Sub

Private Sub cboCategories_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboCategories.SelectedIndexChanged
If b = True Then

Dim strSql As String
strSql = "select * from Categories where CategoryId = " + cboCategories.SelectedValue.ToString()
cmd = New SqlCommand(strSql, cnn)
dr = cmd.ExecuteReader
While (dr.Read())
txtCategoryId.Text = dr("CategoryId")
txtDescription.Text = dr("description")
End While
dr.Close()
End If

End Sub

Enumerations in C#

Enumerations are the mechanism to group related constants. System.Enum class provides the base class for enumerations, it is a value type.
The following example demonstrates using WindowState enum in WPF. In the case of WindowState enumerator there are three constants viz., Maximized, Minimized and Normal.









Creating Enumerations
In the following example I am creating an enum called Tech with three constants Wpf, Silverlight and Xbap and later on I am using using it. Extensive use of enums makes your code more consistent.

enum TEch
{
Wpf, Silverligh, Xbap
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show(TEch.Silverligh.ToString());
}

The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.

In the following example I am extracting the value of the element Wpf.


private void Window_Loaded(object sender, RoutedEventArgs e)
{
int i = (int)TEch.Wpf;
MessageBox.Show(i.ToString());
}


When you run the application you will get 0. If you substitute Wpf with Silverlight or Xbap you will get 1 or 2 respectively.


It is possible to alter the default underlying value by assigning another values.

enum TEch
{
Wpf = 2, Silverligh = 4, Xbap = 6
}









Enum.GetValues() method
Enum.GetValues() method to extract the constants in an Enumeration.
using System.Drawing;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
KnownColor [] color = (KnownColor[])Enum.GetValues(typeof(KnownColor));
foreach (KnownColor colorName in color)
{
listBox1.Items.Add(colorName);
}
}



For this example to work in WPF you should set reference to System.Drawing

WPF Colors

The Brushes class provides 141 colors.

private void btnColor_Click(object sender, RoutedEventArgs e)
{
this.Background = Brushes.Red;
}


You can also have a wide ranging colors using the combination of Red, Green and Blue.

private void btnGreen_Click(object sender, RoutedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromRgb(0, 255, 0));
}

In the previous I am creating Green color by assigning 255, the maximum value to Green component, ie. the second parameter


private void btnWhite_Click(object sender, RoutedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromRgb(255, 255, 255));
}

private void btnYellow_Click(object sender, RoutedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromRgb(255, 255, 0));
}

Grey Scale
private void btnWhite_Click(object sender, RoutedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
}

private void btnBlack_Click(object sender, RoutedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
}

private void btnDarkGrey_Click(object sender, RoutedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromArgb(255, 50, 50, 50));
}

private void btnMGrey_Click(object sender, RoutedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromArgb(255, 150,150, 150));
}

private void slider1_ValueChanged(object sender,

RoutedPropertyChangedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromArgb(255,

(byte)slider1.Value, (byte)slider1.Value, (byte)slider1.Value));
}


LinearGradientBrush
LinearGradientBrush displays a gradualy changing mix of two or more color schemes.
The surface where you are planning to draw the linear gradient is considered to he unit 1 wide and 1 unit high.


private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.Background = new LinearGradientBrush(Colors.Red, Colors.Blue, new Point(0, 0), new Point(1, 1));
}


LinearGradientBrush the Coded way


using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace WPFBrush
{
class Class1 : Window
{
[STAThread]
public static void Main()
{
Application app = new Application();
app.Run(new Class1 { Title = "Shalvin - Colors" });
}
public Class1()
{
Grid LayoutRoot = new Grid();
this.Content = LayoutRoot;
LayoutRoot.Background = new LinearGradientBrush(Colors.Red, Colors.Blue, 0);
}
}
}


RadialGradientBrush

Grid LayoutRoot = new Grid();
this.Content = LayoutRoot;
LayoutRoot.Background = new RadialGradientBrush (Colors.Red, Colors.Blue);


RadialGradientBrush and GradientStops


RadialGradientBrush brush = new RadialGradientBrush();
Background = brush;
brush.GradientStops.Add(new GradientStop(Colors.Red, 0));
brush.GradientStops.Add(new GradientStop(Colors.Green, .33));
brush.GradientStops.Add(new GradientStop(Colors.Blue, .66));

WPF (Windows Presentation Foundation)

This is a beginner level blog on WPF.


Nesting Controls
Styles
Exploring WPF the Code Way

Majority of examples presented in this blog will work with Silverlight also.
Windows Presentation Foundation (WPF) is the Microsoft's presentation technology for creating compelling user interface including graphics and media.
It is based on Vector Graphics
Create a new project in Visual Studio 2008 by selecting File, New Project.
Starting a WPF Application Project

















The WPF editor contains two view the visual representation of the form as well as the XAML implementation of the window.

A WPF Form is in fact a class that inherits from System.Windows.Window. The Window class which in turn inherits from ContentControl class.A ContentControl class can have only a single element as its Content Property.
Inside the Windows is a Grid Control that can hold multiple child controls.









As you set the propeties of an element both the windows designer as well as the xaml gets updated.







Here I am settting the Title for the form.






























You can also edit the xaml and the changes will be immediately apparent in the windows designer.





















Setting the window title at Runtime

private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.Title = "shalvinpd.blogspot.com";
}




WPF do have a collection of common control which you would expect in a presentation technology.

















Button

Drag and drop a button on to the windows design surface.




























On clicking the button you will be taken to the event handler.


private void button1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello welcome to WPF", "Shalvin.com");
}

Run the application. Click on the button and you will receice a welcome message.


















MessageBox.Show Method's Overloads

MessageBox's Show method has 21 overloads, following are a few examples.

private void btnHello_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello");
}

private void btnHelloCaption_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello", "shalvin");
}

private void btnYesNo_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello", "Shalvin", MessageBoxButton.YesNo);
}

private void btnExclamation_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello", "Shalvin", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
}

MessageBoxResult
private void btnClose_Click(object sender, RoutedEventArgs e)
{
if (MessageBox.Show("Do you want to quit ?", "Shalvin", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
Close();
}

String Memory Variable

private void btnMemoryVariable_Click(object sender, RoutedEventArgs e)
{
string strName = "Shalvin";
MessageBox.Show("Hello " + strName);
strName = "Shalvin P D";
MessageBox.Show("Hello " + strName);
}


String Concatenation
In this example instread of simply displaying a Hello message the user will be greated with the name entered in text box.













private void button1_Click(object sender, RoutedEventArgs e)

{
MessageBox.Show("Hello " + txtName.Text);
}




















Integer Memory Variable and Simple Calculator




















int i, j, res;
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
i = Int32.Parse(txtInt1.Text);
j = Int32.Parse(txtInt2.Text);
res = i + j;
lblResult.Content = res.ToString();
}

Here I am defining three integer memory variables i, j and res. Int32.Parse() method is used to convert the textbox data to integer.

<Window x:Class="WpfApplication1.Calc"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Calc" Height="300" Width="300" Loaded="Window_Loaded">
    <Grid>
        <Label Content="Integer 1" Height="28" HorizontalAlignment="Left" Margin="44,33,0,0" Name="label1" VerticalAlignment="Top" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="120,33,0,0" Name="txtInt1" VerticalAlignment="Top" Width="120" />
        <Label Content="Integer 2" Height="28" HorizontalAlignment="Left" Margin="53,88,0,0" Name="label2" VerticalAlignment="Top" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="120,80,0,0" Name="txtInt2" VerticalAlignment="Top" Width="120" />
        <Label Content="Result" Height="28" HorizontalAlignment="Left" Margin="63,132,0,0" Name="label3" VerticalAlignment="Top" />
        <Label Height="28" HorizontalAlignment="Left" Margin="120,132,0,0" Name="lblResult" VerticalAlignment="Top" Width="112" BorderBrush="Black" BorderThickness="1" />
        <Button Content="+" Height="23" HorizontalAlignment="Left" Margin="98,196,0,0" Name="btnAdd" VerticalAlignment="Top" Width="75" Click="btnAdd_Click" />
    </Grid>
</Window>

ListBox

ListBox is used for displaying a number of items at the same time. Place a ListBox on to the form and select the Items collection from the properties window. The Collection Editor dialog will appear. You can add additional items to the ListBox by clicking the Add button and specifying a Content.






Behing the scene it will create ListBoxItems tags inside the ListBox tag.







It is possible to add items to ListBox at runtime. Double click on the title of the form and you will be taken to the Loaded event of the Window.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
lstInterests.Items.Add("Guitar");
}





ComboBox
ComboBox contains similar functionality that of ListBox. Above mentioned functionality also works with ComboBox

RadioButton and If else











private void btnGender_Click(object sender, RoutedEventArgs e)
{
if (rbMale.IsChecked == true)
MessageBox.Show("Male candidate");
else
MessageBox.Show("Female candidate");
}













DatePicker Control
private void btnDate_Click(object sender, RoutedEventArgs e)
{
DateTime dt = DateTime.Parse(datePicker1.SelectedDate.ToString());
MessageBox.Show(dt.ToString());
MessageBox.Show(dt.ToString("d"));
MessageBox.Show(dt.ToString("D"));
}

Nesting Controls

































As usual you can have event handlers of the controls. In this case I am extracting the value of Inner TextBox, concatenating it with a Hello and MessageBoxing it.

private void btnHello_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello " + txtName.Text);
}























































Styles
Styles as WPF equivalent of CSS in Html.


















Working with Styles at Runtime




private void btnBold_Click(object sender, RoutedEventArgs e)
{
btnBold .Style = (Style)FindResource("BoldStyle");
}








Filling Wpf ComboBox with the Contents of a SqlDataReader
using System.Data.SqlClient;
SqlConnection cnn = new SqlConnection(@"Integrated Security=sspi;Initial Catalog=Shalvin;Data Source=.\sqlexpress");
SqlCommand cmd;
SqlDataReader dr;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
cnn.Open();
cmd = new SqlCommand("select * from Categories", cnn);
dr = cmd.ExecuteReader();
while (dr.Read())
{
cboCategories.Items.Add(dr["CategoryName"]);
}
}























Exploring WPF the Code Way
Having seen the fundamentals of working with IDE. Let's turn out attention to the internals of WPF in coded way, means without XAML.

using System;
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication1
{
class Class1 : Window
{
[STAThread]
public static void Main()
{
Application app = new Application();
app.Run(new Class1{Title = "shalvin"});
}
public Class1()
{
Grid LayoutRoot = new Grid();
this.Content = LayoutRoot;
Button btn = new Button();
btn.Width = 75;
btn.Height = 50;
btn.Content = "Hello";
LayoutRoot.Children.Add(btn);
}
}
}

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;
}
}