Unit3 Notes
Unit3 Notes
DIAGNOSTICS
Diagnostics provides a set of attributes and classes to interact with the system
process, event managers, performance counts etc. This namespace can help us
too in debugging jobs.
CODE CONTRACTS
Code contracts provide a way to specify preconditions, postconditions, and
object invariants in your code. Preconditions are requirements that must be met
when entering a method or property. Postconditions describe expectations at the
time the method or property code exits. Object invariants describe the expected
state for a class that is in a good state.
The preconditions specify what requirements the parameters must fulfill, the
postconditions define the requirements on returned data, and the invariants
define the requirements of variables within the method itself.Code contracts
include classes for marking your code, a static analyzer for compile-time
analysis, and a runtime analyzer. The classes for code contracts can be found in
the System.Diagnostics.Contracts namespace.
The benefits of code contracts include the following:
Improved testing: Code contracts provide static contract verification, runtime
checking, and documentation generation.
Automatic testing tools: You can use code contracts to generate more
meaningful unit tests by filtering out meaningless test arguments that do not
satisfy preconditions.
Static verification: The static checker can decide whether there are any contract
violations without running the program. It checks for implicit contracts, such as
null dereferences and array bounds, and explicit contracts.
Code contracts are defined with the Contract class. All contract requirements
that you define in a method,whether they are preconditions or
postconditions, must be placed at the beginning of the method.
Preconditions
Preconditions check the parameters that are passed to a method. With the
Contract class, preconditions are defi ned with the Requires method. With
the Requires method, a Boolean value must be passed, and an optional
message string with the second parameter that is shown when the condition
does not succeed. The
following example requires that the argument min be less than or equal to
the argument max:
static void MinMax(int min, int max)
{
Contract.Requires(min <= max);
//...
}
The Following precondition expresses that x must not be null
Contract.Requires(x != null);
If the code throw a exception on failure of precondition you can use generic
overload of Require
Contract.Requires<ArgumentNullException>(x != null, "x");
postConditions
Postconditions are contracts for the state of a method when it terminates. The
postcondition is checked just before exiting a method. The run-time behavior
of failed postconditions is determined by the runtime analyzer.
Unlike preconditions, postconditions may reference members with less
visibility. A client may not be able to understand or make use of some of the
information expressed by a postcondition using private state, but this does
not affect the client's ability to use the method correctly.
Postconditions define guarantees about shared data and return values after
the method has completed.
Although they define some guarantees on return values, they must be written
at the beginning of a method;all contract requirements must be at the
beginning of the method.
Ensures and EnsuresOnThrow<TException> are postconditions. The
following contract ensures that the
variable sharedState is less than 6 at the end of the method (the value can
change in between):
private static int sharedState = 5;
static void Postcondition()
{
Contract.Ensures(sharedState < 6);
sharedState = 9;
Console.WriteLine("change sharedState invariant {0}", sharedState);
sharedState = 3;
Console.WriteLine("before returning change it to a valid value {0}",
sharedState);
}
invariants
Invariants define contracts for variables during the object’s lifetime.
Contract.Requires defines input requirements of a method, and
Contract.Ensures defines requirements on method end.
Contract.Invariant defines conditions that must succeed during the whole
lifetime of an object.The following code snippet shows an invariant check of the
member variable x, which must be larger than 5. With the initialization of x, x is
initialized to 10, which fulfi lls the contract.
The call to Contract.Invariant can only be placed within a method that has the
ContractInvariantMethod attribute applied.
This method can be public or private, can have any name (the name
ObjectInvariant is suggested), and can only contain contract invariant checks.
private int x = 10;
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(x > 5);
}
Tracing
Tracing enables you to see informational messages about the running
application. To get information about a running application, you can start the
application in the debugger. During debugging, you can walk through the
application step by step and set breakpoints at specific lines and when you reach
specific conditions.
The tracing architecture has four major parts:
➤ Source — The originator of the trace information. You use the source to
send trace messages.
➤ Switch — Defines the level of information to log. For example, you can
request just error information or detailed verbose information.
➤ Listeners — Trace listeners define the location to which the trace messages
should be written.
➤ Filters — Listeners can have filters attached. The filter defines what trace
messages should be written by the listener.
Tracing- source
To write trace messages, you need to create a new TraceSource instance. In the
constructor, the name of the trace source is defined. The method
TraceInformation writes an informational message to the trace output. Instead
of just writing informational messages, the
TraceEvent method requires an enumeration value of type TraceEventType to
define the type of the trace message. TraceEventType.Error specifies the
message as an error message. You can define it with a trace switch to see only
error messages.
public class Program
{
internal static TraceSource trace = new
TraceSource("Wrox.ProCSharp.Instrumentation");
static void TraceSourceDemo1()
{
trace.TraceInformation("Info message");
trace.TraceEvent(TraceEventType.Error, 3, "Error message");
trace.TraceData(TraceEventType.Information, 2, "data1", 4, 5);
trace.Close();
}
Trace Switches
To enable or disable trace messages, you can confi gure a trace switch. Trace
switches are classes derived from the abstract base class Switch. SourceLevels
defi nes the values Off,Error, Warning, Info, and Verbose.
internal static SourceSwitch traceSwitch =
new SourceSwitch("Wrox.ProCSharp.Diagnostics")
{ Level = SourceLevels.Verbose };
internal static TraceSource trace =
new TraceSource("Wrox.ProCSharp.Diagnostics")
{ Switch = traceSwitch };
Setting the level to Verbose means that all trace messages should be written.
If you set the value to Error,only error messages are displayed. Setting the value
to Information means that error, warning, and infomessages are shown. By
writing the trace messages once more, you can see the messages while running
the debugger in the Output window.
Trace listeners
• By default, trace information is written to the Output window of the
Visual Studio debugger; but by changing the application’s confi guration,
you can redirect the trace output to different locations.
• Where the tracing results should be written to is defi ned by trace
listeners. A trace listener is derived from the abstract base class
TraceListener.
Trace Filters
Every listener has a Filter property that defi nes whether the listener should
write the trace message.For example, multiple listeners can be used with the
same trace source. One of the listeners writes verbose messages to a log fi le,
and another listener writes error messages to the event log. Before a listener
writes a trace message, it invokes the ShouldTrace method of the associated fi
lter object to determine whether the trace message should be written.
A filter is a class that is derived from the abstract base class TraceFilter. .NET
offers two filterimplementations: SourceFilter and EventTypeFilter. With the
source filter, you can specify that trace messages are to be written only from
specifi c sources. The event type filter is an extension of the switchfunctionality.
EVENT LOGGING
System administrators use the Event Viewer to get critical messages about the
system and applications, and informational messages.
Event log information is stored in several log files. The most important ones are
application, security, and system. Looking at the registry configuration of the
event log service, you will notice several entries under
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Eventlog
with configurations pointing to the specific files.
The system log file is used from the system and device drivers. Applications
and services write to the application log. The security log is a read-only log for
applications.
The event log contains the following information:
• ➤ Type — The main types are Information, Warning, or Error.
Information is an infrequently used type that denotes a successful
operation; Warning denotes a problem that is not immediately signifi
cant;and Error denotes a major problem. Additional types are
FailureAudit and SuccessAudit, but these types are used only for the
security log.
• ➤ Date — Date and Time show the day and time that the event occurred.
• ➤ Source — The Source is the name of the software that logs the event.
• Event-Logging Classes
The System.Diagnostics namespace has the following classes for event
logging.
CLASS DESCRIPTION
EventLog With the EventLog class, you can read and write entries in the event
log,and establish applications as event sources.
EventLogEntry The EventLogEntry class represents a single entry in the event
log. With the EventLogEntryCollection, you can iterate through EventLogEntry
items.
EventLogInstaller The EventLogInstaller class is the installer for an
EventLogcomponent. EventLogInstaller calls EventLog.CreateEventSource to
create an event source.
EventLogTraceListener With the help of the EventLogTraceListener, traces can
be written to theevent log. This class implements the abstract class
TraceListener
using System;
using System.Diagnostics;
using System.Threading;
class MySample{ public static void Main()
{
// Create the source, if it does not already exist.
if(!EventLog.SourceExists("MySource"))
{ //An event log source should not be created and immediately used. //There
is a latency time to enable the source, it should be created //prior to
executing the application that uses the source. //Execute this sample a second
time to use the new source.
EventLog.CreateEventSource("MySource", "MyNewLog");
Console.WriteLine("CreatedEventSource");
Console.WriteLine("Exiting, execute the application a second time to use
the source.");
// The source is created. Exit the application to allow it to be registered.
return;
} // Create an EventLog instance and assign its source.
EventLog myLog = new EventLog();
myLog.Source = "MySource";
// Write an informational entry to the event log. myLog.WriteEntry("Writing
to event log."); } }
Performance monitoring
Performance monitoring can be used to get information about the normal
behavior of applications,to compare ongoing system behavior with
previously established norms, and to observe changes and trends,
particularly in applications running on the server
Performance-Monitoring Classes
The System.Diagnostics namespace provides the following classes for
performance monitoring:
➤ PerformanceCounter — Can be used both to monitor counts and to write
counts. New performancecategories can also be created with this class.
➤ PerformanceCounterCategory — Enables you to step through all existing
categories, as well as create new ones. You can programmatically obtain all
the counters in a category.
➤ PerformanceCounterInstaller — Used for the installation of performance
counters. Its use issimilar to that of the EventLogInstaller.
MultiThreading
A Thread is defined as the execution path of the program.It is used to run
applications that performs large and complex computations.The execution of
C# program starts with a single thread called the main thread that is
automatically run by the CLR and OS.From main thread we can create other
thread.The process of developing a program for execution with multiple
threads is called Multithreading programming and the process of execution is
called Multithreading.
System.Threading is the namespace contain classes and interfaces for
Multithreading
In c# ,Thread class is used to work with threads.The First thread to be
executed in a process is called the Main Thread.
Main Thread
The Main thread is created automatically on the start up of a c# program
execution.Thread which is created using Thread class is called as Child
threads ,where the main thread is called parent thread or primary thread.You
can access a thread using CurrentThread property of the Thread class
using System;
using System.Threading;
class MainThreadProgram
{
public static void Main()
{
Thread th = Thread.CurrentThread;
th.Name = "MainThread";
Console.WriteLine("This is {0}", th.Name);
}}
o/p
This is called Main Thread
Working with threads
In c#,you create a thread by creating an object of type Thread,giving its
constructor ThreadStart reference and calling the new thread’s Start()
method.There are various methods available with the Thread class.Few of
these methods are,
Start(): start a thread
Sleep():Makes the thread to pause for a period of time
Abort():Terminates the Thread
Suspend():Suspend a thread.
Resume():Resumes the suspended thread
using System;
using System.Threading;
class ThreadCreationProgram
{
public static void CallToChildThread()
{
Console.WriteLine("Child thread starts");
}
public static void Main()
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
}}
o/p
In Main: Creating the Child thread
Child thread starts
using System;
using System.Threading;
class ThreadCreationProgram
{
public static void CallToChildThread()
{
Console.WriteLine("Child thread starts");
// the thread is paused for 5000 milliseconds
int sleepfor = 5000;
Console.WriteLine("Child Thread Paused for {0} seconds", sleepfor / 1000);
Thread.Sleep(sleepfor);
Console.WriteLine("Child thread resumes");
}
public static void Main()
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
}}
o/p
In Main: Creating the Child thread
Child thread starts
Child Thread Paused for 5 seconds
Child thread resumes
Destroying Threads
using System;
using System.Threading;
class ThreadCreationProgram
{
public static void CallToChildThread()
{
try
{
Console.WriteLine("Child thread starts");
for (int counter = 0; counter <= 10; counter++) {
Thread.Sleep(500);
Console.WriteLine(counter);
}
Console.WriteLine("Child Thread Completed");
}
catch (ThreadAbortException e)
{
Console.WriteLine("Thread Abort Exception");
}
finally
{
Console.WriteLine("Couldn't catch the Thread Exception");
}}
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start(); //stop the main thread for some time
Thread.Sleep(2000); //now abort the child
Console.WriteLine("In Main: Aborting the Child thread");
childThread.Abort();} }
o/p
In Main: Creating the Child thread
Child thread starts
012
In Main: Aborting the Child thread Thread
Abort Exception Couldn't catch the Thread Exception
• Thread Life Cycle
The life cycle of a thread starts when an object of the
System.Threading.Thread class is created and ends when the thread is
terminated or completes execution.
Following are the various states in the life cycle of a thread −
The Unstarted State − It is the situation when the instance of the thread is
created but the Start method is not called.
The Ready State − It is the situation when the thread is ready to run and
waiting CPU cycle.
The Not Runnable State − A thread is not executable, when
Sleep method has been called
Wait method has been called
Blocked by I/O operations
The Dead State − It is the situation when the thread completes execution or
is aborted.
PARALLEL CLASS
• One great abstraction of threads is the Parallel class. With this class, both
data and task parallelism is offered. This class is in the namespace
System.Threading.Tasks.
• The Parallel class defines static methods for a parallel for and foreach.
With the C# statements for and foreach, the loop is run from one thread.
The Parallel class uses multiple tasks and, thus, multiple threads for this
job.
• While the Parallel.For and Parallel.ForEach methods invoke the same
code during each iteration,Parallel.Invoke allows you to invoke different
methods concurrently.
• Parallel.Invoke is for taskparallelism,
Parallel.ForEach for data parallelism.
• Looping with the Parallel.For Method
• The Parallel.For method is similar to the C# for loop statement to perform
a task a number of times.With Parallel.For, the iterations run in parallel.
The order of iteration is not defined.
• With the For method, the first two parameters define the start and end of
the loop. The following example has the iterations from 0 to 9. The third
parameter is an Action<int> delegate. The integer parameter is the
iteration of the loop that is passed to the method referenced by the
delegate
• ParallelLoopResult result = Parallel.For(0, 10, i =>
• {
• Console.WriteLine("{0}, task: {1}, thread: {2}", i,
• Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
• Thread.Sleep(10);
• });
• Console.WriteLine("Is completed: {0}", result.IsCompleted);
• o/p
• 0, task: 1, thread: 1
• 2, task: 2, thread: 3
• 4, task: 3, thread: 4
• 6, task: 4, thread: 5
• 8, task: 5, thread: 6
• 5, task: 3, thread: 4
• 7, task: 4, thread: 5
• 9, task: 5, thread: 6
Invoking Multiple Methods with the Parallel.Invoke Method
If multiple tasks should run in parallel, you can use the Parallel.Invoke
method, which offers the task parallelism pattern. Parallel.Invoke allows the
passing of an array of Action delegates, whereby you can assign methods
that should run.
static void ParallelInvoke()
{
Parallel.Invoke(print, disp);
}
static void print()
{
Console.WriteLine(“good");
}
static void disp()
{
Console.WriteLine("bad");
}
ThreadPools
• When you have different short tasks to do, you can create a number of
threads in advance and send requests as they should be done. It would be
nice if this number of threads increased as more were needed, and
decreased as needed to release resources.
• There is no need to create such a list on your own. The list is managed by
the ThreadPool class. This class increases and decreases the number of
threads in the pool as they are needed, up to the maximum number of
threads, which is configurable
• Background Threads
• The process of the application keeps running as long as at least one
foreground thread is running. If more than one foreground thread is
running and the Main method ends, the process of the application remains
active until all foreground threads finish their work.
• A thread you create with the Thread class, by default, is a foreground
thread. Thread pool threads are always background threads
ThreadPriority
In C# thread can be scheduled by setting the priority of the thread using
Priority property of the Thread class.
Highest
Lowest
Normal
AboveNormal
BelowNormal
using System;
using System.Threading;
class sample
{
public static void child1()
{
Console.WriteLine(“thread1 started”);
for(int t=1;t<11;t++)
{
Console.WriteLine(“{0}”,t)
}
Console.WriteLine(“thread1 completed”);
}
public static void child2()
{
Console.WriteLine(“thread2 started”);
for(int t=1;t<11;t++)
{
Console.WriteLine(“{0}”,t)
}
Console.WriteLine(“thread2 completed”);
}
public static void Main()
{
ThreadStart c1=new ThreadStart(child1);
ThreadStart c2=new ThreadStart(child2);
Thread t1=new Thread(c1);
Thread t2=new Thread(c2);
t1.Priority=ThreadPriority.Highest;
t2.Priority=ThreadPriority.Lowest;
t1.Start();
t2.Start();
}
}
SYNCHRONIZATION
• It is best to avoid synchronization issues by not sharing data between
threads. Of course, this is not always possible. If data sharing is
necessary, you must use synchronization techniques so that only one
thread at a time accesses and changes shared state.
• synchronization technologies that you can use with multiple threads:
• ➤ lock statement
• ➤ Interlocked class
• ➤ Monitor class
• ➤ SpinLock struct
• ➤ WaitHandle class
• ➤ Mutex class
• ➤ Semaphore class
• ➤ Events classes
• ➤ Barrier class
• ➤ ReaderWriterLockSlim class
lock, Interlocked, and Monitor classes for synchronization within a process. The
classes Mutex, Event, SemaphoreSlim, and ReaderWriterLockSlim also offer
synchronization among threads of multiple processes
The lock Statement and Thread Safety
C# has its own keyword for the synchronization of multiple threads: the lock
statement. The lock statement provides an easy way to hold and release a
lock.
using System;
using System.Threading;
class sample
{
public void write(string data)
{
Lock(this)
{
Console.WriteLine(“data started”);
for(int c=0;c<100;c++)
{
Console.WriteLine(data);
}
Console.WriteLine(“data ended”);
• }}}
• class test
• {
sample s=new sample();
public static void child1()
{
Console.WriteLine(“thread1 started”);
s.write(“t1”);
}
public static void child2()
{
Console.WriteLine(“thread2 started”);
s.write(“t2”);
}
public static void Main()
{
ThreadStart c1=new ThreadStart(child1);
ThreadStart c2=new ThreadStart(child2);
Console.WriteLine(“main thread started”);
Thread t1=new Thread(c1);
Thread t2=new Thread(c2);
t1.Start();
t2.Start();
}
O/P
main thread started
thread1 started
thread2 started
data started
T1t1t1t1t1t1
data ended
data started
T2t2t2t2t2t2
data ended
• Monitor class
The System.Monitor class enables to serialize the access to blocks of codes.
using System;
using System.Threading;
class sample
{
public void write(string data)
{
• Monitor.Enter(this)
• {
• Console.WriteLine(“data started”);
• for(int c=0;c<100;c++)
• {
• Console.WriteLine(data);
• }
• Console.WriteLine(“data ended”);
• Monitor.Exit(this);
• }}}
• class test
• {
sample s=new sample();
public static void child1()
{
Console.WriteLine(“thread1 started”);
s.write(“t1”);
}
public static void child2()
{
Console.WriteLine(“thread2 started”);
s.write(“t2”);
}
public static void Main()
{
ThreadStart c1=new ThreadStart(child1);
ThreadStart c2=new ThreadStart(child2);
Console.WriteLine(“main thread started”);
Thread t1=new Thread(c1);
Thread t2=new Thread(c2);
t1.Start();
t2.Start();
}
Interlocked
The Interlocked class is used to make simple statements for variables atomic.
i++ is not thread-safe. It consists of getting a value from the memory,
incrementing the value by 1, and storing the value back in
memory. These operations can be interrupted by the thread scheduler. The
Interlocked class provides methods for incrementing, decrementing,
exchanging, and reading values in a thread-safe manner.
Using the Interlocked class is much faster than other synchronization
techniques. However, you can use it only for simple synchronization issues.
SpinLock
If the overhead on object-based lock objects (Monitor) would be too high
because of garbage collection,the SpinLock struct can be used. Available
since .NET 4, SpinLock is useful if you have a large number of locks (for
example, for every node in a list) and hold times are always extremely short.
WaitHandle
WaitHandle is an abstract base class that you can use to wait for a signal to
be set. You can wait for different things, because WaitHandle is a base class
and some classes are derived from it.
Mutex class
A Mutex is a synchronisation primitive that helps to perform interprocess
synchronisation.Mutex allows a thread to have a exclusive access to shared
resources.
• Semaphore
• A semaphore is very similar to a mutex; but unlike the mutex, the
semaphore can be used by multiple threads at once. A semaphore is a
counting mutex, meaning that with a semaphore you can define the
number of threads that are allowed to access the resource guarded by the
semaphore simultaneously
Security
AUTHENTICATION AND AUTHORIZATION
• Two fundamental pillars of security are authentication and authorization.
Authentication is the process identifying the user, and authorization
occurs afterward to verify that the identified user is allowed to access a
specific resource.
• Identity and Principal
• You can identify the user running the application by using an identity.
The WindowsIdentity class represents a Windows user. If you don’t
identify the user with a Windows account, you can use other classes that
implement the interface IIdentity. With this interface you have access to
the name of the user,information about whether the user is authenticated,
and the authentication type.
• A principal is an object that contains the identity of the user and the roles
to which the user belongs. The interface IPrincipal defines the property
Identity, which returns an IIdentity object, and the method IsInRole with
which you can verify that the user is a member of a specific role.
• A role is a collection of users who have the same security permissions,
and it is the unit of administration for users. Roles can be Windows
groups or just a collection of strings that you define. Role-based security
is especially useful when access to resources is an issue. A primary
example is the finance industry, in which employees’ roles define what
information they can access and what actions they can perform.
• The principal classes available with .NET are WindowsPrincipal,
GenericPrincipal, and RolePrinciplal
using System;
using System.Security;
using System.Security.Principal;
using System.Security.Permissions;
class Program
{
public static void Main()
{
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPri
ncipal);
try
{
ShowMessage();
}
catch (SecurityException exception)
{
Console.WriteLine("Security exception caught ({0})",exception.Message);
Console.WriteLine("The current principal must be in the local" +"Users
group");
}
}
[PrincipalPermission(SecurityAction.Demand, Role = "BUILTIN\\Users")]
static void ShowMessage()
{
Console.WriteLine("The current principal is logged in locally ");
Console.WriteLine("(member of the local Users group)");
}
}
}
o/p
The current principal is logged in locally
(member of the local Users group)
• The .NET Framework contains classes for encryption in the namespace
System.Security.Cryptography.Several symmetric and asymmetric
algorithms are implemented.
• CODE ACCESS SECURITY
• Similar to role-based security, which enables you to defi ne what the user
is allowed to do, code access security defines what the code is allowed to
do. The code is grouped into three categories:
• ➤ Security-critical — Any code can run. This code cannot be called by
transparent code.
• ➤ Safe-critical — Code can be called by transparent code. Security verifi
cations are done with this code.
• ➤ Transparent — Code is very limited in what it can do. This code is
allowed to run in a specifiedpermission set and it runs in a sandbox. It
cannot contain unsafe or unverifiable code, and it cannot call security-
critical code.
Permissions
Permissions refer to the actions that each code group is allowed to perform
(or is prevented from performing). For example, permissions include “read fi
les from the file system,” “write to the Active Directory,” and “use sockets
to open network connections.” Several predefined permissions exist, but you
can also create your own permissions.
.NET permissions are independent of operating system permissions. .NET
permissions are just verifiedby the CLR.
PERMISSION DESCRIPTION
DirectoryServicesPermission Controls access to Active
Directory through the
System.DirectoryServices
classes
EnvironmentPermission Controls the use of read
and write environment
variables
FileDialogPermission Controls access to fi les
that have been selected
by the userin the Open
dialog. This permission is
commonly used
whenFileIOPermission is
not granted in order to
maintain limited access to
fi les.
FileIOPermission Controls the ability to
work with fi les (reading,
writing, and appending to
fi les, as well as creating,
altering, and accessing
folders)
SecurityPermission Controls the ability to
execute, assert
permissions, call into
unmanaged code, skip
verification, and other
rights
RegistryPermission Controls the ability to
read, write, create, or
delete registry keys and
values
• A permission set is a collection of permissions. Using a permission set, it
is not necessary to apply every single permission to code; permissionns
are grouped into a permission set.
• The following list explains the seven named permission sets
• included out of the box:
• ➤ FullTrust — No permission restrictions.
• ➤ SkipVerifi cation — Verifi cation is not performed.
• ➤ Execution — Grants the ability to run, but not access, any protected
resources.
• ➤ Nothing — Grants no permissions and prevents the code from
executing.
• ➤ LocalIntranet — Specifies a subset of the full set of permissions. For
example, fi le I/O is restricted to
• read access on the share where the assembly originates..
• ➤ Internet — Specifi es the default policy for code of unknown origin.
This is the most restrictive policy.
• For example, code executing in this permission set has no fi le I/O
capability, cannot read or write event logs, and cannot read or write
environment variables.
• ➤ Everything — Grants all the permissions listed under this set, except
the permission to skip code
• verifi cation. The administrator can alter any of the permissions in this
permission set. This is usefulwhen the default policy needs to be tighter.
• The ability to browse and locate files and directories for a specific
directory is essential for many tasks.You can work with files and
directories by using
• FileInfo and File — These classes represent a file on the file
system.System.IO is a nammespace
• ➤ DirectoryInfo and Directory — These classes represent a folder on
the file system.It is derived from FileSystemInfo class
• PROPERTY DESCRIPTION
• CreationTime : Indicates when the fi le or folder
was created
• DirectoryName (FileInfo only) : Full pathname of the containing
folder
• Parent (DirectoryInfo only) :The parent directory of a specifi ed
subdirectory
• Exists : Specifi es whether a fi le or folder
exists
• Extension :Extension of the file; it returns
blank for folders
• FullName :Full pathname of the fi le or folder
• LastAccessTime :Indicates when the fi le or folder
was last accessed
• LastWriteTime :Indicates when the fi le or folder
was last modifi ed
• Name :Name of the fi le or folder
• Root (DirectoryInfo only) :The root portion of the path
Length (FileInfo only) :Size of the fi le, in bytes
METHOD DESCRIPTION
Create() : Creates a folder or empty fi le of the given name. For a FileInfo
this also returns a
stream object to let you write to the fi le.
Delete() : Deletes the fi le or folder. For folders, there is an option for the
Delete to be
recursive.
MoveTo() : Moves and/or renames the fi le or folder.
CopyTo() (FileInfo only) : Copies the fi le. Note that there is no copy method
for folders. If
you are copying complete directory trees you need to individually copy each file
and create new folders corresponding to the old folders.
GetDirectories() (DirectoryInfo only) :Returns an array of DirectoryInfo objects
representing all folders contained in this folder.
GetFiles() (DirectoryInfo only) :Returns an array of FileInfo objects
representing alfi les contained in this folder.
FileInfo class is derived from the FileSystemInfo class.
property descriptions
Attributes Get or Set attribute associated with current file
CreationTime Get or Set CreationTime of the current time
Directory Get an instance of the directory
Exists Get a Boolean value indicating whether file
exist or not
FullName Get a string containing the full path of thefile
LastAccessTim Get the last accessed time of the file
e
LastWriteTime Get the time of the last written activity to the
file
Length Get the size of the file
Name Get a string containing the name of a file
method Descriptions
Create() Creates a file
AppendText( Append a text to the file
)
Delete() Delete a file
Open() Opens a file
OpenRead() Open a file in read-only mode
• using System;
• using System.IO;
• class sample
• {
• public static void Main()
• {
• DirectoryInfo dir=new DirectoryInfo(@”c:\sa”);// creating a directory
• FileInfo[] f=dir.GetFiles();//to get all files
• foreach(FileInfo f1 in f)
• {
• Console.WriteLine(f1.Name,f1.Length);
• }}}
• FileStream Class
• Syntax
• FileStream obj=new FileStream(filename,filemode enumerator,file access
enumerator,fileshare);
• Eg
• FileStream f=new
FileStream(“abc.txt”,FileMode.open,FileAccess.Read,FileShare.Read);
• FileMode Enumerator
property descriptions
Create Creates a file
Open Open a existing file
OpenOrCreate Specifies to the operating system that it should
open a file if it exist or it creates a file
Truncate Open a existing file.when opened file should be
truncated so that size is zero
Append Append a data to the end of the file
•
• FileAccess enumerator
• Members are Read,Write and ReadWrite
• FileShare Enumerator
•
property descriptions
None Declines the sharing of a current file
Read Read operations
Write Write Operations
Readwrite Both read and write oerations
•
• StreamReader is inherited from the abstract class TextReader.Stream
class is used to read from and to write data in the text files.
• StreamReader class
Methods Descriptions
Close Closes the file object
Peek Returns the next available character
Read Read the next character
Seek Allows the read/Write position to be
moved to any position
StreamWriter class
Methods Descriptions
Close Closes the file object
Flush Clears the buffer
Write Write to the stream
using System;
using System.IO;
class sample
{
public void print()
{
FileStream fs=new FileStream(“a.txt”,FileMode.Open,FileAcces.Read);
StreamReader sr=new StreamReader(fs);
String str=sr.ReadLine();
While(str!=null)
{
Console.WriteLine(str);
Str=sr.ReadLine();
}
sr.Close();
fs.Close();
public static void Main()
{
Sample s=new sample();
s.print();
}}
using System;
using System.IO;
class sample
{
public void print()
{
FileStream fs=new FileStream(“a.txt”,FileMode.Append,FileAcces.Write);
StreamWriter sr=new StreamWriter(fs);
String str=Console.ReadLine();
Sr.Write(str);
sr.Close();
fs.Close();
public static void Main()
{
Sample s=new sample();
s.print();
}}
Registry
• The registry has been the central repository for all configuration
information relating to Windows setup, user preferences, and installed
software and devices. Almost all commercial software these days uses the
registry to store information about itself.
• The Registry
• The registry has a hierarchical structure much like that of the fi le system.
The usual way to view or modify the contents of the registry is with one
of two utilities: regedit or regedt32. Of these, regedit is standard with all
versions of Windows since Windows 95. regedt32 is included with
Windows NT and Windows 2000
• REGEDIT:
• ➤ HKEY_CLASSES_ROOT (HKCR) contains details of types of fi les
on the system (.txt, .doc, and soon) and which applications are able to
open files of each type. It also contains registration information for all
COM components
• ➤ HKEY_CURRENT_USER (HKCU) contains details of user
preferences for the user currently logged on to the machine locally. These
settings include desktop settings, environment variables, network and
printer connections, and other settings that define the operating
environment of the user.
• ➤ HKEY_LOCAL_MACHINE (HKLM) is a huge hive that contains
details of all software and hardware installed on the machine. These
settings are not user-specific but for all users that log on to the machine.
This hive also includes the HKCR hive;
• ➤ HKEY_USERS (HKUSR) contains details of user preferences for all
users
• ➤ HKEY_CURRENT_CONFIG (HKCF) contains details of hardware on
the machine.
• The remaining two keys contain information that is temporary and
changes frequently:
• ➤ HKEY_DYN_DATA is a general container for any volatile data that
needs to be stored somewhere in the
• registry.
➤ HKEY_PERFORMANCE_DATA contains information concerning the
performance of running applications.
Localization
• 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 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.
• NAMESPACE SYSTEM.GLOBALIZATION
• The System.Globalization namespace holds all the culture and region
classes necessary to support different date formats, different number
formats, and even different calendars that are represented in classes such
as GregorianCalendar, HebrewCalendar, JapaneseCalendar.
• System.Globalization
• namespace:
• ➤ Unicode issues
• ➤ Cultures and regions
• ➤ An example showing all cultures and their characteristics
• ➤ Sorting
• Cultures and Regions
• The world is divided into multiple cultures and regions, anapplications
have to be aware of these cultural and regional differences. A culture is a
set of preferences based on a user’s language and cultural habits.
• The System.Globalization namespace CultureInfo.CultureInfo represents
a culture and defines calendars, formatting of numbers and dates, and
sorting strings used with the culture.
• The class RegionInfo represents regional settings (such as the currency)
and indicates whether the region uses the metric system.
• CurrentCulture and CurrentUICulture
• The Thread class has the properties
• CurrentCulture and CurrentUICulture. The property CurrentCulture is for
setting the culture that is used with formatting and sort options, whereas
the property CurrentUICulture is used for the language of the user
interface
• using System;
• using System.Globalization;
• using System.Threading;
• class Program
• {
• static void Main(string[] args)
• {
• NumberFormatDemo();
• }
• private static void NumberFormatDemo()
• {
• int val = 1234567890;
• Console.WriteLine(val.ToString(“N”)); // culture of the current thread
• Console.WriteLine(val.ToString(“N”, new CultureInfo(“fr-FR”))); //
use IFormatProvider
• Thread.CurrentThread.CurrentCulture = new CultureInfo(“de-
DE”); // change the culture of the thread
Console.WriteLine(val.ToString(“N”));
• }
• }
• 1,234,567,890.00
• 1 234 567 890,00
1.234.567.890,00
Date Formatting
• The class DateTimeFormatInfo specifies the possible values. With
DateTimeFormatInfo, the case of the format strings has a different
meaning. D defi nes a long date format, d a short date format. Other
examples of possible formats are ddd for the abbreviated day of the week,
dddd for the full day of the week, yyyy for the year, T for a long time,
and t for a short time format
• DateTime d = new DateTime(2012, 06, 12);
• // current culture
• Console.WriteLine(d.ToLongDateString());
• // use IFormatProvider
• Console.WriteLine(d.ToString("D", new CultureInfo("fr-FR")));
• // use culture of thread
• CultureInfo ci = Thread.CurrentThread.CurrentCulture;
• Console.WriteLine("{0}: {1}", ci.ToString(), d.ToString("D"));
• ci = new CultureInfo("es-ES");
• Thread.CurrentThread.CurrentCulture = ci;
• Console.WriteLine("{0}: {1}", ci.ToString(), d.ToString("D"));
• o/p
• mardi 12 juin 2012
• es-ES: martes, 12 de junio de 2012
PEER-TO-PEER NETWORKING
• Peer-to-peer networking is an alternative approach to network
communication.
• Client-Server Architecture
• Traditionally, you interact with applications over a network (including the
Internet) using a client-server architecture. Websites are a great example
of this.When you look at a website, you send a request over the Internet
to a web server,which then returns the information that you require. If
you want to download a fi le, you do so directly from the web server.
With every client added an increased load is placed on the server, which must
communicate with each client.To return to the website example, this increased
communication load is how websites collapse. When there is too much traffi c,
the server simply becomes unresponsive.
P2P Architecture
The peer-to-peer approach is completely different from either the scaling up or
scaling out approach. You could use P2P technology to prevent this web server
collapse.
• Instead of sending the fi le directly from the server to all the clients, you
send the fi le to just a few clients. A few of the remaining clients then
download the fi le from the clients that already have it; a few more clients
download it from those second-level clients;and so on. This process is
made even faster by splitting the fi le into chunks and dividing these
chunks among clients, some of whom download it directly from the
server, and some whom download chunks from other clients
• Problem in P2P
• how do clients detect that other clients exist
• how do they locate chunks of the fi le that other clients might have
• how can you ensure optimal communication between clients
• SOLUTION
(I)The discovery problem has two obvious solutions. You can either keep a list
of the clients on the server so that clients can obtain this list and contact other
clients (known as peers),
• (II)you can use an infrastructure(for example PNRP, “Peer Name
Resolution Protocol”) that enables clients to fi nd each other directly.
• Most fi le-sharing systems use the “list on a server” solution by using
servers known as trackers.
• P2P Terminology
• peer, which is how clients are referred to in a P2P network.
• Groups of peers connected to each other are known by the
interchangeable terms meshes, clouds, or graphs.
• A given group can be said to be well connected if at least one of the
following statements applies:
• ➤ There is a connection path between every pair of peers so that every
peer can connect to any other
• peer as required.
• ➤ There are a relatively small number of connections to traverse between
any pair of peers.
• ➤ Removing a peer does not prevent other peers from connecting to each
other.
• PEER NAME RESOLUTION PROTOCOL (PNRP)
• The Microsoft Windows Peer-to-Peer Networking platform is Microsoft’s
implementation of P2P technology. It is part of Windows since Windows
XP SP2. You can use the Peer Name Resolution Protocol (PNRP) to
publish and resolve peer addresses.
• Working
• 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.
• PEER NAME RESOLUTION PROTOCOL (PNRP)
• PNRP IDs
• 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.
• NOTE:value of 0 instead of a hashed public key, in which case the peer
name is said to be unsecured
• PNRP Clouds
• 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 defi ne a private global cloud
• 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.
• ➤ 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 specifi ed classifi er.
• 2. Confi gure a registration for the peer name, providing as much of the
following optional information as you choose:
• ➤ A TCP port number.
• ➤ The cloud or clouds with which to register the peer name. (If unspecifi
ed, PNRP registers the
• peer name in all available clouds.)
• ➤ A comment of up to 39 characters.
• ➤ Up to 4,096 bytes of additional data.
• ➤ Whether to generate endpoints for the peer name automatically. (The
default behavior, where
• endpoints will be generated from the IP address or addresses of the peer
and, if specifi ed, the
• port number.)
• ➤ A collection of endpoints.
• 3. Use the peer name registration to register the peer name with the local
PNRP service.
• 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);
• When you are ready to register the peer name, you can call the
PeerNameRegistration.Start method.
• Toremove a peer name registration from the PNRP service, use the
PeerNameRegistration.Stop method.
• 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.
• 3. For any peer name records that you obtain, obtain peer name, endpoint,
comment, and additional data information as required.
• 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.
• 3. For any peer name records that you obtain, obtain peer name, endpoint,
comment, and additional data information as required.
• To resolve peer names use the PeerNameResolver class. When you have
an instance of this class, you can choose to resolve peer names
synchronously by using the Resolve method or asynchronously using the
ResolveAsync method.
• var pn = new PeerName(“0.Peer classifier”);
• var pnres = new PeerNameResolver();
• PeerNameRecordCollection pnrc = pnres.Resolve(pn,
Cloud.AllLinkLocal, 5);
ADO.NET
• ADO.NET is used as a data access technology.It can be used with
all .net framework programming language such as vb.net,vc# and
visual c++.
• It is a model used by .Net applictaions to communicate with a
database for retrieving,accessing and updating data. Sources such as
• ADO.Net is based on the standards laid down by the W3C.This
model has been designed in such a way that a developer can access
and write to a wide variety of data sources as Microsoft Sql server
and XML.By using ADO.Net data can be retrieved from one data
source and saved in another.
• Eg data can be retrieved from MS Excel can be saved as XML
document.
• Ado-active X data object
• System.Data
• Features of ADO.Net
• Disconnected Data architecture:
• ADO.Net support disconnected architecture.Applications
connect to the database only while retrieving and updating
data.After the data is retrieved ,connection with the database is
closed.When the databae needs to be updated the connection is
re-established.In a disconnected architecture ,database can
cater to the needs of several applications simultaneously
because the interaction is for a shorter duration.
Data cached in Datasets:
A dataset is the most common method of accessing data in ADO.Net
because it implements a disconnected architecture.Data is stored and
retrieved in datasets.You can work with the records stored in a dataset as
you work with real data.
Scalability:
ADO.Net supports scalability by working with datasets.Database
operations are performed on the dataset instead of on the database.As a
result resources are saved and the database can meet the increasing
demands of users more efficiently.
• Features of ADO.Net
• Data transfer in xml format:
• XML is the fundamental format for data transfer in ADO.Net.Data is
transferred from a database into a dataset and from dataset to
another by using xml.
• The two key component of the ADO.net object model are:
• Data Provider
• Dataset
Data provider:
• In ADO.Net object model,the data residing in a database is retrieved
through a dataprovider.The Data provider is a set of components
including the connection,command,datareader and dataadapter
objects.It provides data to the application and updates the database
with the changes made in the application.
• The four main types of data provider are:
• .Net Framework data provider for SQL Server-to work with sql
server
• .Net Framework data provider for OLE DB-To support COM
technology
• .Net Framework data provider for ODBC-It uses odbc driver to
enable data access
• .Net Framework data provider for oracle-to work with oracle
• Four Key components of data provider:
• Connection:This component is used to establish a connection with a
data source such as database
• Command:It is used to retrieve,insert,delete or modify data in a data
source
• Datareader:It is used to retrieve data from a datasource in a read-
only and forward only.Read-only means that the records of the table
cannot be updated.Forward-only means that you cannot traverse
back to the previous records of the table.
• Data adapter:It is used to transfer data to and from a database.a
data adapter retrieves dta from a database in to a dataset.
• Dataset:
• A Dataset is present in the DataSet class in the System.Data
namespace.
• The dataset is a memory based relational representations of data.A
dataset is a part of the disconnected architecture.
• There are two types of Dataset
• Typed Dataset:
• A typed dataset is derived from the Dataset class and has an
associated XML schema which is created at the time of the creation
the dataset.The XML schema contains information about the dataset
such as the tables,columns and rows.
• Untyped Dataset:
• A untyped dataset is derived from the Dataset class and does not
have an associated XML schema.In an untyped dataset the tables
and columns are represented as collections.
• The key component of dataset are:
• DataTableCollection:It contains all the tables retrieved from the
datasource.
• DataRelationCollection:It contains the relationship and links
between tables in a dataset
• DataTable:It represents a table in the datatable
• DataRowCollection:It contains all the rows in the datatable
• DataColumnCollection:It contains all the columns in the datatable
An application can access data either through a dataset or datareader
object:
Using a dataset:Data is cached in a dataset and the application accesses the
data from the dataset
Using a datareader:It is a component of the dataprovider uses the
connection object to connect to DB and uses command object to retrieve
data
• Creating and managing connections
• In order to perform these tasks you need to perform the following
steps:
• Create a connection object
• Create a command object
• Open the connection object
• Execute the SQl statements in the command object
• Close the connection object
• Creating a connection object:
• SqlConection class is used to open the connection
name description
ConnectionString It provides information such as
datasource and database name
to establish connection
Open() Opens the connection
Close() Close the connection
• SqlConection class is used to open the connection.Connectionstring
property has the following parameters
name description
Provider It is used to set or return the name of the
provider for the connection
Initial Catalog Specify the name of the database
Data Source Name of the server to be used when a
connection is open
User ID Server login account
Password Login password
Integrated It is used to determine whether or not the
Security connection needs to be a secure
connection.when false userid and password
are specified in the connection.When true
current windows account credentials are used
for authentications
• using System;
• using System.Data;
• class sample
• {
• public static void Main()
• {
• public void print()
• {
• SqlConnection cn=new SqlConnection();
• cn.ConnectionString=“Data Source=sqlserver1;Initial
Catalog=abc;User ID=sa;Password=saec”;
• cn.Open();
• SqlCommand cmd=new SqlCommand(“select * from stud”,cn);
• SqlDataReader reader=cmd. ExecuteReader();
• While(Reader.Read())
• {
• Console.WriteLine(“rollno,name”,reader[0],reader[1]);
• }
• cn.Close();
• }}
Transactions
• A transaction is a logical unit of work that must be completed to maintain
the consistency and integrity of a database.
• Transactions are managed and coordinated by the transaction manager,
and a resource manager manages every resource that influences the
outcome of the transaction. The transaction manager communicates with
resource managers to define the outcome of the transaction.
• Types of Transaction:
• Local Transactions:A local transaction is performed on a single
datasource.It is created and managed within the System.Transactions.
• Distributed Transactions:A distributed transaction is performed on
multiple data sources.distributed transactions are also performed on
multiple connections to a datasource.
• To perform a local transaction,call the BeginTransaction() method.After
this execute a command within a transaction.If all commands using the
same transaction succeed the commit() method is called on the
transaction object to commit the transaction.If command fails,Rollback()
• using System;
• using System.Data;
• using System.Transactions;
• using System.SystemExceptions;
• class sample
• {
• public static void Main()
• {
• SqlConnection cn=new SqlConnection();
• cn.ConnectionString=“Data Source=sqlserver1;Initial Catalog=abc;User
ID=sa;Password=saec”;
• cn.Open();
• SqlTransction tran=null;
• try
• {
• tran=cn.BeginTransaction();
• SqlCommand cmd=new SqlCommand(“select * from stud”,cn,tran);
• SqlDataReader reader=cmd. ExecuteReader();
• tran.Commit();
• Console.WriteLine(“transaction completed”);
• }
• catch(SqlException ex)
• {
• tran.Rollback();
• }
• cn.Close();
• }}
• Distributed Transaction
• Consider a situation where a connection to a database is opened and
transaction has been performed within that connection.Now if you want
to perform another transaction on the same connection it will throw an
exception error.this problem can be solved distributed transactions
• The System.Transaction namespace has a TransactionScope class which
allows to create distributed transaction.Transactionscope object decides
whether to create a local or distributed transaction.This is known as
transaction promotion
• using System;
• using System.Data;
• using System.Transactions;
• class sample
• {
• public static void Main()
• {
• TransactionScope ts=new TransactionScope();
• SqlConnection cn=new SqlConnection();
• cn.ConnectionString=“Data Source=sqlserver1;Initial Catalog=abc;User
ID=sa;Password=saec”;
• cn.Open();
• SqlCommand cmd=new SqlCommand(“insert into
stud(rollno,name)values(10,”sa”)”,cn);
• Int rows=cmd. ExecuteReader();
• If(rows>0)
• {
• SqlConnection cn1=new SqlConnection();
• cn1.ConnectionString=“Data Source=sqlserver1;Initial Catalog=abc;User
ID=sa;Password=saec”;
• cn1.Open();
• SqlCommand cmd1=new SqlCommand(“insert into
dept(rollno,name)values(10,”sa”)”,cn1);
• Int rows1=cmd1.ExecuteReader();
• If(rows1>0)
• {
• ts.Commit();
• Console.WriteLine(“transaction completed”);
• cn1.Close();
• }}
• cn.Close();
• }}
• Isolation levels of transaction
• An isolation level determines the effect a transaction has on other
transaction that are currently running and vice versa.By default all
transactions are completely isolated and to run concurrently without
impacting each other.
• It is important to choose an appropriate isolation level to prevent
concurrency problems when multiple transaction access the same data at
the same time.
Concurrency description
error
Dirty read Another transaction can read records that are
changed within the transaction. Because the
data that is changed within the transaction
might roll back to its original state, reading this
intermediate state from another transaction is
considered “dirty” — the data has not been
committed.
Nonrepeatable A transaction reads the same row more than
reads once and a different transaction modifies the
row between the reads
Phantom read A transaction reads a rowset more than once
and a different transaction inserts or modifies
the row between the reads.
•
• using System;
• using System.Data;
• using System.Transactions;
• class sample
• {
• public static void Main()
• {
• TransactionOptions opt=new TransactionOptions();
• opt.IsolationLevel=IsolationLevel.ReadCommitted;
• TransactionScope ts=new TransactionScope();
• SqlConnection cn=new SqlConnection();
• cn.ConnectionString=“Data Source=sqlserver1;Initial Catalog=abc;User
ID=sa;Password=saec”;
• cn.Open();
• SqlCommand cmd=new SqlCommand(“insert into
stud(rollno,name)values(10,”sa”)”,cn);
• Int rows=cmd. ExecuteReader();
• If(rows>0)
• {
• SqlConnection cn1=new SqlConnection();
• cn1.ConnectionString=“Data Source=sqlserver1;Initial Catalog=abc;User
ID=sa;Password=saec”;
• cn1.Open();
• SqlCommand cmd1=new SqlCommand(“insert into
dept(rollno,name)values(10,”sa”)”,cn1);
• Int rows1=cmd1.ExecuteReader();
• If(rows1>0)
• {
• ts.Commit();
• Console.WriteLine(“transaction completed”);
• cn1.Close();
• }}
• cn.Close();
• }}
Manipulating xml using DOM
• Processing XML data
• XML data can be processed in .Net applications by using System.Xml
namespace.The System.Xml contains many classes to write and read xml
documents.
• Writing XML Data
• The XmlWriter class in the System.Xml provides non-cached,forward
only and write access to xml data.It is used to write either a stream of data
or text data.
• XmlWriter objects are created by using the Create() method.It is a static
method.The Object of XmlWriterSettings class is passed to Create() in
oeder to specify the settings.
• Example
• XmlWriterSettings set=new XmlWriterSettings();
• Set.Indent=true;
• Set.NewLineChars=“”;
• XmlWriter a=new Xmlwriter.Create(“sa.xml”,set);
• Creating xml file:
• By calling WriteElementString()method: or WriteStartElement()
• It takes two parameter,name and value of the element
• //a.WriteElementString(“name”,”sa”);
• Creating attribute
• By calling WriteAttributeString()method:
• It is used to write an attribute in xml file.
• a. WriteAttributeString(“orderid”,”0001”);
• using System;
• using System.Xml;
• class sample
• {
• public static void main()
• {
• XmlWriterSettings set=new XmlWriterSettings();
• Set.Indent=true;
• Set.NewLineChars=“”;
• XmlWriter a=new Xmlwriter.Create(“sa.xml”,set);
a.WriteStartElement(“orderdetails”);// create the root element
a.WriteStartElement(“order”); // create next level element
a.WriteAttributeString(“orderid”,”0001”); //attribute for order element
a.WriteElementString(“pname”,”toys”);
a.WriteElementString(“price”,”100”);
a.WriteEndElement();
a.WriteEndElement(); //closes the root element
}}
Output:
<?xml version=“1.0” encoding=“utf-8” ?>
<orderdetails>
<order orderid=“0001”>
<pname>toys </pname>
<price>100</price>
</order>
</orderdetails>