You are on page 1of 138

LECTURE 01

Shibu lijack

Shibu lijack

OVERVIEW: .NET Enterprise Vision

What is .NET?
.NET Framework

.NET Enterprise Vision


Users
Any device, Any place, Any time

XML Web Services


Scheduling Notification Authentication Integrate business applications and processes

Back Office
Heterogeneous application and server infrastructure

ERP & Billing

Customer Service

Sales

So what is .NET?
.NET is a platform that provides a standardized
set of services.
Its just like Windows, except distributed over the Internet. It exports a common interface so that its programs can be run on any system that supports .NET.

A specific software framework


Includes a common runtime

.NET Framework
Programming model for .NET Platform for running .NET managed code in
a virtual machine Provides a very good environment to develop networked applications and Web Services Provides programming API and unified language-independent development framework.

The Core of .NET Framework: FCL & CLR


Common Language Runtime
Garbage collection Language integration Multiple versioning support (no more DLL hell!) Integrated security

Framework Class Library


Provides the core functionality: ASP.NET, Web Services, ADO.NET, Windows Forms, IO, XML, etc.

.NET Framework Common Language Runtime


CLR manages code execution at runtime Memory management, thread management, etc.

Common Language Runtime


Operating System

.NET Framework Base Class Library

Object-oriented collection of reusable types Collections, I/O, Strings,

.NET Framework (Base Class Library)

Common Language Runtime


Operating System

.NET Framework Data Access Layer

Access relational databases Disconnected data model Work with XML

ADO .NET and XML .NET Framework (Base Class Library)

Common Language Runtime


Operating System

.NET Framework ASP.NET & Windows Forms


Create applications front-end Webbased user interface, Windows GUI, Web services,
ASP .NET
Web Forms Web Services Mobile Internet Toolkit

Windows Forms

ADO .NET and XML .NET Framework (Base Class Library)

Common Language Runtime


Operating System

.NET Framework Programming Languages


Use your favorite language
C++ C#
VB.NET Perl

J#

Windows Forms

ASP .NET
Web Forms Web Services Mobile Internet Toolkit

ADO .NET and XML .NET Framework (Base Class Library)

Common Language Runtime


Operating System

.NET Framework Common Language Specification

C++

VB Common Language Specification C# Perl J#

ASP .NET
Web Forms Web Services Mobile Internet Toolkit

Windows Forms

ADO .NET and XML .NET Framework (Base Class Library)

Common Language Runtime


Operating System

.NET Framework Visual Studio .NET

C++

C#

VB

Perl

J#

Common Language Specification Visual Studio .NET ASP .NET


Web Forms Web Services Mobile Internet Toolkit

Windows Forms

ADO .NET and XML .NET Framework (Base Class Library)

Common Language Runtime


Operating System

.NET Framework Standards Compliance


C++ C#
VB

Perl

J#

C# Language Submitted to ECMA


Open Language Specification
Visual Studio .NET

Common Language Specification ASP .NET


Web Services Web Forms Mobile Internet Toolkit

Windows Web services Forms XML, SOAP-based

ADO .NET and XML .NET Framework (Base Class Library)

XML-based data access

Common Language Runtime


Operating System

Video:-

LECTURE 02

OVERVIEW: Common Language Runtime(CLR)

Managed Code
Automatic Memory Management

Multiple Language Support


Intermediate Language

Common Language Runtime


Manages running code like a virtual machine
Threading Memory management No interpreter: JIT-compiler produces native code during the program installation or at run time Code access security Code can be verified to guarantee type safety No unsafe casts, no un-initialized variables and no out-of-bounds array indexing Role-based security

Fine-grained evidence-based security

Managed Code
Code that targets the CLR is referred to as
managed code All managed code has the features of the CLR
Object-oriented Type-safe Cross-language integration Cross language exception handling Multiple version support

Managed code is represented in special


Intermediate Language (IL)

Automatic Memory Management


