Application of .NET Technology Unit 04 Advanced Features Using C Sharp Notes Set 01

Official Study Materials for Computer Science

Explore structured advanced study materials through the Application of .NET Technology Unit 04 Advanced Features Using C Sharp Notes Set 01. Tailored for learners, utilizing these Computer Science resources ensures thorough preparation and strengthens foundational knowledge before final evaluations.

Advanced Resources for Computer Science

View or download the dedicated Application of .NET Technology Unit 04 Advanced Features Using C Sharp Notes Set 01 resource below. Engaging with these advanced study guides under focused conditions ensures continuous academic progress and mastery of the 2026-27 curriculum for .NET Technology.

This page covers the advanced C# features of the course: ASP.NET web services with WSDL, UDDI and SOAP, Windows services, message queuing and reflection. It continues with COM and COM+ interoperability, resource files and localization, .NET remoting setups and lifetime leasing, XML reading and writing, unsafe code with pointers, GDI+ drawing and a chat program case study.

Web Services

A web service is a network accessible interface to application functionality, built using standard Internet technologies. A web service is a distributed computing technology that enables the exposure and reuse of logical business entities over the Internet.

Creating ASP.NET web services is incredibly easy. ASP.NET web services are web services supported by the ASP.NET infrastructure. Several open standards technologies play a significant role in making web services a reality. These standards can be categorized by description, discovery, and transmission.

StandardRole
Web Services Description Language (WSDL)An XML-based format for describing a web service. It describes what the web service is, its parameters, and how to use it.
Universal Description Discovery and Integration (UDDI)UDDI directories support discovery. These directories manage WSDL documents and provide a means for clients to find and use web services.
Simple Object Access Protocol (SOAP)A communications protocol that enables clients to interact with UDDI directories and web services.

Viewing Web Service Info

The ASP.NET infrastructure provides the means to view information and test the operation of a web service. To do so, point your browser to the location of the web service on a web server. Pointing a browser at the BasicWebService page lists the operations the service supports (here, one operation named Greetings) together with a link to the service description.

Using Web Services

If an application wraps a method call into a SOAP envelope and uses HTTP, it could use the method to communicate with the BasicWebService web service. Alternatively, the client could use one of the HTTP GET or POST methods. It's possible, but that would be a lot of work.

The .NET Framework comes with a utility called wsdl that frees a client from creating all this plumbing. This utility takes the URL to a web service and creates a proxy, which is used by the client to call the web service. Using a web service requires a client to declare an instance of the proxy class and then call the necessary web service operation, defined in the proxy class.

Web services provide a platform-independent means of exposing business logic over the Internet. They are created using several open standards technologies. Creating ASP.NET web services is easy and abstracts much of the complexity associated with Internet communications. This allows developers to concentrate on business logic rather than underlying plumbing.

Use of a web service involves creating a proxy class that communicates with the web service on behalf of a client. The client application then communicates directly with the proxy to invoke necessary web service operations.

Windows Services

Visual Studio has supported Windows service projects since .NET 1.0. To create a Windows service project, select File, New, Project, select the Visual C#\Windows branch of the navigation tree, and then select Windows Service.

The Windows service project contains a couple of items that are unique. This section explains what they are and how to get to the code that is created in a new Windows service project. Notice that there aren't any spaces in the name of the project, which names the assembly by default; spaces don't work with Windows services.

A Windows service consists of method overrides that you implement to make your service work. The code for a service has several overridden methods, corresponding to the events of a service, such as Start, Pause, Continue, and Stop. You implement OnStart and OnStop, which are already provided in the shell code that the Windows Service Project Wizard creates for you. To view the code for the Windows service, either select the blank design surface or the Solution Explorer file for Service1.cs, right-click, and select View Code.

Implementing Windows Service Method Overrides

The method overrides in a Windows service get your program to work. Implement the OnStart and OnStop methods as a minimal implementation.

The OnStart method can be called when the OS boots and starts services marked as Automatic. It can also be called manually via the Services console that you can find via your OS Administrative Tools panel. The OnStart method of a Windows service has a total of 60 seconds to complete. To avoid the timeout, you can launch long-running processes on a thread, which enables the OnStart method to finish on time.

