Dot Net Notes
Dot Net Notes
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++
- 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
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
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()
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 System;
Console.WriteLine(“Hello”);
Example
using c=System.Console;
c.WriteLine(“Hello”);
Data Types in C#
Literals
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
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);
}
}
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;
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
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;
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
Example
- When we pass data from DOS prompt to the program is goes to Main(string []args)
If case of ref, the variable must be initialized while in case of out, no initialization is required.
20.01.2009
- Use /out switch while compilation to define the output file name
- Extension can be .exe or .dll
- 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");
}
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
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
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();
}
}
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
Note: While using classes from one namespace to another one in different assemblies (exe/dll) they must
be public.
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
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
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
}
- 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);
Real Applications
1 . Windows Applications
2 . Web Applications
3 . Mobile Applications
4 . Web Services
5 . Window Services
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
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)
PictureBox control
- To show an image
o Image
o SizeMode
o BorderStyle
- Use Image class with FromFile() method to load an image dynamically
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
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);
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
- 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
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
- Creating a Database
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
19.02.2009
Example
string sql = String.Format("INSERT INTO employee values {0},'{1}','{2}')",
txtEmpId.Text, txtName.Text, txtEmail.Text);
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
<configuration>
<appSettings>
<add key="cs" value="Data Source=oraimp;User ID=scott;Password=tiger"/>
</appSettings>
</configuration>
21.02.2009
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");
OR
- Data can be filled by xxxDataAdapter into some DataTable or DataSet type containers from System.Data
namespace
- Use Fill() method to fill the data
or
or
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; > ©
- 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)
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
Example 1
public partial class CreatingDataTable : Form
{
DataTable dt;
public CreatingDataTable()
{
InitializeComponent();
}
Example 2
public partial class CreatingDataTable : Form
{
DataTable dt;
DataSet ds;
public CreatingDataTable()
{
InitializeComponent();
}
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
- 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
Example
SqlConnection cn = new SqlConnection();
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);