The CLR manages memory for managed code
All allocations of objects and buffers made from a Managed Heap Unused objects and buffers are cleaned up automatically through Garbage Collection

Some of the worst bugs in software development


are not possible with managed code
Leaked memory or objects References to freed or non-existent objects Reading of uninitialized variables

Pointerless environment

Multiple Language Support

IL (MSIL or CIL) Intermediate Language

It is low-level (machine) language, like Assembler, but is Object-oriented Implements various types (int, float, string, ) And operations on those types

CTS is a rich type system built into the CLR


CLS is a set of specifications that all languages and libraries need to follow

This will ensure interoperability between languages

Intermediate Language
.NET languages are compiled to an
Intermediate Language (IL) IL is also known as MSIL or CIL CLR compiles IL in just-in-time (JIT) manner each function is compiled just before execution The JIT code stays in memory for subsequent calls Recompilations of assemblies are also possible

Example of MSIL Code


.method private hidebysig static void Main() cil managed { .entrypoint // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Hello, world!" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method HelloWorld::Main

Common Type System (CTS)


All .NET languages have the same primitive
data types. An int in C# is the same as an int in VB.NET When communicating between modules written in any .NET language, the types are guaranteed to be compatible on the binary level Types can be:
Value types passed by value, stored in the stack Reference types passed by reference, stored in the heap

Strings are a primitive data type now

Common Language Specification (CLS)

Any language that conforms to the CLS is a


.NET language

A language that conforms to the CLS has the


ability to take full advantage of the Framework Class Library (FCL)

CLS is standardized by ECMA

.NET Languages
Languages provided by Microsoft
C++, C#, J#, VB.NET, JScript Perl, Python, Pascal, APL, COBOL, Eiffel, Haskell, ML, Oberon, Scheme, Smalltalk

Third-parties languages Advanced multi-language features

Cross-language inheritance and exceptions handling


No additional rules or API to learn

Object system is built in, not bolted on

QUESTIONS????

LECTURE 03

OVERVIEW
C# Language

Code Compilation and Execution


The Visual Studio .NET Development
Environment

Console Applications

Windows Application Forms

C# Language
Mixture between C++, Java and Delphi Component-oriented
Properties, Methods, Events Attributes, XML documentation All in one place, no header files, IDL, etc. Can be embedded in ASP+ pages Primitive types arent magic Unified type system == Deep simplicity Improved extensibility and reusability

Everything really is an object

C# Language Example
using System;
class HelloWorld { public static void main() { Console.WriteLine(Hello, world!); } }

Code Compilation and Execution


Compilation
Source Code Language Compiler Code MSIL Metadata Also called Assembly (.EXE or .DLL file)

Execution
Native Code JIT Compiler

Before installation or the first time each method is called

The Visual Studio .NET Development Environment

Console Applications

Windows Application Forms

private void button1_Click(object sender, EventArgs e) { MessageBox.Show("The first Windows app in the book!"); }

Output

Video for the program:-

SUMMARY
How the Visual Studio 2008 development
environment works

How to create a simple console application

How to get a Windows application up and


running

QUESTIONS????

LECTURE 04

OVERVIEW
Basic C# Console Application Structure

Variables and Expressions


Using simple type variables

Naming Convention
Flow Control

Complex Variable Types

using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine("The first app in Beginning C# Programming!"); Console.ReadKey(); } } }

Basic C# Console Application Structure

Variables and Expressions


variables are concerned with the storage of
data.

The C# syntax for declaring variables simply


involves specifying the type and variable name
as follows:

<type> <name>;

Using simple type variables


static void Main(string[] args) { int myInteger; string myString; myInteger = 17; myString = "\"myInteger\" is"; Console.WriteLine("{0} {1}.", myString, myInteger); Console.ReadKey(); }

The output is followed by:-

Video of output:-

Naming convention: Variable names are something you will use a


lot.

Until recently the most popular system was what


is known as Hungarian notation.

There are currently two naming conventions in


