0% found this document useful (0 votes)
60 views488 pages

C# Notes

The document provides an overview of C# and .NET programming regulations for the 2017 semester. It covers C# language basics like variables, data types, flow control, objects, classes, inheritance, generics, arrays, tuples, operators, and casts. It also introduces .NET architecture and the core components of the .NET framework like the common language specification, base class libraries, and common language runtime. Key concepts covered include object-oriented programming in C#, the C# programming language, and control structures like conditional if/else statements and loops in C#.

Uploaded by

Gopi Nath
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
60 views488 pages

C# Notes

The document provides an overview of C# and .NET programming regulations for the 2017 semester. It covers C# language basics like variables, data types, flow control, objects, classes, inheritance, generics, arrays, tuples, operators, and casts. It also introduces .NET architecture and the core components of the .NET framework like the common language specification, base class libraries, and common language runtime. Key concepts covered include object-oriented programming in C#, the C# programming language, and control structures like conditional if/else statements and loops in C#.

Uploaded by

Gopi Nath
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 488

2017 REGULAITON- CSE

C# AND .NET PROGRAMMING


CS8073

VII SEMESTER – FINAL CSE

Mrs.P.KAVITHAPANDIAN
ASP/CSE
UNIT- I

C# LANGUAGE BASICS
.Net Architecture - Core C# - Variables -
Data Types - Flow control - Objects and
Types- Classes and Structs - Inheritance-
Generics – Arrays and Tuples - Operators
and Casts – Indexers
www.rejinpaul.com

Introduction to .NET
• Content :
– Introduction to .NET Technology
Introduction to .NET Technology
What is .NET ?

Microsoft.NET is a Framework
– Microsoft .NET is a Framework which provides a common
platform to Execute or, Run the applications developed in
various programming languages.

– Microsoft announced the .NET initiative in July 2000.


– The main intention was to bridge the gap in
interoperability between services of
various programming languages.
.NET Framework Objectives

• The .NET Framework is designed to fulfill the


following objectives:
– Provide object-oriented programming environment

– Provide environment for developing various types of


applications, such as Windows-based applications and Web-
based applications
– To ensure that code based on the .NET Framework can
integrate with any other code
.NET Framework
• The .NET Framework consists of:

– The Common Language Specification (CLS)


It contains guidelines, that language should follow so that they
can communicate with other .NET languages. It is also
responsible for Type matching.
– The Framework Base Class Libraries (BCL)

A consistent, object-oriented library of prepackaged


functionality and Applications.
– The Common Language Runtime (CLR)

A language-neutral development & execution environment


that provides common runtime for application execution .
– ActiveX Data Objects:
ADO.NET is a set of classes (a framework) to interact with
data sources such as databases and XML files
Common Language Specification

CLS performs the following functions:


• Establishes a framework that helps enable cross-language
integration, type safety, and high performance code
execution
• Provides an object-oriented model that supports the
complete implementation of many programming
languages
• Defines rules that languages must follow, which helps
ensure that objects written in different languages can
interact with each other
.NET Framework Base Class Library

• The Class Library is a comprehensive, object-oriented collection


of reusable types
• These class library can be used to develop applications
that include:
– Traditional command-line applications
– Graphical user interface (GUI) applications
– Applications based on the latest innovations provided by ASP.NET
• Web Forms
• XML Web services
Common Language Runtime (CLR)

• CLR ensures:
– A common runtime environment for all .NET languages
– Uses Common Type System (strict-type & code-verification)
– Memory allocation and garbage collection
– Intermediate Language (IL) to native code compiler.
Which Compiles MSIL code into native executable code
– Security and interoperability of the code with
other languages
• Over 36 languages supported today
– C#, VB, Jscript, Visual C++ from Microsoft
– Perl, Python, Smalltalk, Cobol, Haskell, Mercury, Eiffel, Oberon, Oz, Pascal, APL,
CAML, Scheme, etc.
Execution in CLR

Compiler Compiler
Compiler
Managed code Assembly IL Code

Common Language Runtime


JIT Compiler
Visual Studio 2008 IDE

Microsoft has introduced Visual Studio.NET,


which is a tool (also called Integrated Development
Environment) for developing .NET applications by
using programming languages such as VB, C#,
VC++ and VJ#. etc.
C# (C Sharp)

• Microsoft C# (pronounced C Sharp) developed by


Microsoft Corporation, USA

• New programming language that runs on the .NET Framework

• C# is simple, modern, type safe, and object oriented


• C# code is compiled as managed code

• Combines the best features of Visual Basic, C++ and Java


C# Features

• Simple
• Modern
• Object-Oriented
• Type-safe
• Versionable
• Compatible
• Secure
Core c#

• C# is a strongly typed object-oriented


programming language. C# is open source,
simple, modern, flexible, and versatile. In
this article, let’s learn what C# is, what C#
can do, and how C# is different than C++ and
other programming languages.
• A programming language on computer science
is a language that is used to write software
programs.
• C# is a programming language developed and
launched by Microsoft in 2001. C# is a simple,
modern, and object-oriented language that
provides modern day developers flexibility
and features to build software that will not
only work today but will be applicable for
years in the future.
Key characteristics of C# language

include:

• Modern and easy


• Fast and open source
• Cross platform
• Safe
• Versatile
• Evolving
• .NET Core is the latest general purpose
development platform maintained by
Microsoft. It works across different platforms
and has been redesigned in a way that makes
.NET fast, flexible and modern. .NET Core
happens to be one of the major
contributions by Microsoft. Developers can
now build Android, iOS, Linux, Mac, and
Windows applications with .NET, all in Open
Source.
First C# Program

using System;
namespace Wrox
{

public class MyFirstClass


{
static void Main()
{
Console.WriteLine("Hello from Wrox.");
Console.ReadLine();
return; } } }
Compiling and Running the

Program

• You can compile this program by simply running the


C# command-line compiler (csc.exe) against the
source file, like this: csc First.cs

• If you want to compile code from the command


line using the csc command, you should be aware
that the .NET command-line tools, including csc,
are available only if certain environment variables
have been set up. Depending on how you installed
.NET (and Visual Studio), this may or may not be
the case on your machine
Variables

• You declare variables in C# using the following


syntax: datatype identifier;
• For example: int i;
• This statement declares an int named i.
• You can also declare the variable and initialize its value at
the same time: int i = 10;
• If you declare and initialize more than one variable in a
single statement, all the variables will be of the same data
type:
• int x = 10, y =20; // x and y are both ints
• To declare variables of different types, you
need to use separate statements. You cannot
assign different data types within a multiple-
variable declaration:
• int x = 10; bool y = true; // Creates a variable
that stores true or false
• int x = 10, bool y = true; // This won't
compile!
1. Value types

2. Reference types
• Variables of value types directly contain their data
whereas variables of reference types store
references to their data, the latter being known as
objects. With reference types, it's possible for two
variables to reference the same object and thus
possible for operations on one variable to affect the
object referenced by the other variable. With value
types, the variables each have their own copy of the
data, and it isn't possible for operations on one to
affect the other (except for ref and out parameter
variables).
• Types and variables.docx
Flow Control

• The statements that allow you to control the


flow of your program.
• Conditional Statements:
Conditional statements allow you to
branch your code depending on whether certain
conditions are met or the value of an
expression.
C# has two constructs for branching code:

the if statement, which allows you to test


whether a specific condition is met; and the
switch statement, which allows you to compare
an expression with several different values
The if Statement

For conditional branching, C# inherits the C and


C++ if.else construct. The syntax should be fairly
intuitive for anyone who has done any
programming with a procedural language:
if (condition)
statement(s)
else

