C Sharp QR
C Sharp QR
C Sharp QR
Source :
http://www.visualbuilder.com/csharp/tutorial/
Introduction to C sharp
C# (pronounced "C sharp") is a simple, modern, object-oriented, and type-safe
programming language. It will immediately be familiar to C and C++ programmers.
C# combines the high productivity of Rapid Application Development (RAD)
languages. The following are the advantages C# provides :-
Features of C# language:
• Simple
• Type safe
• Versioning: making new version of an application from existing
• One to work .
• Follows all OOPs paradigm
• Automatic garbage collection
• Flexible
Application Types in C#
1. Class Library:- Creates a project for creating classes that can be used in
other applications.
2. Console Application:- Creates a Visual C# application with a command-line
interface.
3. Asp.Net Web Application:- Creates a Visual C# application with a Web user
interface.
4. Asp.Net Web Service:- Creates an XML Web service with Visual C# that
other applications can access.
5. Asp.Net Mobile Web Application:- Creates an application viewable on
PDAs, cell phones, and other mobile devices.
Starting C#
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace cSHARPEXAMPLES
/// <summary>
/// </summary>
[ STAThread ]
Application .EnableVisualStyles();
Compilation:- This project can be compiled through command prompt using the
following command. The command will create a file called “Program.exe”, which we
can execute.
Csc.exe Program.cs
Types in C#:-
C# supports two kinds of types: value types and reference types. Value types
include simple types (e.g., char, int, and float), enum types, and struct types.
Reference types include class types, interface types, delegate types, and array
types.
A value type variable contains Reference type variable contains the address of
the data itself memory location where data is actually stored
When we copy a value type When copying a reference type variable to another
variable to another one, the variable, only the memory address is copied. Both
actual data is copied and each variables will still point to the same memory
variable can be independently location, which means, if we change one variable,
manipulated. the value will be changed for the other variable too.
1. if-else statement
2. switch statement
IF-ELSE Statement:
If Statement allows you to take different path depending on the decision condition.
The condition must return boolean. When the condition evaluates to a boolean true,
a block for that true condition will be executed.
Syntax:
• If (condition) {
// Single if statement
//execute block if condition, returns true.}
• If (condition) {
// execute block if condition, return false
} else {
// execute block if condition, return false
}
• If (condition1) {
// execute block if condition1 is true
} else if (condition2) {
// execute block if condition2 is true
} else if (condition 3) {
// execute block if condition3 is true
} else {
// otherwise if none condition satisfied then, this block will execute.
}
Switch Statement:
Another selection statement is the switch statement, which executes a set of logic
depending on the value of a given parameter that is evaluated by switch statement.
The type of values a switch statement operates on can be Boolean, Enums, Integral
Type and Strings.
Syntax:
Break;
Break;
Break;
Break;
Note:- The switch block follows the switch expression, where one or more choices
are evaluated for a possible match with the switch expression. Each choice is
labeled with the case keyword, followed by an example that is of the same type as
the switch expression and followed by a colon (:). When the result evaluated in the
switch expression matches one of these choices, the statement immediately
following the matching choice is executed. The block ends with either break,
continue, goto, return or throw statement.
Example: Demonstrate Selection Statement
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace cSHARPEXAMPLES
public Form2()
InitializeComponent();
txtEnter.Text = "" ;
MessageBox .Show( "Value is greater than 100 but less than 200" );
txtEnter.Text = "" ;
} else {
txtEnter.Text = "" ;
case 1:
case 4:
case 5: //Here the case 1 and 4 has no break, this will falls to this statement
txtEnter.Text = "" ;
break ;
case 2:
break ;
case 3:
break ;
default :
break ;
}
Output:
LOOPS……
………………………
Methods
Methods help you to separate code into modules that perform a given task. Every
program or application have a starting entry point to there application that decide
the path execution and all. We already come across different application where the
starting point or entry point is main ( ) method. Methods provide the flexibility
where we can separate the code into modules. This will make easy understanding of
code, more reusability and increase performance. The method can pass parameters
to another method and return the value that is optional. If the method contains
“void” keyword, this means method will not return any thing.
Syntax:
access specifier return-type methodname (parameter list) {
//Statement
}
Method Chaining:- The method chaining is the process by which one method calls
another method. The caller method can pass parameters to the called method and in
return the called method return some value (this is optional).
Example
The following example will demonstrate the method concepts along with the method
chaining.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace cSHARPEXAMPLES
/// <summary>
/// </summary>
[ STAThread ]
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault( false );
Method Chaining: Here we can add two values to the form and User can select the
options i.e. 1 Add, 2 Subtract, 3 Multiply and 4 Divide. And result will be displayed
when the user click Execute.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace cSHARPEXAMPLES
public Form4()
InitializeComponent();
lblEnter.Text = "" ;
switch (_valDec)
default :
break ;
}
void fxadd( int firstarg, int secondarg) {
txtResult.Text = _add.ToString();
txtResult.Text = _sub.ToString();
txtResult.Text = _mul.ToString();
txtResult.Text = _div.ToString();
}
Output
Namespaces
Namespaces are C# program elements that are used for logical grouping of the
classes. They also provide assistance in avoiding name clashes between two sets of
codes. Namespaces doesn't corresponds to file or directory names. The using
directives e.g.
Using System;
This contains number of classes, by including this namespace we can access those
classes that are there in the System namespace.
Example:- Demonstrate Namespace
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace cSHARPEXAMPLES
public Form5()
InitializeComponent();
namespace rootnamespace
// nested namespace
namespace firstlevelnamespace
class TestDemo
class TestDemo11
namespace secondnamespace
// nested namespace
namespace firstlevelnamespace
{
class TestDemo1
Example Explanation:
In above example we have 3 namespaces i.e. cSHARPEXAMPLES, rootnamespace,
secondnamespace.Rootnamespace contains irstlevelnamespace namespace,2 classes
i.e TestDemo, TestDemo11 and these classes contains methods i.e.
fxTest(),fxDisplay(). Secondnamespace contains nested namespace i.e.
firstlevelnamespace, 1 class i.e. TestDemo1 and the class contains methods i.e
fxTest1(),fxTest().
Introduction to Classes
Classes are the core of OOP's. Classes are declared by using the keyword classes.
Classes contain data members that represent the class. We can create object of the
class, objects are entities and we can create as many number of objects of a given
class.
Syntax:
Class classname {
//Variable declaration
// Method declaration
}
Classes can contain the following entities inside its declaration:
• Constructors
• Destructors
• Fields
• Methods
• Properties
• Indexers
• Delegates
• Events
• Nested Classes.
• Default Constructor
• Parameterized Constructor
• Copy Constructor
TestDemo.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace cSHARPEXAMPLES
{
public class TestDemo
{
String str;
static String str2 = "default" ;
public TestDemo() {
//Constructor
str = "Hi" ;
}
public TestDemo( String strdefault) {
//Parameterized Constructor
str = strdefault;
}
public String display(){
return str;
}
public static String staticfx() {
return str2 + " This comes from Static fx" ;
}
~TestDemo() {
// Clean Up Code Here.
}
}
}
Form6.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace cSHARPEXAMPLES
{
public partial class Form6 : Form
{
public Form6()
{
InitializeComponent();
}
Output:
Click on: Default Constructor Button
Inheritance
Inheritance is one of the primary concepts of object-oriented programming.
Inheritance is the process by which we can inherits the properties or methods of one
class into the other class. The concept behind inheritance, take the base class that
contains methods and properties and inherits it into the derived class, that now
contains all the members and properties of the base class as well as its own newly
added members or properties. The following are the advantages of Inheritance:-
• Reuse the existence code
• Save time, we need not do the code verification and testing.
• Here, we can add and modify the methods of the existing class.
• Help in modularization of code.
Types of Inheritance:
The following are the types of inheritance exist in C# programming.
Single Inheritance:
Here we have single base class that is inherited by the derived class. Here the
derived class has all the features of the base class and can add new features or
modify existing features. The inheritance also depends on the access specifier that is
used at the time of base class inheritance.
Multi-level Inheritance:
In the multi-level inheritance, here we having a chain of inheritance i.e. the base
class A is inherited by derived class B, and it is further inherited by another derived
class C. So, the feature we have in base class A, is also there in Derived class B, and
all the combination features of class A and class B are there in derived class C.
Multiple Inheritance:
In C#, we don't have multiple inheritance where one class can inherit two base
classes. So, the multiple inheritance can be done by using the concept of interfaces.
Here one class can inherit one class and can implements more than one interface.
Hybrid Inheritance:
The hybrid inheritance can also be done through with the help of interface. Here the
derived class cans implements more than two interfaces and only one class.
Example: Demonstrate Inheritance
DerivedClass7.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace cSHARPEXAMPLES
{
public class parentClass7
{
String str = "Parent:::" ;
public parentClass7() {
str = "Parent Constructor" ;
}
namespace cSHARPEXAMPLES
{
public partial class Form7 : Form
{
public Form7()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{
DerivedClass7 obj = new DerivedClass7 ();
MessageBox.Show( "Call to Parent Method :: " + obj.display());
MessageBox.Show( "Call to Derived Method :: " + obj.display1());
}
private void button2_Click( object sender, EventArgs e)
{
DerivedClass7 obj = new DerivedClass7 ();
MessageBox.Show( "Call in Derived method that further call Base method
===>" + obj.Show1());
}
}
}
OutPut:
When User Clicks On :Simple Inheritance Button
When User Clicks On :Calling Base Method in Derived Method Button
Polymorphism
Polymorphism is the core concept of OOP's. Polymorphism means one name many
forms.
Types of polymorphism
• Method Overloading
• Operator Overloading
Method Overloading:
In complex applications written in C#, we may need many methods which do
essentially similar functions but are just different enough to be considered unique.
So, we can define method overloading as if two or three method in a class has same
name but they differ by number of arguments or type of argument.
Operator Overloading:
This provides a meaningful understanding of the operation by using operator
overloading. Here what we did is we overload an operator and change its meaning,
so that a valuable information is send to the programmer and this help in reducing
the complexity.
E.g.
If we need to add two matrix of 3X3
Matrix result = Matrix.Add(mat1, mat2); // this doesn't give any relevant
information
Run Time Polymorphism
The run time polymorphism, here the compiler doesn't know which method to call at
runtime. Here we can call the derived method through base class pointer at runtime.
The run time polymorphism can be implemented through: Virtual – Override
Keyword.
Vitual function:
The virtual function is used to implement runtime polymorphism; here we have
same name method in the base class as well as in the derived class. We can access
the derived method using the base pointer. The virtual keyword should be write in
front of the base class method and in the derived class we have to write override in
front of the method. For Example:-
Class BaseClass {
Virtual void display () {//statements}
}
Class DerivedClass {
Override void display () {//statements}
}
Output
Properties
Properties are used to protect the field in a class by reading and writing it through
the property. Here the field consists of one getter and one setter that are associated
with a given field. We can access this field through this getter/setter combination.
Two ways to declare property in the class
class PropertyDemo {
private String name; //Declare a field
public String getName() { //Getter
return name;
}
public void setName( String Value) {//Setter
name = value;
}
}
class PropertyDemo {
private String name; //Declare a field
public String Name{
get{ return name;} //Getter
set{ name = value;} // Setter
}
}
Read-Only property:
We can declare a property as read-only; by only have its getter. So that the user
can't set the value of the field, because there is no setter for the field. Hence we
restrict the user to change the value of the field at any given time.
Write-Only property:
We can declare a property as write-only, by only have its setter. Here the user can't
access the value that is there in the field. We can manipulate the value of the field
by using its setter, but we can't get the value of this field.
Example: Demonstarte propery, Read-Only Property, Write Only Property.
ClsProperty9.cs
using System;
usingusing System.Collections.Generic;
using System.Text;
namespace cSHARPEXAMPLES
{
class ClsProperty9
{
private int age;
private String name;
private String lastName = "Dogra" ;
private String address;
public int getAge() {
return age;
}
public void setAge( int Value) {
age = Value;
}
public String getName()
{
return name;
}
public void setName( String Value)
{
name = Value;
}
//Read-Only property:Only Getter
public String getLastName()
{
return lastName;
}
• Regardless of the internal implementation of the class, its data can be obtained
consistently through the use of indexers.
• Indexers aren't differentiated by name, and a class cannot declare two indexers with
the same signature. However, this does not entail that a class is limited to just one
indexer. Different indexers can have different types and numbers of indexing
elements (these being equivalent to method parameters, except that each indexer
must have at least one indexing element, and the 'ref' and 'out' modifiers cannot be
used).
ClsIndexers10.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace cSHARPEXAMPLES
{
class ClsIndexers10
{
private String [] arrString;
private int arrSize;
public ClsIndexers10( int sizeofArray) { //Constructor
arrSize = sizeofArray;
arrString = new String [arrSize];
for ( int i=0;i<arrSize;i++){
arrString[i] = "No Value" ;
}
}
public string this [ int indexValue]
{
get {
return arrString[indexValue];
}
set {
arrString[indexValue] = value ;
}
}
public string [] this [ string data]
{
get {
for ( int i = 0; i < arrSize; i++)
{
if (arrString[i] == data)
{
arrString[i] = "Hi" ;
}
}
return arrString;
}
set
{
for ( int i = 0; i < arrSize; i++)
{
if (arrString[i] == data)
{
arrString[i] = "Hi" ;
}
}
}
}
}
}
Form10.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace cSHARPEXAMPLES
{
public partial class Form10 : Form
{
static int arrSize = 10;
ClsIndexers10 obj = new ClsIndexers10 (arrSize);
public Form10()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{ //Indexers Implementation : Using Integer
label1.Text = "" ;
obj[2] = "HHHI" ;
obj[5] = "Vikrant" ;
obj[9] = "Amit" ;
for ( int i = 0; i < arrSize; i++)
{
label1.Text = label1.Text + "Indexer at " + i + obj[i] + "\n" ;
}
}
private void button2_Click( object sender, EventArgs e)
{ //Indexers Implementation : Using String
label1.Text = "" ;
String [] arrString = obj[ "No Value" ];
for ( int i = 0; i < arrString.Length; i++)
{
label1.Text = label1.Text + "Indexer at " + i + obj[i] + "\n" ;
}
}
}
}
Output:
Click On: Indexer Implementation
Form11.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace cSHARPEXAMPLES
{
public partial class Form11 : Form
{
public Form11()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{
// Structs Implementation
label1.Text = "" ;
ClsStruct11 obj = new ClsStruct11 ();
label1.Text = obj.display();
}
private void button2_Click( object sender, EventArgs e)
{ // Structs Implementing Interface
label2.Text = "" ;
ClsStruct11 obj = new ClsStruct11 ();
label2.Text = obj.print();
}
}
}
Output:
Clicking On Both the Buttons: The concept behind the structs will be
executed and displayed.
Interfaces
An interface looks like a class, but has no implementation. Aninterface is a C#
reference type with members that do not have implementations. Interfaces only
have method signatures. The following are the properties of the interfaces:-
• We have the concept of inheritance in interface. One interface can extends another
interface.
Syntax:
Interface InterfaceName {
// method signature
}
Class implementing the Interfaces.
Class clsTest: ITestInterface
{
// method defined here
}
Structs Implementing Interface.
struct strTest: IstructsInterface
{
// method defined here
}
Interfaces may inherit other interfaces.
Example: Demonstrate Interfaces
ClsInterface12.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace cSHARPEXAMPLES
{
interface IParentInterace
{
String display();
}
interface IChildInterface : IParentInterace
{
String Show();
}
class ClsInterface12 : IChildInterface
{
String str = "Hi" ;
public ClsInterface12( String pStr) {
str = pStr;
}
public String Test() {
return str;
}
public String display()
{
return str + " : Display Of Base Interface" ;
}
public String Show()
{
return str + " : Show Of Child Interface" ;
}
}
}
Form12.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace cSHARPEXAMPLES
{
public partial class Form12 : Form
{
public Form12()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{
ClsInterface12 obj = new ClsInterface12 ( "Hello" );
label1.Text = obj.Test();
label2.Text = obj.display();
label3.Text = obj.Show();
}
private void Form12_Load( object sender, EventArgs e)
{
label1.Text = "" ;
label2.Text = "" ;
label3.Text = "" ;
}
}
}
Output:
Click On: Interface Executed Button
Delegates
A delegate in C# language allows us to reference a method. The other way to say
this delegate is a function pointer. The function pointer is same as we have pointer
to an address now in this case we have pointer to a method address. There are two
types of delegates :-
• Single-Cast Delegate:- Here the delegate will refer to or point to single method or
we can Say that the pointer is to single method from the delegate.
• Multi-Cast Delegate:-In the multi-cast delegate, the delegate refer to or point to
more than One method at runtime.
Delegates features:
• Delegate is a function pointer.
• Delegate declaration is same as method declaration, except they have delegate
modifier in front of it.
• The method that a delegate refers or pointing to must have same signature as of
delegate method.
• To use a delegate, we have to create the instance of the delegate and pass the
method that it is pointing too or referring to.
• Invoke (), This method can be used to invoke the delegate.
The delegates can be declared by adding a delegate keyword in front of any method.
For Example- delegate void Mydelegate();
Note:- This is declaration of the delegate and it specifies the method signature that
it is pointing or referring. This means the signature of the method that a delegate
pointing has no parameter and will not return any thing. But this is an example and
we can say the delegate can refer to any type of method.
Example: Demonstrate Delegates
ClsDelegate13.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace cSHARPEXAMPLES
{
class ClsDelegate13
{
delegate void Mydelegate ();
static String str = "" ;
static String sd = "" ;
public String singlecastfx()
{
sd = "" ;
sd = "Single Cast Delegate ==> " ;
Mydelegate d = null ;
d += new Mydelegate (singlecastdelegatefx);
d.Invoke();
sd = sd + " :: appender" ;
return sd;
}
public String multicastfx() {
str = "" ;
str = "starting Value ==> " ;
Mydelegate d = null ;
d += new Mydelegate (firstfx);
d += new Mydelegate (secondfx);
d();
str = str + " :: appender" ;
return str;
}
public void firstfx()
{
str = str + " :: firstfx" ;
}
public void secondfx()
{
str = str + " :: secondfx" ;
}
public void singlecastdelegatefx()
{
sd = sd + " ::singlecastdelegatefx" ;
}
}
}
Form13.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace cSHARPEXAMPLES
{
public partial class Form13 : Form
{
public Form13()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{ //Multi-cast delegate
ClsDelegate13 objDelegate = new ClsDelegate13 ();
MessageBox .Show(objDelegate.multicastfx());
}
private void button2_Click( object sender, EventArgs e)
{ //Single-cast delegate
ClsDelegate13 objDelegate = new ClsDelegate13 ();
MessageBox .Show(objDelegate.singlecastfx());
}
}
}
Output:
Clicking On: Single-cast Delegate Button
• Try Block:- In this block, we include all the suspected code. This means the code that
is most likely to cause exception.
• Catch Block:- In this block we include all handlers that will be take care of
exception that occurs. We can have number of catch blocks associated to single try
block.
• Finally Block : The finally block contains the cleanup code that we needed whether
the code is succeed or not. Most of the time we write a code that will deal locate the
memory that we associated in the beginning like memory allocated to connection
object.
Output:
Click On: Simple Try/catch Block Button
Click On: Try/catch and Finally Block Button
Attributes
Attributes are elements that allow you to add declarative information to your
programs. This declarative information is used for various purposes during runtime
and can be used at design time by application development tools. Attributes are also
used extensively in securing .NET assemblies, forcing calling code to be evaluated
against pre-defined security constraints. Attribute declared using the ‘[‘and ‘]'
brackets before any type declaration.
The following are the advantages the attributes provide:
Examples of Attributes:-
[ Obsolete ]
public String firstDeprecatedFX(){}
[ ObsoleteAttribute ]
public String secondDeprecatedFX(){}
Obsolete ( "Don't Use This Method." )]
public String thirdDeprecatedFX()
[ STAThread ]
static void Main () {}
Note:- This attribute declare that this is the entry point for the application. This
indicates that C# program should communicate with unmanaged COM code using
the single threading apartment. The parameter provide additional information about
the attribute
Example To Demonstrate Attributes
The following is the screen appeared when run the form 15 program in the source.
ClsAttribute15.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace cSHARPEXAMPLES
{
class ClsAttribute15
{
[ Obsolete ]
public String firstDeprecatedFX()
{
return "Call firstDeprecatedFX" ;
}
[ ObsoleteAttribute ]
public String secondDeprecatedFX()
{
return "Call secondDeprecatedFX" ;
}
[ Obsolete ( "Don't Use This Method." )]
public String thirdDeprecatedFX()
{
return "Call thirdDeprecatedFX" ;
}
}
}
Form15.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace cSHARPEXAMPLES
{
public partial class Form15 : Form
{
public Form15()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{ //Attribute : use to create method deprecated
ClsAttribute15 obj = new ClsAttribute15 ();
obj.firstDeprecatedFX();
//Deprecated Methods
obj.secondDeprecatedFX();
MessageBox .Show(obj.thirdDeprecatedFX());
}
}
}
Output:
Clicking On: Attribute fire up Button
Enums
An enumeration is a special kind of value type limited to a restricted and
unchangeable set of numerical values. Enums are strongly typed constants. They
are essentially unique types that allow you to assign symbolic names to integral
values.
Advantages of Enums:-
• In the C# tradition, they are strongly typed, meaning that an enum of one type may
not be implicitly assigned to an enum of another type even though the underlying
value of their members are the same.
• By default, these numerical values are integers, but they can also be longs, Bytes,
etc.
• When you define an enumeration you provide literals which are then used as
Constants for their corresponding values.
• Values specified in enumeration are static.
• These values are final and you can't change the value at runtime.
• The System.Enum BCL type is the base class of enum types and contains methods
that allow you to work with enums in different ways, such as working with a list of
names or values, converting from value to name, and converting from name to
value.
Syntax
enum enumname { //values}
Example:-
enum DayOfWeek {
Monday=2,
Tuesday,
Wednesday,
Thursday=10,
Friday,
Saturday,
Sunday
}
Note:-
Note:- Here the value will be Monday-2, Tuesday-3, Wednesday-4 and Thursday-
10, Friday-11, Saturday-12, Sunday-13.
ClsEnum16.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace cSHARPEXAMPLES
{
enum DayOfWeek {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
enum ValuesEnum : byte
{
One = 1,
two,
three=5,
four,
five
}
class ClsEnum16
{
public String GetvalueEnteredByUser( int enteredValue) {
//user entered value
ValuesEnum valuesEnum = ( ValuesEnum )enteredValue;
String str = "" ;
switch (valuesEnum)
{
case ValuesEnum .One: str = "FIRST" ;
break ;
case ValuesEnum .two: str = "SECOND" ;
break ;
case ValuesEnum .three: str = "THIRD" ;
break ;
case ValuesEnum .four: str = "FOURTH" ;
break ;
case ValuesEnum .five: str = "FIFTH" ;
break ;
default : str = "default" ; break ;
}
return str;
}
public String CreateAndUseEnumType(){
DayOfWeek dayofWeek = DayOfWeek .Thursday;
//DayOfWeek dayofWeek = (DayOfWeek)4;
String strDay = "" ;
switch (dayofWeek)
{
case DayOfWeek .Monday: strDay = "Monday" ;
break ;
case DayOfWeek .Tuesday: strDay = "Tuesday" ;
break ;
case DayOfWeek .Wednesday: strDay = "Wednesday" ;
break ;
case DayOfWeek .Thursday: strDay = "Thursday" ;
break ;
case DayOfWeek .Friday: strDay = "Friday" ;
break ;
case DayOfWeek .Saturday: strDay = "Saturday" ;
break ;
case DayOfWeek .Sunday: strDay = "Sunday" ;
break ;
}
return strDay;
}
}
}
Form16.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace cSHARPEXAMPLES
{
public partial class Form16 : Form
{
public Form16()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
The following table will give the description of the Access modifiers
available in C#.
Protected Protected members scope can be outside the class but only
limited to the immediate derived class that is inheriting the
base class where the protected members resides.
Internal Here the internal members are accessible within the same
assembly.
Sealed Class
The sealed keyword provides the restriction that no other class in the context can
inherit this class. By this, we can make our class not to be inherited by other class.
If the class tries to inherit the class that is declared as sealed, the compile time
error occurs.
1] Class declared as sealed
sealed class ClsSealed17 {// Any members }
Abstract Class
The class declared with abstract keyword, this means the class is only provide the
essential elements and not including the background details. Abstraction is the
process of including the essential elements and hiding the details. In layman terms,
we can say that a computer is the abstract form, because we are not aware of the
internal technicality.
If the class is declared as abstract, we have to give the body to all the methods that
are declared as abstract.
1] Class declared as abstract
abstract class clsAbstractDemo{
// This can contains abstract or concrete methods.
}
2] Abstract Members
public abstract string displayname();
Note:- The abstract methods can only include the signature of the method.
Example: Demonstrate Encapsulation
ClsEncapsulation17.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace cSHARPEXAMPLES
{
class Customer
{
public void CustomerRecord()
{
AddNewRecord();
UpdateExistingRecord();
DeleteRecord();
}
protected virtual string AddNewRecord()
{ return "Base: AddNewRecord" ; } //ADD NEW RECORD
protected virtual string UpdateExistingRecord()
{ return "Base: UpdateExistingRecord" ; } //UPDATE EXISTING RECORD
protected virtual string DeleteRecord()
{ return "Base: DeleteRecord" ; } //DELETE EXISTING RECORD
}
class ClsEncapsulation17 : Customer
{
private string name = "" ; //Can't Access Outside the Class
private string address = "" ; //Can't Access Outside the Class
private string pri_Display() //Can't Access Outside the Class
{
return "This method can't be access outside the class" ;
}
public string CustomerName { //Public Property
get { return name; }
set { name = value ; }
}
public string CustomerAddress //Public property
{
get { return address; }
set { address = value ; }
}
public string CombineDisplay() //Public Method
{
return CustomerName + " :::" + CustomerAddress;
}
protected override string AddNewRecord() //Protected Method
{
return "protected method :: AddNewRecord" ;
}
protected override string UpdateExistingRecord() //Protected Method
{
return "protected method :: UpdateExistingRecord" ;
}
protected override string DeleteRecord() //Protected Method
{
base .DeleteRecord();
return "protected method :: DeleteRecord" ;
}
public string combineString()
{
string cmbStr = "" ;
cmbStr = cmbStr + AddNewRecord() + "\n" ;
cmbStr = cmbStr + UpdateExistingRecord() + "\n" ;
cmbStr = cmbStr + DeleteRecord();
return cmbStr;
}
}
}
ClsSealed17.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace cSHARPEXAMPLES
{
sealed class ClsSealed17
{
private string name = "" ;
public string CustomerName
{
get { return name; }
set { name = value ; }
}
public string displayName()
{
return name;
}
}
//Can't inherited a Sealed Class
class derivedClass //: ClsSealed17
{
}
}
ClsAbstract17.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace cSHARPEXAMPLES
{
abstract class clsAbstractDemo
{
private int _number = 10;
public string _name = "" ;
public abstract string displayname(); // Abstract method
public int calcTotal() //Concreate Method
{
return (_number * 10);
}
}
class ClsAbstract17 : clsAbstractDemo
{
public override string displayname() { //Abstract Method
return "Abstract Method Provide Body in Derived Class" ;
}
}
}
Output
Click On: Private Members Button
Click On: Public Members Button
• Passing by Value
• Passing by Reference
• ‘Output' Parameter.
Passing By Value:
The parameter modifiers 'ref' and 'out' relate to how the parameter is passed into
the method. Where neither of these modifiers is used, the parameter is passed in 'by
value'. By default we are passing variable by value. Here the new copy of the
variable is send to the called method. So changes done to the variables are not
reflected on the actual parameter.
Syntax:
passValueByValueType(_initialValue); //Call a method
private void passValueByValueType( int iV)
{ iV = 20; }
Passing By Reference:
In C# we can pass variables into methods 'by reference'. Where a variable is passed
by reference, the 'ref' modifier must be used both in the method head and the
method invocation (illustrated by the next code block). The changes made to the
formal argument will reflect on the actual argument.
Syntax:
passValueByReferenceType( ref _initialValue); //Calling Method
private void passValueByReferenceType( ref int iV)
{ iV = 20; }
‘Output' parameter:
Where a method parameter is defined (and invoked) using the 'out' modifier, it is
passed by reference. The difference between the 'out' and the 'ref' modifier is this: a
parameter modified by the 'out' keyword need not be assigned a value before being
passed into the method, but must be assigned a value in the method.
Syntax:
passValueByOutParameter( out _initialValue, out _bValue);//Calling
‘Params' Modifier
One can pass an arbitrary number of types to a method by declaring a parameter
array with the 'params' modifier.
Syntax:
public int getTheTotalUsingParam( params int [] intArr)
Example: Demonstrate Parameter Passing in C#
Form18.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace cSHARPEXAMPLES
{
public partial class Form18 : Form
{
public Form18()
{
InitializeComponent();
}
private void btnValue_Click( object sender, EventArgs e)
{ //Value
int _initialValue = Int16 .Parse(textBox1.Text);
MessageBox .Show( "Before Calling " +
_initialValue.ToString());
passValueByValueType(_initialValue);
textBox1.Text = _initialValue.ToString();
MessageBox .Show( "After Calling " +
_initialValue.ToString());
}
private void btnReference_Click( object sender, EventArgs e)
{ //Reference
int _initialValue = Int16 .Parse(textBox2.Text);
MessageBox .Show( "Before Calling " +
_initialValue.ToString());
passValueByReferenceType( ref _initialValue);
textBox2.Text = _initialValue.ToString();
MessageBox .Show( "After Calling " +
_initialValue.ToString());
}
Method Overloading
Each method has a signature. The signature comprises the method's name and its
parameters (excepting their names), but not the method's return type. Method
Overloading is one of the forms of polymorphism. This is compile time polymorphism
because at compile time the compiler able to distinguish between the methods that
is declared with same name but different number of arguments.
Conditions which should be fulfilled for Method overloading:
• Method Name should be same for all the methods that are participating in method
Overloading.
• The number of arguments or type of arguments should be different.
• No class allowed two methods to have same signature.
ClsOverLoading19.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace cSHARPEXAMPLES
{
class ClsOverLoading19
{
int a;
int b;
//Constructor OverLoading
public ClsOverLoading19() { a = 10; b = 20; }
public ClsOverLoading19( int a, int b) { this .a = a; this .b = b;}
public ClsOverLoading19( ClsOverLoading19 obj) { this .a = obj.a;
this .b = obj.b; }
public int result() { return a + b; }
//Method OverLoading
public string display() { return "single method with no parameter" ; }
public string display( string strA) { return strA; }
public string display( string strA, string strB) { return strA + ":: "+ strB ; }
public string display( string strA, int intA) { return strA + " :: " + intA.ToString()
;}
}
}
Form19.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace cSHARPEXAMPLES
{
public partial class Form19 : Form
{
public Form19()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{ // Call Single Parameter Method
ClsOverLoading19 obj = new ClsOverLoading19 ();
MessageBox .Show(obj.display());
}
private void button2_Click( object sender, EventArgs e)
{ //Call Parameterized Method
ClsOverLoading19 obj = new ClsOverLoading19 ();
MessageBox .Show(obj.display( "vikrant" ));
MessageBox .Show(obj.display( "Vikrant" , "Dogra" ));
MessageBox .Show(obj.display( "Hi I am " ,27));
}
private void button3_Click( object sender, EventArgs e)
{ //Constructor overloading
ClsOverLoading19 obj = new ClsOverL oading19 ();
ClsOverLoading19 obj1 = new ClsOverLoading19 (30,40);
ClsOverLoading19 obj2 = obj1;
MessageBox .Show( "Default Constructor result " +obj.result());
MessageBox .Show( "Parameterized Constructor result " +obj1.result());
MessageBox .Show( "Copy Constructor result " + obj2.result());
}
}
}
Output:
Click On: Calling Single Parameter Method
ADO.NET OBJECTS
Ado.net includes many objects you can use to work with data. Some of the primary
objects are as follows:-
ClsOverloadingConversion.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace _CSharpApplication
{
class ClsOverloadingConversion
{
public int X;
public int Y;
public static implicit operator double ( ClsOverloadingConversion RValue)
{
double total_Distance;
double total_Sum;
total_Sum = (RValue.X * RValue.X) + (RValue.Y * RValue.Y);
total_Distance = System. Math .Sqrt(total_Sum);
return total_Distance;
}
}
}
ClsOverloadingEqualityInequality.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace _CSharpApplication
{
class ClsOverloadingEqualityInequality
{
public int X;
public int Y;
public static bool operator ==( ClsOverloadingEqualityInequality objFirst,
ClsOverloadingEqualityInequality objSecond)
{
if (objFirst.X != objSecond.X)
return false ;
if (objFirst.Y != objSecond.Y)
return false ;
return true ;
}
public override bool Equals( object o)
{
return true ;
}
public override int GetHashCode()
{
return 0;
}
public static bool operator !=( ClsOverloadingEqualityInequality objFirst,
ClsOverloadingEqualityInequality objSecond)
{
if (objFirst.X != objSecond.X)
return true ;
if (objFirst.Y != objSecond.Y)
return true ;
return false ;
}
}
}
Form3.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace _CSharpApplication
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{ //Overloading True and False operator
ClsOverloadingBooleanOpertors objBoolean = new
ClsOverloadingBooleanOpertors ();
objBoolean.X = 20;
objBoolean.Y = 30;
if (objBoolean)
MessageBox.Show( "The point is at the origin." );
else
MessageBox.Show( "The point is not at the origin." );
}
private void button2_Click( object sender, EventArgs e)
{ //Overloadable Conversion Operator
double conDistance;
ClsOverloadingConversion objConversion = new ClsOverloadingConversion
();
objConversion.X = 100;
objConversion.Y = 200;
conDistance = objConversion;
MessageBox.Show(conDistance.ToString());
}
private void button3_Click( object sender, EventArgs e)
{ //Overloading Equality/Inequality Operator
ClsOverloadingEqualityInequality MyFirstPoint = new
ClsOverloadingEqualityInequality ();
ClsOverloadingEqualityInequality MySecondPoint = new
ClsOverloadingEqualityInequality ();
ClsOverloadingEqualityInequality MyThirdPoint = new
ClsOverloadingEqualityInequality ();
MyFirstPoint.X = 100;
MyFirstPoint.Y = 200;
MySecondPoint.X = 500;
MySecondPoint.Y = 750;
MyThirdPoint.X = 100;
MyThirdPoint.Y = 200;
if (MyFirstPoint == MySecondPoint)
MessageBox.Show( "MyFirstPoint and MySecondPoint are at the same
coordinates." );
else
MessageBox.Show( "MyFirstPoint and MySecondPoint are not at the same
coordinates." );
if (MyFirstPoint == MyThirdPoint)
MessageBox.Show( "MyFirstPoint and MyThirdPoint are at the same
coordinates." );
else
MessageBox.Show( "MyFirstPoint and MyThirdPoint are not at the same
coordinates." );
}
}
}
Output:
Sockets
In socket-based network programming, you do not directly access the network
interface device to send and receive packets. Instead, an intermediary file descriptor
is created to handle the programming interface to the network. The special file
descriptors used to reference network connections are called sockets . The socket
defines the following:
After the socket is created, it must be bound to either a specific network address or
port on the system, or to a remote network address and port. Once the socket is
bound, it can be used to send and receive data from the network.
Network Addresses
After the socket is created, it must be bound to a network address/port pair. UNIX
offers an IP-specific address structure, sockaddr_in , which uses the following
elements. Using the sockaddr_in structure requires placing the appropriate IP
address and port values in the proper data element.
.NET defines two classes in the System.Net namespace to handle various types of IP
address information.The classes are IPAddress and IPEndPoint IPAddress object is
used to represent a single IP address. This value can be used in the various socket
methods to represent the IP address.
IPAddress Methods:-
Description
Method
PEndPoint Methods:
Description
Method
Form4.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
namespace _CSharpApplication
{
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{ //Introduction to IP Addresses.
IPAddress _address1 = IPAddress .Parse( "192.168.1.1" );
IPAddress _address2 = IPAddress .Broadcast;
IPAddress _address3 = IPAddress .Loopback;
IPAddress _address4 = IPAddress .None;
IPAddress _address5 = IPAddress .Any;
IPHostEntry _hostName = Dns .GetHostEntry( Dns .GetHostName());
IPAddress _myMachine = _hostName.AddressList[0];
if ( IPAddress .IsLoopback(_address3))
lstAddresses.Items.Add( "Loopback address is: " + _address3.ToString());
else
lstAddresses.Items.Add( "Error obtaining the LoopbackAddress" );
lstAddresses.Items.Add( "Local IP address is: " + _myMachine.ToString());
if (_myMachine == _address3)
lstAddresses.Items.Add( "Loopback Address Is Same AsLocal Address.\n" );
else
lstAddresses.Items.Add( "The loopback address is not the local address.\n" );
lstAddresses.Items.Add( "Given Address is: " + _address1.ToString());
lstAddresses.Items.Add( "Broadcast address: " + _address2.ToString());
lstAddresses.Items.Add( "ANY address is: " + _address5.ToString());
lstAddresses.Items.Add( "NONE address is: " + _address4.ToString());
}
private void button2_Click( object sender, EventArgs e)
{ //Introduction To IPEndPoint
IPAddress test1 = IPAddress .Parse( "192.168.1.1" );
IPEndPoint _endPoint = new IPEndPoint (test1, 8000);
lstIPEndPoint.Items.Add( "IPEndPoint is ::" +_endPoint.ToString());
lstIPEndPoint.Items.Add( "AddressFamily is ::" +_endPoint.AddressFamily);
lstIPEndPoint.Items.Add( "Address is :: " + _endPoint.Address);
lstIPEndPoint.Items.Add( "Port is :: " + _endPoint.Port);
lstIPEndPoint.Items.Add( "Min port number is :: " + IPEndPoint.MinPort);
lstIPEndPoint.Items.Add( "Max port number is :: " +IPEndPoint .MaxPort);
_endPoint.Port = 80;
lstIPEndPoint.Items.Add( "Changed IPEndPoint is :: " +_endPoint.ToString());
SocketAddress _socketAddress = _endPoint.Serialize();
lstIPEndPoint.Items.Add( "SocketAddress is :: " + _socketAddress.ToString());
}
}}
Output:
DNS Structure
The first (or top) level of distribution is divided into domains based on country codes.
Additional top-level domains for specific organizations were created to prevent the
country domains from getting overcrowded.
Domain Description
Educational institutions
.edu
Nonprofit organizations
.org
Canadian organizations
.ca
German organizations
.de
Using DNS
The last way to determine system IP information is to utilize the C# DNS (Domain
Name System) classes. DNS can be used to obtain Internet hostnames and IP
Addresses. The C# System.Net namespace contains the DNS class, which comprises
several methods that allow you to obtain DNS information about hosts. The
GetHostName() method retrieves the hostname of the local system. The
GetHostByName() method attempts to find the IP address of a hostname.
DNS Configuration
When your C# application is running on a customer's system, you have no
guarantee that there are any DNS servers configured. You can find out what (if any)
DNS servers are configured by using the .NET Registry class methods to examine
the DNS Registry values.
Fortunately, all Windows platforms store the DNS server information in the same
place:
HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
Registry Data Values for DNS Servers
Data Value Description
The value of most interest here is NameServer . This should contain a single string
value representing all the configured DNS servers, separated by spaces. The primary
DNS server will be listed first, followed by the alternate servers.
Close Method Close the Binary writer class and the underlying stream.
Flush Method Flushes out all data to the underlying stream and then
clears buffers.
Seek Method Sets the current position within the current stream.
Write Method This overloaded method writes a value out to the current
stream.
BinaryReader
The BinaryReader class, much like the BinaryWriter class, relies on a FileStream
object to read files .
Method Description
Close Close the binary reader object and the base stream.
PeekChar Reads the next available byte from the stream but does not
advance the byte or character position within the file.
ReadByte Reads a single byte from the stream. There is also a readbytes
method for specifying the number of bytes to read.
ReadChar Reads a single char value from the stream. There is also a
readchars method for specifying the number of chars to read.
• Use three slashes for comments(///). The C# compiler does not generate any XML
Documentation for any comments that do not begin with three slashes. Nor does the
C# compiler generates any XML documentation for regular, multi line, comments.
• Use the /doc option of the C# compiler to specify the name of the file that should
contain the generated XML documentation.
• Zone: The region from which the code originated. A zone is one of the commonly
used condition. A zone is the region of origin of a piece of code and refers to one of
the following: My Computer, Internet, Intranet, Trusted, or not trusted.
• Site: The Web site from which the code originated.
• Strong Name: A unique, verifiable name for the code.
• Publisher: The publisher of the code.
• URL: The specific location from which the code originated.
• Hash Value: The hash value for the assembly.
• Skip Verification: This condition requests that it bypasses code verification checks.
• Application Directory: The location of the assembly within the application.
• All Code: All code fulfills this condition.
• Custom: A user-specified condition.
Code groups are arranged hierarchically with the All Code membership condition at
the root.
Permissions
Permissions are the actions we allow each code group to perform? For example,
permissions include “able to access the user interface” and “able to access local
storage.” The system administrator usually manages the permissions at the
enterprise, machine, and user levels.
Multi-Threading
A thread is a sequence of execution in a program. All our C# programs up to this
point have one entry point—the Main () method. Execution starts with the first
statement in the Main () method and continues until that method returns. A thread
is the basic unit to which the operating system allocates processor time.
Processes are made up of one or more threads. A thread is defined as a single flow
of operation within a program. When a program executes on the CPU, it traverses
the program statements in a single thread until the thread is complete.
Amultithreaded application distributes functions among multiple program flows,
allowing two or more paths of execution to occur. Each path of execution is a
separate thread.
Multi-tasking: It's a feature of modern operating systems with which we can run
multiple programs at same time example word, excel etc
Multi-Threading: Multi-threading forms subset of multi-tasking instead of having
to switch between programs this feature switches between different parts of the
same program. Example we are writing a word document and at the same time
word is doing a spell check in background.
Multithreaded programs create their own threads that can be executed separately
from the main thread of the program. All threads created by the primary thread
share the same memory address space as the primary thread. Often the secondary
threads are used to perform computationally intensive functions, allowing the main
thread to continue responding to Windows events. Without the secondary threads,
the user could not select anything from the menu or click any buttons while an
application computed a mathematical function
System.Threading: This namespace has all the classes that are related to
implement threading. Any .Net application who wants to implements threading has
to import this namespace.
Note: In .Net program, there are always at least two threads running, i.e. one is the
main program and other is the garbage collector.
States:
Threads have several operational states, which are enumerated using the .NET
Thread State enumeration, found in the System.Threading namespace.
Thread priority: The thread priority determines the order in which thread has to
execute. The thread priority can be changed by using Threadname.Priority =
ThreadPriority.Highest.
Different levels of priority provided by .Net:
• ThreadPriority.Highest
• ThreadPriority.AboveNormal
• ThreadPriority.Normal
• ThreadPriority.BelowNormal
• ThreadPriority.Lowest
RegistryKey Class :
The RegistryKey class contains members to add, remove, replace, and read registry
data. Some of its common methods and properties are defined in the following
table.
Properties:
Name - Represents the name of the key.
SubKeyCount - Represents the count of subkeys at the base level, for theCurrent
key.
ValueCount - Represents the count of values in the key.
Methods:
GetValueNames Retrieves an array of strings that contains all the value names
associated with this key.
GetSubKeyNames Returns an array of strings that contains all the subkey names.
Windows Service
The core function of a Windows Service is to run an application in the background.
One of the ways that it differs from an windows application in that a Windows
Service starts before any user logs in to the system (if it has been setup to start at
boot up), although it can also be setup in such a way that it requires user to start it
manually. A Windows Service also has its own process hence it runs very efficiently.
Normally a Windows Service will not have a user interface for a simple reason it can
be run even if no one is logged on to the system but this is not a rule, you can still
have a Windows Service with a user interface.
Creating a Windows Service:
Step 1:- Open VS 2005, Click on File > Projects.
Step 2:- This will open up a project and clicking on the hyperlink that is there on
the page, you will be able to open the code behind page where you can code for the
web service.
Step 3:- Add Functionality to the web service that you have created. There are two
overridden function i.e. “OnStart” and “OnStop”. The OnStart function executes
when you start your service and the OnStop function gets execute when you stop a
service.
//OnStart
protected override void OnStart( string [] args)
{}
//OnStop
protected override void OnStop()
{}
Step 4:- Install and Run the Service: For Installation of the service on the computer,
one need to have the administrator rights to install the service on the computer. The
installUtil tool is provided by with the .Net framework to install the application.
Note:- The use should have administrator rights to install the utility. If the utility is
not installed then it will display a popup when you run the program.
Example: Demonstrate Windows Services.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
namespace winServiceFirst
{
public partial class OTestService : ServiceBase
{
public OTestService()
{
InitializeComponent();
}
protected override void OnStart( string [] args)
{
//This will be printed at the start of the service....
FileStream fs = new FileStream
( @"C:\windowServiceTest\trackerForWebService.txt" , FileMode
.OpenOrCreate, FileAccess .Write);
StreamWriter m_streamWriter = new StreamWriter (fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin .End);
m_streamWriter.WriteLine( " ************************** \n" );
m_streamWriter.WriteLine( " mcWindowsService: Service Started \n" );
m_streamWriter.WriteLine( " ************************** \n" );
m_streamWriter.Flush();
m_streamWriter.Close();
}
protected override void OnStop()
{ // TODO: Add code here to perform any tear-down necessary to stop your
service.
//This will be printed at the end of the service...
FileStream fs = new FileStream
( @"C:\windowServiceTest\trackerForWebService.txt" , FileMode .OpenOrCreate,
FileAccess .Write);
StreamWriter m_streamWriter = new StreamWriter (fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin .End);
m_streamWriter.WriteLine( " *************************** \n" );
m_streamWriter.WriteLine( " mcWindowsService: Service Stopped \n" );
m_streamWriter.WriteLine( " *************************** \n" );
m_streamWriter.Flush();
m_streamWriter.Close();
}
}
}
Output:
Note:- Thr program will write the content in the text file that we specified. The
following lines gets printed in the text file.
**************************
***************************
***************************
Web Service
The term "web service" refers to a form of a component that can be used remotely.
Web services are invoked remotely using SOAP or HTTP-GET and HTTP-POST
protocols. Web services are based on XML and return an "answer" to the client in
XML format. Web services have all the advantages of components plus many more.
The most significant benefits include:
Soap calls are remote function calls that invoke methods executions on Web Service
components at Location 2. The output is render as XML and pass back to the
Location 1 where the user wants to access the Web Service.
At Location 1, the user need to consume some of the functions of the web service
that is available on the internet, to make the remote function calls (RFC). All the
processing can't be done on the remote machine, therefore, we have to create the
proxy of the web service from where we can process our data. This whole process is
also called as marshalling of data.
Due to security threats, we create the proxy of the server object here it is web
service. That means we are creating a " proxy object " to act on behalf of the
original Web service. The proxy object will have all the public available data
interfaces as the original Web service.
Consuming a Web Service
The following are the steps to call/consume a webservice.
Step 1: Create a Web Service project and run it so that no compilation error exists.
Step 2: Create new Web Site that will consume this web site that is there in your
system using the VS.Net. Create New Web Site with the name: Web Site Name that
will consume web service:WebService_Consume.
Step 3: Once you are done with the creation of the new site that will consume the
web Service. Let example the web service run as this
URL:http://localhost:1508/WebService_New/MyWebService.asmx
Step 4: Right click on the solution, Click on “Add Web Reference”. This will open up
a new pop-up window where you can specify theURL name of your web service .
Here we specify the web service URL and if you look at the right panel there is Web
Reference Name: localhost [This the default name that is there].
Step5: We specify “localhost_myWebService” name for the web reference. This will
include 3 files under this folder.
• MyWebService.disco
• MyWebService.discomap
• MyWebService.wsdl
Click on the Fetcher button: This will fetch the value from the Web Service.
1. The first way is to use a SOAP Proxy Client Object generated by the WSDL
utility, and it provides programmers with their familiar object model that they
can use to call methods provided by the generated Proxy Interface.
2. The second way is to use HTTP-POST and HTTP-GET protocols.
3. The third way is to use a SOAP standard Request message that parses SOAP
response messages with the help of the XMLHTTP COM object that is installed
by the Microsoft XML Parser.
WSDL: Web Services Description Language (WSDL) is an XML based protocol for
information exchange in decentralized and distributed environments. A WSDL
document defines services as collections of network endpoints, or ports. A WSDL
document uses the following elements in the definition of network services:
• Types – a container for data type definitions using some type system (such as XSD).
• Message – an abstract, typed definition of the data being communicated.
• Operation – an abstract description of an action supported by the service.
• Port Type –an abstract set of operations supported by one or more endpoints.
• Binding – a concrete protocol and data format specification for a particular port
type.
• Port – a single endpoint defined as a combination of a binding and a network
address.
• Service – a collection of related endpoints.
Proxy Class: This proxy class serves as an intermediate between the ASP.NET Web
page and the Web service
1. The Asp.Net page instantiates an instance of the proxy class. For e.g.
ProxyClassName objproxy = new ProxyClassName();
2. Once the object is instantiated, then with the help of proxy object, this will
make a call to the web service method. For e.g.
objproxy.WebMethodName(any Parameter that has to send);
3. The proxy class marshals the parameter list and makes an HTTP request to
the Web service sitting on Web Server 2.
4. The Web service unmarshals the incoming parameters, runs the method, and
marshals the output parameters. These are sent back in an HTTP response.
5. The proxy class unmarshals the return parameters and passes back the result
to the ASP.NET Web page.
1. Clicking “Ok” will include the proxy class to the solution under “Bin folder”.
2. Now we can use this proxy class and the methods that are there in the web
services.
Note: A proxy class is a class containing all of the methods and objects exposed by
the Web service. These methods handle the marshalling of the parameters into
SOAP, sending the SOAP request over HTTP, receiving the response from the Web
service, and unmarshalling the return value. The proxy class allows the client
program to call a Web service as if the Web service was a local component.
Once you create a proxy class using the .NET command-line toolwsdl.exe , a Web
service client may invoke proxy class methods, which communicate with a Web
service over the network by processing the SOAP messages sent to and from the
Web service.
Example: Demonstrate the Creation of Proxy Class and its Usage
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI. Page
{
protected void Page_Load( object sender, EventArgs e)
{
}
protected void btnCustomer_Click( object sender, EventArgs e)
{ //Fetching the Customer Data from the Proxy Class.
try
{
Service objService = new Service ();
txtCustomerAge.Text = objService.getEmployeeAge();
txtCustomerName.Text = objService.getEmployeeName();
}
catch ( Exception ex) {
Response.Write(ex.Source);
}
}
}
Output:
Click On the “Customer Data” Button:
Clicking on the “Create XML Document” after filling all the fields.
Clicking On the ‘ Read XML “ button the following screen will be displayed.
• Evidence:- From where the code comes? Is the code managed or unmanaged.
• Permissions:- The permission set on which the code executes.
2. Creating a new Permission Set à Expand “Runtime Security Policy”. There are 3
security policy levels i.e. Enterprise , Machine and User. We are creating the
permission set for the machine security level.
3. Assign the permission to the permission set: Each permission set is a collection of
much different permission to various resources on the computer. Select the
permission that you need in the permission set.
4. Here I am selecting the “File IO” permission from the pool of permission set. And
then change the settings for this permission. Here specify the “C:\” in the file path
and assign only reading permission to this.
5. Here we assign 3 permission to the newly create permission set i.e. File IO,
Security and User Interface.
Create an Application: That will perform read and write operations on file.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace winCreatingPSET
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click( object sender, EventArgs e)
{ //Writing to the Document
StreamWriter _streamWriter = new StreamWriter
( "c:\\TestPermission.txt" );
_streamWriter.WriteLine( " Security is Important" );
_streamWriter.WriteLine( " Security can provide Authentication " );
_streamWriter.Close();
}
private void button1_Click( object sender, EventArgs e)
{ //Reading from the Document
StreamReader _streamWriter = new StreamReader
( "c:\\TestPermission.txt" );
lstPSET.Items.Add(_streamWriter.ReadLine());
lstPSET.Items.Add(_streamWriter.ReadLine());
_streamWriter.Close();
}
}
}
Output:
Now run the application and try to click on the “write” button the screen, this will
give you following exception.:-
Description
Property
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace _CSharpApplication
{
public partial class Form5 : Form
{
public Form5()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{ // Demonstrate Socket Properties
IPAddress _ipAddress = IPAddress .Parse( "127.0.0.1" );
IPEndPoint _ipEndPoint = new IPEndPoint (_ipAddress, 8000);
Socket _socketTest = new Socket ( AddressFamily .InterNetwork,
SocketType .Stream, ProtocolType .Tcp);
lstSocketProperties.Items.Add( "AddressFamily :: " +
_socketTest.AddressFamily);
lstSocketProperties.Items.Add( "SocketType :: " + _socketTest.SocketType);
lstSocketProperties.Items.Add( "ProtocolType :: " +
_socketTest.ProtocolType);
lstSocketProperties.Items.Add( "Blocking :: " +_socketTest.Blocking);
_socketTest.Blocking = false ;
lstSocketProperties.Items.Add( "new Blocking :: " + _socketTest.Blocking);
lstSocketProperties.Items.Add( "Connected :: " + _socketTest.Connected);
_socketTest.Bind(_ipEndPoint);
IPEndPoint _newIpEndPoint = ( IPEndPoint )_socketTest.LocalEndPoint;
lstSocketProperties.Items.Add( "Local EndPoint :: " +
_newIpEndPoint.ToString());
_socketTest.Close();
}
private void button2_Click( object sender, EventArgs e)
{ //Socket Exceptions
IPAddress _hostIPAddress = IPAddress .Parse( "192.168.1.1" );
IPEndPoint _hostIPEndPoint = new IPEndPoint (_hostIPAddress, 8000);
Socket _socket = new Socket ( AddressFamily .InterNetwork, SocketType
.Stream, ProtocolType .Tcp);
try
{
_socket.Connect(_hostIPEndPoint);
}
catch ( SocketException e1)
{
lstSocketExceptions.Items.Add( "Problem Connecting To Host ........" );
lstSocketExceptions.Items.Add(e1.ToString());
_socket.Close();
return ;
}
try
{
_socket.Send( Encoding .ASCII.GetBytes( "testing" ));
}
catch ( SocketException ex)
{
lstSocketExceptions.Items.Add( "Problem Sending Data" );
lstSocketExceptions.Items.Add(ex.ToString());
_socket.Close();
return ;
}
_socket.Close();
}
}
}
Output:
Clicking On both the Buttons will display the respective outputs in the
listbox