use in the .NET Framework namespaces, known as Pascal Case and camel Case.

Expressions
By combining operators with variables and
literal values (together referred to as operands
when used with operators), you can create expressions, which are the basic building blocks of computation.

There are 3 operators namely unary, binary and


ternary.

Flow Control
Two methods of controlling program flow: Branching, where you execute code conditionally,
depending on the outcome of an evaluation. Looping, or repeatedly executing the same statements.

foreach Loops A foreach loop allows you to address each


element in an array using this simple syntax:

foreach (<baseType> <name> in <array>) { //


can use <name> for each element }

Lets see an example..


static void Main(string[] args) { string[] friendNames = {"Robert Barwell", "Mike Parry", "Jeremy Beacock"}; Console.WriteLine("Here are {0} of my friends:", friendNames.Length); foreach (string friendName in friendNames) { Console.WriteLine(friendName); } Console.ReadKey(); }

Output.

Video:-

Complex Variable Types


Complex Variable Types: Enumerations
Structures Arrays

Example for Enums:Namespace { enum orientation : byte { north = 1, south = 2, east = 3, west = 4 } class Program { static void Main(string[] args) { orientation myDirection = orientation. north; Console.WriteLine("myDirection = {0}", myDirection); Console.ReadKey(); } } }

Output

Video:-

Example for array:string[] friendNames = {"Robert Barwell", "MikeParry","Jeremy Beacock"}; int i; Console.WriteLine("Here are {0} of myfriends:",friendNames.Length); for (i = 0; i < friendNames.Length; i++) { Console.WriteLine(friendNames[i]); } Console.ReadKey();

Output

Summary
How basic C# syntax works? What Visual Studio does when you create
a console application project?

How to understand and use variables? How to understand and use expressions? Techniques for structuring your code

Exercises
Write a console application that obtains four int values from the
user and displays the product. Hint: you may recall that the Convert.ToDouble() command was used to covert the input from the console to a double; the equivalent command to convert from a string to an int is Convert.ToInt32().

Write an application that includes the logic from Exercise 1, obtains


two numbers from the user, and displays them, but rejects any input where both numbers are greater than 10 and asks for two new numbers.

QUESTIONS???

LECTURE 05

OVERVIEW
String Manipulation

Functions
Overloading and Delegate Functions

String Manipulation
string myString = "This is a test."; char[] separator = {' '}; string[] myWords; myWords=myString.Split(separator); foreach (string word in myWords) { Console.WriteLine("{0}", word); } Console.ReadKey();

Output

Video:-

Functions
Functions in C# are a means of providing blocks
of code that can be executed at any point in an
application.

Overloading and Delegate Functions


Function overloading provides you with the ability to create multiple
functions with the same name, but each working with different parameter types.

A delegate is a type that enables you to store references to


functions.

The delegate declaration specifies a function signature consisting of


a return type and the parameter list.

Example..
class Program { static int MaxValue(int[] intArray) { int maxVal = intArray[0]; for (int i = 1; i < intArray.Length; i++) { if (intArray[i] > maxVal) maxVal = intArray[i]; } return maxVal; } static void Main(string[] args) { int[] myArray = {1, 8, 3, 6, 2, 5, 9, 3, 0, 2}; int maxVal = MaxValue(myArray); Console.WriteLine("The maximum value in myArray is {0}", maxVal); Console.ReadKey(); } }

Output

Video:-

Summary
Passing parameter arrays to functions

Function overloading, where you can supply


different parameters to the same function to get additional functionality

Delegates and how to dynamically select


functions for execution at runtime

QUESTIONS???

Exercises
Write an application that uses two commandline arguments to place values into a string and
an integer variable, respectively. Then display these values.

Create a delegate and use it to impersonate the


Console.ReadLine() function when asking for user input.

LECTURE 06

OVERVIEW
Debugging and Error Handling

Object Oriented Programming


Objects

Properties and Fields


Methods

Debugging and Error Handling