Configuring a Windows Service

There are different configuration settings for a Windows service. The service itself permits specifying logging options, naming, and allowed states (for example, continue and pause).

After the 60 seconds, Windows will fail your service, which you can verify by looking at the Windows Event Log if it happens to you. To avoid the timeout, you can launch long-running processes on a thread, which enables the OnStart method to finish on time.

Installing a Windows Service

The installer has two parts: a ServiceProcessInstaller and a ServiceInstaller. The ServiceProcessInstaller is configured first and then the ServiceInstaller. The ServiceInstaller provides setup for individual services, meaning that you can have multiple services running in the same process.

Select the ServiceProcessInstaller and open the Properties window to configure it. The most important property to set is Account. The available settings are one of the ServiceAccount enum's values. The most configurable option is User, where you can give the service a machine or domain account.

Controller to Communicate with a Windows Service

A Windows service can be controlled from a separate application; the SQL Server taskbar app is a good example. The example we use is a WPF application. If you are following along, create a new WPF application and add a couple of buttons to the window with Content properties set to Start and Stop and with Name properties set to btnStart and btnStop, respectively.

Messaging

The Message class provides access to the properties needed to define a Message Queuing message.

Inheritance Hierarchy

1. System.Object,
2. System.MarshalByRefObject,
3. System.ComponentModel.Component,
4. System.Messaging.Message.

Use the Message class to peek or receive messages from a queue to have fine control over message properties when sending a message to a queue. MessageQueue uses the Message class when it peeks or receives messages from queues, because both the MessageQueue.Peek and MessageQueue.Receive methods create a new instance of the Message class and set the instance's properties.

The Message class's read-only properties apply to retrieving messages from a queue, while the read/write properties apply to sending and retrieving messages.

The MessageQueue class's Send method allows you to specify any object type for a message being sent to that queue. You can use the MessageQueue instance's DefaultPropertiesToSend property to specify settings for generic messages sent to the queue. The types of settings include

1. Formatter,
2. Label,
3. Encryption, and
4. Authentication.

You can also specify values for the appropriate DefaultPropertiesToSend members when you coordinate your messaging application to respond to acknowledgment and report messages.

Using a Message instance to send a message to the queue gives you the flexibility to access and modify many of these properties, either for a single message or on a message-by-message basis. Message properties take precedence over DefaultPropertiesToSend.

Message data is stored in the Body property and to a lesser extent, the AppSpecific and Extension properties. When data is encrypted, serialized, or deserialized, only the contents of the Body property are affected. The contents of the Body property are serialized. Change the Body or Formatter properties at any time before sending the message, and the data will be serialized appropriately when you call Send.

The properties defined by the MessageQueue.DefaultPropertiesToSend property apply only to messages that are not of type Message. If you specify the DefaultPropertiesToSend property for a MessageQueue, the identically named properties in a Message instance sent to that queue cause these default properties to be ignored.

Syntax

public class Message : Component

Reflection

Reflection objects are used for obtaining type information at runtime. The classes that give access to the metadata of a running program are in the System.Reflection namespace. The System.Reflection namespace contains classes that allow you to obtain information about the application and to dynamically add types, values and objects to the application.

Use of Reflection

Reflection has the following uses:

1. It allows viewing attribute information at runtime.
2. It allows examining various types in an assembly and instantiating these types.
3. It allows late binding to methods and properties.
4. It allows creating new types at runtime and then performing some tasks using those types.

Viewing Metadata

Using reflection you can view the attribute information. The MemberInfo object of the System.Reflection class needs to be initialized for discovering the attributes associated with a class. To do this, you define an object of the target class, as:

System.Reflection.MemberInfo info = typeof(MyClass);

C# Reflection

The following program demonstrates this:

using System;
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute
{
   public readonly string Url;
   public string Topic  // Topic is a named parameter
   {
      get
      {
         return topic;
      }
      set
      {
         topic = value;
      }
   }
   public HelpAttribute(string url)  // url is a positional parameter
   {
      this.Url = url;
   }
   private string topic;
}
[HelpAttribute("Information on the class MyClass")]
class MyClass
{
}
namespace AttributeAppl
{
   class Program
   {
      static void Main(string[] args)
      {
         System.Reflection.MemberInfo info = typeof(MyClass);
         object[] attributes = info.GetCustomAttributes(true);
         for (int i = 0; i < attributes.Length; i++)
         {
            System.Console.WriteLine(attributes[i]);
         }
         Console.ReadKey();
      }
   }
}

When it is compiled and run, it displays the name of the custom attributes attached to the class MyClass:

HelpAttribute

COM and C#

Communicating with COM

One of the most likely interop scenarios is communicating from .NET to existing COM components. This can allow preservation of existing infrastructure and reduction in overall development cost. COM components may be called via either early or late binding.

Via early binding, legacy COM components can be made to appear as managed objects in the .NET environment. This is accomplished by a utility that reads an existing type library and creates a proxy for the .NET component to interact with. Early bound components are those that are bound at compile time. This promotes type safety and improves a program's overall performance.

Early-Bound COM Component Calls

A C++ COM Component: ComObj.dll

STDMETHODIMP CCom4DotNet::GetResponseFromCom(void)
{
   printf("Hello from COM!");
   return S_OK;
}

The .NET Framework is used to create a proxy for the COM component. The proxy is then compiled into the C# program, and the COM component can be instantiated and called just like any other managed component.

Output:

Hello from COM!

Late-Bound COM Component Calls

When a type library isn't available, or there's a dynamic invocation requirement, a C# program can perform a late-bound call to a COM component. Late-bound COM component invocations are performed using C# reflection. It first obtains a ProgID from the COM object, as listed in the Windows registry. When a type object is obtained, an object is created using the static CreateInstance method of the Activator class. The GetResponseFromCom method of the COM component is then invoked with the InvokeMember method of the Type object, lateBoundType.

Exposing a .NET Component as a COM Component

A C# Component Exposed as a COM Component: CallFromCom.dll

C# components are accessible as COM components. .NET Framework tools are used to create an unmanaged proxy and enter the proper settings in the registry. This enables unmanaged code to use .NET components as if they were COM components.

The regasm command line registers the C# library as a COM component. In addition, the /tlb option creates a type library to facilitate early binding. To generate a type library without registering the library, use the TlbExp program as shown in the following command line:

TlbExp CallFromCom.dll

Calling a C# Component Exposed as a COM Component: a VB program calls the C# COM component, and a message box shows the response from the C# COM component.

Introduction to .NET Support for COM+ Services

The .NET Framework provides extensive support for COM+ services such as

1. Transactions,
2. JIT activation,
3. Object pooling, and others.

COM+ services are activated through the use of attributes, which decorate a specific C# element as appropriate. These attributes are analogous to the COM+ concepts.

Installed Assembly

The other step necessary to make this C# program work as a COM+ service is to register it. The ApplicationName attribute identifies the COM+ name, and the AssemblyKeyFile attribute specifies the strong name key to register the assembly with. The following command line shows how to create a strong name key:

sn -k CPSkel.snk

Transactions

A transaction is a way to combine multiple actions into a single body of work to guarantee that all actions either succeed or fail together.

A COM+ Transactional Component in C#: CPTrans.cs

C# programs can participate in COM+ services transactions by inheriting from the ServicedComponent class and marking their classes with a Transaction attribute. Another transaction-related attribute is AutoComplete, which enables a transaction to commit automatically if all items succeed. However, if an exception is raised, AutoComplete causes the transaction to abort.

JIT Activation

Just-In-Time (JIT) activation is the capability to instantiate a new component; the component goes away automatically when it's no longer needed. By using COM+ services and associated attributes, a C# component can participate in JIT activation. Implementing JIT activation requires specifying the JustInTimeActivation attribute. JIT activation is true by default, but if you want to turn it off, specify false as the first attribute parameter.

Object Pooling

Another COM+ service enabling efficient use of resources is object pooling. An object pool is a group of components that stay activated and ready for connections at all times. This reduces the overhead associated with activation and deactivation of components. The ObjectPooling attribute has three parameters:

1. Enabled,
2. MinPoolSize, and
3. MaxPoolSize.

The Enabled parameter turns object pooling on. The MinPoolSize parameter specifies the minimum number of objects held in the pool, and the MaxPoolSize parameter specifies the maximum number of objects to be held in the pool.

Other Services

COM+ services include several other technologies such as roles, security, and message queuing. These can be used by applying the techniques described in the other sections and examining the applicable attributes in the System.EnterpriseServices namespace.

C# and COM+ services security are mutually exclusive.

Localization - Resource Files

Setting up and using resource files is the primary means of localizing programs. Resource files are specialized binary files that can be bound to a standalone DLL or added into a program assembly. They contain strings, graphics, and other binary resources that assist in localizing a program.

Creating a Resource File

The resource generator utility ResGen is a string resource creation utility that comes with the Microsoft .NET Framework SDK. Given a properly formatted .txt (text) file, ResGen converts it into a .resources (binary resources) file that can subsequently be added to an assembly.

Without a special resource creation tool, string resources begin life as a specially formatted .txt file. They have headers, comments, and name/value pairs.

Using Resources: StringRes.cs

Output:

Greeting: Hello

Header elements must match the filename without the extension. For example, if the resource file's name is myResources.txt, the header contents must be [myResources]. Comments are useful for delimiting groups of resource strings or adding more information to the use of a string. All comments are removed from compiled resources.

Writing a Resource File

Resource files may be created programmatically. This is useful for automated .resources file generation utilities or resource tools in IDEs. The steps involved in creating a .resources file are to open a ResourceWriter stream, add whatever resources are needed, and then close the stream.

Writing a Resource File: ResWrite.cs

The default ResourceWriter class in the System.Resources namespace implements IResourceWriter. This is why it's possible to create an IResourceWriter object within the Main method; the ResourceWriter constructor accepts a string parameter specifying the resource file to create. If a file by that name exists, it will be overwritten.

Reading a Resource File

Reading a Resource File: ResRead.cs

The ResourceReader class is also useful in creating resource manipulation utilities and IDE tools to manage resources. A utility uses the ResourceReader functionality to read in an existing resource file, the program performs any necessary manipulations, and then the ResourceWriter helps write the new resources back to the persistent .resources file.

Converting a Resource File

Generated .resx File: strings.resx

Another use of ResGen is to convert between .txt, .resources, and .resx files. Resx files are XML format files used for binary resources such as graphics, fonts, icons, and cursors. For example, the following command line converts the .resources file to a .resx file:

resgen strings.resources strings.resx

This produces an XML format file. The same exact file would have been generated if you had performed the following command line:

resgen strings.txt strings.resx

Creating Graphical Resources

Path:

C:\Program Files\Microsoft.Net\FrameworkSDK\Samples\tutorials\resources and localization\graphics\cs\images directory

Run Command:

ResXGen /i:un.jpg /o:graphics.resx /n:flag

The .NET Framework SDK includes a couple of sample programs that help manage graphical resources.

The ResXGen Utility: One is the ResXGen program, which adds a graphic to a .resx file.

The ResEditor Utility: The other is the ResEditor program, which manages all types of resources for .resources files.

Using Graphical Resources: An added bonus is that these two utilities come with source code, enabling you to examine graphical resource manipulation code in detail.

Multiple Locales

The purpose of resource files is to support multiple locales. The official way of specifying locales is via cultures, as specified in RFC 1766, ISO 639, and ISO 3166. Cultures are denoted with four-letter designations: the first two characters specify the language in lowercase, and the second two specify the country or region in uppercase (for example en-US). A separate resource file must be created for each locale.

There are multiple ways to deploy these resources: compiled into a program, via satellite assembly, or via a global assembly. Through a combination of resource files and a directory structure geared toward targeted cultures, any program can be localized. The directory structure corresponds to each culture implemented in a program. The following directory structure supports localization for a program named MultiCulture:

MultiCulture
   en
   en-US
   en-GB

A Localized Program: MultiCulture.cs

If the appropriate culture subdirectory is present, a localized program can automatically pick up the resources corresponding to its default locale.

