Sie sind auf Seite 1von 30

13.01.

2009

What is .NET?

It is a technology from Microsoft based on .NET Framework. It provides a common model to all the
languages which are based on .NET

Microsoft provides some of its own languages based on .NET Framework and other third party
languages.

Microsoft Languages
1 . Visual C-Sharp (C#)
2 . Visual Basic
3 . Visual J-Sharp (J#)
4 . Visual C++

Third Party Languages


• COBOL.NET
• Eiffel.NET
• Ruby.NET
Etc.

What is .NET Framework?

- A software from Microsoft for .NET based programs provided for free
- Various frameworks are
o 1.0
o 1.1
o 2.0
o 3.0
o 3.5
- All such frameworks are installed in <windows>\Microsoft.NET\framework folder
- Framework provides some set of rules and tools along with the common libraries used in
any .NET based language

Feature of .NET

1 . Any kind of application development using one language


2 . All languages get compiled into a common format called as MSIL (Microsoft Intermediate
Language)
3 . It provides a big set of common classes used by all .NET based languages
4 . All .NET languages are based on Common Type System (CTS) where data types of the
languages get mapped to some structure or class
a . C# (int – 4 byte) à System.Int32
b . VB (Integer – 4 byte) à System.Int32
5 . All .NET based languages are interoperable
6 . It defines a set of rules for interoperable programs called as Common Languages Specifications
(CLS)
7 . It provides Common Language Runtime (CLR) to run programs written in any .NET based
language
8 . Provides distributed programming with the help of Web Services
9 . Supports latest technologies like AJAX, Web 2.0, RSS Feeds etc.
1 0 .All .NET based languages are Object Oriented
Common Language Runtime

Source code à compiler à.exe (MSIL)àClass Loader à Code Verifier à Just-in-Time compiler à
binary code à Execution

Requirements
1 . .Net Frameworks
a . 2.0+
2 . Visual Studio.NET 2005+
a . Express
b . Standard
c . Professional
d . Team Suite
3 . Databases

Working with Visual C#

- A new languages from Microsoft based on C


- File extension must be .cs
- Every executable program must have an entry point
o public static void Main()
o public static int Main()
o public static void Main(string []args)
o public static int Main(string []args)
- Hierarchy in C#
o DLL Files
§ Namespaces
• Class/Structure/Enumerator etc.
o Field/Method/Property/Indexer/Delegates etc.

Namespaces
- A collection of related set of classes, interfaces, structure etc.
o System
o System.Windows
o System.Data
o System.Data.OracleClient

General IO

System namespace
Console class
static void Write()
static void WriteLine()
static string ReadLine()

Writing First Program


//Writing first C# program – First.cs
class Test
{
public static void Main()
{
System.Console.WriteLine("Hello to C#");
}
}

Compiling a CS program

CSC <filename>

Example
CSC First.cs à First.exe

Note: Use ILDASM (Intermediate Language De-assembler) to view contents of an MSIL file

ILDASM First.exe

15.01.2009

Using Visual Studio for Console Programming

- Start the Visual Studio à File à New à Project à Console Application


- Use Ctrl+F5 to run the application

Importing the Namespace

- Use using keyword to import the namespace

using System;

Console.WriteLine(“Hello”);

Creating and using aliases

- We can define shortcut for namespaces, classes, structures etc.


- Use the using keyword again

using <aliasname>=<class with namespace>;

Example
using c=System.Console;
c.WriteLine(“Hello”);
Data Types in C#

- Data types are categorized in three sections


o Value Types
§ All are structure
o Reference Types
§ All are classes
- Value Types are
o Integrals
§ byte – 1 byte
§ short – 2 bytes
§ int – 4 bytes
§ long – 8 bytes
§ sbyte
§ ushort
§ uint
§ ulong
o Floats
§ float – 4 bytes (6/7)
§ double – 8 bytes (15/16)
§ decimal – 16 bytes (28)
o Characters
§ char – 2 bytes
o Booleans
§ bool – 1 byte
- Reference Types
o string
o object

Literals

- The values used without keyboard input


- Integral Literals
o Default is int. Use l or L for long as suffix
§ int m=67;
§ long p=67L;
- Floating Literals
o Default is double
o Use f or F for floats and m or M for decimal
§ double k=6.7;
§ float p=5.6; //error
§ float p=5.6F; //correct
§ decimal p=5.6M;
- Character Literals
o Same as C
- Boolean literals
o Can have only true or false values. Default is false
o bool married;
§ married=true;
- String literals
o Enclosed in double quotes
o Strings do not have any NULL character like in C
§ string name=”Ravi”;
o Use @ to neutralize the escape character in the string and to create-preformatted strings
§ string path=”c:\kamal”; //error
§ string path=@”c:\kamal”;
§ string path=”c:\\kamal”;
Preformatted string
string path=@"
Amit

Rakesh

Sanjay
";
c.WriteLine(path);

Conditional Statements
1 . if
2 . switch
3 . ternary

Looping Statements
1 . while
2 . do-while
3 . for
4 . foreach
a . Works with arrays and collections

foreach(datatype variable in arrayorcollection)


{
statements;
}

Example
using c = System.Console;
class Program
{
static void Main(string[] args)
{
int[] num ={ 4, 7, 9, 3, 5 };
for (int i = 0; i < num.Length; i++)
c.WriteLine(num[i]);
foreach (int n in num)
c.WriteLine(n);
}
}

Using Keywords as Identifiers

- Use @ before the keywords to make the identifiers

string @float;

Arrays
- A variable that holds values of similar data type
- Arrays can be of two types
o Rectangular Array
§ Having equal number of columns in each row
o Jagged Array
§ Can have equal or un-equal number of columns in each row

Rectangular Array

1 . One dimensional
a . int []num1=new int[5];
2 . Two dimensional
a . int [,]num2=new int[2,5];
3 . Three Dimension
a . int [,,]num3=new int[3,5,6];

num2[0,1]=67;

- Each array provides Length property


- To get length of specific dimension use GetLength() method
o int GetLength(int dimension)

Example
int[,] num = new int[4, 6];
c.WriteLine("Length is " + num.Length);
c.WriteLine("First Dimension : " + num.GetLength(0));
c.WriteLine("Second Dimension : " + num.GetLength(1));

Jagged Array

- Array within Array is called as Jagged Array

Example
int[][] num = new int[3][];
num[0] = new int[3];
num[1] = new int[5];
num[2] = new int[7];

num[0][2] = 67;
num[0][1] = 44;

foreach (int k in num[0])


c.WriteLine(k);
17.01.2009
Class and Objects

- A class is a set of specifications or blue print or template about an entity

Classname reference=new Constructor(<paramaeters>);

Components of a class
1 . Field – To hold the values
a . Variables
b . Constants
c . Read Only Fields
2 . Methods
a . General Methods
b . Abstract methods
c . Sealed Methods
3 . Properties
4 . Indexer
5 . Delegate

Types of Fields
1 . Variables (default)
2 . Constants (const keyword)
3 . ReadOnly – Updated like constant or through constructors. Use readonly keyword

Testing a Multiple Class in Same Project


- Add a new class file from Projectà Add Class…
- If multiple classes have the entry points the we need to set the startup object from project
properties
o Projectà Properties à Startup Object

Reading data from Keyboard

- Use ReadLine() method of Console class


o string ReadLine()
- To convert data from string type to value type using any of two methods
o Parse() method of data types
o Use Convert class with conversion methods
§ ToInt32()
§ ToInt16()
§ ToDouble() etc.

Example

- Get a name and basic of an employee and print the DA as 92%

Getting Input from Command Line

- When we pass data from DOS prompt to the program is goes to Main(string []args)

Passing arguments to the Methods


- Arguments can be passed using following methods
o Pass by value (default)
o Pass by Reference (ref keyword)
o Pass by Output (out keyword)
o Pass by Address (Using pointers)
o Pass by Params (to provide dynamic number of arguments with params). A method
can have only one params type argument. If used with other arguments, it must the last
argument.

Difference between ref and out?

If case of ref, the variable must be initialized while in case of out, no initialization is required.

20.01.2009

Define the filename of exe or dll while compiling

- Use /out switch while compilation to define the output file name
- Extension can be .exe or .dll

CSC /out:outputname.ext <filename.cs>

Dealing with multiple entry points in same program

- To define the entry point use the class name with /main switch while compilation

Example
//Multimain.cs
class Home
{
public static void Main()
{
System.Console.WriteLine("This is a home edition");
}
}

class Professional
{
public static void Main()
{
System.Console.WriteLine("This is a professional edition");
}

Working with Pointers in .NET


- When using pointers in C#, it is known as unsafe or unmanaged code
- Such code get place in separate memory space called un-managed area
- Use unsafe keyword to define the pointers and direct accessing of address
- Unsafe keyword is used with functions or with block
- Use /unsafe switch while compilation

Example
//PointerTest.cs
class PointerTest
{
unsafe public static void Swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
public static void Main()
{
int x=5,y=10;
unsafe
{
Swap(&x,&y); //pass by address
}
System.Console.WriteLine("X is {0} and y is {1}",x,y);

}
}
Types of Methods
1 . General or Concrete Methods
a . Can called, inherited and overridden
2 . Abstract Methods
a . A method having the signature but no body contents
b . Such methods can be declared at two places
i. Inside Abstract class
ii. Inside Interfaces
c . If declared inside the class, it must be declared as abstract
d . No keyword is required if declared inside the interface
e . If a class contains any abstract method, it must be declared as abstract
3 . Sealed Method
a . A class that can never be overridden(final method of Java)
b . Use sealed keyword

Working with Properties


- A property is a special procedure that works with values rather than action
- Such procedures use set and get sections
- Use set to input with value reserve word and use get to send data from the procedure

<scope> <return type> PropertyName


{
set
{
variable=value;
}
get
{
return variable;
}
}

Properties will be used as


Object.property=value;

Indexers
- A property without any name
- We can pass an index number with an object where the object is not an array
- It returns some value from the class with that index
- Use this keyword instead of property name

Delegates

- Special classes that allows invoking the methods indirectly


- Use delegate keyword to declare the delegates

22.01.2009

Namespaces
- A namespace is a collection of classes, structures, interfaces, enumerators etc.
- Use namespace keyword to declare a namespace
- A namespace can have sub-namespace
- If no namespace name is provided then it goes to global namespace
- They can be of two types
o Pre-provided with .NET
§ System
§ System.Windows
§ System.Web
§ System.Data
§ System.Data.OracleClient
§ System.Data.SqlClient
o Customized Namespace
§ Can be designed inside an exe or dll

namespace <namespacename>
{
//members
}

Example 1
namespace MySpace
{
class Test
{
public void Testing()
{
System.Console.WriteLine("Hello to All");
}
}
}

namespace Hi
{
class Hello
{
public static void Main()
{
MySpace.Test t=new MySpace.Test();
t.Testing();
}
}

Placing the Namespaces into different files


- Create multiple files and divide the namespace those files
- While compiling provide all file names with CSC

File1.cs

namespace MySpace
{
class Test
{
public void Testing()
{
System.Console.WriteLine("Hello to All");
}
}
}

File2.cs
namespace Hi
{
class Hello
{
public static void Main()
{
MySpace.Test t=new MySpace.Test();
t.Testing();
}
}

Compiling

CSC file1.cs file2.cs à file2.exe

Creating Dynamic Link Library (DLL)


- A dynamic link library contains the namespace and their component
- To create a library use /t:library option with CSC
- to use this library in some program use /r:filename.dll with CSC

Note: While using classes from one namespace to another one in different assemblies (exe/dll) they must
be public.

Creating DLLs with Visual Studio.NET


- Create a new project as Class Library
- Give the project name e.g. MyTestLibary

Using a DLL in Visual Studio Projects


- Open a project
- Give reference to your DLL from Project à Add Reference… à Browse…

Creating Structures in C#
- Structures are value type custom data types
- They get created inside the stack
- Do not participate in inheritance
- Do not have parameter less constructor
- Cannot have the destructors
- Use struct keyword

Enumerators
- Names assigned to some values
- Use enum keyword to declare the enumerators
- Here we can define the datatype of enumerators

24.01.2009

Object Oriented Programming System (OOPs)

- It is a methodology for better project management


- It is based on four pillars
o Encapsulation
o Abstraction
o Polymorphism
o Inheritance

Encapsulation
- It states that all members of a class must be available at one place and none of the members can
be accessible outside class
o In C# all members must be declared inside the class and all members are private by
default
Abstraction
- It defines the accessibility control on the members
- C# provides five accessibility controls
o Private (private) – Default
§ Within the class
o Public (public)
§ Anywhere access
o Protected (protected)
§ Can be inherited inside or outside the assembly
o Internal (internal)
§ Within the assembly
o Protected Internal (protected internal)
§ Direct access within the assembly and inheritance into same or other assembly

Example
- Create a new project as Console Application
- Save Project as Project1
- Add another project into the same solution
- File à Add à New Project… à Console Application
- Save Project as Projec2
- The solution now contains two projects
- To make a project as current one use Set as Startup Object property from shortcut menu of the
project

Polymorphism
- A concept which allows to take multiple activities from an item
- It is achieved using two ways in C#
o Method Overloading
o Operator Overloading
- Method Overloading
o Multiple methods with the same name but different number of arguments or type of
arguments
- Operator Overloading
o A method to allow an operator to do more than one job
o It is an anonymous method created with operator keyword along with the operator to be
overloaded
o The method must be static
o Works with objects

27.01.2009

Inheritance
- Provides re-usability of code
- It reduces the code size, project cost and standardize the process
- Use : operator to inherit a class into other class
- C# allows only single inheritance
- While inheriting a class to a child class, it called as base class and represented by base keyword
(super keyword of Java)
- When a child class has the method with same signature as in parent class, the method can or
cannot be accessed by the reference of parent class.
- If the method in parent class is abstract method or virtual method then it can be overridden in
child class otherwise that hides the methods of childs class and cannot be access by the reference
of parent class; called as method hiding.
- Even if the method is virtual in parent class, we can hide or override that method in child class.
Use override keyword to overriding and new keyword for hiding. Hiding is default.
- Only overridden method can participate in dynamic polymorphism or Dynamic Method Dispatch
(DMD)

Example

Create a class Num2 with two parameters and define all possible methods.
Create another class Num3 to operate on three numbers and inherit Num2

Note: In inheritance, a parent can access those members of child whose signature is provided from
parent to the child and overriding is done. The methods in parent class must be virtual or abstract.
If the method is virtual, use override keyword for overriding. This concept is called as Dynamic
Polymorphism.

Abstract Class

- A class which is in-complete in itself but give completeness to others


- It may or may not have any abstract method
- All or none methods can be abstract
- It any of the methods is abstract then class must be abstract
- Such classes can never be instantiated
- Such classes are used for inheritance purpose only

Interfaces
- A collection of abstract methods. All methods are public and abstract by default
- Use interface keyword to declare the interfaces
- A class can inheritance any number of interfaces
- All methods are overridden in child class

29.01.2009
Working with sealed class and sealed methods
- Sealed class is the class that can never be inherited
- A sealed method cannot be overridden in child class. It can be applied only while overriding a
method and we don’t want to further override the methods. Use sealed and override together.
Sealed cannot be used with virtual.

Exception Handling
- An exception is a runtime error handled by special set of classes called Exceptions which are
used to report an exception.
- Each such class is inherited from Exception class and has Exception word at the end
- Every such class provideds
o Message property
o ToString() method
- C# provides four keywords for exception handling
o try
o catch
o throw
o finally
- try-catch is block of statements to execute the given statements and trap the error
try
{
Statements;
}catch(classname reference)
{
//action
}

- One try can have any number of catches


- finally is also a block provides at the end which always executes the commands irrespective of
exception

Creating Custom Exceptions

- Create a class to send the message when some kind of exception occurs and inherit the class with
Exception class
- Override Message property and ToString() method
- Throw an object of this class which that kind of exception occurs using throw keyword
- Use try-catch blocks to trap the error while using the method in a class

03.02.2009

String Handling
- Strings are managed by System.String class and System.Text.StringBuilder class
- String class hold immutable (fixed size) strings while StringBuilder class holds mutable strings
- String class provides various methods
o ToUpper()
o ToLower()
o Length
o Substring(int start, int length)
o int IndexOf(String s) – returns -1 if not found
o string [] split(params char ch)

Example
StringBuilder sb = new StringBuilder();
sb.Append("Amit");
sb.Append(" Kumar");
Console.WriteLine(sb);

string s = "Rakesh,kumar verma";


Console.WriteLine(s);
Console.WriteLine(s.ToLower());
Console.WriteLine(s.Length);
Console.WriteLine(s.Substring(1,4));
int n = s.IndexOf("Verma");
Console.WriteLine(n);
string[] str = s.Split(' ',',');
foreach (string x in str)
Console.WriteLine(x);

Real Applications
1 . Windows Applications
2 . Web Applications
3 . Mobile Applications
4 . Web Services
5 . Window Services

Windows Application Development


- Create a new project as Windows Application
- The application starts with a Window Form
- To a class as Window Form it must inherit from Form class
- The form works a container for other controls
- Each control has a fixed set of
o Properties
o Methods
o Events
- Properties
o Deals with values
o Can be of two types
§ Design Time (Property Window) – F4
§ Run Time (Code Window)
- Events are the moments or callback to do some action
o Can be user events (keyboard, mouse), System Generated (Load, UnLoad) or Hardware
(Tick) etc.

Common Properties for all controls

1 . Name – To define the name of the control. Every control must have a unique name. Use
Hungarian Notation to denote name with type of control and purpose of control. Use three
character pre-fix to define the type
a . txt à Textbox
b . frm à Form
c . cmd à Command Button
d . chk à Checkbox
2. BackColor
3. ForeColor
4. Font
5. Tag
6. Visible
7. Enabled

Form Control
1 . Text – caption of the form
2 . Icon
3 . BackgroundImage
4 . WindowState
5 . ShowInTaskBar
6 . StartPosition
7 . MinimizeBox
8 . MaximizeBox

Label control
- To provide fixed kind of information
o Text
o TabIndex
- Use & to define the hotkey

TextBox control
- To create single line, multiline text and password field
o Text
o PasswordChar
o Multiline
o MaxLength
o ReadOnly
o ScrollBars
o WordWrap
ToolTip control
- Used to provide the tooltips on the controls

Button control
- To create the push buttons
o Text
o Image
o TextAlign
o ImageAlign

LinkButton control
- A button that looks like hyper link
o Text
o Image
- Use Process class to start a process

System.Diagnostics.Process.Start("http://www.yahoo.com");

System.Diagnostics.Process.Start("notepad");
05.02.2009

Checkbox Control
- To select none or all
o Text
o Image
o TextAlign
o ImageAlign
o Checked
RadionButton control
- To select only one out of all
o Text
o Image
o TextAlign
o ImageAlign
o Checked
- Use containers GroupBox or Panel for grouping of radio buttons

ComboBox control
- To allow selection of only one item
- It provides Items collection
o It provides
§ Add() method
§ RemoveAt() method
§ Count property
- SelectedIndex
- SelectedItem
- DropDownStyle

Creating the Message Dialogs


- Use MessageBox class to create the dialogs with Show() method
- It can create two kind of dialogs
o Normal message dialogs
o Response Dialogs
- MessageBox.Show(“message”) – Normal dialog
- DialogResult MessageDialog.Show(“message”) – response dialog

Example Simple Dialogs


MessageBox.Show("Welcome to India");
MessageBox.Show("Welcome to India","Welcome");
MessageBox.Show("Welcome to India", "Welcome", MessageBoxButtons.OK,
MessageBoxIcon.Information);

ListBox control
- To select one or more items
- Provides Items collection
o SelectedIndex
o SelectedIndices
o SelectedItem
o SelectedItems
o SelectionMode
o bool GetSelected(int index)

Adding a new form


- Project àAdd Window Form

Making a form as current form


- Select the solution explorer from View Menu
- Select Program.cs file
- Define the class name to run in Application.Run() method of Main()

PictureBox control
- To show an image
o Image
o SizeMode
o BorderStyle
- Use Image class with FromFile() method to load an image dynamically

Working with Dialog controls

.NET provides five dialogs


- OpenFileDialog
- SaveFileDialog
- FontDialog
- ColorDialog
- FolderBrowerDialog
- Each of these dialogs provides ShowDialog() method

OpenFileDialog control
- provides a selected filename
o FileName

07.02.2009

ColorDialog control
- Allows selection of a color
o ShowDialog()
o Color
o FullOpen=true/false

FontDialog control
- To select a font and its properties and with some colors
o ShowDialog()
o Font
o Color
o ShowColor=true/false
Example
fontDialog1.ShowColor = true;
fontDialog1.ShowDialog();
textBox1.ForeColor = fontDialog1.Color;
textBox1.Font = fontDialog1.Font;

OpenFileDialog/SaveFileDialog
- Provides a filename to open/Save
o ShowDialog()
o FileName
o Filter
- To validate a file type using System.IO.Path class to get an extension of the
file and trap it

RichTextBox control

- Provides additional properties on text


- We can work on selected portion of text
o Cut()
o Copy()
o Paste()
o LoadFile()
o SaveFile()
o SelectionFont
o SelectionColor

Working with Menus


- .NET provides two kind of menus
o DropDown Menu or MenuStrip
o Popup Menu or ContextMenuStrip
- Select MenuStrip control from Menus and Toolbars section
- Create a ContextMenuStrip control and apply on any control with same property

10.02.2009

StatusStrip control
- To create a status bar
- It provides Items collection

Timer control
- Used to execute some statement after given interval of time
- Time is provided in milliseconds
o Interval
o Enabled
- Use Tick event for coding
- Found in Components section of ToolBox

ProgressBar control
- To show the progress of work
- Provides
o Minimum
o Maximum
o Value

DateTimePicker control
- To select date or time or both
o Value
o Format
o CustomFormat
o ShowCheckbox
o Checked

NotifyIcon control
- To show an icon and context menu in System Tray
o Icon
o ContextMenuItem
12.02.2009

ToolStrip control
- To create a toolbar

MDI Applications
- To create Multiple Document Interface (MDI) Applications
- To create such applications we need a main form and a child form
- To make a form as MDI form set its IsMdiContainer property as True
- To define a form as child form set its MdiParent property
- To arrange the child forms in main form use LayoutMdi() method of parent form

Example
this.LayoutMdi(MdiLayout.Cascade);

- To find out the current form use ActiveMdiChild property


- Use its Controls collection to fetch any control from the form

RichTextBox t = (RichTextBox)this.ActiveMdiChild.Controls["txtMain"];

ADO.NET
- A technology from Microsoft called as ActiveX Data Objects for .NET
- A part of .NET common base classes for database operations
- Namespaces used
o System.Data
o System.Data.Odbc
o System.Data.OleDb
o System.Data.OracleClient
o System.Data.SqlClient
- Namespaces are categories in two categories
o Generalized
§ System.Data.Odbc
• For any database using Data Source Name (DSN)
§ System.Data.OleDb
• For any database without using DSN
o Specific
§ System.Data.SqlClient
• Only for MS SQL Server and Express
§ System.Data.OracleClient
• Only for Oracle
- Use the two libraries
o System.Data.dll
o System.Data.OracleClient.dll

Kind of classes inside the namespaces


1 . Connections
a . To setup the connection with database
i. xxxConnection
1 . Odbc
2 . OleDb
3 . Oracle
4 . Sql
2 . Commands
a . To execute the SQL statements and stored procedures
i. xxxCommand
3 . Data Readers
a . Used to hold the records returned by some SQL statement
i. xxxDataReader
4 . DataAdapters
a . Used to pick the data from the server and give it to some container like DataTable or DataSet

Steps for Database handling


1 . Create and Establish the connection
a . xxxConnection cn=new xxxConnection();
b . Provide the ConnectionString property
c . cn.ConnectionString=”commands”;
i. Commands can be
1 . DSN=<dsnname>
2 . Provider=<drivername>
3 . Data Source=<server name or ip address>
4 . User Id or uid=<loginname>
5 . Password or pwd=<password>
6 . Database or Initial Catalog=<databasename>
d . Open the connection
i. cn.Open()
2 . Create the SQL statement to be executing
a . string sql=”sql command”;
3 . Create the Command type object and execute the statements
a . xxxCommand cmd=new xxxCommand();
b . cmd.Connection=cn;
c . cmd.CommandText=sql;
d . Execute any of three methods depending on type of SQL statement
i. ExecuteNonQuery()
1 . For all command except SELECT
ii.xxxDataReader ExecuteReader()
iii. object ExecuteScaler()
4 . Close the connection
a . cn.Close()

Using the OleDb Technology

- This technology using the concept of Provider rather than Data Source Name
- We can create the ConnectionString directly from Visual Studio.NET
o Data à Add New Data Source… àDatabase àNew Connection…

Example
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\Batches2009\04\ADO\TestData.mdb

Creating Dynamic Path for the MS Access files


- Use Application.StartupPath property to get the folder name having the executable program
- Place the Access file inside the BIN folder along with the executable program

Example
cn.ConnectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+
Application.StartupPath +@"\TestData.mdb";
Using MS SQL Server 2005
- Start SQL Server Management Studio

- top level user is called as sa

- Creating a Database

o Select the Databases then select New Database from properties


o Define the database name and Ok
- Creating a login
o Select Security à Logins à New Login
§ General Page
• Give the Login Name and Password
• Select the Default Database
§ User Mapping Page
• Select database
• Select rights are db_owner

Example
- Data Source=.;Database=batch04;uid=b04;pwd=1234
- Data Source=Impeccable;Initial Cataloge=batch04;User Id=b04;Password=1234
- Data Source=12.56.77.88;Database=batch04;uid=b04;pwd=1234

Working with SQL Express 2005


- It allows to create a database directly from Visual Studio
- Project à Add New Item… à SQL Database
Example
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\testdata.mdf;Integrated Security=True;User
Instance=True

19.02.2009

Creating SQL statements with Format() method String class

Example
string sql = String.Format("INSERT INTO employee values {0},'{1}','{2}')",
txtEmpId.Text, txtName.Text, txtEmail.Text);

Passing Parameters to Command Objects


- We do not define the data while creating the SQL statements but pass data later using Parameters
collection
- For MS Access use ?
- For MS Sql Server use @variable
- For Oracle use :variable

Example
For Sql Server
string sql = "INSERT INTO employee VALUES(@empid,@name,@email)";
SqlCommand cmd = new SqlCommand(sql, cn);
cmd.Parameters.AddWithValue("@empid", txtEmpId.Text);
cmd.Parameters.AddWithValue("@name", txtName.Text);
cmd.Parameters.AddWithValue("@email", txtEmail.Text);
Using Oracle Database
- Give reference to System.Data.OracleClient.dll
- Import the namespace System.Data.OracleClient

Opening connection for One way entry one way exit


- Create the reference of connection type at class level
- Open the connection inside the constructor
- Close the connection on FormClosing()

Placing information for global access in a project


- Add special files called as application configuration named as app.config
- Add an entry of connection string under <appSettings> tag

<configuration>
<appSettings>
<add key="cs" value="Data Source=oraimp;User ID=scott;Password=tiger"/>
</appSettings>
</configuration>

- Import System.Configuration namespace

Creating Central library of functions


- Add a class file from Project à Add Class…

21.02.2009

Reading Data from Database


- We can read the records or single set of value
- To read the single value use ExecuteScaler() method of xxxCommand object
o object ExecuteScaler()
- To read the records from database use any of two methods
o Connected Mode
o Disconnected Mode
- In connected mode we can read only one records at a time. We cannot go back. Use xxxDataReader to
refer the data in database. Once the connection is closed data cannot be access.
- In disconnected model, data is available on the client even after closing the connection. We can read all
data from server and place into a data container called DataTable or DataSet using xxxDataAdapter class
objects

Example for Scaler


string cs = ConfigurationSettings.AppSettings["cs"];
//MessageBox.Show(cs);
SqlConnection cn = new SqlConnection(cs);
cn.Open();
string sql = "Select name from employee where empid=@empid";
SqlCommand cmd = new SqlCommand(sql, cn);
cmd.Parameters.AddWithValue("@empid", txtEmpId.Text);
try
{
txtName.Text = cmd.ExecuteScalar().ToString();
}
catch (NullReferenceException ex)
{

MessageBox.Show("Sorry! Empid Not found", "Error", MessageBoxButtons.OK,


MessageBoxIcon.Stop);
}
cn.Close();
Example 2: Reading Records in Connected Mode
- Use ExecuteReader() method of xxxCommand object and pass reference to xxxDataReader class
- xxxDataReader provides HasRows property to know about records
- use Read() method to move the next records until end of file reached
o bool HasRows
o bool Read()
- When reading only one record, cursor is on beginning of file. To send it on first record use Read() method

string cs = ConfigurationSettings.AppSettings["cs"];
//MessageBox.Show(cs);
SqlConnection cn = new SqlConnection(cs);
cn.Open();
string sql = "Select * from employee where empid=@empid";
SqlCommand cmd = new SqlCommand(sql, cn);
cmd.Parameters.AddWithValue("@empid", txtEmpId.Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Read();//Move pointer to first record
txtName.Text = dr["name"].ToString();
txtEmail.Text = dr["email"].ToString();
}
else
MessageBox.Show("Employee Id not found");

Example 3 : Reading data in disconnected mode

- Use xxxDataAdapter class or combination or xxxCommand and xxxDataAdapter

xxxDataAdapter da=new xxxDataAdapter(sql,cn);

OR

xxxCommand cmd=new xxxCommand(sql,cn);


xxxDataAdapter da=new xxxDataAdapter(cmd);

- Data can be filled by xxxDataAdapter into some DataTable or DataSet type containers from System.Data
namespace
- Use Fill() method to fill the data

DataTable dt=new DataTable();


da.Fill(dt);

or

DataSet ds=new DataSet();


da.Fill(ds);

or

DataSet ds=new DataSet();


da.Fill(ds,”tablename”);

- A dataset is connection of DataTable type objects represented by Tables collections


Working with DataTable class
- DataTable class provides Rows and Columns collections
- DataTable and DataSet container manage data in XML format

22.02.2009

Introduction to XML
- It is a meta language known as eXtensibile Markup Language
- It allows to create custom
o Tags – e.g. <body></body>
o Attributes e.g. bgColor=”red”
o Entities e.g &npsp; &gt; &copy;
- XML is case-sensitive
- File extension must be .xml
- XML documents can be divided in three segments
o Prolog
o Data Islands
o Epilog
- Every document must have a root tag

Prolog
<? xml version=”1.0” ?>

DataSet class of .NET provides the method to read and create the XML files
- ReadXml(string filename)
- WriteXml(string filename)

DataSet class provides Tables collection to read the data

Creating DataTables
- A datatable is made of Rows and Columns
- Rows are denoted by DataRow class and columns by DataColumn class
- First create the columns in the Table

DataTable dt=new DataTable(“emp”);


dt.Columns.Add(“Name”);
dt.Columns.Add(“Email”);

- To create a blank row use NewRow() method of DataTable


o DataRow NewRow()
- Provide the data to the data row and add into Rows collection

Example 1
public partial class CreatingDataTable : Form
{
DataTable dt;
public CreatingDataTable()
{
InitializeComponent();
}

private void CreatingDataTable_Load(object sender, EventArgs e)


{
dt = new DataTable("emp");
dt.Columns.Add("Name");
dt.Columns.Add("Email");
dataGridView1.DataSource = dt;
}

private void button1_Click(object sender, EventArgs e)


{
DataRow dr = dt.NewRow();
dr["name"] = txtName.Text;
dr["email"] = txtEmail.Text;
dt.Rows.Add(dr);
txtName.Text = "";
txtEmail.Text = "";
txtName.Focus();
}
}

Example 2
public partial class CreatingDataTable : Form
{
DataTable dt;
DataSet ds;
public CreatingDataTable()
{
InitializeComponent();
}

private void CreatingDataTable_Load(object sender, EventArgs e)


{
ds = new DataSet();
try
{
ds.ReadXml("emp.xml");
dt = ds.Tables["emp"];
}
catch (System.IO.FileNotFoundException ex)
{
dt = new DataTable("emp");
dt.Columns.Add("Name");
dt.Columns.Add("Email");
ds.Tables.Add(dt);
}
dataGridView1.DataSource = dt;
}

private void button1_Click(object sender, EventArgs e)


{
DataRow dr = dt.NewRow();
dr["name"] = txtName.Text;
dr["email"] = txtEmail.Text;
dt.Rows.Add(dr);
txtName.Text = "";
txtEmail.Text = "";
txtName.Focus();
ds.WriteXml("emp.xml");
}
}
Creating Master/Detail Forms
- While create the master/detail forms the information is shown generally in combo box
- Use concept of DataBinding to read the values from the master tables and use the foreign key values for
details tables
o DataSource=<sourcename>
o DisplayMember=”fielname”
o ValueMember=”fieldname”
o SelectedValue

24.02.2009
Creating Printable Reports with Crystal Report Tools
- A report tool from Seagate to provide advance report for printing and export
- We can start a new project with Crystal Report or We can add crystal report any existing projects
- File à New à Project à Crystal Report Application
- Create the reports as .rpt files
- To create more reports
o Project à Add new item… à Crystal Reports
- To place a report on a form add a new form
- To place a report a crystal on a form add the CrystralReportViewer control from Toolbox along with
CrystalReportDocument control

Using DataView Control


- Use to filter and short the existing data inside a DataTable
- Use RowFilter and Sort properties

DataView dv=new DataView(dt);


dv.RowFilter=”condition”;

- Re-bind the data to any data controls

Creating Setup of a Windows Application

- Open the project for which you want to create the setup
- Set the Icon of the forms and the application
o Project à Properties à Icon
- Build the project
- Add a new project the same solutions from
o Fileà AddàNew Project à Other Project Types
o Setup and Deployment
o Setup Project
- Select the Mode as Release Mode
- Select properties of Setup Project
o Add à Project Output…
o Add other files if required like icon, access file, other libraries etc.
o Create Shortcuts of the Project Output files and place into User’s Desktop and User’s Program
Menu folders
28.02.2009

Creating Stored Procedures


- Start the SQL Server 2005
- Select the Database
- Select Programmability

CREATE PROCEDURE SaveData


@eid int,
@name varchar(50),
@email varchar(50)
AS
BEGIN
INSERT INTO employee VALUES(@eid,@name,@email);
END
GO

- Calling stored procedures from Client Side

Example
SqlConnection cn = new SqlConnection();

cn.ConnectionString = "Data Source=.;uid=sa;pwd=123456;database=batch04";


cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SaveData";
cmd.Parameters.AddWithValue("@eid", textBox1.Text);
cmd.Parameters.AddWithValue("@name", textBox2.Text);
cmd.Parameters.AddWithValue("@email", textBox3.Text);
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Record Saved");

Saving Images to the Databases


SqlConnection cn = new SqlConnection();

cn.ConnectionString = "Data Source=.;uid=sa;pwd=123456;database=batch04";


cn.Open();
string sql = "INSERT INTO photo VALUES(@name,@photo)";
SqlCommand cmd = new SqlCommand(sql, cn);
cmd.Parameters.AddWithValue("@name", txtName.Text);
MemoryStream ms = new MemoryStream();
picPhoto.Image.Save(ms, picPhoto.Image.RawFormat);
byte[] data = ms.GetBuffer();
SqlParameter p = new SqlParameter("@photo",SqlDbType.Image);
p.Value = data;
cmd.Parameters.Add(p);
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Image Saved");
picPhoto.Image = null;
txtName.Text = "";
txtName.Focus();

Reading data

txtName.Text = dt.Rows[i]["name"].ToString();
byte[] b = (byte [])dt.Rows[i]["photo"];
MemoryStream ms = new MemoryStream(b);
picPhoto.Image = Image.FromStream(ms);

Das könnte Ihnen auch gefallen