error-handling techniques available in C#
enable us to take precautions in cases where errors are likely, and write code that is resilient enough to cope with errors that might otherwise be fatal.

Debugging
Console.WriteLine("MyFunc() Function about to

be called.");
MyFunc ("Do something."); Console.WriteLine("MyFunc() Function execution completed.");

Exceptions
The C# language includes syntax for Structured
Exception Handling Try { ... } Catch (<exceptionType> e) { ... } finally { ... }

Object Oriented Programming


Object-oriented programming is a relatively new
approach to creating computer applications that
seeks to address many of the problems with socalled traditional programming techniques.

Objects
An object is a building block of an OOP application. This building
block encapsulates part of the application, which may be a process, a chunk of data, or some more abstract entity.

Objects in C# are created from types, just like the variables. We picture classes and objects using Universal Modeling Language
(UML) syntax. UML is a language designed for modeling applications, from the objects that build them up, to the operations they perform, and to the use cases that are expected.

UML representation
UML representation of printer class, called Printer and of an instance of this Printer class called myPrinter.

Properties and Fields


Properties and fields provide access to the
data contained in an object. This object data

is what differentiates separate objects,


because it is possible for different objects of the same class to have different values stored in properties and fields.

Example of property and fields


Accessibility: A + symbol is used for a public
member, a - symbol is used for a private member. In general, though, I won't show private members in the diagrams in this chapter, because this information is internal to the class. No information is provided as to read/write access.

The member name. The type of the member. A colon is used to separate the member names
and types.

Methods
Method is the term used to refer
to functions exposed by objects. These may be called in the same way as any other function and may use return values and parameters in the same way.

Video:-

QUESTIONS???

LECTURE 07

OVERVIEW
OOP Techniques

OOP in windows Applications

OOP Techniques
Interfaces

Inheritance

Interfaces

An interface is a collection of
public methods and properties that are grouped together to encapsulate specific

functionality.

One interface of particular interest is IDisposable. An object that supports the

IDisposable
implement method

interface
the

must

Dispose()

Inheritance
Inheritance is one of the most important
features of OOP. Any class may inherit
from another, which means that it will have all the members that the class it inherits from has. In OOP terminology, the class being inherited (also known as derived) from is the parent class (also known as the base class).

OOP in Windows Applications


private void button1_Click(object sender, EventArgs e) { ((Button)sender).Text = "Clicked!"; Button newButton = new Button(); newButton.Text = "New Button!"; newButton.Click += new EventHandler(newButton_Click); Controls.Add(newButton); } private void newButton_Click(object sender, System.EventArgs e) { ((Button)sender).Text = "Clicked!!"; }

OUTPUT..

Video:-

SUMMARY
What object-oriented programming is?

The key terms and features of OOP.


How to create, use, and delete an object?

How to use OOP in a Windows application?

QUESTIONS???

EXERCISES
Write some code for a function that will accept
either of the two cup objects in the preceding example as a parameter. The function should call the AddMilk(), Drink(), and Wash() methods for any cup object it is passed.

LECTURE 08

OVERVIEW

Class definitions in C# Access Modifiers Interfaces The System.Object class Constructors and Destructors A comparison between interfaces and abstract classes

Class Definitions in C#
C# uses the class keyword to define classes.
The basic structure required is: class MyClass
{ // Class members.

Access Modifiers
Modifier none or internal public abstract or internal abstract public abstract sealed or internal sealed public sealed Meaning Class accessible only from within the current project Class accessible from anywhere Class accessible only from within the current project, cannot be instantiated, only derived from Class accessible from anywhere, cannot be instantiated, only derived from Class accessible only from within the current project, cannot be derived from, only instantiated Class accessible from anywhere, cannot be derived from, only instantiated

Video:-

Interfaces
Interfaces are declared in a similar way to
classes, but using the interface keyword rather than class. For example: interface IMyInterface { // Interface members. }

System. Object
Since all classes inherit from System. Object, all
classes will have access to the protected and
public members of this class.

System. Object contains the methods shown in the following table:Method Object() Return Type N/A Virtual No Static No Description Constructor for the System.Object type. Automatically called by constructors of derived types. Compares the object for which this method is called with another object and returns true if they are equal. The default implementation checks to see if the object parameter refers to the same object (because objects are reference types). This method can be overridden if you wish to compare objects in a different way, for example if they hold equivalent data. Returns a string corresponding to the object instance. By default, this is the qualified name of the class type (see earlier example), but this can be overridden to provide an implementation appropriate to the class type. Returns the type of the object in the form of a System.Type object. Used as a hash function for objects where this is required. A hash function is one that returns a value identifying the object state in some compressed form.

Equals(object)

bool

Yes

No

ToString()

string

Yes

No

GetType() GetHashCode()

System.Type int

No Yes

No No

Video:-

Constructors
A simple constructor can be added to a class
using the following syntax: class MyClass { public MyClass() { // Constructor code. } }

Video:-

Destructors
The destructors used in .NET is called Finalize().
class MyClass { ~MyClass() { // Destructor body. } }

Interfaces versus Abstract Classes Similarities: First, the similarities: both abstract classes and
interfaces may contain members that can be inherited by a derived class. Neither interfaces nor abstract classes may be directly instantiated, but you can declare variables of

these types.

Differences: derived classes may only inherit from a single base


class, which means that only a single abstract class may be inherited directly (although it is possible for a chain of inheritance to include multiple abstract classes).

Conversely, classes may use as many interfaces as


they wish.

Summary
How to define classes and interfaces in C#

The basic syntax for C# declarations


How to define constructors and destructors

How to use System. Object

LECTURE 09

OVERVIEW
We will here learn about field, property, and
method class members

Interface Implementation

Defining Fields
Fields are defined using standard variable
declaration format (with optional initialization),
along with the modifiers discussed previously. For example: class MyClass { public int MyInt; }

Defining Methods
Methods use standard function format, along
with accessibility and optional static modifiers.
For example:
class MyClass { public string GetString() { return "Here is a string."; } }

Defining Properties
Properties are defined using get and set
keywords.
public int MyIntProp {

get{ // Property get code. }


set { // Property set code. } }

Interface Implementation
Interface members are defined like class members except
for a few important differences: No access modifiers (public, private, protected, or internal) are allowed all interface members are implicitly public. Interface members can't contain code bodies. Interfaces can't define field members. Interface members can't be defined using the keywords static, virtual, abstract, or sealed. Type definition members are forbidden.

Summary
Learned how to define fields, methods, and
properties.

Learned about interface definition and


implementation.

LECTURE 10

OVERVIEW
Collections

Comparisons
Generics

Collections
Collections enable you to maintain groups of
objects.

Collections enable you to maintain groups of


objects.

There are number of interfaces in


System.Collections namely IEnumerable,IComparable.

IEnumerable
Provides the capability to loop through items in
a collection. The IEnumerable interface requires only one method: GetEnumerator. The job of GetEnumerator is to return an object of a class that implements IEnumerator.

Enumerator Provides following Methods or the properties:-

Method or property MoveNext() Reset()

Description Advance the enumerator Set the enumerator to initial position

Current

Get the current element

IComparable
To sort the Array List, the objects in the array
must implement IComparable.

IComparable has only one method:


CompareTo().

Comparisons
Here we come across two values: Type comparisons
Value comparisons

Type Conversion
Syntax:if (myObj.GetType() == typeof(MyComplexClass)) { // myObj is an instance of the class MyComplexClass. }

Value Comparison
Syntax:if (person1.Age > person2.Age) { ... } if (person1 > person2) { ... }

Generics
A generic class is one that is built around
whatever type, or types.
class MyGenericClass<T> { ... } Where T can be any identifier.

Followed by
A generic class can have any number of types
in its definition, separated by commas, for example: class MyGenericClass<T1, T2, T3> { ... }

You might also like