Finding Resources

1. Search the global assembly cache for the specific resource. The global assembly cache is a central repository for all programs on a machine to access.
2. Search culture subdirectories of the localized program.
3. Search the global assembly cache for parent resources. For instance, if the original resource selected, but not found, was en-US, search the global assembly cache for en only.
4. Search culture subdirectories of the localized program for the parent resources.
5. Search culture subdirectories of the localized program for parent resources of the last parent resource searched.

A resource has only a single parent, but the chain of parents can extend multiple levels.

Distributed Application

Remoting is an infrastructure that allows the developer to use remote objects. Remote objects are objects that are based (or instantiated) outside of the caller's Application Domain.

In the remoting architecture a client application talks to a proxy object, and the proxy communicates across the remoting boundary with the remote object on the server; the remote object in turn can use a database and other server resources, and can raise events back to the proxy.

This example shows you how to use both remote object access mechanisms (pass by value and pass by reference). It also shows you the power of remoting for distributed computing with a simple yet powerful implementation of a Task Server.

Basic Remoting

Remoting is the capability to communicate with components in separate AppDomains. A simplified view of two objects communicating via remoting is: a client component in AppDomain A communicates with a server component in AppDomain B.

An AppDomain is an execution environment within a process. It separates managed applications during execution. This provides several benefits including reliability and security.

Remoting supports multitiered as well as distributed architectures; the server component in AppDomain B could easily be extended to a client role, communicating with a server component in another AppDomain. Furthermore, a remote component could be located in another process on either the same or a different machine.

When a component is set up, the underlying plumbing required to maintain remote communications is hidden by the remoting architecture. There is a server, which is a DLL that must be hosted by another application, either IIS or a custom host that you build. There is also a client, which is an executable that makes an out-of-process call to communicate with the remoting server.

We build the remoting server first, then the client, and finally show a couple of ways to host the server. After the server is hosted and the host is running, the client can call it.

Remoting Server

A remoting server object is just a class that derives from MarshalByRefObject.

BasicRemotingServer.cs

The BasicServer class inherits MarshalByRefObject, which supports the basic functionality for a callable component over the remoting architecture. This class is implemented as a DLL, negating the need for a Main method. The only method in this class is the GetServerResponse method, keeping things simple.

web.config

Each remoted component requires a configuration file, named web.config, to specify necessary operating parameters.

Remoting Client

BasicRemotingClient.cs

Writing a remoting client is just a little more involved than writing a remoting server. Writing a client requires finding out the type and location of the remote server object, initializing configuration from a file, and creating an instance of the remote object with the type and location information obtained earlier.

The System.Runtime.Remoting namespace contains all the basic remoting classes. Our remote server component that will be instantiated and called is in the BasicServer namespace.

BasicRemotingClient.exe.config

Within the Main method, the type of the BasicRemotingServer class is obtained with the typeof operator and stored in a Type object. Next, the URL of the BasicRemotingServer is used.

Remoting Setup

There are two ways to get a remoting application up and running: via a web server or a host utility.

1. Web Server Setup.
2. Host Utility Setup.

Use Microsoft Internet Information Services (IIS) as the web server to host the remote server component.

Web Server Setup

Demonstrating the host utility requires code for a new client and server program and the utility. The following steps show how to set up a remote server component via the IIS web server.

1. Before actually starting this procedure, work out a directory structure so that it will be easy to follow along. Here's what your directory structure should look like:

<path>\BasicServer
   BasicServer.cs
   Web.config
<path>\BasicServer\bin
<path>\BasicClient
   BasicClient.cs
   BasicClient.exe.config

2. Compile the server component from the BasicServer directory with the following command line:

csc /t:library BasicServer.cs

3. Open Internet Information Services (IIS). The following steps work for Windows XP but are different for other operating systems. For example, WinNT, Win2K, Win2003, Win2008, and Vista are all different. If the actions don't match your OS exactly, consult your documentation to accomplish the same tasks.

4. Expand the server node under which you want to create a virtual directory and right-click Default Web Site. From the menu, select New, Virtual Directory. This opens the Virtual Directory Creation Wizard. Click Next.

