- •Foreword
- •About Programmer’s Heaven
- •About Faraz Rasheed
- •Contents In Summary
- •Just In Time Compilers (JITers)
- •The Framework Class Library (FCL)
- •The Common Language Specification (CLS)
- •The Common Type System (CTS)
- •Garbage Collection (GC)
- •The .Net Framework
- •C# compared to C++
- •Tools of the trade
- •The C# Language
- •The .Net Architecture and .Net Framework
- •The Common Language Runtime (CLR)
- •MSIL (Microsoft Intermediate Language) Code
- •The Visual Studio.Net IDE
- •Projects and Solutions
- •Toolbox, Properties and Class View Tabs
- •Writing Your First Hello World Console Application in C#
- •Working Without Visual Studio.Net
- •With Visual Studio.Net
- •Understanding the Hello World Application Code:
- •Namespaces in C#
- •The using Keyword
- •The class Keyword
- •The Main() Method
- •Printing on the Console
- •Comments
- •Important points to remember
- •A more interactive Hello World Application
- •Discussing a more interactive Hello World Application
- •2. C# Language Fundamentals
- •Lesson Plan
- •Basic Data Types and their mapping to CTS (Common Type System)
- •Integral Types
- •Floating Point Types
- •Other Types
- •Variables
- •Constant Variables or Symbols
- •Naming Conventions for variables and methods
- •Operators in C#
- •Arithmetic Operators
- •Operand
- •Prefix and Postfix notation
- •Assignment Operators
- •Operand
- •Relational Operators
- •Operand
- •Operand
- •Other Operators
- •Operand
- •Operator Precedence
- •Flow Control And Conditional Statements
- •The if...else statement
- •The switch...case statement
- •Loops In C#
- •The for Loop
- •Some important points about the for loop
- •The do...while Loop
- •while Loop
- •Arrays in C#
- •Array Declaration
- •Accessing the values stored in an array
- •foreach Loop
- •3. Classes and Objects
- •Lesson Plan
- •Concept of a Class
- •Objects
- •Fields
- •Data Type
- •Methods
- •Instantiating the class
- •Accessing the members of a class
- •Access Modifiers or Accessibility Levels
- •Access Modifier
- •Properties
- •Using Properties
- •Precautions when using properties
- •Static Members of the class
- •Some More about Methods
- •Constructors
- •Finalize() Method of Object class
- •Destructors
- •Method and Constructor Overloading
- •Overloading Constructors
- •Value types (out & ref Keywords)
- •Reference types
- •Some more about references and objects
- •4. Inheritance & Polymorphism
- •Lesson Plan
- •Inheritance
- •Inheritance in C#
- •Implementing inheritance in C#
- •Constructor calls in Inheritance
- •The base keyword - Calling Constructors of the base-class explicitly
- •Object class - the base of all classes
- •Polymorphism
- •Using the reference of the base type for referencing the objects of child types
- •Protected Access Modifier
- •The Protected internal Access Modifier
- •The sealed keyword
- •Using methods with the same name in the Base and the Sub-class
- •Overriding the methods - virtual and override keywords
- •The new keyword
- •Type casting the objects - Up-casting and Down-casting
- •The is and as keywords
- •Boxing and Un-boxing
- •5. Structures, Enumeration, Garbage Collection & Nested Classes
- •Lesson Plan
- •Structures (struct)
- •Defining a struct
- •Instantiating the struct
- •structs as Value Types
- •Enumeration
- •The Need for Enumeration
- •Using Enumeration (enum)
- •More about Enumerations
- •Garbage Collection in .Net
- •Destructors and Performance Overhead
- •System.GC.Collect() method
- •Nested Classes in C#
- •6. Abstract Classes & Interfaces
- •Lesson Plan
- •Abstract Classes
- •Interfaces
- •Implementing More Than One Interface
- •Explicit implementation of methods
- •Casting to an interface using is and as operators
- •An interface inheriting one or more interfaces
- •7. Arrays, Collections & String Manipulation
- •Lesson Plan
- •Arrays Revisited
- •Multidimensional Arrays
- •Instantiating and accessing the elements of multidimensional arrays
- •Instantiating and accessing Jagged Arrays
- •Some other important points about multidimensional arrays
- •The foreach Loop
- •Collections
- •The ArrayList class
- •The Stack class
- •The Queue class
- •Dictionaries
- •The Hashtable class
- •Constructing a Hashtable
- •Adding items to a Hashtable
- •Retrieving items from the Hashtable
- •Removing a particular item
- •Getting the collection of keys and values
- •Checking for the existence of a particular item in a hashtable
- •The SortedList class
- •String Handling in C#
- •The string class and its members
- •The StringBuilder class
- •8. Exception Handling
- •Lesson Plan
- •Exceptions Basics
- •The need for Exceptions
- •Exceptions in C# and .Net
- •Handling Exceptions using the try...catch...finally blocks
- •Use of the try...catch block
- •Exception class' Message and StackTrace Properties
- •The finally block
- •Catching Multiple Exceptions using multiple catch blocks
- •An important point to remember in multiple catch blocks
- •Other important points about Exception Handling in C#
- •Defining your own custom exceptions
- •Exception Hierarchy in the .Net Framework
- •Throwing an exception: the throw keyword
- •9. Delegates & Events
- •Lesson Plan
- •Delegates Basics
- •The type or signature of the method the delegate can point to
- •The delegate reference, that can be used to reference a method
- •3.The actual method referenced by the delegate
- •Calling the actual method through its delegate
- •Confusion in terminology
- •Delegates in the .Net Framework
- •Passing delegates to methods
- •Multicast Delegates
- •Implementing a Multicast Delegate
- •Removing a method from the multicast delegate's invocation list
- •Events and Event Handling
- •Event Handling in C#
- •A Clock Timer Example
- •Multicast events
- •Passing some data with the Event: Sub-classing System.EventArgs
- •10. WinForms & Windows Applications
- •Lesson Plan
- •Windows Applications and .Net
- •WinForm Basics
- •Building the "Hello WinForm" Application
- •Understanding the Code
- •Adding Event Handling
- •Visual Studio.Net & its IDE (Integrated Development Environment)
- •IntelliSense and Hot Compiler
- •Code Folding
- •Integrated Compiler, Solution builder and Debugger
- •Form Designer
- •Solution Explorer
- •Menus in the Visual Studio .Net IDE
- •Using Visual Studio.Net to build the "Hello WinForm" Application
- •Creating a new Project
- •Setting various properties of the form
- •Adding Controls to the Form
- •Adding Event Handling
- •Executing the application
- •The code generated by the Form Designer
- •Using More Controls
- •Using various controls in an application: Programmer's Shopping Cart
- •Designing the form and placing the controls
- •Writing Code for Event Handling
- •Some Important Points for designing Windows Applications
- •11. More Windows Controls & Standard Dialog Boxes
- •Lesson Plan
- •Collection Controls
- •List Box Control
- •Adding items to the list box
- •Accessing items in the list box
- •Removing items from the list box
- •List Box Events
- •Combo Box Control
- •Tree View
- •The TreeNode Editor
- •Adding/Removing items at runtime
- •Tree View Events
- •Image List Control
- •Attaching An Image List to different controls
- •List View Control
- •Two Image Lists in the List View Control
- •Adding items to the list view control using designer
- •Adding Items at runtime using code
- •Events for List View Control
- •Main Menu
- •Tool Bar
- •Date Time Picker
- •Windows Standard Dialog Boxes
- •Open File Dialog Box
- •Using the Open File Dialog Box
- •Save File Dialog Box
- •Font and Color Dialog Boxes
- •12. Data Access using ADO.Net
- •Lesson Plan
- •Introducing ADO.Net
- •Different components of ADO.Net
- •A review of basic SQL queries
- •SQL SELECT Statement
- •SQL INSERT Statement
- •SQL UPDATE Statement
- •SQL DELETE Statement
- •Performing common data access tasks with ADO.Net
- •Accessing Data using ADO.Net
- •Defining the connection string
- •Defining a Connection
- •Defining the command or command string
- •Defining the Data Adapter
- •Creating and filling the DataSet
- •A Demonstration Application
- •Loading tables
- •Filling the controls on the Form
- •Navigating through the records
- •Updating the table
- •Building the Application
- •Loading the table and displaying data in the form's controls
- •Initialing Commands
- •Adding Parameters to the commands
- •The ToggleControls() method of our application
- •Editing (or Updating) Records
- •Event Handler for the Save Button
- •Event Handler for the Cancel Button
- •Inserting Records
- •Deleting a Record
- •Using Stored Procedures
- •Sample Stored Procedures
- •UPDATE Stored Procedure
- •INSERT Stored Procedure
- •DELETE Stored Procedure
- •SELECT Stored Procedure
- •Using Stored Procedures with ADO.Net in C#
- •The modified InitializeCommands() method
- •Using Data Grid Control to View .Net data
- •A Demonstration Application for Data Grid Control
- •Second Demonstration - Using multiple related tables
- •Retrieving data using the SELECT command
- •Updating Records using INSERT, UPDATE and DELETE commands
- •13. Multithreading
- •Lesson Plan
- •What is Multithreading
- •Multithreading in C#
- •Thread Functionality
- •Static members of the System.Threading.Thread class
- •Instance members of the System.Threaing.Thread class
- •Thread Demonstration Example - Basic Operations
- •Thread Demonstration Example - Thread Priority
- •Thread Demonstration Example - Thread Execution Control
- •Using Join() to wait for running threads
- •Thread Synchronization
- •The C# Locking Mechanism
- •Threads may cause Deadlock
- •14. The File System & Streams
- •Lesson Plan
- •Working with the File System
- •Obtaining the Application’s Environment Information – The System.Environment class
- •Demonstration Application – Environment Information
- •Obtaining the paths of various Windows Standard folders – Environment.GetFolderPath()
- •Manipulating Files using System.IO.File and System.IO.FileInfo classes
- •System.IO.File class
- •Creating a file using Create() method
- •Copying and Moving a file using Copy() and Move() methods
- •Checking the existence of the file using Exists() method
- •Getting Attributes of a file using GetAttributes() method
- •System.IO.FileInfo class
- •A quick and simple example
- •Manipulating Directories (folders) using System.IO.Directory and System.IO.DirectoryInfo classes
- •System.IO.Directory class
- •Creating, deleting and checking for the existence of directories
- •Getting the contents (files and sub-directories) of a directory
- •System.IO.DirectoryInfo class
- •Demonstration application for the DirectoryInfo class
- •Streams
- •An overview of the different types of streams
- •The System.Stream class – the base of all streams in the .Net framework
- •Different types of file streams – Reading and Writing to files
- •Using System.IO.FileStream to read and write data to files
- •A string representing the path and name of the file
- •Opening and reading from a file
- •Using BinaryReader and BinaryWriter to read and write primitives to files
- •Using StreamReader and StreamWriter to read and write text files
- •Serialization and De-serialization
- •Implementing Serialization and Deserialization – A simple example
- •Formatters in Serialization
- •Preventing certain elements from Serializing – The [NonSerialized] attribute
- •Getting notified when Deserializing - the IDeserializationCallBack interface
- •Asynchronous Reading and Writing with Streams
- •A demonstration application
- •Issues Regarding Asynchronous Read/Write
- •Important points regarding the use of Streams
- •15. New Features In C# 2.0
- •C# evolves
- •The need for generics
- •Generic collections
- •Creating generic types
- •Constraining type parameters
- •Final thoughts on generics
- •Partial types
- •Nullable types
- •Anonymous methods in event handling
- •Adventures with anonymous methods
- •Final thoughts on C# 2.0
- •16. The Road Ahead
- •Learning More
- •Getting Help
- •Book.revision++
- •Good Luck!
Programmers Heaven: C# School
A FileAccess enumeration instance defines which operations are allowed during the file access. The possible values include Read, Write and ReadWrite. If FileAccess is Read, you can only read from the file stream.
A FileShare enumeration instance that defines the sharing options for the file. The possible values include None, Read, ReadWrite, Write. If FileShare is None, no other stream can open this file until you have got this stream open. If FileShare is Read, other streams can open and only read from this file.
Opening and reading from a file
Now we've got a good grasp of the theory of file streams, let's do something practical. In practice, handling a file stream is as easy as anything else in C#. Let’s create a windows application that reads a file into a text box, allows the user to change the text and saves it back to the file. The application will finally look like:
The code behind it is very simple. The event handler for the Read File button (btnGo) is:
private void btnGo_Click(object sender, System.EventArgs e)
{
string fileName = "C:\\C-sharp.txt";
lblFileName.Text = "File Name: " + fileName;
304
Programmers Heaven: C# School
// Open existing file in Read only mode without allowing any sharing
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
//create an array of bytes of the size of file\
//and read file contents to it.
byte[] byteText = new byte[fs.Length]; fs.Read(byteText, 0, byteText.Length);
//convert bytes array to string and display in the text box txtFileText.Text = System.Text.Encoding.ASCII.GetString(byteText);
//close the file stream so that other streams may use it fs.Close();
}
Here, we have used the file stream to open the existing file (FileMode.Open) in read only mode (FileAccess.Read) and without allowing any other stream to use it while our application is using this file (FileShare.None). We then created an array of bytes with length equal to the length of the file and read the file into it.
fs.Read(byteText, 0, byteText.Length);
Here we have specified that we want to read the file contents into the byteText array, that the file stream should start filling the array from the ‘0’ index and that it should read byteText.Length (size of file) bytes from the file. After reading the contents, we need to convert the byte array to a string so that it can be displayed in the text box. Finally, we have closed the stream (and thus the file) so that other streams may access it.
Similarly, the event handler for Save File button (btnSaveFile) is:
private void btnSaveFile_Click(object sender, System.EventArgs e)
{
string fileName = "C:\\C-sharp.txt";
// Open existing file in Read only mode without allowing any sharing
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Write, FileShare.None);
//covert the text (string) in the text box to bytes array
//and make the byteText reference to point to that byte array
byte[] byteText = System.Text.Encoding.ASCII.GetBytes(txtFileText.Text);
// write the byte array to file from the start to end fs.Write(byteText, 0, byteText.Length);
305
Programmers Heaven: C# School
// close the file stream so that other streams may use it
fs.Close();
}
Here we have first converted the text in the text box to a byte array and then written it to the file using FileStream class’ Write() method:
fs.Write(byteText, 0, byteText.Length);
In the above line we have told the FileStream class to write the bytes in the byteText array to the associated file. We have asked it to start writing from the first byte of the array and write the complete array to the file.
Using BinaryReader and BinaryWriter to read and write primitives to files
The problem with using the FileStream class is that we can only read and write bytes to the file. We have to explicitly convert other types of data (int, double, bool, string) to bytes before writing to the file (and vice versa for reading). The Dot Net (.Net) framework class library provides two classes that allow us to read and write primitive data types to a file. We can use System.IO.BinaryReader to read primitive data types from a file and System.IO.BinaryWriter to write primitives to the file.
An important point about the BinaryReader and BinaryWriter classes is that they need a stream to be passed in their constructor. These classes use the stream to read and write primitives.
Let’s create an application that writes different primitives to a file and then read them back. The application will finally look like this:
306
Programmers Heaven: C# School
The text box in the application is read only. At first, the Read File button is also disabled and the user needs to select the Save File button to save the file first, and then read the file back to the text box. The contents written to the file are hard coded in the Save File button’s click event handler which is:
private void btnSaveFile_Click(object sender, System.EventArgs e)
{
string fileName = "C:\\C-sharp.txt";
// Open existing file in Read only mode without allowing any sharing
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Write, FileShare.None);
//Open the Writer over this file stream BinaryWriter writer = new BinaryWriter(fs);
//write different types of primitives to the file writer.Write("I am Fraz\r\n");
writer.Write("Age: "); writer.Write(23); writer.Write("\r\nWeight: "); writer.Write(45.5);
//close the file stream so that other streams may use it writer.Close();
fs.Close();
btnLoadFile.Enabled = true;
}
Here we have first created the file stream and used it to instantiate the BinaryWriter class. We have then written different primitives to the stream using BinaryWriter’s Write() method, which has many overloaded versions to write different type of primitives. Finally we have closed the two streams and enabled the Load File button.
The event handler for the Load File button is:
private void btnGo_Click(object sender, System.EventArgs e)
{
string fileName = "C:\\C-sharp.txt"; lblFileName.Text = "File Name: " + fileName;
// Open existing file in Read only mode without allowing any sharing
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
307