statement(s)
• If more than one statement is to be executed
as part of either condition, these statements
need to be joined together into a block using
curly braces ({.}). (This also applies to other C#
constructs where statements can be joined
into a block, such as the for and while loops):
bool
isZero; if (i
== 0)
{

isZero = true;
Console.WriteLine("i is
Zero");
}
else
{
isZero = false; C
onsole.WriteLine("i is
Non-zero");
}
using System;

namespace Wrox
{
class MainEntryPoint {
static void Main(string[] args)
{
Console.WriteLine("Type in a string");
string input; input = Console.ReadLine();
if (input == "")
{

Console.WriteLine("You typed in an empty string.");


}
else if (input.Length < 5)
{
Console.WriteLine("The string had less than 5 characters.");
}
else if (input.Length < 10)
{ Console.WriteLine("The string had at least 5 but less than 10 Characters."); }
Console.WriteLine("The string was " + input); } }
The switch Statement

switch (integerA)

{
case 1: Console.WriteLine("integerA
=1"); break;
case 2: Console.WriteLine("integerA
=2"); break;
case 3: Console.WriteLine("integerA
=3"); break;
default:

Console.WriteLine("integerA is not 1,2, or 3");


break;
}
Loops

• C# provides four different loops (for, while,

do. . .while, and foreach) that enable you to execute a


block of code repeatedly until a certain condition is
met.
The for Loop C# for loops provide a mechanism for
iterating through a loop whereby you test whether
a particular condition holds true before you perform
another iteration.
The syntax is
for (initializer; condition;
iterator): statement(s)
• The while Loop
Like the for loop, while is a pretest loop.
The syntax is similar, but while loops take only
one expression:
while(condition)
statement(s);
Unlike the for loop, the while loop is most often used to
repeat a statement or a block of statements for a
number of times that is not known before the loop
begins.
Usually, a statement inside the while loop’s body

will set a Boolean flag to false on a certain


iteration, triggering the end of the loop, as
in the following example:
bool condition =
false; while
(!condition)
{
// This loop spins until the condition is true.
DoSomeWork();
condition = CheckCondition(); // assume
CheckCondition() returns a bool
}
• The do...while loop is the post-test version of
the while loop. This means that the loop’s test
condition is evaluated after the body of the
loop has been executed. Consequently,
do...while loops are useful for situations in
which a block of statements must be
executed at least one time, as in this example:
bool condition;

Do
{
// This loop will at least execute once, even if
Condition is false.
MustBeCalledAtLeastOnce(); condition =
CheckCondition();
}
while (condition);
The foreach Loop

The foreach loop enables you to iterate through each


item in a collection.
foreach (int temp in arrayOfInts)
{
Console.WriteLine(temp);
}
Here, foreach steps through the array one
element at a time. With each element, it places the
value of the element in the int variable called temp
and then performs an iteration of the loop.
www.rejinpaul.com
Generics

• Generic is a class which allows the user


to define classes and methods with the
placeholder.
• Generics were added to version 2.0 of
the C# language.
• The basic idea behind using Generic is to allow
type (Integer, String, … etc and user-defined
types) to be a parameter to methods, classes,
and interfaces.
Use of generics in C#:

• Use generic types to maximize code reuse,


type safety, and performance. The most
common use of generics is to create
collection classes. The . NET class library
contains
several generic collection classes in
the System
Why do we need generics in C#?

Let us understand the need for Generics in C#


with one example. Let us create a simple
program to check whether two integer numbers
are equal or not.
{
public class ClsMain
{
private static void Main()
{
bool IsEqual = ClsCalculator.AreEqual(10, 20);
if (IsEqual){
Console.WriteLine("Both are
Equal");} else
{

Console.WriteLine("Both are Not


Equal");} Console.ReadKey();}}
public class ClsCalculator

{
public static bool AreEqual(int value1, int

value2)
{
return value1 == value2;
}
}
}
• The above code implementation is very straight forward.
Here we created two classes with the
name ClsCalculator and ClsMain. Within

the ClsCalculator class, we have AreEqual() method which


takes two integer values as the input parameter and then it
checks whether the two input values are equal or not.

• If both are equal then it returns true else it will return false.
• The above AreEqual() method works as expected as it is
and more importantly it will only work with the integer
values as this is our initial requirement.
• Suppose our requirement changes, now we also need
to check whether two string values are equal or not.
• Here in the above example, in order to make

the AreEqual() method generic (generic means the same


method will work with the different data type), we specified
the type parameter T using the angular brackets <T>. Then we
use that type as the data type for the method parameters as
shown in the below image
In C#, the Generics can be applied to the

following:

• Interface
• Abstract class
• Class
• Method
• Static method
• Property
• Event
• Delegates
• Operator
Advantages of Generics in C#

• It Increases the reusability of the code.


• The Generics are type-safe. We will get the
compile-time error if we try to use a
different type of data rather then the one we
specified in the definition.
• We get better performance with Generics as it
removes the possibilities of boxing and
unboxing.
• More reference:

https://dotnettutorials.net/lesson/generics-

csharp/
what is boxing and unboxing in c#

• Boxing is the process of converting a value


type to the type object or to any interface
type implemented by this value type.
• Unboxing extracts the value type from the
object. Boxing is implicit; unboxing is explicit.
boxing and unboxing with example

• An int value can be converted into object and


back again into int. This example shows
both, boxing and unboxing.
• When a variable of a value type needs to be
converted into a reference type, an object
box is allocated to hold the value, and the
value is copied into the box. Unboxing is just
the opposite
The use of boxing and unboxing in

C#

• With Boxing and unboxing one can link


between value-types and reference-types by
allowing any value of a value-type to be
converted to and from type object. Boxing
and unboxing enables a unified view of the
type system wherein a value of any type can
ultimately be treated as an object
• Arrays are used to store multiple values in a
single variable, instead of declaring separate
variables for each value.
• To declare an array, define the variable type
with square brackets:
• string[] cars;
• For example,
• double[] balance;
www.rejinpaul.com
Tuple
Operators and Casts

• An operator is a symbol that tells the compiler to


perform specific mathematical or logical
manipulations. C# has rich set of built-in operators
and provides the following type of operators −

• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
• Operators are used to perform operations on
variables and values.Example int x = 100 + 50;
www.rejinpaul.com
www.rejinpaul.com
Operator Precedence in C#

• Operator precedence determines the grouping of terms in


an expression. This affects evaluation of an expression.
Certain operators have higher precedence than others; for
example, the multiplication operator has higher precedence
than the addition operator.
• For example x = 7 + 3 * 2; here, x is assigned 13, not 20
because operator * has higher precedence than +, so the
first evaluation takes place for 3*2 and then 7 is added into
it.
• Here, operators with the highest precedence appear at the
top of the table, those with the lowest appear at the
bottom. Within an expression, higher precedence operators
are evaluated first.
C# Type Casting

• Type casting is when you assign a value of one data type


to another type.
• In C#, there are two types of casting:
• Implicit Casting (automatically) - converting a smaller type
to a larger type size
char -> int -> long -> float -> double
• Explicit Casting (manually) - converting a larger type to
a smaller size type
double -> float -> long -> int -> char
Implicit Casting

• Implicit casting is done automatically when passing


a smaller size type to a larger size type:
Explicit Casting

• Explicit casting must be done manually by placing


the type in parentheses in front of the value:
Type Conversion Methods

• It is also possible to convert data types


explicitly by using built-in methods, such as
• Convert.ToBoolean
• Convert.ToDouble,
• Convert.ToString,
• Convert.ToInt32 (int)
• Convert.ToInt64 (long):
www.rejinpaul.com
• C# indexer is a class property that allows you to
access a member variable of a class or struct using
the features of an array. ... Defining an indexer allows
you to create a class like that can allows its items to
be accessed an array (or)

• An indexer allows an object to be indexed such as an


array. When you define an indexer for a class, this
class behaves similar to a virtual array. You can then
access the instance of this class using the array
access operator ([ ]).
Use of indexers in C#

• Indexers are a syntactic convenience that


enable you to create a class, struct, or
interface that client applications can access
just as an array. Indexers are most frequently
implemented in types whose primary
purpose is to encapsulate an internal
collection or array
www.rejinpaul.com
C# program to illustrate the Indexer
UNIT I
C# LANGUAGE
BASICS

.Net Architecture - Core C# - Variables - Data Types - Flow control -


Objects and Types- Classes and Structs - Inheritance- Generics – Arrays
and Tuples - Operators and Casts – Indexers.

Introduction to C#
C# is a general-purpose, modern and object-oriented programming
language pronounced as “See sharp”. It was developed by Microsoft led
by Anders Hejlsberg and his team within the .Net initiative and was
approved by the European Computer Manufacturers Association (ECMA)
and International Standards Organization (ISO).

C# is among the languages for Common Language Infrastructure and the


current version of C# is version 7.2. C# is a lot similar to Java syntactically
and is easy for the users who have knowledge of C, C++ or Java

A bit about .Net Framework


.Net applications are multi-platform applications and framework can be
used from languages like C++, C#, Visual Basic, COBOL etc. It is
designed in a manner so that other languages can use it.

Why C#?
C# has many other reasons for being popular and in demand. Few of
the reasons are mentioned below:
1. Easy to start: C# is a high-level language so it is closer to other
popular programming languages like C, C++, and Java and thus
becomes easy to learn for anyone.

2. Widely used for developing Desktop and Web Application: C# is


widely used for developing web applications and Desktop
applications. It is one of the most popular languages that is used in
professional desktop. If anyone wants to create Microsoft apps, C# is
their first choice.

3. Community:The larger the community the better it is as new tools


and software will be developing to make it better. C# has a large
community so the developments are done to make it exist in the
system and not become extinct.

CS8073 C# AND .NET PROGRAMMING Page 1


4. Game Development: C# is widely used in game development and
will continue to dominate. C# integrates with Microsoft and thus has a
large target audience. The C# features such as Automatic Garbage
Collection, interfaces, object- oriented, etc. make C# a popular game
developing language.

There are various online IDEs such as GeeksforGeeks ide, CodeChef ide
etc. which can be used to run C# programs without installing.

Windows: Since the C# is developed within .Net framework initiative by


Microsoft, it provide various IDEs to run C# programs: Microsoft Visual
Studio, Visual Studio Express, Visual Web Developer

Linux: Mono can be used to run C# programs on Linux.

Programming in C#:
Since the C# is a lot similar to other widely used languages syntactically,
it is easier to code and learn in C#.
Programs can be written in C# in any of the widely used text editors like
Notepad++, gedit, etc. or on any of the compilers. After writing the
program save the file with the extension .cs

Example: A simple program to print Welcome IV cse A & B

// C# program to print Welcome


IV cse A & B using System;
namespace Hello
{
class Demo
{
// Main function
static void Main(string[] args)
{

// Printing Welcome IV cse A & B


Console.WriteLine("Welcome IV cse A & B ");

Console.ReadKey();
}
}
}

CS8073 C# AND .NET PROGRAMMING Page 2


Output:
Welcome IV cse A & B

Explanation:

1. Comments: Comments are used for explaining code and are used
in similar manner as in Java or C or C++. Compilers ignore the comment
entries and does not execute them. Comments can be of single line or
multiple lines.
Single line Comments:
Syntax:
// Single line comment

Multi line comments:


Syntax:
/* Multi line comments*/

2. using System: using keyword is used to include the System


namespace in the program.
namespace declaration: A namespace is a collection of
classes. The HelloGeeksApp namespace contains the class
HelloGeeks.
3. class: The class contains the data and methods to be used in
the program. Methods define the behavior of the class. Class
HelloGeeks has only one method Main similar to JAVA.
4. static void Main(): static keyword tells us that this method is
accessible without instantiating the class. 5. void keywords tells that this
method will not return anything. Main() method is the entry-point of our
application. In our program, Main()
method specifies its behavior with the statement Console.WriteLine(“Hello
Geeks”); .
6. Console.WriteLine(): WriteLine() is a method of the Console
class defined in the System namespace.
7. Console.ReadKey(): This is for the VS.NET Users. This makes
the program wait for a key press and prevents the screen from running
and closing quickly.
Note: C# is case sensitive and all statements and expressions
must end with semicolon (;).
Advantages of C#:
● C# is very efficient in managing the system. All the garbage is
automatically collected in C#.
● There is no problem of memory leak in C# because of its high memory
backup.
● Cost of maintenance is less and is safer to run as
compared to other languages.
● C# code is compiled to a intermediate language (Common (.Net)
Intermediate Language) which is a standard language,
independently irrespective of the target operating system and
architecture.

CS8073 C# AND .NET PROGRAMMING Page 3


Disadvantages of C#:
● C# is less flexible as it depends alot on .Net framework.
● C# runs slowly and program needs to be compiled each
time when any changes are made.

Applications:
● C# is widely used for developing desktop applications, web
applications and web services.
● It is used in creating applications of Microsoft at a large scale.
● C# is also used in game development in Unity (game engine).

NET architecture is the programming model for the . NET platform.


... NET Framework provides a managed execution environment,
simplified development and deployment and integration with a wide
variety of programming languages.

What is C# used for?


C# can be used to create almost anything but is particularly strong at
building Windows desktop applications and games. C# can also be
used to develop web applications and has become increasingly
popular for mobile development too
CS8073 C# AND .NET PROGRAMMING Page 4
UNIT- II

C# ADVANCED FEATURES
Delegates - Lambdas - Lambda Expressions -
Events - Event Publisher - Event
Listener - Strings and Regular Expressions -
Generics - Collections - Memory
Management and Pointers - Errors and
Exceptions - Reflection
Delegates
www.rejinpaul.com
www.rejinpaul.com
www.rejinpaul.com
www.rejinpaul.com
Lambdas

Lambda Expressions
Events

Event Publisher
www.rejinpaul.com
Event Listener

• An event listener represents the target for


all events generated by event source
(EventSource object) implementations in the
current application domain. When a
new event listener is created, it is logically
attached to all event sources in that
application domain. This type implements the
IDisposable interface.
Strings and Regular Expressions

• Regular expressions are a pattern matching


standard for string parsing and replacement
and is a way for a computer user to express
how a computer program should look for a
specified pattern in text and then what the
program is to do when each pattern match is
found.
www.rejinpaul.com
www.rejinpaul.com
www.rejinpaul.com
• When the above code is compiled and
executed, it produces the following result

Matching words that start with 'S':


The Expression: \bS\S*
Splendid
Suns
Generics - Collections
www.rejinpaul.com
www.rejinpaul.com

Memory
Management and Pointers
www.rejinpaul.com
• The following figure shows the managed heap
after a collection.
• The following code demonstrates how
resources are allocated and managed:
• class Application

public static int Main(String[] args)

// ArrayList object created in heap, myArray is


now in root
ArrayList myArray = new ArrayList();

// Create 10000 objects in the


heap for (int x = 0; x < 10000; x++)
{

myArray.Add(new Object()); // Object object


created in heap
}
Errors and Exceptions

• An exception is an unwanted or unexpected


event, which occurs during the execution of a
program i.e at runtime, that disrupts the normal
flow of the program’s instructions. Sometimes
during the execution of the program, the user
may face the possibility that the program may
crash or show an unexpected event during its
runtime execution. This unwanted event is
known as Exception and it generally gives the
indication regarding something wrong within the
code.
www.rejinpaul.com
• Errors:

• Errors are unexpected issues that may


arise during computer program execution.
• Errors cannot be handled.
• All Errors are exceptions.
• Exceptions:
• Exceptions are unexpected events that may
arise during run-time.
• Exceptions can be handled using try-catch
mechanisms.
• All exceptions are not errors.
Exception Hierarchy
• Different Exception Classes: There are different

kinds

of exceptions which can be generated in C# program:

• Divide By Zero exception: It occurs when the


user attempts to divide by zero
• Out of Memory exceptions: It occurs when then
the program tries to use excessive memory
• Index out of bound Exception: Accessing the
array element or index which is not present in it.
• Stackoverflow Exception: Mainly caused due to
infinite recursion process
• Null Reference Exception : Occurs when the user
attempts to reference an object which is of NULL
type.
• …..and many more.
many properties which help the user to get information
about the exception during the exception.
• Data: This property helps to get the information about the
arbitrary data which is held by the property in the key-value
pairs.
• TargetSite: This property helps to get the name of the
method where the exception will throw.
• Message: This property helps to provide the details about
the main cause of the exception occurrence.
• HelpLink: This property helps to hold the URL for
a particular exception.
• StackTrace: This property helps to provide the information
about where the error occurred.
• InnerException: This property helps to provide the
information about the series of exceptions that might have
occurred.
• Reflection provides objects (of type Type) that
describe assemblies, modules, and types. You
can use reflection to dynamically create an
instance of a type, bind the type to an existing
object, or get the type from an existing object
and invoke its methods or access its fields and
properties.
What is Reflection in C#?

• Reflection is the process of describing the


metadata of types, methods and fields in a
code. The
namespace System.Reflection enables you to
obtain data about the loaded assemblies, the
elements within them like classes, methods
and value types. Some of the commonly used
classes of System.Reflection are:
CLASS DESCRIPTION

describes an assembly which is a reusable, versionable, and self-describing


Assembly
building block of a common language runtime application

AssemblyName Identifies an assembly ith a unique name

ConstructorInfo Describes a class constructor and gives access to the metadata

MethodInfo Describes the class method and gives access to its metadata

ParameterInfo Describes the parameters of a method and gives access to its metadata

EventInfo Describes the event info and gives accessto its metadata

PropertyInfo Discovers the attributes of a property and provides access to property metadata
Obtains information about the attributes of a member and provides access to
MemberInfo
member metadata
• Note: There are numerous other classes, the

above table gives info about only the


commonly used.
• Let us now look at an example to depict how
reflection works in C#.

• Example 1: In the code given below, we load


the type t as a string using the typeof method.
Then we apply reflection on t to find any
information about string class, like its name,
fullname, namespace, and basetype.
// the use of Reflection
using System;
using System.Reflection;

namespace Reflection_Demo {

class Program {

// Main Method

static void Main(string[] args)


{
// Initialise t as typeof
string Type t =
typeof(string);

// Use Reflection to find about


// any sort of data related to t
Console.WriteLine("Name : {0}", t.Name);
Console.WriteLine("Full Name : {0}", t.FullName);
Console.WriteLine("Namespace : {0}",
t.Namespace); Console.WriteLine("Base Type : {0}",
t.BaseType);
} }}
Output:

Name : String
Full Name : System.String
Namespace : System
Base Type : System.Object
UNIT III

BASE CLASS LIBRARIES AND DATA


MANIPULATION
Diagnostics -Tasks, Threads and Synchronization
- .Net Security - Localization - Manipulating
XML- SAX and DOM - Manipulating files and the
Registry- Transactions -ADO.NET- Peer-to-Peer
Networking - PNRP - Building P2P Applications -
Windows Presentation Foundation (WPF).

3
Diagnostics.

• The System. Diagnostics namespace provides

classes that allow you to interact with system


processes, event logs, and performance counters.
• The EventLog component provides functionality to
write to event logs, read event log entries, and
create and delete event logs and event sources on
the network.
• A system diagnostic is a computer utility which is
used to test a computer system for the purpose of
identifying weak points, determining the cause of a
problem, or assisting with setup.
www.rejinpaul.com
Example

• [System.Diagnostics.DebuggerDisplay("{ID} - {Mod
el}- {Manufacturer} - {ProductionDate}")]
• public class Car
• {
• public int ID { get; set; }
• public string Model { get; set; }
• public string Manufacturer { get; set; }
• public DateTime ProductionDate { get; set; }
• }
Tasks, Threads and Synchronization
Why need Tasks

It can be used whenever you want to execute


something in parallel. Asynchronous
implementation is easy in a task, using’ async’
and ‘await’ keywords.
How to create a Task

static void Main(string[] args) {


Task < string > obTask = Task.Run(() => (
return“ Hello”));
Console.WriteLine(obTask.result);
}
Thread
Why need a Thread

When the time comes when the application is


required to perform few tasks at the same time.
How to create a Thread
static void Main(string[] args) {
Thread thread = new Thread(new ThreadStart
(getMyName));
thread.Start();
}
public void getMyName() {}
Differences Between Task And Thread

1. Here are some differences between a task and a thread.

The Thread class is used for creating and manipulating a thread in


Windows. A Task represents some asynchronous operation and is part of
the Task Parallel Library, a set of APIs for running tasks asynchronously
and in parallel.
2. The task can return a result. There is no direct mechanism to return the
result from a thread.
3. Task supports cancellation through the use of cancellation tokens. But
Thread doesn't.
4. A task can have multiple processes happening at the same time. Threads
can only have one task running at a time.
5. We can easily implement Asynchronous using ’async’ and ‘await’
keywords.
6. A new Thread()is not dealing with Thread pool thread,
whereas Task does use thread pool thread.
7. A Task is a higher level concept than Thread.
www.rejinpaul.com
Sleep

It pauses the execution of a program for a


defined time. It does not utilize CPU during the
pause time. It is useful for waiting on an external
Task.

Eg: Thread.Sleep(300)
Join

It is also a part of blocking mechanism in the


thread synchronization. It is similar to Sleep but
it does not pauses all threads. It pauses the
calling thread until the thread whose join
method is called has completed.
Example
Output:

Thread2 Executed.
Thread1 Executed.
After Thread1
After Thread2
www.rejinpaul.com
Output:

Total: 50028434
Count: 1000000
Locking

Locking is also a synchronization mechanism. It limits the


access to a resource in multiple thread. Exclusive locking
mechanism is used for it.

The following are the two main Locking mechanism:

• Lock
• Mutex

Lock

It locks the critical section of code so that only one


thread can execute the critical section of code at a time.
If another thread tries to enter into critical section of
code then it is prevented and blocked and then it will
wait until the object is released from the using thread.
www.rejinpaul.com
Output:

Total Balance 45000

Note: Avoid lock on a public type, or instances


beyond the control of code.

Mutex
Mutex stands for Mutual Exclusion. The Mutex type
ensures blocks of code are executed only once at a
time. It is basically used in a situation where
resources has to be shared by multiple threads
simultaneously.
.Net Security

• The common language runtime and the

. NET provide many useful classes and services


that enable developers to easily
write secure code and enable system
administrators to customize the permissions
granted to code so that it can access
protected resources
What is localization?

• In general, localization is the process in which


we adapt our applications to a specific region or
market place.

• The goal of localization is to provide a tailored


experience that intends to give users the most
comfortable experience possible.
• Localization not only focuses on text but may
also include graphics, layout, currency,
date/phone/address formats, and local
regulations and legal requirements.
Localization

• Localization is the process of customizing your


application for a given culture and locale. The
language needs to be associated with the particular
region where it is spoken, and this is done by using
locale (language + location). For example: fr is the
code for French language
Difference between localization and globalization in c#
• the globalization and localization concepts

in C#. Globalization is the process of designing and


developing applications that function for multiple
cultures. Localization is the process of customizing
your application for a given culture and locale
localization and globalization in C#

• Globalization is the process of designing the


application in such a way that it can be used
by users from across the globe (multiple
cultures).
• Localization, on the other hand, is the process
of customization to make our application
behave as per the current culture and locale.
These two things go together
• Formatting of numbers and dates
• ➤➤ Using resources for localized content
• ➤➤ Creating and using satellite assemblies
• ➤➤ Localizing Desktop Applications
• ➤➤ Localizing Web Applications
• ➤➤ Localizing Windows Store apps
• ➤➤ Creating custom resource readers
• ➤➤ Creating custom cultures
• The code for this chapter is divided into the
following major examples:
• ➤➤ NumberAndDateFormatting
• ➤➤ CreateResource
• ➤➤ CultureDemo
• ➤➤ BookOfTheDay
• ➤➤ DatabaseResourceReader
• ➤➤ CustomCultures
The globalization and localization of

.NET applications

• Globalization is about internationalizing applications:

preparing applications for international markets. With


globalization, the application supports number and date formats
that vary according to culture, calendars, and so on.
• Localization is about translating applications for specific cultures.
For translations of strings, you can use resources such as .NET
resources or WPF ( Windows Presentation Foundation)resource
dictionaries.

• .NET supports the globalization and localization of Windows and


web applications. To globalize an application, you can use
classes from the namespace System.Globalization; to localize an
application, you can
use resources supported by the namespace System.Resources.
The System.Resources Namespace

• System.Resources namespace that deal with


resources:

• ResourceManager — Can be used to get resources for


the current culture from assemblies or resource files.
Using the ResourceManager, you can also get a
ResourceSet for a particular culture.

• ResourceSet — Represents the resources for a


particular culture. When a ResourceSet instance is
created, it enumerates over a class, implementing the
interface IResourceReader, and it stores allresources
in a Hashtable.
• IResourceReader — This interface is used from the
ResourceSet to enumerate resources. The class
ResourceReader implements this interface.
• ResourceWriter — This class is used to create a resource file.
ResourceWriter implements the interface.
• ResXResourceSet, ResXResourceReader, and
ResXResourceWriter — These are similar to ResourceSet,
ResourceReader, and ResourceWriter, but they are used to
create an XML-based resource file, .resX, instead of a binary
file. You can use ResXFileRef to make a link to a resource
instead of embedding it inside an XML file.
• System.Resources.Tools — This namespace contains the class
StronglyTypedResourceBuilder to create a class from a
resource.
GetObject uses the CurrentUICulture property of the

current thread to find the correct

localization of the resources.


The following table shows the changes needed for the
German version:
• German Name Value
• $this.Text (title of the form) Buch des Tages
• labelItemsSold.Text Bücher verkauft:
• labelBookOfTheDay.Text Buch des Tages:
The next table shows the changes for the French version:
• French Name Value
• $this.Text (title of the form) Le livre du jour
• labelItemsSold.Text Des livres vendus:
• labelBookOfTheDay.Text Le livre du jour:
Hello World Of Localization

• We’ll start by creating a console application,


either via the command line or our favourite
IDE. In this , I’ll be using JetBrains Rider,
• dotnet new console -o wt && take wt
• The next step is we’ll be creating some resx
files file the following cultures: English, French,
and Spanish.
• Language.resx Language.es.resx
Language.fr.resx
• All three resx files will have a companion
file of *.
• Designer.cs which will include our
generated access mechanisms for our
resources.
• Only our top-level Language.resx file
will have any code associated with it.
• Before continuing, we need to mark
each resx file as an embedded resource.
The Resx XML

• To understand how resources are stored, let us peek into the XML
file. In our case, let us look at our first resource of HelloWorld.
The Generated Access

Class
• Resx files also generate access classes so that
we can more naturally access our resources.
• In our case, we have a Language class created
using the filename of our parent resx file.
• The sub topics:
• 1. Resource manager
• 2.Culture
• 3. ResourceProperties
ResourceManawgwewr.rejinpaul.c
om

• The ResourceManager is the manager of our resources,


reading our XML files into memory, and storing our values.
www.rejinpaul.com
Culture

• The Culture property allows us to set the CultureInfo of our Language class.
• As we’ll see later in the post, we can affect what resources we access
by changing this property.
Resource
w w w. rejinpaul.com
Proper t ie s
• The resource generator will be helpful and
generate named properties for each of our resource
values.
• In this post, we can see a created string property
for HelloWorld and Woot.
Putting Our Resx
w w w .re ji npaul.com
Fi l e s T o
Work
Conclusion:

• Localization may seem scary at first, but the .NET


Framework has thought about and solved this issue
for a long time now.
• There are definite advantages to localizing our
applications from a broader userbase and a more
efficient codebase.
• Using resx files is one of the better options as it allows
us to store more than strings.
Manipulating XML

XML stands for Extensible Markup Language file format, which


is used to create common information formats and share both
the format and the data on the World Wide Web, intranet, etc.

1. It has the advantages given below.

2. Human and machine-readable format.

3. It is platform independent.
4. Its self-documenting format describes the structure and
field names as well as specific values.
5. XML is heavily used to store the data and share the data.

6. XML data is stored in text format. This makes it easier to expand


or upgrade to new operating systems, new applications, or new
browsers, without losing data.
7. It strictly follows closing node, case-sensitive and node name.
Refer:
https://www.c-sharpcorner.com/article/xml-manipulation-in-c-sharp
/
We will use mostly XDocument and

XMLDocument class to manipulate XML


data. The following is the LINQ to
XML(XDocument) class hierarchy, which will
help to understand it more.
SAX and DOM

• SAX is a parser that parses

serialized DOM structures. ... The document


object model (DOM) is an abstract data model
that describes a hierarchical, tree-based
document structure; a document tree consists
of nodes, namely element, attribute and text
nodes (and some others
XML Parsers

• An XML parser is a software library or package


that provides interfaces for client applications
to work with an XML document. The XML
Parser is designed to read the XML and create
a way for programs to use XML.
• XML parser validates the document and check
that the document is well formatted.
Dom and sax in c# xml

• DOM stands for Document Object Model while SAX stands


for Simple API for XML parsing. DOM parser load full XML file
in memory and creates a tree representation of XML
document, while SAX is an event based XML parser and
doesn't load whole XML document into memory.

• In SAX, events are triggered when the XML is being parsed.

In DOM, there are no events triggered while parsing. The

entire XML is parsed and a DOM tree (of the nodes in the XML) is
generated and returned.
• DOM Stands for Document Object Model and it
represent an XML Document into tree format which each
element
representing tree branches. dom package while DOM Parser for
Java is in JAXP (Java API for XML Parsing) package. SAX XML Parser
in Java. SAX Stands for Simple API for XML Parsing.
Let's understand the working of XML

parser by the figure given below:


Simple API for XML

• SAX (Simple API for XML) is an event-driven online

algorithm for parsing XML documents, with an API developed by the


XML-DEV mailing list XML-DEV

• (serves as an open, publicly archived, unmoderated list

supporting XML implementation and development. XML-DEV emphasizes


active participation through code development, creation of protocols and
specifications, and other material contributions such as reference
resources).

• SAX provides a mechanism for reading data from an XML document that is
an alternative to that provided by the Document Object Model (DOM).

• Where the DOM operates on the document as a whole—building


the full abstract syntax tree of an XML document for convenience of
the user—SAX parsers operate on each piece of the XML document
sequentially, issuing parsing events while making a single pass through the
input stream.
Definition

• Unlike DOM, there is no formal specification


for SAX. The Java implementation of SAX is
considered to be normative.SAX processes
documents state-independently, in contrast to
DOM which is used for state-dependent
processing of XML documents.
• XML processing with SAX.
• A parser that implements SAX (i.e., a SAX Parser)
functions as a stream parser, with
an event-driven API.The user defines a number
of callback methods that will be called when
events occur during parsing.
• The SAX events include (among others):
• XML Text nodes
• XML Element Starts and Ends
• XML Processing Instructions
• XML Comments
• Given the following XML document:
• <?xml version="1.0" encoding="UTF-8"?>

<DocumentElement param="value">

<FirstElement> &#xb6; Some Text

• </FirstElement>
• <?some_pi some_attr="some_value"?>
• <SecondElement param2="something"> Pre-Text
• <Inline>Inlined text</Inline> Post-text.

</SecondElement>

• </DocumentElement>
generate a sequence of events like the following :

• XML Element start, named DocumentElement, with an attribute param equal to


"value"
• XML Element start, named FirstElement

• XML Text node, with data equal to "&#xb6; Some Text" (note: certain white spaces
can be changed)
• XML Element end, named FirstElement

• Processing Instruction event, with the target some_pi and


data some_attr="some_value" (the content after the target is just text; however, it is
very common to imitate the syntax of XML attributes, as in this example)
• XML Element start, named SecondElement, with an attribute param2 equal to
"something"
• XML Text node, with data equal to "Pre-Text"
• XML Element start, named Inline

• XML Text node, with data equal to "Inlined text"

• XML Element end, named Inline

• XML Text node, with data equal to "Post-text."

• XML Element end, named SecondElement

• XML Element end, named DocumentElement


Reading And Writing XML Documents In .NET

Introduction
XML provides platform independent, self-descriptive and very flexible
way to represent your data. .NET has harnessed the capabilities of XML
in variety of ways. In addition to providing W3C compatible classes
.NET also provides additional classes which make XML document
manipulation easy.
XML Parsers
To access the content of an XML document you need to parse the
document and reach to the specific parts of it. The software which
allows you to do that is called as XML parser.
The parsers are of two types:
■ DOM parsers : These parsers built a tree of XML document in
memory and allow navigation to various nodes and attributes.
■ SAX parsers : These parsers process XML document in sequential
fashion. They have low memory footprint than DOM parsers.
In MSXML Ver.3, (Microsoft XML Core Services (MSXML) are set of
services that allow applications written in JScript, VBScript, and
Microsoft development tools to build Windows-native XML-based
applications). Microsoft has provided both of the parsers for our use.
In .NET we have DOM parser matching closely with existing MSXML
parser. The SAX parser has undergone some variation but provides
similar functionality.
The pre-.NET parser i.e. MSXML provided classes and interfaces closely
matching W3C recommendations. .NET also follows the same tradition
but adds many easy to use and flexible ways to manipulate XML
documents.
XML and .NET

XML related classes are available in System.XML namespace. In this article we will primarily discuss
about .NET specific classes for reading and writing XML documents.

To read XML documents System.XML provides a class called XmlTextReader. This class is derived from
XmlReader and provides easy access to various parts of XML document. This class can be thought as
forward-only and read only cursor.

To write XML documents System.XML provides a class called XmlTextWriter. This class is derived from
XmlWriter and allows quick writing of XML documents.

The methods provided by these classes are very easy to use and self explaining as compared to W3C
DOM . This is mainly because these classes allow various methods to be called directly on themselves.
They provide 'current node' for you to manipulate as opposed to W3C DOM classes where you have to
track individual nodes. These classes do not require some thing like
mydoc.ChildNodes(0).ChildNodes(1). to access various attributes or content of the node.
Using XmlTextReader Class

Now, we will see how to use XmlTextReader class.

■ First import the System.XML namespace. If you are using Visual Studio.NET then Add
Reference to System.Xml.dll

e.g. In VB.NET

Imports System.Xml
■ Create instance of XmlTextReader class and load the XML document.

e.g. In VB.NET

dim reader as XmlTextReader


reader = new XmlTextReader
("c:\xml\books.xml")
■ Start reading the XML document

e.g. In VB.NET

do while (reader.Read())
'do some action here
loop
The Read() method returns true if the node is successfully read else returns false. If node is successfully
read, you can use properties and methods on the node to perform tasks like checking node type, access
attributes, access content of node etc. You can call these methods directly on reader object.

Using XmlTextWriter Class

Now, let us see how to use XmlTextWriter Class.

■ As usual you need to import System.Xml namespace.


■ Specify the file to which XmlTextWriter should write its content
e.g. In VB.NET

dim writer as xmltextwriter


writer=new
xmltextwriter("d:\newcatalog.
xml",null)
The second argument of the constructor indicates the encoding to be used. The value of null indicates
default encoding (ASCII)
SAX for .NET

SAX is the Simple API for XML,


originally a Java-only API. SAX was the
first widely adopted API for XML in
Java, and is a de facto standard. SAX
for
.NET is the port of SAX to C#.

Reading XML via SAX


The .NET framework provides the XmlReader class for reading XML via SAX. Let's create
an instance of it. Just like with the XmlWriter class, we'll use the Create() factory method
for it whose parameter is the filename. Don't forget to add using System.Xml. Everything
will be in a using block, which will take care of closing the file:
{

Let's prepare the necessary variables for the user properties. We can't assign values
directly to the instance since its properties are read-only. Another option would be to
allow for it to be modified externally, but if we did we'd lose a part of the encapsulation.
We'll initialize the properties with default values which will remain there in case the
value isn't written in the XML file. The current element's name needs to be stored
somewhere, so we'll declare a string variable element for it. We'll write the code in a
using block.

string name =
""; int age = 0;
DateTime registered = DateTime.Now;
string element = "";
Let's start by parsing the file. The XmlReader class reads a file line by line, from top to
bottom. We call the Read() method on its instance. It returns the next Node each time it
calls it. A node can be an element, an attribute, or an element's text value (we'll mainly
focus on Element, Text, and EndElement), another node type could be a comment,
which isn't very important for us at the moment. Once the reader reaches the end of the
file, the Read() method returns false, otherwise, it returns true. We'll load the document
nodes gradually using a while loop:

while (xr.Read())

There are several useful properties on the XmlReader instance. We'll be using NodeType
which is where the type of the current node, on which the reader is located at, is stored.
Next, we'll use the Name and Value property in which the name of the current node and
its value is stored (if it has any).
We'll mainly focus on two types of nodes: Element and Text. Let's react to them. We'll
add in empty condition bodies for now:

// reads the element

if (xr.NodeType == XmlNodeType.Element)

// reads the element value

else if (xr.NodeType == XmlNodeType.Text)

}
Every time we encounter a user element, we load the age attribute using the
getAttribute() method whose parameter is the attribute's name. The current element's
attribute can be read easily. However, it's not that simple with reading its value.
Although there are methods like ReadContentAs-Type(), beware, they implicitly call the
Read() method for some reason which messes with the while loop. Reading values like
this would work properly in non-nested XML files. I tried to find a workaround for this
but the solutions were so awkward that I ended up not using the ReadContentAs...()
methods at all. Here's what the first condition looks like:

element = xr.Name; // the name of the current element

if (element == "user")

age = int.Parse(xr.GetAttribute("age"));

}
Let's move on to the next branch, i.e. processing the element's values. We'll use the
element variable and add it to a switch. We'll assign the value to the corresponding
property according to the value in element:

switch (element)

case "name":

name = xr.Value;

break;

case "registered":

registered = DateTime.Parse(xr.Value);

break;

}
We're already very close to finishing. The brighter ones among you surely noticed that
we won't be adding users anywhere. We'll do so after we reach the closing user
element. Now, let's add one last condition:

// reads the closing element

else if ((xr.NodeType == XmlNodeType.EndElement) && (xr.Name == "user"))

users.Add(new User(name, age, registered));


DOM FOR .NET

Document object model (DOM) is a platform and language neutral interface that allows
programs and scripts to dynamically access and update XML and HTML documents. The
DOM API is a set of language independent, implementation neutral interfaces and
objects based on the Object Management Group (OMG) Interface Definition Language
(IDL) specification (not the COM) version of IDL).

DOM defines the logical structure of a document's data. You can access the document in
a structured format (generally through a tree format). Tree nodes and entities represent
the document's data. DOM also helps developers build XML and HTML documents, as
well as to add, modify, delete, and navigate the document's data.
DOM IN A TREE STRUCTURE:
This is the tree structure implementation of an XML file.

● <table>
● <tr>
● <td>Mahesh </td>
● <td>Testing</td>
● </tr>
● <tr>
● <td> Second Line</td>
● <td> Tested</td>
● </tr>
● </table>
DOM TREE REPRESENTATION OF THIS XML:
In DOM, a document takes a hierarchical structure, which
is similar to a tree structure. The document has a root
node, and the rest of the document has branches and
leaves.
These nodes are defines as interfaces object. You use the
interfaces to access and manipulate document objects.
The DOM core API also allows you to create and populate
documents load documents and save them.
Manipulating files and the Registry
Manipulating Files

and the Registry

• Exploring the directory structure


• Moving, copying, and deleting files and folders
• Reading and writing text in files
• Reading and writing keys in the registry
• Reading and writing to isolated storage
.NET Classes That Represent Files and

Folders

• Directory and File contain only static methods


and are never instantiated. You use these
classes bysupplying the path to the
appropriate file system object whenever you
call a member method.
• If you want to do only one operation on a
folder or file, using these classes is more
efficient because it saves the overhead of
instantiating a .NET class.
• DirectoryInfo and FileInfo implement roughly
the same public methods as Directory and
File, as well as some public properties and
constructors, but they are stateful and the
members of these classes are not static.
• You need to instantiate these classes before
each instance is associated with a particular
folder or file.
The pathname of the file system object

FileInfo myFile = new


FileInfo(@"C:\ProgramFiles\My
Program\ReadMe.txt");
myFile.CopyTo(@"D:\Copies\ReadMe.txt");
same effect as
File.Copy(@"C:\Program Files\My
Program\ReadMe.txt",
@"D:\Copies\ReadMe.txt");
The pathname of the Directoryobject

• DirectoryInfo myFolder = new


DirectoryInfo(@"C:\Program Files");
The Path Class

• The Path class is not a class that you would instantiate. Rather, it
exposes some static methods that make operations on path
names easier. For example, suppose that you want to display the
full path name for a file, ReadMe.txt in the folder C:\My
Documents. You could find the path to the file using the
following code:

• Console.WriteLine(Path.Combine(@"C:\My Documents",
"ReadMe.txt"));
• Using the Path class is a lot easier than using separation symbols
manually, especially because the Path class is aware of different
formats for path names on different operating systems. At the
time of writing, Windows is the only operating system
supported by .NET. However, if .NET were later ported to Unix,
Path would be able to cope with Unix paths, in which /, rather
than \, is used as a separator in path names. Path.Combine() is
the method of this class that you are likely to use most often,
but Path also implements other methods that supply
information about the path or the required format for it.
Moving, Copying, and Deleting Files

• The File and Directory classes


are Move() and Delete().
The FileInfo and File classes also implement
the methods CopyTo() and Copy(),
respectively. However, no methods exist to
copy complete folders - you need to do that
by copying each file in the folder.
Refer text book :

wrox-press-professional-c-5-0-and-net-4-5-1-
201

Refer this link:


https://www.c-sharpcorner.com/UploadFile/f9f
215/windows-registry/
Manipulating files and the Registry

Read and Write Windows Registry to Store Data Using C#


• The Windows Registry is a hierarchical database for storing many kinds of
system and application settings. Prior to the Registry, .ini files in the form
of text files were commonly used for storing these settings. However,
these files were unable to meet all the requirements of a modern
application. Especially in multi-user scenarios the .ini files were nearly
useless.

• On the other hand, the Windows Registry uses one logical repository that
is able to store user-specific settings. According to Microsoft, there are
several advantages over the obsolete .ini files like faster parsing, backup
or restoration.
• Structure of the Registry

• The Registry is based on the two basic elements, keys and


values and the entire structure is a tree with several root
elements that slightly differ depending on the version of
Windows you are currently using. The keys are container
objects very similar to folders that can contain other keys or
values. The values can be a string, binary,
or DWORD depending on the scenario.

• The most common root element structure is as follows:



• Figure 1: root elements structure
• HKEY_CLASSES_ROOT
• This root element holds the information about registered
(installed) applications and associated file extensions. For
example, Windows is able to open the .pdf extension with
Acrobat Reader because of the settings in this key. It is not
advised to alter these keys manually and the Folder Options in
the Windows Explorer should be used instead.

• HKEY_CURRENT_USER
• This root element represents the currently logged-in user and
their specific settings. It is a link to a subkey of HKEY_USERS
that corresponds to the current user. It cannot be edited.
• HKEY_LOCAL_MACHINE

• This root element contains five subkeys (hardware,


security accounts manager, security, software,
system) that are used for storing many kinds of
settings used by the operating system. Hardware,
security and security accounts manager subkeys
can't be edited. It is not advised to manully alter
the rest as it might result in a system crash.
• HKEY_USERS
• This root element holds all the user profiles used
on the machine. Even though it can be edited, you
should be very cautious when doing so.
FILE
File is a utility class. It provides methods for the creation,
copying, deletion, moving, and opening of a single file, and
aids in the creation of FileStream objects

C# includes static File class to perform I/O operation on


physical file system. The static File class includes various
utility method to interact with physical file of any type e.g.
binary, text etc.
STATIC FILE OPERATIONS

They are used to perform some quick operation on


physical file. It is not recommended to use File class for
multiple operations on multiple files at the same time due
to performance reasons.

Some of the functions used to manipulate files are given


on the next slide
File operations
Multiple file operations in a single program
C# REGISTRY

The registry is an optimal location for saving information about your


application as well as individual user settings.

The Registry comprises a number of logical sections called Hives. The


following are the predefined keys that are used by the system.

• HKEY_CURRENT_USER

• HKEY_USERS

• HKEY_LOCAL_MACHINE

• HKEY_CLASSES_ROOT

• HKEY_CURRENT_CONFIG
Each key has many subkeys and may have a value.
The operations on the registry in .NET can be done using
two classes of the Microsoft.Win32 Namespace: Registry
class and the RegistryKey class. The Registry class
provides base registry keys as shared public methods:

Creating a Registry entry

Deleting a Subkey
The following C# program shows how to create a registry entry , set values to
registry entries, retrieve values from registry and delete keys on Registry. Drag
and drop four buttons on the form control and copy and paste the following
source code.
using System;
using
System.Data;
using System.Windows.Forms;
using Microsoft.Win32;
namespace WindowsFormsApplication1

{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs
e)
{
RegistryKey rKey ;
rKey =
Registry.LocalMachine.OpenSubKey("SOFTWARE", true);
rKey.CreateSubKey("AppReg");
rKey.Close();
MessageBox.Show ("AppReg created !");
}

private void button2_Click(object sender,


EventArgs e)
{
RegistryKey rKey ;
rKey =
Registry.LocalMachine.OpenSubKey("Software\\AppReg",
true);
rKey.SetValue("App
Name", "RegApp");
rKey.SetValue("Ver
sion", 1.1);
created"); rKey.Close();
} MessageBox.Show("A
ppname , version
private void button3_Click(object sender,
EventArgs e)
{

RegistryKey rKey ;
Object ver ;
string app = null;
rKey =
Registry.LocalMachine.OpenSubKey("Software\\AppR
eg", true);
app = (string)rKey.GetValue("AppName");
ver = rKey.GetValue("Version");
rKey.Close();
MessageBox.Show("App Name " + app + "
Version " + ver.ToString());
}
private void button4_Click(object sender, EventArgs
e)
{
RegistryKey rKey ;
rKey =
Registry.LocalMachine.OpenSubKey("Software", true);
rKey.DeleteSubKey("AppReg", true);
rKey.Close();
MessageBox.Show("AppReg deleted");
}
}

}
TRANSACTION
TRANSACTION

• A transaction is a single unit of work which means either ALL or NONE.


• If a transaction is successful, all of the data operations are committed and
become a durable part of the database. If a transaction encounters
errors/exceptions and must be canceled or rolled back, then all of the data
modifications/operations need to be removed.

• Example: Transfer money from Bank Account1 to Account2.

• It consists of two processes:

1. Withdraw amount from Account1


2. Deposit that amount to Account2.

• Transferring money will only be accurate and successful if both the


processes are individually successful. If that is not happening, suppose
process 1 succeeds but process 2 fails, then the money will be deducted
from Account 1 but not deposited to Account 2. If that happens, it will be
very bad and no one will accept it.
ACID PROPERTIES
• The characteristics of transactions can be defined by the term ACID.
• ACID is a four-letter acronym for
▪ Atomicity
▪ Consistency
▪ Isolation
▪ Durability
• Atomicity—Represents one unit of work. With a transaction, either the
complete unit of work succeeds or nothing is changed.
• Consistency—The state before the transaction was started and after
the transaction is completed must be valid. During the transaction, the
state may have interim values
Isolation—Transactions that happen concurrently are isolated from the state, which is
changed during a transaction. Transaction A cannot see the interim state of transaction B
until the transaction is completed.

Durability—After the transaction is completed, it must be stored in a durable way. This


means that if the power goes down or the server crashes, the state must be recovered at
reboot.
Using Code:

For demonstration, we create two tables (ProjectMember,


Project). In ProjectMember table, column ProjectID is a
foreign key to Project table's ProejctID column.

-- Table1
CREATE TABLE tblProject
(
ProjectID int PRIMARY KEY,
Name varchar(50) NULL
);

--Table2
CREATE TABLE tblProjectMember
(
MemberID int,
ProjectID int foreign Key references Project(ProjectID)
);
Often we use ADO.NET to perform Database opertaions. Here is the
sample code to implement transaction in ADO.NET.

string strConnString = "myconnectionstring"; // get it from Web.config file


SqlTransaction objTrans = null;

using (SqlConnection objConn = new SqlConnection(strConnString))


{
objConn.Open();
objTrans = objConn.BeginTransaction();
SqlCommand objCmd1 = new SqlCommand("insert into tblProject values(1, 'Tes
tProject')", objConn);
SqlCommand objCmd2 = new SqlCommand("insert into tblProjectMember(Mem
berID, ProjectID) values(2, 1)", objConn);
try
{ objCmd1.ExecuteNonQuery();
objCmd2.ExecuteNonQuery(); //Throws
exception due to foreign key constraint

objTrans.Commit();
}

catch (Exception)
{
objTrans.Rollback();
}
finally
{
objConn.Close();
}
}
SYSTEM TRANSACTION
• The property
• Current Current is a
static property
that doesn’t
require an
instance.
Transaction.Cu
• Isolation Level rrent returns an
ambient
transaction if
one exists..

• The
IsolationLevel
property
returns an
object of type
IsolationLevel.
IsolationLevel
is an
enumeration
that defines
what access
other
transactions
have to the
interim results
of the
transaction. ACID; not all
This reflects transactions
the “I” in are isolated.
• The TransactionInformation
property returns a
• Transaction Information TransactionInformation object,
which provides information about
the current state of the transaction,
the time when the transaction was
created, and transaction identifiers.

• With these enlist methods, you


EnlistVolatile EnlistDurable can enlist custom resource
managers that participate with the
EnlistPromotableSinglePhase transaction.
• Roll back • With the Rollback
method, you can abort a
transaction and undo
everything, setting all
results to the state
before the transaction.
• Dependent clone
• With the
DependentClone
method, you can create
a transaction that
depends on the current
• TransactionCompleted transaction.

• TransactionCompleted is
an event that is fired when
the transaction is
completed—either
successfully or
unsuccessfully. With an
event handler object of
type
TransactionCompleted
EventHandler, you can
access the Transaction
object and read its status.
Committable Transactions:

• The Transaction class cannot be committed programmatically; it does not


have a method to commit the transaction. The base class Transaction just
supports aborting the transaction. The only transaction class that supports a
commit is the class CommittableTransaction.

•With ADO.NET, a transaction can be enlisted with the connection. To make this
possible, an AddStudentAsync method is added to the class StudentData that
accepts a System.Transactions .

•Transaction object as second parameter. The object tx is enlisted with the


connection by calling the method EnlistTransaction of the SqlConnection class.
This way, the ADO.NET connection is associated with the transaction (code file
DataLib/StudentData.cs)
PROGRAM:
public async Task AddStudentAsync(Student student, Transaction tx) {

Contract.Requires<Argument Null Exception>(student != null);

var connection = new SqlConnection(

Properties.Settings.Default.CourseManagementConnectionString);

await connection.OpenAsync();

try
{ if (tx != null)
connection.EnlistTransaction(tx);
SqlCommand command = connection.CreateCommand();

command.CommandText = "INSERT INTO Students (FirstName, " + "LastName,


Company)" + "VALUES (@FirstName, @LastName, @Company)";
command.Parameters.AddWithValue("@FirstName", student.FirstName);

command.Parameters.AddWithValue("@LastName", student.LastName);

command.Parameters.AddWithValue("@Company", student.Company);

await

command.ExecuteNonQueryAsync();

finally

{ connection.Close();

}I
OUTPUT:

The transaction is active and has a local identifier. In addition, the user has
chosen to abort the transaction. After the transaction is finished, you can see
the aborted state:

TX created
Creation Time: 7:30:49 PM
Status: Active
Local ID: bdcf1cdc-a67e-4ccc-9a5c-cbdfe0fe9177:1
Distributed ID: 00000000-0000-0000-0000-000000000000

Abort the Transaction (y/n)? y


Transaction abort

TX completed
Creation Time: 7:30:49 PM
Status: Aborted
Local ID: bdcf1cdc-a67e-4ccc-9a5c-cbdfe0fe9177:1
Distributed ID: 00000000-0000-0000-0000-000000000000
PROGRAM 2:
static async Task CommittableTransactionAsync()
{
var tx = new CommittableTransaction();
Utilities.DisplayTransactionInformation("TX created", tx.TransactionInformation);

try {
var s1 = new Student
{ FirstName = "Stephanie",
LastName = "Nagel",
Company = "CN innovation"
};

var db = new StudentData();


await db.AddStudentAsync(s1, tx);

if ( Utilities.AbortTx() )

throw new ApplicationException("transaction abort");


}
tx.Commit();
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
Console.WriteLine();
tx.Rollback();
}

Utilities.DisplayTransactionInformation("TX completed",
tx.TransactionInformation); }

With this output of the application that follows

The transaction is not aborted by the user. The transaction has


the status committed, and the data is written to the database
OUTPUT 2:

TX Created
Creation Time: 7:33:04 PM

Status: Active

Local ID: 708bda71-fa24-46a9-86b4-18b83120f6af:1

Distributed ID: 00000000-0000-0000-0000-000000000000 Abort the


Transaction (y/n)?

n TX completed

Creation Time: 7:33:04 PM Status:

Committed Local ID:

708bda71-fa24-46a9-86b4-18b83120f6af:1 Distributed ID:


00000000-0000-0000-0000-000000000000
Ambient Transactions:

The really big advantage of System. Transactions is the ambient


transactions feature. With ambient transactions, there is no need to
manually enlist a connection with a transaction; this is done from the
resources supporting ambient transactions.

The members of Transaction Scope are listed in the following table


If an ADO.NET connection should not enlist with an ambient transaction, you can
set the value Enlist=false with the connection string.
Running the application, you can see an active ambient transaction
after an instance of the Transaction Scope class is created.

The last output of the application is the output from the


Transaction Completed event handler to display the finished
transaction state Ambient TX created

Creation Time: 9:55:40 PM


Status: Active
Local ID: a06df6fb-7266-435e-b90e-f024f1d6966e:1
Distributed 1D: 00000000-0000-0000-0000-0000000000

Abort the Transaction (y/n)? n


TX ccmpleted
Creation Time: 9:55:40 PM
Status: Committed
Local ID: a06df6fb-7266-435e-b90e-f024f1d6966e:l
Distributed 1D: 00000000-0000-0000-0000-0000000000

Press any key to continue …


SUMMARY

• In this chapter, you learned the attributes of transactions and


how you can create and manage transactions with the classes
from the System.

• Transactions namespace. Transactions are described with ACID


properties: atomicity, consistency, isolation, and durability. Not all
of these properties are always required, as you have seen with
volatile resources that don’t support durability but have isolation
options.

• The easiest way to deal with transactions is by creating ambient


transactions and using the Transaction Scope class. Ambient
transactions are very useful for working with the ADO.NET
data adapter and the ADO.NET Entity Framework, for which
you usually do not open and close database connections
explicitly.
INTRODUCTION TO
PEER TO PEER
NETWORKS
Client-Server Mode
Client-Server Model

• In the client-server architecture, when the client


computer sends a request for data to the server
through the internet, the server accepts the requested
process and deliver the data packets requested back to
the client. Clients do not share any of their resources.
• Client: A Client is a computer (Host) i.e. capable of
receiving information or using a particular service from
the service providers (Servers).
• Servers: A Server is a remote computer which provides
information (data) or access to particular services.
PEER TO PEER NETWORK

• In a P2P network, the "peers" are computer


systems which are connected to each other via the
Internet.
• Files can be shared directly between systems on

the network without the need of a central server. In


other words, each computer on a P2P
network becomes a file server as well as a client.

• Peer-to-peer computing or networking is a


distributed application architecture that partitions
tasks or workloads between peers. Peers are equally
privileged, equipotent participants in the
application.
P2P network

A P2P network is created when two or more


computers are connected and share resources
without going through a separate server
computer. All computers in a P2P
network have an equal privilege. There is no
need for central coordination.
PEER TO PEER ARCHITECTURE

• All nodes are both


clients and
servers

• Provide and
consume data

• No centralized
data source
P2P (peer-to-peer):
• The primary goal of peer-to-peer networks is to share resources
and help computers and devices work collaboratively, provide
specific services, or execute specific tasks.
• P2P is used to share all kinds of computing resources such as
processing power, network bandwidth, or disk storage space.
• However, the most common use case for peer-to-peer networks
is the sharing of files on the internet.
• Peer-to-peer networks are ideal for file sharing because they
allow the computers connected to them to receive files and send
files simultaneously.
Why are peer-to-peer networks

useful?

• It's hard to take them down. Even if one of the


peers is shut down, the others are still
operating and communicating. For a P2P
(peer-to-peer) network to stop working, you
have to close down all its peers.
• Peer-to-peer networks are incredibly scalable.
Adding new peers is easy as you don't need to
do any central configuration on a central
server.
• When it comes to file-sharing, the larger a
BENEFITS:

• Easy file sharing: An advanced P2P network can share


files quickly over large distances.
• Reduced costs: There is no need to invest in a
separate computer for a server when setting up a P2P
network.
• Adaptability: P2P network extends to include new clients
easily. This benefit makes these networks more flexible
than client-server networks.
• Reliability: Unlike a client-server network, which can fail if
the central server malfunctions, a P2P network will likely
remain functional even if the central server crashes.
• High performance: While a client-server network performs
less effectively when more clients join the network, a P2P
network can improve its performance when more clients join
it. This is due to the fact that each client in a P2P network is
also a server that contributes resources to the network.
DISADVANTAGES
• It is difficult to backup the data as it is stored in
different computer systems and there is no central
server.

• It is difficult to provide overall security in the peer


to peer network as each system is independent and
contains its own data.
PNRP
BUILDING P2P
APPLICATIONS
What is PNRP

• A PNRP (Peer Name Resolution

Protocol) "cloud" represents a set of nodes


that can communicate with each other
through the network.
• There is only a single global cloud. The

link-local cloud corresponds to the link-local


IPv6 address scope and link-local addresses.
Use of PNRP

• NET P2P applications: The Peer Name


Resolution Protocol (PNRP), which is used to
publish and resolve peer addresses.
• The People Near Me server, which is used to
locate local peers (currently Vista only)
Microsoft Windows Peer-to-Peer

Networking C#

• The Microsoft Windows Peer-to-Peer

Networking platform is Microsoft’s implementation of


P2P technology.
• It is part of Windows XPSP2 and Windows Vista, and is
also available as an add-on for Windows XPSPI.
• It includes two technologies that you can use when
creating .NET P2P applications:

1. The Peer Name Resolution Protocol (PNRP), which is


used to publish and resolve peer addresses
2. The People Near Me server, which is used to locate
local peers (currently Vista only)
• Peer Name Resolution Protocol (PNRP) is used to publish and resolve peer
addresses. One can use any protocol to implement a P2P application, but to work in
a Microsoft Windows 8 environment it makes sense to at least consider PNRP.
• In itself, PNRP doesn’t give you everything you need to create a P2P application.
Rather, it is one of the underlying technologies that you use to resolve peer
addresses.
• PNRP enables a client to register an endpoint (known as a peer name) that is
automatically circulated among peers in a cloud. This peer name is
encapsulated in a PNRP ID.
• A peer that discovers the PNRP ID can use PNRP to resolve it to the actual
peer name and can then communicate directly with the associated client.
• PNRP makes no assumptions about what a peer name actually represents. It is up to
peers to decide how to use them when discovered.
• The information a peer receives from PNRP when resolving a PNRP ID
includes the IPv6 (and usually also the IPv4) address of the publisher of the ID,
along with a port number and optionally a small amount of additional data.
Peer Name Resolution

Protocol (PNRP)

• Peer Name Resolution Protocol (PNRP) is

a peer-to-peer protocol designed by Microsoft.

• PNRP enables dynamic name publication and resolution,


and requires IPv6.
• PNRP was first mentioned during a presentation at a P2P conference in
November 2001.
• It appeared in July 2003 in the Advanced Networking Pack for Windows
XP, and was later included in the Service Pack 2 for Windows XP.
• PNRP 2.0 was introduced with Windows Vista and is available for
download for Windows XP Service Pack 2 users.
• PNRP 2.1 is included in Windows Vista SP1, Windows Server
2008 and Windows XP SP3.
• PNRP v2 is not available for Windows XP Professional x64 Edition or any
edition of Windows Server 2003.
• Windows Remote Assistance in Windows 7 uses PNRP, Teredo and IPv6
when connecting using the Easy Connect option
PNRP services

• The PNRP is a distributed name resolution protocol allowing Internet hosts


to publish "peer names" and corresponding IPv6 addresses and optionally
other information.
• Other hosts can then resolve the peer name, retrieve the corresponding
addresses and other information, and establish peer-to-peer connections.
• With PNRP, peer names are composed of an "authority" and a "qualifier".
The authority is identified by a secure hash of an associated public key, or
by a place-holder (the number zero) if the peer name is "unsecured".
• The qualifier is a string, allowing an authority to have different peer names
for different services.[4]
• If a peer name is secure, the PNRP name records are signed by the
publishing authority, and can be verified using its public key.
• Unsecured peer names can be published by anybody, without possible
verification.
• Multiple entities can publish the same peer name. For example, if a peer
name is associated with a group, any group member can publish addresses
for the peer name.
• Peer names are published and resolved within a specified scope. The
scope can be a local link, a site (e.g. a campus), or the whole Internet.
Hashtable in C#

• The Hashtable class represents a collection of


key-and-value pairs that are organized based
on the hash code of the key. It uses the key to
access the elements in the collection. A hash
table is used when you need to access
elements by using key, and you can identify a
useful key value.
PNRP IDs are 256-bit identifiers. The low-order 128 bits can uniquely identify a
particular peer, and the high-order 128 bits identify a peer name. The high-order
128 bits are a hashed combination of a hashed public key from the publishing
peer and a string of up to 149 characters that identifies the peer name. The
hashed public key (known as the authority) combined with this string (the
classifier) are together referred to as the P2P ID. You can also use a value of 0
instead of a hashed public key, in which case the peer name is said to be
unsecured (as opposed to secured peer names, which use a public key).
• The PNRP service on a peer is responsible to maintain a list
of PNRP IDs, including the ones that it publishes and a
cached list of those it has obtained by PNRP service
instances elsewhere in the cloud.

• When a peer attempts to resolve a PNRP ID, the PNRP


service either uses a cached copy of the endpoint to resolve
the peer that published the PNRP or it asks its neighbours if
they can resolve it.

• Eventually a connection to the publishing peer is made, and


the PNRP service can resolve the PNRP ID. Peers can use
PNRP to locate PNRP IDs that match a particular P2P ID.

• You can use this to implement a basic form of discovery for


unsecured peer names.

• This is because if several peers expose an unsecured peer


name that uses the same classifier, the P2P ID will be the
same.
PNRP CLOUDS:
A cloud is maintained by a seed server, which can be any server running
the PNRP service that maintains a record of at least one peer. Two types
of clouds are available to the PNRP service:

➤➤ Link local: These clouds consist of the computers attached to a local


network. A PC may connect to more than one link local cloud if it has
multiple network adapters.

➤➤ Global: This cloud consists of computers connected to the Internet


by default; although you can define a private global cloud. The difference
is that Microsoft maintains the seed server for the global Internet cloud,
whereas if you define a private global cloud you must use your own seed
server. You can discover what clouds you are connected to with the
following command:
(network shell

In computing, netsh , or network shell, is a command-line utility included in


Microsoft's Windows NT line of operating systems beginning with Windows 2000. It
allows local or remote configuration of network devices such as the interface.)

netsh p2p pnrp cloud show


list A typical result is shown
here:
Scope Id Addr State Name

1 0 1 Virtual Global_
3 13 1 Virtual LinkLocal_ff00::%13/8
3 19 1 Virtual LinkLocal_ff00::%19/8

The output shows that three clouds are available: one is a global and two are link
local clouds. You can tell this from both the name and the Scope value, which is 3
for link local clouds and 1 for global clouds. To connect to a global cloud, you must
have an IPv6 address.
Clouds may be in one of the following states:

➤➤ Active: If the state of a cloud is active, you can use it to publish and resolve
peer names.
➤➤ Alone: If the peer you query the cloud from is not connected to any other peers, it
has a state
of alone.

➤➤ No Net: If the peer is not connected to a network, the cloud state may change
from active to no net.
➤➤ Synchronizing: Clouds are in the synchronizing state when the peer
connects to them. This state changes to another state extremely quickly because
this connection does not take long, so you will probably never see a cloud in this
state.
➤➤ Virtual: The PNRP service connects to clouds only as required by peer name
registration and resolution. If a cloud connection has been inactive for more than
15 minutes, it may enter the virtual state.
Clouds may be in one of the following states:

➤➤ Active: If the state of a cloud is active, you can use it to publish and resolve
peer names.
➤➤ Alone: If the peer you query the cloud from is not connected to any other peers, it
has a state
of alone.

➤➤ No Net: If the peer is not connected to a network, the cloud state may change
from active to no net.
➤➤ Synchronizing: Clouds are in the synchronizing state when the peer
connects to them. This state changes to another state extremely quickly because
this connection does not take long, so you will probably never see a cloud in this
state.
➤➤ Virtual: The PNRP service connects to clouds only as required by peer name
registration and resolution. If a cloud connection has been inactive for more than
15 minutes, it may enter the virtual state.
BUILDING P2P APPLICATIONS:

• The classes in the System.Net.PeerToPeer namespace encapsulate the API


for PNRP and enable you to interact with the PNRP service. You can use
these classes for two main tasks:

• Registering peer names


• Resolving peer names

• Registering Peer Names:

• To register a peer name follow these steps:

1. Create a secured or unsecured peer name with a specified classifier.


2. Configure a registration for the peer name, providing as much of the following
optional information as
you choose:

i. A TCP port number.


PNRP registers the peer name in all available clouds.)
ii. A comment of up to 39 characters.

iii. Up to 4,096 bytes of additional data.

iv. Whether to generate endpoints for the peer name automatically. (The default
behaviour, where endpoints will be generated from the IP address or
addresses of the peer and, if specified, the port number.)
v. A collection of endpoints.

3. Use the peer name registration to register the peer name with the local PNRP
service.

After step 3, the peer name is available to all peers in the selected cloud (or
clouds). Peer registration continues until it explicitly stops, or until the process that
registers the peer name is terminated.
To create a peer name, you use the PeerName class.

You create an instance of this class from a string representation of a P2P


ID in the form authority.classifier or from a classifier string and a
PeerNameType.
You can use PeerNameType.Secured or PeerNameType.Unsecured, for
example:

var pn = new PeerName("Peer classifier", PeerNameType.Secured);

Because an unsecured peer name uses an authority value of 0, the


following lines of code are equivalent:

var pn = new PeerName("Peer classifier", PeerNameType.Unsecured);


var pn = new PeerName("0.Peer classifier");

After you have a PeerName instance, you can use it along with a port number
to initialize a PeerNameRegistration object:

var pnr = new PeerNameRegistration(pn, 8080);


Alternatively, you can set the PeerName and (optionally) the Port properties on a
PeerNameRegistration object created using its default parameter. You can also
specify a Cloud instance as a third parameter of the PeerNameRegistration
constructor, or through the Cloud property. You can obtain a Cloud instance from
the cloud name or by using one of the following static members of Cloud:

Cloud.Global: This static property obtains a reference to the global cloud. This may
be a private global cloud depending on peer policy configuration.

Cloud.AllLinkLocal: This static field gets a cloud that contains all the link local clouds
available to the peer.

Cloud.Available: This static field gets a cloud that contains all the clouds available
to the peer, which includes link local clouds and (if available) the global cloud.
When created, you can set the Comment and Data properties if you want.

You can also add endpoints by using the EndPointCollection property. This
property is a System.Net.IPEndPointCollection collection of
System.Net.IPEndPoint objects. If you use the EndPointCollection property you
might also want to set the UseAutoEndPointSelection property to false to prevent
automatic generation of endpoints. When you are ready to register the peer name,
you can call the PeerNameRegistration.Start method.
To remove a peer name registration from
thewwPNwR.Prejisneprvaicuel,.cousme the PeerNameRegistration.Stop
method. The following code registers a secured peer name with a comment:

var pn = new PeerName("Peer classifier", PeerNameType.Unsecured);


var pnr = new PeerNameRegistration(pn, 8080);
pnr.Comment = "Get pizza here";
pnr.Start();

Resolving Peer Names:

To resolve a peer name you must carry out the following steps:
1. Generate a peer name from a known P2P ID or a P2P ID obtained through a
discovery technique.
2. Use a resolver to resolve the peer name and obtain a collection of peer name
records. You can limit the resolver to a particular cloud and a maximum number of
results to return.
www.rejinpaul.com

3. For any peer name records that you obtain, obtain peer name, endpoint,
comment, and additional data information as required.

This process starts with a PeerName object similar to a peer name


registration. The difference here is that you use a peer name registered by
one or more remote peers.

The simplest way to get a list of active peers in your link local cloud is for
each peer to register an unsecured peer name with the same classifier and
to use the same peer name in the resolving phase.

However, this is not a recommended strategy for global clouds because


unsecured peer names are easily spoofed. To resolve peer names use the
PeerNameResolver class.
synchronously by using the Resolve method or asynchronously using the
ResolveAsync method. You can call the Resolve method with a single PeerName
parameter, but you can also pass an optional Cloud instance to resolve in, an int
maximum number of peers to return, or both. This method returns a
PeerNameRecordCollection instance, which is a collection of PeerNameRecord
objects. For example, the following code resolves an unsecured peer name in all link
local clouds and returns a maximum of five results:
var pn = new PeerName("0.Peer
classifier"); var pnres = new
PeerNameResolver();
PeerNameRecordCollection pnrc = pnres.Resolve(pn, Cloud.AllLinkLocal, 5);
The ResolveAsync method uses a standard asynchronous method call pattern. You
pass a unique userState object to the method and listen for
ResolveProgressChanged events for peers being found and the ResolveCompleted
event when the method terminates. You can cancel a pending asynchronous
request with the ResolveAsyncCancel method. Event handlers for the
ResolveProgressChanged event use the ResolveProgressChangedEventArgs event
arguments parameter, which derives from the standard System.ComponentModel
.ProgressChangedEventArgs class. You can use the PeerNameRecord property of
the event argument object you receive in the event handler to get a reference to the
peer name record that was found. Similarly, the ResolveCompleted event requires
an event handler that uses a parameter of type ResolveCompletedEventArgs, which
derives from AsyncCompletedEventArgs.
private pnres_ResolveProgressChanged(object sender,
ResolveProgressChangedEventArgs e)
{
// Use e.ProgressPercentage (inherited from base event args)
// Process PeerNameRecord from e.PeerNameRecord
}
private pnres_ResolveCompleted(object sender,
ResolveCompletedEventArgs e)
{
// Test for e.IsCancelled and e.Error (inherited from base event args)
// Process PeerNameRecordCollection from e.PeerNameRecordCollection
}
After you have one or more PeerNameRecord objects you can proceed to
process them. This
PeerNameRecord class exposes Comment and Data properties to examine the
comment and data set
in the peer name registration (if any), a PeerName property to get the PeerName
object for the peer name
record, and, most important, an EndPointCollection property.
System.Net.PeerToPeer namespace classes register a peer name:
// Create peer name
peerName = new PeerName("P2P Sample", PeerNameType.Unsecured);
// Prepare peer name registration in link www.rejinpaul.com
local clouds

peerNameRegistration = new PeerNameRegistration(peerName, int.Parse(port));


peerNameRegistration.Cloud = Cloud.AllLinkLocal;
// Start registration
peerNameRegistration.Start();
}
When the Refresh button is clicked, the RefreshButton_Click event handler uses
PeerNameResolver.ResolveAsync to get peers asynchronously:
private async void RefreshButton_Click(object sender, RoutedEventArgs e)
{
// Create resolver and add event handlers
var resolver = new PeerNameResolver();
resolver.ResolveProgressChanged +=
new EventHandler<ResolveProgressChangedEventArgs>(
resolver_ResolveProgressChanged);
resolver.ResolveCompleted +=
new EventHandler<ResolveCompletedEventArgs>(
resolver_ResolveCompleted);
// Prepare for new peers
peerList.Clear();
RefreshButton.IsEnabled = false;
// Resolve unsecured peers asynchronously
resolver.ResolveAsync(new PeerName("0.P2P Sample"), 1);
ResolveCompleted events are fired where the peer information is received. If case
peers are not active yet, a timeout is defined to cancel the resolve process to fire
the ResolveCompleted. The timeout is dealt with the Task.Delay method, and after
the timeout ResolveAsyncCancel is invoked with the same user state value, that is
passed to the ResolveAsync method. With the user state value, the same resolve
task is mapped for cancellation.

await Task.Delay(5000);
resolver.ResolveAsyncCancel(1);
}
Windows Presentation

Foundation (WPF)
• Windows Presentation Foundation (WPF) is a
library to create the UI for smart client
applications.
• It covers a large number of different controls and
their categories, including how to arrange the
controls with panels, customize the appearance
• using styles, resources, and templates, add some
dynamic behavior with triggers and animations,
and create 3-D with WPF.
Define WPF?

• Windows Presentation Foundation (WPF) is a


UI framework that creates desktop client
applications. The WPF development platform
supports a broad set of application
development features, including an
application model, resources, controls,
graphics, layout, data binding, documents,
and security.
Managed Layer
Unmanaged Layer
www.rejinpaul.com
www.rejinpaul.com
Shapes are the core elements of WPF. With shapes you can draw two-dimensional graphics using rectangles,
lines, ellipses, paths, polygons, and polylines that are represented by classes derived from the abstract base
class Shape.
Shapes are defined in the namespace System.Windows.Shapes.
The following XAML example (code file ShapesDemo/MainWindow.xaml) draws a yellow face consisting
of an ellipse for the face, two ellipses for the eyes, two ellipses for the pupils in the eyes, and a path for the
mouth:
<Window x:Class="ShapesDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="300" Width="300">
<Canvas>
<Ellipse Canvas.Left="10" Canvas.Top="10" Width="100" Height="100"
Stroke="Blue" StrokeThickness="4" Fill="Yellow" />
<Ellipse Canvas.Left="30" Canvas.Top="12" Width="60" Height="30">
<Ellipse.Fill>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5, 1">
<GradientStop Offset="0.1" Color="DarkGreen" />
<GradientStop Offset="0.7" Color="Transparent" />
</LinearGradientBrush>
</Ellipse.Fill>
</Ellipse>
<Ellipse Canvas.Left="30" Canvas.Top="35" Width="25" Height="20" Stroke="Blue"
StrokeThickness="3" Fill="White" />
<Ellipse Canvas.Left="40" Canvas.Top="43" Width="6" Height="5" Fill="Black" />

c35.indd 1055 30-01-2014 20:41:46

1056 ❘ CHAPTER 35 Core WPF


<Ellipse Canvas.Left="65" Canvas.Top="35" Width="25" Height="20" Stroke="Blue"
StrokeThickness="3" Fill="White" />
<Ellipse Canvas.Left="75" Canvas.Top="43" Width="6" Height="5" Fill="Black" />
<Path Name="mouth" Stroke="Blue" StrokeThickness="4"
Data="M 40,74 Q 57,95 80,74 " />
</Canvas>
</Window>
shows the result of the XAML code.

All these WPF elements can be accessed programmatically, even if they are buttons or
shapes, such as lines or rectangles. Setting the Name or x:Name property with the Path
element to mouth enables you to access this element programmatically with the variable
name mouth:

<Path Name="mouth" Stroke="Blue" StrokeThickness="4"


Data="M 40,74 Q 57,95 80,74 " />
In the code-behind Data property of the Path element (code file ShapesDemo/MainWindow
.xaml.cs), mouth is set to a new geometry. For setting the path, the Path class supports
PathGeometry with path markup syntax. The letter M defines the starting point for the
path; the letter Q specifies a control point and an endpoint for a quadratic Bézier curve.
Running the application results in the image shown in Figure 35-3.
public MainWindow()
{
InitializeComponent();
mouth.Data = Geometry.Parse("M 40,92 Q 57,75 80,92");
}
The following table describes the shapes available in the namespace System.Windows.Shapes.
What is .NET framework in C#?

C# programs run on the . NET Framework, an integral component of Windows


that includes a virtual execution system called the common language runtime
(CLR) and a unified set of class libraries. ... Source code written in C# is
compiled into an intermediate language (IL) that conforms to the CLI
specification.

In easy words, it is a virtual machine for compiling and executing programs


written in different languages like C#, VB.Net etc.

It is used to develop Form-based applications, Web-based applications and Web


services. There is a variety of programming languages available on the .Net
platform, VB.Net and C# being the most common ones are . It is used to build
applications for Windows, phone, web etc. It provides a lot of functionalities and
also supports industry standards.

Basic Architecture and Component Stack of .NET Framework


The first three components from bottom are considered as the basic
architecture of .Net framework which came in the year 2005 and after this
more components were added by Microsoft in the .Net Framework as
following :

1. CLR (Common Language Runtime) : It is a run-time environment


which executes the code written in any .NET programming language. .Net
framework provides the support for many languages like C#, F#, C++,
Cobra, Jscript.Net, VB.Net, Oxygeneetc
2. FCL (Framework Class Library) : A large number of class libraries
are present in this framework which is known as FCL.
3. Types of Applications : Mainly the applications which are built in
.Net framework is divided into the following three categories :

● WinForms : Form – Based applications are considered under this


category. In simple terms, we can say client based applications which
read and writes the file system comes under this category.
● ASP .NET : Web-Based applications come under this category.
ASP.Net is a framework for web and it provides the awesome
integration of HTML, CSS and JavaScript which makes it useful to
develop the web applications, websites and web services. Web
services were added in .Net Framework 2.0 and considered as a
part of ASP.NET web applications.
● ADO .NET : It includes the application which are developed to
communicate with the database like MS SQL Server, Oracle etc.
comes. It mainly consists of classes that can be used to connect,
retrieve, insert and delete data.
4. WPF (Windows Presentation Foundation) : Windows
Presentation Foundation (WPF) is a graphical subsystem given by
Microsoft which uses DirectX and is used in Windows-based applications
for rendering UI (User Interface). WPF was initially released as part of
.NET Framework 3.0 in 2006 and previously known as “Avalon”.
5. WCF (Windows Communication Foundation) : It is a framework
for building connected and service-oriented applications used to transmit
the data as asynchronous from one service endpoint to another service
point. It was previously known as the Indigo.

6. WF (Windows Workflow Foundation) : It is a technology given by


Microsoft which provides a platform for building workflows within .Net
applications.
7. Card Space : It is a Microsoft .NET Framework software client
which is designed to let users provide their digital identity to online
services in a secure, simple and trusted way.
8. LINQ (Language Integrated Query) : It is introduced in .Net
framework version 3.5. Basically, it is a query language used to make the
query for data sources with VB or C# programming languages.
9. Entity Framework : It is open–source ORM (Object Relational
Mapping) based framework which comes into .Net Framework version 3.5.
It enables the .Net developer
to work with database using .Net objects. Before entity framework, .Net
developers have performed a lot of things related database. Like to open a
connection to the database, developers have to create a Data Set to fetch
or submit the data to the database, convert data from the Data Set to .NET
objects or vice-versa. It creates the difficulties for developers and also it
was the error-prone process, then “Entity Framework” comes to
automate all these database related activities for the application. So, Entity
Framework allows the developers to work at a higher level of abstraction.
Note : REST (Representational State Transfer) and AJAX were added
in .Net Framework 3.5 as an extension and services of ASP.NET for
enhancing web services of .NET Framework.
10. Parallel LINQ (Language Integrated Query) : It comes in .Net Framework
version
4.0 and also termed as PLINQ. It provides a concurrent query execution
engine for LINQ. It executes the LINQ in parallel such that it tries to use as
much processing power system on which it is executing.
11. TPL (Task Parallel Library) : It is a set of public types and APIs. It
allows the developers to be more productive by simplifying the process of
adding concurrency and parallelism to .Net applications.
12. .NET API For Store/UWP Apps : In 2012, Microsoft added some
APIs for creating UWP(Universal Windows Platform) apps for Windows
using C# or VB.
13. Task-Based Asynchronous Model : It is model used to describe
the asynchronous operations and tasks in .Net Framework.

C# | Data Types
Data types specify the type of data that a valid C# variable can hold. C# is
a strongly typed programming language because in C#, each type of
data (such as integer, character, float, and so forth) is predefined as part
of the programming language and all constants or variables defined for a
given program must be described with one of the data types.
Data types in C# is mainly divided into three categories
● Value Data Types
● Reference Data Types
● Pointer Data Type
1. Value Data Types : In C#, the Value Data Types will directly store the
variable value in memory and it will also accept both signed and
unsigned literals. The derived class for these data types are
System.ValueType. Following are different Value Data
Types in C# programming language :
● Signed & Unsigned Integral Types : There are 8 integral
types which provide support for 8-bit, 16-bit, 32-bit, and 64-bit
values in signed or unsigned form.
DEFAULT

ALIAS TYPE NAME TYPE SIZE(BITS) RANGE VALUE

sbyte System.Sbyte signed integer 8 -128 to 127 0

-32768 to

short System.Int16 signed integer 16 32767 0

Int System.Int32 signed integer 32 -231 to 231-1 0

long System.Int64 signed integer 64 -263 to 263-1 0L

unsigned

byte System.byte integer 8 0 to 255 0

unsigned

ushort System.UInt16 integer 16 0 to 65535 0

unsigned

uint System.UInt32 integer 32 0 to 232 0

unsigned

ulong System.UInt64 integer 64 0 to 263 0


● Floating Point Types :There are 2 floating point data types
which contain the decimal point.
● Float: It is 32-bit single-precision floating point type. It has 7
digit Precision. To initialize a float variable, use the suffix f or
F. Like, float x = 3.5F;. If the suffix F or f will not use then it is
treated as double.
● Double:It is 64-bit double-precision floating point type. It
has 14 – 15 digit Precision. To initialize a double variable, use
the suffix d or D. But it is not mandatory to use suffix because
by default floating data types are the double type.
DEFAULT

ALIAS TYPE NAME SIZE(BITS) RANGE (APROX) VALUE

±1.5 × 10-45 to ±3.4 ×

float System.Single 32 0.0F


1038

±5.0 × 10-324 to ±1.7 ×

double System.Double 64 0.0D


10308

● Decimal Types : The decimal type is a 128-bit data type suitable


for financial and monetary calculations. It has 28-29 digit Precision.
To initialize a decimal variable, use the suffix m or M. Like as,
decimal x = 300.5m;. If the suffix m or M will not use then it is
treated as double.
DEFAULT

ALIAS TYPE NAME SIZE(BITS) RANGE (APROX) VALUE

±1.0 × 10-28 to ±7.9228

decimal System.Decimal 128 × 1028 0.0M

● Character Types : The character types represents a UTF-16 code


unit or represents the 16-bit Unicode character.
SIZE DEFAULT

ALIAS TYPE NAME IN(BITS) RANGE VALUE

U +0000 to U

char System.Char 16 +ffff ‘\0’

Example :

// C# program to demonstrate
// the above
data types
usingSystem;
namespaceVal
ueTypeTest {

classGeeksforGeeks {

//
Main
func
tion
stat
icvo
idMa
in()
{

//
declaring
character
chara =
'G';

// Integer data type is generally


// used for
numeric values
inti = 89;

shorts = 56;

// this will give error as number


// is larger than short range
// short s1 = 87878787878;

// long uses Integer values which


// may signed
or unsigned
longl = 4564;

// UInt data type is generally


// used for unsigned
integer values uintui =
95;

ushortus = 76;
// this will give error as number is
// larger than short range

// ulong data type is generally


// used for unsigned
integer values ulongul
= 3624573;
// by default fraction value
// is
double in
C# doubled
=
8.35867453
2;

// for float use


'f' as suffix
floatf =
3.7330645f;

// for float use


'm' as suffix
decimaldec =
389.5m;

Console.WriteLine("char: "+ a);


Console.WriteLine("integer: "+
i); Console.WriteLine("short: "+
s); Console.WriteLine("long: "+
l); Console.WriteLine("float: "+
f); Console.WriteLine("double:
"+ d);
Console.WriteLine("decimal: "+
dec);
Console.WriteLine("Unsinged
integer: "+ ui);
Console.WriteLine("Unsinged
short: "+ us);
Console.WriteLine("Unsinged
long: "+ ul);
}
}
}
Output :
Example :

// C# program to demonstrate the Sbyte


// signed
integral data
type
usingSystem;
namespaceValueTy
peTest {

classGeeksforGeeks {
//
Main
func
tion
stat
icvo
idMa
in()
{
sbytea = 126;

// sbyte is 8 bit
// singned
value
Console.Wr
iteLine(a)
;

a++;
Console.WriteLine(a);

// It overflows here because


// byte can hold values
// from
-128 to
127
a++;
Console.WriteLine(a);

// Looping back within


/
/
t
h
e
r
a
n
g
e
a
+
+
;
Console.WriteLine(a);
}
}
}
Output :
Example :

Output :

Boolean Types : It has to be assigned either true or false value.


Values of type bool are not converted implicitly or explicitly (with casts)
to any other type. But the programmer can easily write conversion
code.
ALIAS TYPE NAME VALUES

bool System.Boolean True / False

Example :

// C# program to demonstrate the


// boolean
data type
usingSystem;
namespaceVal
ueTypeTest {

classGeeksforGeeks {

//
Main
func
tion
stat
icvo
idMa
in()
{

//
boolean
data
type
boolb =
true;
if(b == true)
Console.WriteLine("Hi Geek");
}
}
}
Output :
Hi Geek

2. Reference Data Types : The Reference Data Types will contain


a memory address of variable value because the reference types won’t
store the variable value directly in memory. The built-in reference types
are string, object.
● String : It represents a sequence of Unicode characters and
its type name is System.String. So, string and String are
equivalent.
Example :

● Object : In C#, all types, predefined and user-defined, reference types


and value
types, inherit directly or indirectly from Object. So basically it is the
base class for all the data types in C#. Before assigning values, it
needs type conversion. When a variable of a value type is converted
to object, it’s called boxing. When a variable of type object is
converted to a value type, it’s called unboxing. Its type name
is System.Object.

Example :
// C# program to demonstrate
// the
Reference data
types
usingSystem;
namespaceValueT
ypeTest {

classGeeksforGeeks {

//
Main
Func
tion
stat
icvo
idMa
in()
{

//
declari
ng
string
stringa
=
"Geeks"
;

/
/
a
p
p
e
n
d
i
n
a
a
+
=
"
f
o
r
"
;
a =
a+"Geeks";
Console.Wr
iteLine(a)
;

//
declare
object
obj
objectobj
;
obj = 20;
Console.WriteL
ine(obj);

// to show type of object


// using GetType()
Console.WriteLine(obj.G
etType());
}
}
}
Output :

3. Pointer Data Type : The Pointer Data Types will contain a


memory address of the variable value.
To get the pointer details we have a two symbols ampersand (&) and
asterisk (*). ampersand (&): It is Known as Address Operator. It is
used to determine the address of a variable.
asterisk (*): It also known as Indirection Operator. It is used to access
the value of an address.
Syntax :
type* identifier;

Example :
int* p1, p; // Valid syntax
int *p1, *p; // Invalid

Example :

// Note: This program will not work on


// online compiler
// Error: Unsafe code requires the `unsafe'
// command line option to be specified
// For its solution:
// Go to your project properties page and
// check under Build the checkbox Allow
// unsafe
code.
usingSystem;
namespacePoin
terprogram {

classGFG {

//
Main
func
tion
stat
icvo
idMa
in()
{
unsafe
{

//
declare
variabl
e intn
= 10;

// store variable n address


// location in pointer
variable p int* p = &n;
Console.WriteLine("Valu
e :{0}", n);
Console.WriteLine("Address :{0}", (int)p);
}
}
}
}

You might also like