5. In the text box for an Alias, type in any meaningful name for the virtual directory, such as BasicServerDemo. Click Next.

6. In the text box for the physical path that the virtual directory will refer to, enter the <path>\BasicServer directory, where <path> is the actual directory you specified in step 1. Click Next.

7. There are several access permissions from which to choose. The Read and Run Scripts (such as ASP) options are already checked, and that's fine. Accept the defaults, click Next, and then click Finish on the last screen.

IIS will use the web.config file in the BasicServer directory when it loads the server component. The remote server component is now set up.

Use the following command line to compile the remoting client program from the BasicClient directory:

csc /r:..\BasicServer\BasicServer.dll BasicClient.cs

Optionally, in Visual Studio, add a reference to the BasicServer project: right-click the References folder in BasicClient, select Add Reference, click the Projects tab, select the BasicServer project, and click the OK button. You'll also need to add a using declaration for the BasicServer namespace.

Finally, run the BasicClient.exe program in the BasicClient folder to test the system out. If all goes well, the following output will be printed to the console:

Greetings from the BasicRemotingServer component!

Host Utility Setup

The host utility setup method uses a program that configures the remote server component. The process isn't necessarily easier or harder than the web server setup method. Replace the BasicServer with HostedServer and the BasicClient with the HostedClient directory names.

Hosted Server Demo: HostedServer.cs

using System;
namespace Host
{
   /// <summary>
   /// Hosted Server Component Demo.
   /// </summary>
   public class HostedServer : MarshalByRefObject
   {
      public string GetServerResponse()
      {
         return
            "Greetings from the HostedServer component!";
      }
   }
}

Remoting Client Demo: HostedClient.cs

Replace the BasicServer with HostedServer and the BasicClient with the HostedClient directory names.

Remoting Client Configuration File: HostedClient.exe.config

The host utility setup method uses a program that configures the remote server component. The process isn't necessarily easier or harder than the web server setup method. Channels marshal, format, and transmit messages across AppDomains. Each of a channel's tasks opens new opportunities for extensibility.

Host Utility Demo: RemotingHost.cs

For example, message contents can be marshaled to conform to the proper data representation using custom sinks.

Host Utility Configuration File: RemotingHost.exe.config

The message itself can be formatted via the built-in Simple Object Access Protocol (SOAP) or binary formatters. In addition, transport protocols, such as HTTP or TCP, which are built in, can be configured with ease. The architecture also supports customizable marshalling, formatting, and transmission components that can be plugged in as needed.

Programmatic Remoting Channel Registration: RemotingProxyClient.cs

The HTTPChannel, linking the proxy in AppDomain A to the stub in AppDomain B, is a built-in channel component supporting default marshalling, XML/SOAP formatting, and HTTP protocol transmission.

Lifetime Management

A remote server component exists for a default amount of time and then makes itself available for garbage collection. It's often more desirable to explicitly manage the lifetime of remote components. This is why the remoting framework provides a leasing mechanism for finer granularity of control in remote component lifetime management.

Remote leasing operates via a collaborative protocol between one or more client components, a server component, and a lease manager. Remote server components begin life with a designated amount of time before garbage collection. Client components register with the server component's lease manager for notification of when the server's lifetime is expiring.

Remote Leasing Demo: LeasingDemo.cs

The lease manager keeps track of server components and notifies clients of when the server will expire. When a server has reached its expiration time, the lease manager notifies the client and waits for a designated amount of time for a reply from the client. If the client wants the server to remain alive, it returns the amount of time the server can live to the lease manager. If the designated reply time from the client to the lease renewal query expires, the lease manager marks the server object for garbage collection.

Extensible Markup Language (XML)

XML is an international standard; computer systems can communicate effectively, and applications can read and parse information with a common API. XML is an open standard that can work everywhere, regardless of your hardware platform, operating system, programming language. XML permeates nearly every part of the .NET.

XML class libraries are used to interact with XML data. XML is the essential data transport format for web services, the format for configuration files, and the source of data from external systems. The .NET APIs make it easy to use XML as a standardized method of passing information between programs, file saving and reading, data validation, and many other useful tasks. This unit explains how to use C# and the XML class libraries to interact with XML data.

Writing XML

Writing XML documentation is greatly simplified with the System.Xml class library. The particular class used in this section is the XmlTextWriter class. It has numerous convenience methods that make producing XML documents a snap. The .NET Framework documentation lists all the available methods for the XmlTextWriter class.

Writing an XML Document with XmlTextWriter

The XML streaming APIs encapsulate the code necessary to parse XML files and obtain data related to specific tags. Sometimes you need the flexibility of working with XML data in memory, via the Document Object Model (DOM).

This is a common technique for making the code more maintainable, because if the node name changes, you need only change the TalkNode constant. The second string parameter is the element value. There's no need for formatting, because the WriteElementString method calls do it automatically.

Reading an XML Document with XmlTextReader

To work with XML in memory, you can use an XPathDocument and then use an XPathNavigator to read each node efficiently. The difference between this technique and the XmlTextReader, in addition to what has been previously stated, is that an XPathNavigator can move anywhere in the document, whereas an XmlTextReader is forward only.

The task of modifying an XML document in memory requires using the XmlDocument and XPathNavigator.

Unsafe Mode

C# allows using pointer variables in a function or code block when it is marked by the unsafe modifier. The terms involved are:

1. Safe,
2. Unsafe,
3. Managed,
4. Unmanaged.

The unsafe code or the unmanaged code is a code block that uses a pointer variable. Unsafe code permits the use of pointers, which supports certain performance optimizations and interface to legacy code and operating systems. Unsafe code is identified with a special keyword, unsafe, which marks either a block of code or a field. This establishes an unsafe context where pointer operations can be implemented.

The normal mode of operation in a C# program is safe. When code is safe, its type is safe and secure. Unsafe code is identified by the unsafe keyword. This is code that is allowed to use pointers. All C# code is managed. Managed code is under control of the CLR, which has full control of all memory and security operations.

A pointer is a variable whose value is the address of another variable i.e., the direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address. You can retrieve the data stored at the location referenced by the pointer variable, using the ToString() method. You can pass a pointer variable to a method as parameter. The following example illustrates this:

using System;
namespace UnsafeCodeApplication
{
   class TestPointer
   {
      public unsafe void swap(int* p, int* q)
      {
         int temp = *p;
         *p = *q;
         *q = temp;
      }
      public unsafe static void Main()
      {
         TestPointer p = new TestPointer();
         int var1 = 10;
         int var2 = 20;
         int* x = &var1;
         int* y = &var2;
         Console.WriteLine("Before Swap: var1:{0}, var2: {1}", var1, var2);
         p.swap(x, y);
         Console.WriteLine("After Swap: var1:{0}, var2: {1}", var1, var2);
         Console.ReadKey();
      }
   }
}

Accessing Array Elements Using a Pointer

In C#, an array name and a pointer to a data type same as the array data, are not the same variable type. For example, int *p and int[ ] p are not the same type. You can increment the pointer variable p because it is not fixed in memory but an array address is fixed in memory, and you can't increment that.

To access an array data using a pointer variable, as we traditionally do in C or C++, you need to fix the pointer using the fixed keyword. For compiling unsafe code, you have to specify the /unsafe command-line switch with the command-line compiler.

Graphical Device Interface

The general framework that deals with the DC (Device Context) is referred to as the GDI (Graphical Device Interface). In .NET, the GDI interface has been greatly refined and is referred to as GDI+.

The .NET GDI+ classes encapsulate some of the important Windows API to create graphical outputs. The popular GDI+ classes are needed in creating windows applications. The System.Drawing namespace contains other namespaces for specialized applications such as System.Drawing.Imaging for image processing, System.Drawing.Design for design time controls such as dialog boxes, property sheets etc., System.Drawing.Text for controlling fonts, and System.Drawing.Printing for controlling printing and print preview.

Example

1. Create a windows application. Name the project "gditest".
2. Right click on Form1.cs in the project explorer and choose "view code".
3. Type the following code in the constructor for the Form1 class.
4. Add a Paint event handler by clicking on the lightning symbol above the properties window and double clicking on the Paint event.
5. Type the following code in it.

private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
   // Graphics dc = this.CreateGraphics(); normally, but Paint gets a
   // PaintEventArgs parameter
   Graphics dc = e.Graphics;
   Pen bluePen = new Pen(Color.Blue, 3);   // 3 pixels wide
   dc.DrawEllipse(bluePen, 30, 30, 40, 50); // 30,30 is top,left; 40=width, 50=height
   Pen redPen = new Pen(Color.Red, 2);
   dc.DrawLine(redPen, 30, 30, 100, 100);

   Pen greenPen = new Pen(Color.Green);
   dc.DrawRectangle(greenPen, 60, 60, 50, 50);
}

Note that the Paint event handler gets a DC through the PaintEventArgs parameter, so you can simply use, Graphics dc = e.Graphics; to obtain the DC. The PaintEventArgs parameter in the Paint handler also contains information about the clipping rectangle.

The clipping rectangle is the rectangular area that needs to be repainted (this is similar to the invalidated region in MFC). The clipping rectangle becomes important when there are a large number of objects to be redrawn in the Paint handler. Using the clipping region information, we can choose to redraw only a few of these objects which are being affected.

Brushes are used to fill a particular region with a color or a pattern. For example, the DC has a FillRectangle method and a FillEllipse method which you can pass the brush and the bounding rectangle to fill the shape with the brush.

Case Study (Chat Program)

The application is a simple chat tool. Anyone who connects to the chat server receives all chat communication between the connected users. The application is deliberately kept simple to clarify .NET remoting. This application also demonstrates event and delegate usage in an application that uses .NET remoting.

Most of you will have noticed that there are wizards to develop ASP.NET web services in Visual Studio .NET. However, if you want to develop a Client/Server application that runs over a local area network, there are no wizards available. This application shows how to do .NET remoting in a Local Area Network. This application acts much like a DCOM server and client application.

This Visual Studio .NET solution contains three modules:

1. ChatCoordinator: The server implementation.
2. ChatClient: The client implementation.
3. ChatServer: The runtime host for ChatCoordinator.

CBSE Computer Science Study Material: .NET Technology

Essential Notes for Computer Science

Explore essential learning tools for Computer Science .NET Technology. This curated collection features in-depth notes and targeted practice questions built around the active 2026 curriculum to streamline your daily revision.

Verified Solutions for Computer Science

Built using official NCERT guidelines for Computer Science, these materials provide reliable academic support. Integrating past examination questions and step-by-step solutions helps students understand official CBSE grading criteria.

Enhance Accuracy with Online Tests

Wrap up your chapter revision by testing your knowledge against standard objective question formats. Explore our full library of free, up-to-date sample papers and online assessments to secure top grades in your CBSE examinations.

FAQs

Where can I find the most advanced study material for [current-page:node:field_board] [current-page:node:field_class] Computer Science for 2026-27?

The latest 2026-27 advanced study resources for Computer Science are available for free on StudiesToday.com which includes NCERT Exemplars, high-order thinking skills (HOTS) questions, and deep-dive concept summaries.

What does the 2026-27 Computer Science study package for [current-page:node:field_class] include?

Our exhaustive Computer Science package includes chapter wise revision notes, solved practice sheets, important formulas and Concept Maps to help in better understanding of all topics.

Is this study material enough for both [current-page:node:field_board] exams and competitive tests?

Yes. For , our resources have been developed to help you get better marks in school exams and also build fundamental strength needed for entrance tests including Competency Based learning.

How should [current-page:node:field_class] students use this Computer Science material for maximum marks?

in , students should use Active Recall method, read the concept summary, then solve the Important Questions section without looking at the answers and then check your answers.

Can I download [current-page:node:field_class] Computer Science study notes in PDF for offline use?

All Computer Science study materials are provided in mobile-friendly PDF. You can download and save them on your device.

Are the [current-page:node:field_class] Computer Science resources updated for the latest NEP guidelines?

Yes, our team has ensured that all Computer Science materials for are strictly aligned with the National Education Policy (NEP) 2020 and the latest 2026-27 syllabus.