Professional Documents
Culture Documents
Introduction to .NET
.NET is a major technology change for Microsoft and the software world. Just like the computer world moved from DOS to Windows, now they are moving to .NET. It is the technology from Microsoft, on which all other Microsoft technologies will be depending on in future. .NET technology was introduced by Microsoft, to catch the market from the SUNs Java. Few years back, Microsoft had only VC++ and VB to compete with Java, but Java was catching the market very fast. With the world depending more and more the Internet/Web and java related tools becoming the best choice for the web applications, Microsoft seemed to be loosing the battle. Thousands of programmers moved to java from VC++ and VB. This was alarming for Microsoft and many of the Microsoft fans kept on asking is Microsoft sleeping?. And Microsoft had the answer. One fine morning, they announced: We are not sleeping. We have the answer for you.. And that answer was .NET. But Microsoft has a wonderful history of starting late but catching up quickly. This is true in case of .NET too. Microsoft put their best men at work for a secret project called Next Generation Windows Services (NGWS)., under the direct supervision of Mr. Bill Gates. The outcome of the project is what we now know as .NET. Even though .NET has borrowed most of its ideas from Suns J2EE, it has really outperformed their competitors. Microsofts VC++ was a powerful tool. But it was too complex. It has too many datatypes, and developers had to learn many libraries including WIndows SDK, MFC, ATL, COM etc. There were many datatype compatibility issues while exchanging data between different layers. Visual Basic was too easy, and many serious programmers hated it just for that reason. Even though Visual basic was very easy to use, it was not very flexible to develop serious applications. SUNs Java became a very good choice for
his chapter gives you an introduction to the .NET technology and explains what is .NET.
these reasons. It had the flexibility and power of C++ and at the same time easy enough to catch the attention of VB programmers. Microsoft recognized these factors and they introduced the .NET considering all these factors. All unwanted complexities are eliminated and a pure object oriented programming model was introduced. This makes programmers life very easy. .NET framework comes with a single class library and thats all programmers need to learn!! Whether they write the code in C# or VB.NET or J#, it doesnt matter, you just use the .NET class library. There is no classes specific to any language. There is nothing more you can do in a language, which you cant do in any other .NET language. You can write code in C# or VB.NET with the same number of lines of code, same performance and same efficiency, because everyone uses same .NET class library.
1.1
What is .NET ?
It is a platform neutral framework. Is a layer between the operating system and the programming language. It supports many programming languages, including VB.NET, C# etc. .NET provides a common set of class libraries, which can be accessed from any .NET based programming language. There will not be separate set of classes and libraries for each language. If you know any one .NET language, you can write code in any .NET language!! In future versions of Windows, .NET will be freely distributed as part of operating system and users will never have to install .NET separately . NET is not an operating system. .NET is not a programming language.
.NET is a framework
We cannot define .NET as a single thing. It is a new, easy, and extensive programming platform. It is not a programming language, but it supports several programming languages. By default .NET comes with few programming languages including C# (C Sharp), VB.NET, J# and managed C++. .NET is a common platform for all the supported languages. It gives a common class library, which can be called from any of the supported languages. So, developers need not learn many libraries when they switch to a different language. Only the syntax is different for each language. When you write code in any language and compile, it will be converted to an Intermediate Language
(Microsoft Intermediate Language - MSIL). So, your compiled executable contains the IL and not really executable machine language. When the .NET application runs, the .NET framework in the target computer take care of the execution. (To run a .NET application, the target computer should have .NET framework installed.) The .NET framework converts the calls to .NET class libraries to the corresponding APIs of the Operating system. Whether you write code in C# or VB.NET, you are calling methods in the same .NET class libraries. The same .NET framework executes the C# and VB.NET applications. So, there wont be any performance difference based on the language you write code.
1.2
Many people always get confused with Visual Studio .NET (VS.NET) and .NET technology. VS.NET is just an editor, provided by Microsoft to help developers write .NET programs easily. VS.NET editor automatically generates lot of code, allows developers to drag and drop controls to a form, provide short cuts to compile and build the application etc. VS.NET is not a required thing to do .NET programming. You can simply use a notepad or any other simple editor to write your .NET code!!! And you can compile your .NET programs from the command prompt. Well, what I said is true theoretically.. but if you decide to use notepad for .NET programming, by the time you develop few sample applications, Microsoft would have introduced some other new technology and .NET would be outdated. You may not want that. So, let us go by VS.NET, just like every other .NET guys.
1.3
The above languages are from Microsoft. Many third parties are writing compilers for other languages with .NET support.Difference between VB and VB.NETBelieve us, there is not much in common between VB and VB.NET other than the name. VB.NET is a totally new programming language. It just retains
the syntax of old VB. So, if you are a vb programmer, probably you may like VB.NET than C# just because of the syntax. The .NET Framework is an integral Windows component that supports building and running the next generation of applications and XML Web services.
1.4
To build all communication on industry standards to ensure that code based on The .NET Framework has two main components: the common language runtime and the .NET Framework class library. The common language runtime is the foundation of the .NET Framework. You can think of the runtime as an agent that manages code at execution time, providing core services such as memory management, thread management, and remoting, while also enforcing strict type safety and other forms of code accuracy that promote security and robustness. In fact, the concept of code management is a fundamental principle of the runtime. Code that targets the runtime is known as managed code, while code that does not target the runtime is known as unmanaged code. The class library, the other main component of the .NET Framework, is a comprehensive, object-oriented collection of reusable types that you can use to develop applications ranging from traditional command-line or graphical user interface (GUI) applications to applications based on the latest innovations provided by ASP.NET, such as Web Forms and XML Web services. The .NET Framework can be hosted by unmanaged components that load the common language runtime into their processes and initiate the execution of managed code, thereby creating a software environment that can exploit both managed and unmanaged features. The .NET Framework not only provides several runtime hosts, but also supports the development of third-party runtime hosts. For example, ASP.NET hosts the runtime to provide a scalable, server-side environment for managed
code. ASP.NET works directly with the runtime to enable ASP.NET applications and XML Web services, both of which are discussed later in this topic. Internet Explorer is an example of an unmanaged application that hosts the runtime (in the form of a MIME type extension). Using Internet Explorer to host the runtime enables you to embed managed components or Windows Forms controls in HTML documents. Hosting the runtime in this way makes managed mobile code (similar to Microsoft ActiveX controls) possible, but with significant improvements that only managed code can offer, such as semi-trusted execution and isolated file storage. The following illustration shows the relationship of the common language runtime and the class library to your applications and to the overall system. The illustration also shows how managed code operates within a larger architecture.
1.5
The following sections describe the main components and features of the .NET Framework in greater detail.
1.6
The common language runtime manages memory, thread execution, code execution, code safety verification, compilation, and other system services. These features are intrinsic to the managed code that runs on the common language runtime. With regards to security, managed components are awarded varying degrees of trust, depending on a number of factors that include their origin (such as the Internet, enterprise network, or local computer). This means that a managed component might or might not be able to perform file-access operations, registry-access operations, or other sensitive functions, even if it is being used in the same active application. The runtime enforces code access security. For example, users can trust that an executable embedded in a Web page can play an animation on screen or sing a song, but cannot access their personal data, file system, or network. The security features of the runtime thus enable legitimate Internet-deployed software to be exceptionally feature rich. The runtime also enforces code robustness by implementing a strict type-and-code-verification infrastructure called the common type system (CTS). The CTS ensures that all managed code is selfdescribing. The various Microsoft and third-party language compilers generate managed code that conforms to the CTS. This means that managed code can consume other managed types and instances, while strictly enforcing type fidelity and type safety. In addition, the managed environment of the runtime eliminates many common software issues. For example, the runtime automatically handles object layout and manages references to objects, releasing them when they are no longer being used. This automatic memory management resolves the two most common application errors, memory leaks and invalid memory references. The runtime also accelerates developer productivity. For example, programmers can write applications in their development language of choice, yet take full advantage of the runtime, the class library, and components written in other languages by other developers. Any compiler vendor who chooses to target the runtime can do so. Language compilers that target the .NET Framework make the features of the .NET Framework available to existing code written in that language, greatly easing the migration process for existing applications. While the runtime is designed for the software of the future, it also supports software of today and yesterday. Interoperability between managed and unmanaged code enables developers to continue to use necessary COM components and DLLs.
The runtime is designed to enhance performance. Although the common language runtime provides many standard runtime services, managed code is never interpreted. A feature called just-in-time (JIT) compiling enables all managed code to run in the native machine language of the system on which it is executing. Meanwhile, the memory manager removes the possibilities of fragmented memory and increases memory locality-of-reference to further increase performance. Finally, the runtime can be hosted by high-performance, server-side applications, such as Microsoft SQL Server and Internet Information Services (IIS). This infrastructure enables you to use managed code to write your business logic, while still enjoying the superior performance of the industrys best enterprise servers that support runtime hosting. The .NET Framework class library is a collection of reusable types that tightly integrate with the common language runtime. The class library is object oriented, providing types from which your own managed code can derive functionality. This not only makes the .NET Framework types easy to use, but also reduces the time associated with learning new features of the .NET Framework. In addition, thirdparty components can integrate seamlessly with classes in the .NET Framework. For example, the .NET Framework collection classes implement a set of interfaces that you can use to develop your own collection classes. Your collection classes will blend seamlessly with the classes in the .NET Framework. As you would expect from an object-oriented class library, the .NET Framework types enable you to accomplish a range of common programming tasks, including tasks such as string management, data collection, database connectivity, and file access. In addition to these common tasks, the class library includes types that support a variety of specialized development scenarios. For example, you can use the .NET Framework to develop the following types of applications and services: Console applications Windows GUI applications. Windows Presentation Foundation (WPF) applications. ASP.NET applications. Web services. Windows services. Service-oriented applications using Windows Communication Foundation (WCF). Workflow-enabled applications using Windows Workflow Foundation (WF).
8 Summary
Microsoft has developed .NET framework. .NET framework is comprised of programming methodologies like Visual Studio .NET and mixed programming language. Platform technologies like ADO.NET, Windows Form etc. and Code Execution environment. The .Net framework has integrated few main languages and other existing technologies within it. They are C , C++, J++, VB.NET, ASP.NET, Scripting languages Jscript.NET, ADO.NET, COM and Com+.
QUESTIONS
1. 2. 3. 4. 5. 6. 7. 8. 9. What is .NET? What is .Net Framework? What is .Net technology? Describe briefly its origins. What is web service? How it is achieved using .Net strategy? What is Microsoft Intermediate Language ? With what objectives .NET framework is designed. Explain. What is Visual Studio.Net ? List the different languages supported by .NET? With a neat diagram explain relationship of the common language runtime and the class library to your application.
10. Explain salient features of common language runtime. 11. Briefly explain what types of applications and services can be developed using .NET framework.
Chapter 2
N
.
ET (dot-net) is the name Microsoft gives to its general vision of the future of computing, the view being of a world in which many applications run in a distributed manner across the Internet. We can identify a number of different motivations driving this vision.
Firstly, distributed computing is rather like object oriented programming, in that it encourages specialised code to be collected in one place, rather than copied redundantly in lots of places. There are thus potential efficiency gains to be made in moving to the distributed model. Secondly, by collecting specialised code in one place and opening up a generally accessible interface to it, different types of machines (phones, handhelds, desktops, etc.) can all be supported with the same code. Hence Microsofts run-anywhere aspiration. Thirdly, by controlling real-time access to some of the distributed nodes (especially those concerning authentication), companies like Microsoft can control more easily the running of its applications. It moves applications further into the area of services provided rather than objects owned. Interestingly, in taking on the .NET vision, Microsoft seems to have given up some of its proprietary tendencies (whereby all the technology it touched was warped towards its Windows operating system). Because it sees its future as providing software services in distributed applications, the .NET framework has been written so that applications on other platforms will be able to access these services. For example, .NET has been built upon open standard technologies like XML and SOAP. At the development end of the .NET vision is the .NET Framework. This contains the Common Language Runtime, the .NET Framework Classes, and higher-level features like ASP.NET (the next generation of Active Server Pages technologies) and WinForms (for developing desktop applications).
The .NET Framework provides a run-time environment called the common language runtime, which runs the code and provides services that make the development process easier. Compilers and tools expose the common language runtimes functionality and enable you to write code that benefits from this managed execution environment. Code that you develop with a language compiler that targets the runtime is called managed code; it benefits from features such as cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services. To enable the runtime to provide services to managed code, language compilers must emit metadata that describes the types, members, and references in your code. Metadata is stored with the code; every loadable common language runtime portable executable (PE) file contains metadata. The runtime uses metadata to locate and load classes, lay out instances in memory, resolve method invocations, generate native code, enforce security, and set run-time context boundaries. The runtime automatically handles object layout and manages references to objects, releasing them when they are no longer being used. Objects whose lifetimes are managed in this way are called managed data. Garbage collection eliminates memory leaks as well as some other common programming errors. If your code is managed, you can use managed data, unmanaged data, or both managed and unmanaged data in your .NET Framework application. Because language compilers supply their own types, such as primitive types, you might not always know (or need to know) whether your data is being managed. The common language runtime makes it easy to design components and applications whose objects interact across languages. Objects written in different languages can communicate with each other, and their behaviors can be tightly integrated. For example, you can define a class and then use a different language to derive a class from your original class or call a method on the original class. You can also pass an instance of a class to a method of a class written in a different language. This cross-language integration is possible because language compilers and tools that target the runtime use a common type system defined by the runtime, and they follow the runtimes rules for defining new types, as well as for creating, using, persisting, and binding to types. As part of their metadata, all managed components carry information about the components and resources they were built against. The runtime uses this information to ensure that your component or application has the specified versions of everything it needs, which makes your code less likely to break because of some unmet dependency. Registration information and state data are no longer stored in the registry where they can be difficult to establish and maintain. Instead, information about the types you define (and their dependencies) is stored with the code as metadata, making the tasks of component replication and removal much less complicated. Language compilers and tools expose the runtimes functionality in ways that are intended to be useful and intuitive to developers. This means that some features of the runtime might be more noticeable in one
11
environment than in another. How you experience the runtime depends on which language compilers or tools you use. For example, if you are a Visual Basic developer, you might notice that with the common language runtime, the Visual Basic language has more object-oriented features than before.
2.2
In the past, a software component (.exe or .dll) that was written in one language could not easily use a software component that was written in another language. COM provided a step towards solving this problem. The .NET Framework makes component interoperation even easier by allowing compilers to emit additional declarative information into all modules and assemblies. This information, called metadata, helps components to interact seamlessly. Metadata is binary information describing your program that is stored either in a common language runtime portable executable (PE) file or in memory. When you compile your code into a PE file, metadata is inserted into one portion of the file, and your code is converted to Microsoft intermediate language (MSIL) and inserted into another portion of the file. Every type and member that is defined and referenced in a module or assembly is described within metadata. When code is executed, the runtime loads metadata into memory and references it to discover information about your codes classes, members, inheritance, and so on. Metadata describes every type and member defined in your code in a language-neutral manner. Metadata stores the following information:
12
Description of the assembly. Identity (name, version, culture, public key). The types that are exported. Other assemblies that this assembly depends on. Security permissions needed to run. Description of types. Name, visibility, base class, and interfaces implemented.
Members (methods, fields, properties, events, nested types). Attributes. Additional descriptive elements that modify types and members.
2.3
BENEFITS OF METADATA
Metadata is the key to a simpler programming model, and eliminates the need for Interface Definition Language (IDL) files, header files, or any external method of component reference. Metadata enables .NET Framework languages to describe themselves automatically in a language-neutral manner, unseen by both the developer and the user. Additionally, metadata is extensible through the use of attributes. Metadata provides the following major benefits: Self-describing files. Common language runtime modules and assemblies are self-describing. A modules metadata contains everything needed to interact with another module. Metadata automatically provides the functionality of IDL in COM, so you can use one file for both definition and implementation. Runtime modules and assemblies do not even require registration with the operating system. As a result, the descriptions used by the runtime always reflect the actual code in your compiled file, which increases application reliability. Language interoperability and easier component-based design. Metadata provides all the information required about compiled code for you to inherit a class from a PE file written in a different language. You can create an instance of any class written in any managed language (any language that targets the common language runtime) without worrying about explicit marshaling or using custom interoperability code.
13
Attributes. The .NET Framework lets you declare specific kinds of metadata, called attributes, in your compiled file. Attributes can be found throughout the .NET Framework and are used to control in more detail how your program behaves at run time. Additionally, you can emit your own custom metadata into .NET Framework files through user-defined custom attributes.
2.4
CROSS-LANGUAGE INTEROPERABILITY
Visual Studio 2008 .NET Framework 3.0 Visual Studio 2005 .NET Framework 1.1
This section describes the common language runtimes built-in support for language interoperability and explains the role that the Common Language Specification (CLS) plays in enabling guaranteed crosslanguage interoperability. Language interoperability is the ability of code to interact with code that is written by using a different programming language. Language interoperability can help maximize code reuse and improve the efficiency of the development process. Because developers use a wide variety of tools and technologies, each of which might support different features and types, it has historically been difficult to ensure language interoperability. However, language compilers and tools that target the common language runtime benefit from the runtimes built-in support for language interoperability. The common language runtime provides the necessary foundation for language interoperability by specifying and enforcing a common type system and by providing metadata. Because all languages targeting the runtime follow the common type system rules for defining and using types, the usage of types is consistent across languages. Metadata enables language interoperability by defining a uniform mechanism for storing and retrieving information about types. Compilers store type information as metadata, and the common language runtime uses this information to provide services during execution; the runtime can manage the execution of Multilanguage applications because all type information is stored and retrieved in the same way, regardless of the language the code was written in. Managed code benefits from the runtimes support for language interoperability in the following ways: Types can inherit implementation from other types, pass objects to another types methods, and call methods defined on other types, regardless of the language the types are implemented in.
14
Debuggers, profilers, or other tools are required to understand only one environmentthe Microsoft intermediate language (MSIL) and metadata for the common language runtimeand they can support any programming language that targets the runtime. Exception handling is consistent across languages. Your code can throw an exception in one language and that exception can be caught and understood by an object written in another language. Even though the runtime provides all managed code with support for executing in a multilanguage environment, there is no guarantee that the functionality of the types you create can be fully used by the programming languages that other developers use. This is primarily because each language compiler targeting the runtime uses the type system and metadata to support its own unique set of language features. In cases where you do not know which language the calling code will be written in, you are unlikely to know whether the features your component exposes are accessible to the caller. For example, if your language of choice provides support for unsigned integers, you might design a method with a parameter of type UInt32. However; that method would be unusable from a language that has no notion of unsigned integers. To ensure that your managed code is accessible to developers who are using other programming languages, the .NET Framework provides the Common Language Specification (CLS), which describes a fundamental set of language features and defines rules for how those features are used.
2.5
Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly. An assembly performs the following functions: It contains code that the common language runtime executes. Microsoft intermediate language (MSIL) code in a portable executable (PE) file will not be executed if it does not have an associated assembly manifest. Note that each assembly can have only one entry point (that is, DllMain, WinMain, or Main). It forms a security boundary. An assembly is the unit at which permissions are requested and granted. It forms a type boundary. Every types identity includes the name of the assembly in which it resides. A type called MyType that is loaded in the scope of one assembly is not the same as a type called MyType that is loaded in the scope of another assembly.
15
It forms a reference scope boundary. The assemblys manifest contains assembly metadata that is used for resolving types and satisfying resource requests. It specifies the types and resources that are exposed outside the assembly. The manifest also enumerates other assemblies on which it depends. It forms a version boundary. The assembly is the smallest versionable unit in the common language runtime; all types and resources in the same assembly are versioned as a unit. The assemblys manifest describes the version dependencies you specify for any dependent assemblies. It forms a deployment unit. When an application starts, only the assemblies that the application initially calls must be present. Other assemblies, such as localization resources or assemblies containing utility classes, can be retrieved on demand. This allows applications to be kept simple and thin when first downloaded. It is the unit at which side-by-side execution is supported. Assemblies can be static or dynamic. Static assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk in portable executable (PE) files. You can also use the .NET Framework to create dynamic assemblies, which are run directly from memory and are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed. There are several ways to create assemblies. You can use development tools, such as Visual Studio 2005, that you have used in the past to create .dll or .exe files. You can use tools provided in the Windows Software Development Kit (SDK) to create assemblies with modules created in other development environments. You can also use common language runtime APIs, such as Reflection. Emit, to create dynamic assemblies.
2.6
APPLICATION DOMAINS
Operating systems and runtime environments typically provide some form of isolation between applications. For example, Windows uses processes to isolate applications. This isolation is necessary to ensure that code running in one application cannot adversely affect other, unrelated applications. Application domains provide an isolation boundary for security, reliability, and versioning, and for unloading assemblies. Application domains are typically created by runtime hosts, which are responsible for bootstrapping the common language runtime before an application is run. The topics in this section of the documentation explain how to use application domains to provide isolation between assemblies.
16
This overview contains the following sections: The Benefits of Isolating Applications Related Topics Reference
Historically, process boundaries have been used to isolate applications running on the same computer. Each application is loaded into a separate process, which isolates the application from other applications running on the same computer. The applications are isolated because memory addresses are process-relative; a memory pointer passed from one process to another cannot be used in any meaningful way in the target process. In addition, you cannot make direct calls between two processes. Instead, you must use proxies, which provide a level of indirection. Managed code must be passed through a verification process before it can be run (unless the administrator has granted permission to skip the verification). The verification process determines whether the code can attempt to access invalid memory addresses or perform some other action that could cause the process in which it is running to fail to operate properly. Code that passes the verification test is said to be type-safe. The ability to verify code as type-safe enables the common language runtime to provide as great a level of isolation as the process boundary, at a much lower performance cost. Application domains provide a more secure and versatile unit of processing that the common language runtime can use to provide isolation between applications. You can run several application domains in a single process with the same level of isolation that would exist in separate processes, but without incurring the additional overhead of making cross-process calls or switching between processes. The ability to run multiple applications within a single process dramatically increases server scalability. Isolating applications is also important for application security. For example, you can run controls from several Web applications in a single browser process in such a way that the controls cannot access each others data and resources. The isolation provided by application domains has the following benefits: Faults in one application cannot affect other applications. Because type-safe code cannot cause memory faults, using application domains ensures that code running in one domain cannot affect other applications in the process. Individual applications can be stopped without stopping the entire process. Using application domains enables you to unload the code running in a single application. Code running in one application cannot directly access code or resources from another application. The common language runtime enforces this isolation by preventing direct calls between objects
17
in different application domains. Objects that pass between domains are either copied or accessed by proxy. If the object is copied, the call to the object is local. That is, both the caller and the object being referenced are in the same application domain. If the object is accessed through a proxy, the call to the object is remote. In this case, the caller and the object being referenced are in different application domains. Cross-domain calls use the same remote call infrastructure as calls between two processes or between two machines. As such, the metadata for the object being referenced must be available to both application domains to allow the method call to be JIT-compiled properly. If the calling domain does not have access to the metadata for the object being called, the compilation might fail with an exception of type System.IO.FileNotFound. The mechanism for determining how objects can be accessed across domains is determined by the object. The behavior of code is scoped by the application in which it runs. In other words, the application domain provides configuration settings such as application version policies, the location of any remote assemblies it accesses, and information about where to locate assemblies that are loaded into the domain. Permissions granted to code can be controlled by the application domain in which the code is running.
2.7
The .NET Framework includes classes, interfaces, and value types that expedite and optimize the development process and provide access to system functionality. To facilitate interoperability between languages, most .NET Framework types are CLS-compliant and can therefore be used from any programming language whose compiler conforms to the common language specification (CLS). The .NET Framework types are the foundation on which .NET applications, components, and controls are built. The .NET Framework includes types that perform the following functions: Represent base data types and exceptions. Encapsulate data structures. Perform I/O. Access information about loaded types. Invoke .NET Framework security checks. Provide data access, rich client-side GUI, and server-controlled, client-side GUI. The .NET Framework provides a rich set of interfaces, as well as abstract and concrete (non-abstract)
18
classes. You can use the concrete classes as is or, in many cases, derive your own classes from them. To use the functionality of an interface, you can either create a class that implements the interface or derive a class from one of the .NET Framework classes that implements the interface.
2.8
NAMING CONVENTIONS
.NET Framework types use a dot syntax naming scheme that connotes a hierarchy. This technique groups related types into namespaces so they can be searched and referenced more easily. The first part of the full name up to the rightmost dot is the namespace name. The last part of the name is the type name. For example, System.Collections.ArrayList represents the ArrayList type, which belongs to the System.Collections namespace. The types in System.Collections can be used to manipulate collections of objects. This naming scheme makes it easy for library developers extending the .NET Framework to create hierarchical groups of types and name them in a consistent, informative manner. It also allows types to be unambiguously identified by their full name (that is, by their namespace and type name), which prevents type name collisions. It is expected that library developers will use the following guideline when creating names for their namespaces: CompanyName.TechnologyName For example, the namespace Microsoft.Word conforms to this guideline. The use of naming patterns to group related types into namespaces is a very useful way to build and document class libraries. However, this naming scheme has no effect on visibility, member access, inheritance, security, or binding. A namespace can be partitioned across multiple assemblies and a single assembly can contain types from multiple namespaces. The assembly provides the formal structure for versioning, deployment, security, loading, and visibility in the common language runtime.
2.9
SYSTEM NAMESPACE
The System namespace is the root namespace for fundamental types in the .NET Framework. This namespace includes classes that represent the base data types used by all applications: Object (the root of the inheritance hierarchy), Byte, Char, Array, Int32, String, and so on. Many of these types correspond to the primitive data types that your programming language uses. When you write code using .NET Framework types, you can use your languages corresponding keyword when a .NET Framework base data type is expected. The following table lists the base types that the .NET Framework supplies, briefly describes each type, and indicates the corresponding type in Visual Basic, C#, C++, and JScript.
19
Visual Basic. C# NET Byte byte SByte sbyte No builtin type. Short short Integer int Long long UInt16 No builtin type. UInt32 No builtin type. UInt64 No builtin type. Single ushort
Description An 8-bit unsigned integer. An 8-bit signed integer. Not CLS compliant.
Managed JScript C++ Char Signed char Short int ,long __int64 unsigned short unsigned int , unsigned long unsigned __int64 float double bool wchar_t byte SByte short int long UInt16
A 16-bit signed integer. A 32-bit signed integer. A 64-bit signed integer. A 16-bit unsigned integer. Not CLS compliant. A 32-bit unsigned integer.
UInt32 Not CLS compliant. A 64-bit unsigned integer. UInt64 Not CLS compliant. Floating Single point A single-precision (32-bit) floating-point number. A double-precision (64-bit) Double floating-point number. A Boolean value (true or Boolean false). A Unicode (16-bit) Char character. Decimal A 96-bit decimal value. A signed integer whose size depends on the underlying platform (a 32-bit value on IntPtr a 32-bit platform and a 64bit value on a 64-bit platform).
uint
UInt32
ulong
UInt64
float
Logical Other
IntPtr
20
An unsigned integer whose size depends on the underlying platform (a 32- UIntPtr UIntPtr UIntPtr bit value on a 32-bit UIntPtr UIntPtr platform and a 64-bit value No built- No built- No built-in on a 64-bit platform). in type. in type. type. Not CLS compliant. The root of the object Object hierarchy. An immutable, fixed-length string of Unicode String characters.
Class objects
Object String
object string
Object* String*
Object String
In addition to the base data types, the System namespace contains over 100 classes, ranging from classes that handle exceptions to classes that deal with core runtime concepts, such as application domains and the garbage collector. The System namespace also contains many second-level namespaces.
QEUSTIONS
1. 2. 3. 4. 5. 6. 7. 8. 9. What are the components of .NET framework? What is Common Language Runtime? Enumerate major services provided by CLR. How does CLR implements C# program? What is Common Type System? What is common Language Specification? What is manages code? List some of the important services the Framework Base Classes offer to the user. What are the benefits of .Net strategy advanced by microsoft?
21
d. e.
f. System Namespace 11. Briefly explain the different base data type supported by .NET framework.
Chapter 3
he .NET framework is a new computing platform that simplifies application development in the highly distributed environment of the internet. This section gives technical description about .NET architecture.
22
23
3.1
ARCHITECTURE OF CLR
3.2
It is a subset of CTS. All instruction is in CLS i.e. instruction of CTS is written in CLS. Code Manager Code manager invokes class loader for execution. .NET supports two kind of coding 1) Managed Code 2) Unmanaged Code
3.3
MANAGED CODE
The resource, which is with in your application domain is, managed code. The resources that are within domain are faster. The code, which is developed in .NET framework, is known as managed code. This code is directly executed by CLR with help of managed code execution. Any language that is written in .NET Framework is managed code.
24
Managed code uses CLR which in turns looks after your applications by managing memory, handling security, allowing cross - language debugging, and so on.
3.4
UNMANAGED CODE
The code, which is developed outside .NET, Framework is known as unmanaged code. Applications that do not run under the control of the CLR are said to be unmanaged, and certain languages such as C++ can be used to write such applications, which, for example, access low - level
25
functions of the operating system. Background compatibility with code of VB, ASP and COM are examples of unmanaged code. Unmanaged code can be unmanaged source code and unmanaged compile code. Unmanaged code is executed with help of wrapper classes. Wrapper classes are of two types: CCW (COM callable wrapper) and RCW (Runtime Callable Wrapper). Wrapper is used to cover difference with the help of CCW and RCW.
3.5
26 3.6
3.7
NATIVE CODE
The code to be executed must be converted into a language that the target operating system understands, known as native code. This conversion is called compiling code, an act that is performed by a compiler. Under the .NET Framework, however, this is a two - stage process. With help of MSIL and JIT.
3.8
It is language independent code. When you compile code that uses the .NET Framework library, you dont immediately create operating system - specific native code. Instead, you compile your code into Microsoft Intermediate Language (MSIL) code. The MSIL code is not specific to any operating system or to any language.
27
3.9
JIT (Just-in-Time)
Just - in - Time (JIT) compiler, which compiles MSIL into native code that is specific to the OS and machine architecture being targeted. Only at this point can the OS execute the application. The just - in time part of the name reflects the fact that MSIL code is only compiled as, and when, it is needed. In the past, it was often necessary to compile your code into several applications, each of which targeted a specific operating system and CPU architecture. Often, this was a form of optimization. This is now unnecessary, because JIT compilers (as their name suggests) use MSIL code, which is independent of the machine, operating system, and CPU. Several JIT compilers exist, each targeting a different architecture, and the appropriate one will be used to create the native code required. The beauty of all this is that it requires a lot less work on your part - in fact, you can forget about system - dependent details and concentrate on the more interesting functionality of your code.
28
In addition to containing MSIL, assemblies also include meta information (that is, information about the information contained in the assembly, also known as metadata) and optional resources (additional data used by the MSIL, such as sound files and pictures). The meta information enables assemblies to be fully self - descriptive. You need no other information to use an assembly, meaning you avoid situations such as failing to add required data to the system registry and so on, which was often a problem when developing with other platforms. This means that deploying applications is often as simple as copying the files into a directory on a remote computer. Because no additional information is required on the target systems, you can just run an executable file from this directory and (assuming the .NET CLR is installed) youre good to go. Of course, you wont necessarily want to include everything required to run an application in one place. You might write some code that performs tasks required by multiple applications. In situations like that, it is often useful to place the reusable code in a place accessible to all applications. In the .NET Framework, this is the Global Assembly Cache (GAC). Placing code in the GAC is simple - you just place the assembly containing the code in the directory containing this cache.
Will try to explain the processing in terms of C# code which is written using .NET Framework.
Step 1- Application code is written using a .NET - compatible language C#.
29
Step 2 - Code is compiled into MSIL, which is stored in an assembly (see Figure 1 - 2).
Step 3 - When this code is executed (either in its own right if it is an executable or when it is used from other code), it must first be compiled into native code using a JIT compiler.
Step 4 - The native code is executed in the context of the managed CLR, along with any other running applications or processes.
Note: One additional point concerning this process. The C# code that compiles into MSIL in step 2 neednt be contained in a single file. Its possible to split application code across multiple source code files, which are then compiled together into a single assembly. This extremely useful process is known as linking. This is because it is far easier to work with several smaller files than one enormous one. You can separate out logically related code into an individual file so that it can be worked on independently and then practically forgotten about when completed.
30
This also makes it easy to locate specific pieces of code when you need them and enables teams of developers to divide up the programming burden into manageable chunks, whereby individuals can check out pieces of code to work on without risking damage to otherwise satisfactory sections or sections other people are working on.
QUESTIONS
1. 2. 3. 4. 5. 6. 7. 8. 9. With a neat diagram explain the architecture of .NET framework. List out the objectives of .Net Framework. How the windows programming is different from .Net programming? What are the functionalities of CLR ? Give the steps involved in managed code execution process. What are assemblies? What are static and dynamic assemblies? How the .Net execution environment with application domain differs from traditional way of execution? What is CTS? Explain the classification of types in CTS with a diagram. Write a note on metatdata. With a neat diagram explain the architecture of Common Language Runtime.
10. Briefly explain the following. a. b. c. d. e. 11. Managed Code Unmanaged Code Microsoft Intermediate Language Just-In-Time Compiler Garbage Collector
Explain the different process of executing the C# code which is written using .NET framework.
Chapter 4
icrosofts new .NET technology is a welcome deviation from this path. It has been thought out and designed from scratch. It does not mean that .NET is not backward compatible. We can import the existing components to work in .NET. We can also create components in .NET that can be used by the existing clients. .NET is a new framework for programming Windows. It provides an application execution environment that manages memory, addresses versioning issues and improves the reliability, scalability, and security of any application.
Microsoft has upgraded VB and languages like C++, COBOL, etc. to target the .NET environment. In addition to these languages, it has provided a fresh .NET compliant languageC# (read as C Sharp). It is natural to think that migration from Microsofts popular Visual Basic language to VB.NET or transition from VC++ to VC++.NET would be smooth. But one quick look at C# would convince you that in many cases coding in C# is cleaner more clean, pleasant and efficient. There are two main components of .NET framework .NET Framework Base Class Library (FCL) and Common Language Runtime (CLR). Let us understand each of them.
4.1
The base class library is an extensive common class library that can be used by any .NET compliant language. These classes encapsulate a high degree of functionality that programmers can use in their programs. The library includes classes for creating and displaying Windows forms, Web forms, serialisation, accessing the network and the Internet, manipulating XML documents, accessing databases, etc. Common Language Runtime is the heart of the .NET framework. It actually manages the code during execution. The code that runs under CLR is called managed code. The code that is executed under
31
32
.NET runtime gets benefits like cross-language inheritance, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services.
4.2
The applications created in .NET compliant languages use the classes provided by the Base Class Library. These applications run under .NET runtime that manages the lifetime of objects created by applications, throws up exceptions, etc.
33
language is that it provides the hardware abstraction layer. We can view the IL code of our application using the ILDASM tool shipped with Visual Studio.NET. JIT Compilation JIT (Just In Time) compiler is a crucial component of the .NET framework. The JIT compiler converts IL code into machine code, which is then executed. The JIT compiler does not compile the entire code at once because it could hamper the performance of the program. It compiles the code at runtime, at the time it is called. The code that is compiled gets stored until the execution comes to an end. This avoids recompilation of code. The reason why conversion from IL code to machine code takes place at runtime is that the JIT first gets information on the processor type and appropriately converts the IL code so that it would run on that type of processor. Assemblies An assembly is a unit containing IL code of a program. It is similar to a DLL file, but one difference is that unlike DLL, an assembly is self-describing. Assemblies contain assembly metadata (or manifest) that gives details of the assembly, type metadata describing the types, methods, etc, defined in the assembly and resources. Garbage Collection Garbage Collection is a program that is invoked by the CLR to free the memory that is not being used by the application. Because of this technique the programmers no more need to take care of memory leakages, dangling pointers and clean up of memory. Thats it for a brief introduction to the .NET framework. Let us now create a simple program in C# that uses the .NET framework. It is assumed that you have installed Visual Studio.NET on a machine running under Windows NT/2000/XP.
4.4
34
(d) Select a location where this project should get saved. Name the project as Simple. Click the OK button. (e) A Class1.cs file (cs stands for CSharp) would get created with the skeleton code given below:
using System; namespace Simple { class Class1 { static void Main ( string[ ] args ) { Console.WriteLine ( Hello C# ); } } }
Compile and execute the program by pressing Ctrl+F5. The program execution starts from the Main() function. Since C# is a pure object-oriented language it does not allow us to create global variables and functions. Instead, all variables and functions including Main() should be defined inside a class. To send output to the screen we have used the WriteLine() function. We can display any data type through this function. Since WriteLine() belongs to the Console class we have to use the form Console.WriteLine() to call it. To be able to use the Console class in any program we need to import it from a namespace, which has been done in our program through the statement using System. Like the Console class our class is also enclosed in the Simple namespace.
QUESTIONS
1. 2. 3. 4. With a neat diagram explain the components of .NET framework. Explain the important features of .NET. Write down the steps to be followed while creating a C# program. Describe the structure of typical C# program.
35
5. 6. 7. 8. 9.
Why do we use the using directive in a C# program? What is the importance of the Main method in a C# program? Why do we use comments in a program? Describe the difference between the two styles of comments used in C#. How does the Write() method is different from WriteLine() method?
10. What is syntax error? How do we detect them? 11. Write a C# program to display the text Hello C#. Explain it.
Chapter 5
C# Language Syntax
T
5.1
his article will show you the basic statements in C# language and language syntax.
DECLARING VARIABLES
The following sample shows different ways you can declare a variable:
int a; int salary, incomeTax, sum; int count = 10; string name; string fullName= Little John;
5.2
LOOP STATEMENTS
5.2.1 While
int i = 0; while ( i < 5 ) { Console.WriteLine ( i ); ++i; }
36
37
The above loop repeates 5 times and prints the value of i. The output of above code would be like this : 0 1 2 3 4
5.2.2
for
The above loop repeates 5 times just like the while loop and prints the value of i. The output of above code would be like this : 0 1 2 3 4
5.2.3
do ... while
38
The above loop is pretty much same as the while loop. The only difference is, the condition is checked only after executing the code inside the loop.
5.2.4 foreach
string [] names = new string[]{ Little John, Pete, Jim, Bill }; foreach ( string name in names ) { Console.WriteLine ( name ); }
foreach loop can be used to iterate through a collection like array, ArrayList etc. The above code displays the following output:
Little john Pete Jim Bill
5.3
CONDITIONAL OPERATORS
if ... else This is the conditional operator, used to selectively execute portions of code, based on some conditions.
string name = Little John; if ( name == Jim ) { Console.WriteLine( you are in if block ); } else { Console.WriteLine( you are in else block ); }
39
5.4
5.4.1 Break
break statement is used to break out of loops (while, for , switch etc).
string [] names = new string[] { Little John, Pete, Jim, Bill }; foreach ( string name in names ) { Console.WriteLine ( name ); if ( name == Pete ) break; }
In the above sample, it iterates through the array of 4 items, but when it encounters the name Pete, it exits the loop and will not continue in the loop anymore. The output of above sample would be :
Little John Pete
5.4.2 Continue
continue statement is also used to in the loops (while, for etc). When executed, continue statement will move the exection to the next iteration in the loop, without continuing the lines of code after the continue inside the loop.
40
string [] names = new string[]{ Little John, Pete, Jim, Bill }; foreach ( string name in names ) { if ( name == Pete ) continue; Console.WriteLine ( name ); }
In the above sample, when the value of name is Pete, it executes the continue which will change the execution to the next iteration, without executing the lines below it. So, it will not print the name, if the name is Pete. The output of above sample would be :
Little John Jim Bill
5.5
SWITCH
if you have to writeseveral if...else conditions in your code, switch statement is a better way of doing it. The following sample is self explanatory:
int i = 3; switch ( i ) { case 5: Console.WriteLine( Value of i break; case 6: Console.WriteLine( Value of i break; case 3: Console.WriteLine( Value of i break; case 4: Console.WriteLine( Value of i break; default: Console.WriteLine( Value of break; }
is : + 5 ); is : + 6 ); is : + 3 ); is : + 4 ); i is : + i );
41
In the above sample, depending on the value of the conditional item, it executes appropriate case. In our code, since the value of i is 3, it executes the third case. The output will be as shown below:
Value of i is : 3
QUESTIONS
1. 2. With an example explain how to declare variables in C#. With an example explain the following loop statements in C#. a. b. c. d. 3. 4. 5. 6. 7. 8. 9. While Do..While For Foreach
With an example explain break and continue statement in C#. Write a program to print whether a given number is even or odd. Write a program to print all possible roots of the quadratic equation ax2+bx+c=0. Write a program to print the factorial of a given number. Write a program to print the first n terms of the Fibonacci series. Write a program to reverse the given number. Write a program to find the sum of the digit of a given number.
10. Demonstrate the typical use of goto statement. 11. Compare and contrast if..else statement and switch statement.
Chapter 6
DataTypes in C#
ataTypes are the basic building block of any language. Microsoft has tried to standardise the datatypes in .NET framework by introducing a limited, fixed set of types that can be used to represent almost anything in programming world.
C++ was very rich in datatypes, but that leads to confusion too. Especially, when you write components that may be consumed by applications written in other platforms, you have to make sure the types used are compatible with other platforms too! .NET types start from a clean slate. All .NET languages share the same types. So, they are all compatible and no worries.This means, you can call C# code from VB.NET and vice versa, without worrying about type conversions. .NET data types are either structures or classes, part of the System namespace. For example, the following data types are implemented as struct in .NET: Int16 Int32 Double (String is implemented as a class in .NET, for various reasons.) If you are not very familiar with struct and class, dont worry about it. You can just use them as if they are simple data types. Here is how you can declare variables of type Int, Double and String: Int16 age, employeeNumber;
42
Chapter 6 - DataTypes in C#
43
Double salary; String name, address; You can use any of the .NET data types directly in any .NET language - in C#, VB.NET or xyz.NET.But in addition to the .NET types, each language provides a set of primitive types, which map to the corresponding types in .NET class library. This is why you may see some people use string and some others use String. There is no big difference. string is a primitive data type in C# and String is the corresponding class in .NET class library. The string in C# is mapped to the class in .NET class library. So, whether you use string or String,there is no real difference.
6.1
The following list shows the list of data types available in C# and their corresponding class/struct in .NET class library.
C# Data type Mapped to .NET class/struct Sbyte Byte Char Float Decimal Double Ushort Short Uint Int Ulong Long Bool String Object System.SByte System.Byte System.Char System.Single System.Decimal System.Double System.UInt16 System.Int16 System.UInt32 System.Int32 System.UInt64 System.Int64 System.Boolean System.String System.Object
The following tables shows some of the differences between values types and reference types.
value types allocated on stack A value type variable contains the data itself reference types allocated on heap reference type variable contains the address of memory location where data is actually stored.
when copying a reference type variable to another variable, only the when you copy a value type variable memory address is copied. Both to another one, the actual data is variables will still point to thesame copied and each variable can be memory location, which means, if independently manipulated. you change one variable, the value will be changed for the other variable too. integer, float, boolean, double etc are string and object are reference types. value types. struct is value type. classes and interfaces are reference types.
QUESTIONS
1. 2. 3. 4. 5. 6. 7. 8. Briefly explain data types in C# and .NET. List the data types in C# and their corresponding class/struct in .NET class library. What is a literal? What is a constant? What is variable? There are thirteen simple value types. List them. List the two different reference types. Differentiate between value types and reference data types in C#.
Chapter 7
n modern object oriented programming, large computer programs are divided into several classes. Typically, a large project will have several hundred classes. A class represents an entity in a program. For example, if you are doing a small program called calculator, you will typically have a single (or more) class called Calculator (you can give any name for your class). The class will have several methods, that will do the functionality of the class. So, your calculator may have methods like the following: Add() Subtract() Multiply() Divide() A sample calculator class, written in C# is given below:
45
46
using System; public class Calculator { public int Add(int value1, int value2) { return value1 + value2; } public int Subtract(int value1, int value2) { return value1 - value2; } public int Multiply(int value1, int value2) { return value1 * value2; } public int Divide(int value1, int value2) { return value1 / value2; } }
7.2
PROPERTY IN C# CLASS
How do you access member variables of any class from outside the class ? In most of the languages including C++ , you will make the member variables public so that you can create an instance of the class and directly access the public fields, as shown below:
public class Car { // private fields. public string color; // constructor public Car() { } }
The above class has one public field : color. You may access this field from outside the class as shown below:
47
But this is the old way ! This would still work with C#, but the suggested approach is to use Property instead of directly accessing member variables. The following code snippet shows how to create Property in a class.
public class Car { // private fields. private string color; // constructor public Car() { } public string Color { get { return color; // return the value from privte field. } set { color = value; // save value into private field. } } }
The above class has one private field - color. Then we have one Property called Color, which is used to represent the private field. Note that the field is private and the Property is public. (We have used the same name with upper/lower case to represent the Property and field, but you may give any name you want.) Each property has two parts : 7.2.1 get set
48
The get part is executed when you access the value of the Property as shown below:
Car car = new Car(); string color = car.Color;
When executed, the above get accessor will return the value stored in the field color . The set part is executed when you assign a value to the Property as shown below:
Car car = new Car(); car.Color = RED;
When executed, the above set accessor will assign the value RED to the private field color. (Note thatvalue is a keyword, which will have the value assigned to it.) So, what is the difference ? On the first look, there is no difference! You can achieve the same behaviour by writing 2 different methods ( like SetColor(...), GetColor() ). First advantage of using property is, code looks cleaner than having 2 separate methods. You can simply call a property as if it was a field in the class Well, then you may ask why make it 2 methods, we can make it a public field, so that we can access it by creating an instance of the class. The main advantage over using a Property instead of a public field is, with the property, you will get a chance to write few lines of code (if you want) in the get and set accessors. So, you can perform some validation or any other logic before returning any values or assigning to the private field. See the modifed class below:
public class Car { // private fields. private string color; // constructor public Car() { } public string Color {
49
get { if ( color == ) return GREEN; else return color; } set { if ( value == ) thrown new Exception (Wrong value.); else color = value; } } }
Let us analyze the get part first. Here we are checking whether there is a valid value in the field color before we return the value. If it is empty, we are getting a chance to return a default value Green. This way, we can make sure that whoever calls the property Color will always get a valid color, never an empty string. In the set part, we are doing a validation to make sure we always assign a a valid value to our field. If someone assign an empty string to the Color property, he will get an exception (error).
Car car = new Car(); car.Color = ;
The above code will throw an error because we are trying to assign an empty string and the set accessor will throw an error if it an empty string. This way, we can make sure that we allow only valid values to be assigned. So, i guess now you would appreciate the purpose of Property. So, no more public fields! Always have private fields and write public properties as wrapper for them if required to expose them to outside the class.
7.3
NAMESPACES IN .NET
A Namespace is a group of related classes. It is a good practice to group related classes into a namespace when you create a class library.
50
The main advantage of using namespaces is, to avoid conflicts when you have multiple classes with the same name. For example, .NET comes with a class called Form. Suppose you also write another class called Form in your application and if you refer to the class Form, how does the compiler know which Form you are refering to ? Here is the importance of namespace. You can refer to the .NET Form using the fully qualified name, including the namespace like this : System.Windows.Forms.Form And you can refer to your own Form like this : MyApplication.Form, where MyApplication is your namespace. So, namespaces allow you to avoid name conflicts! All classes in .NET class library are grouped into namespaces. You can use all the classes using the fully qualified name, including the namespace also along with the class name. System.Windows.Forms.Form System.String System.Double If you want to declare a Button object, you must do the following : System.Windows.Forms.Button myButton; It is not mandatory to use the namespace also along with the name. You may use the using directive on top of the class and safely avoid the need to write the fully qualified name everytime when you refer to a class. using System.Windows.Forms.Button; If you have the above line of code on top of the class file, you dont need to type the namespace name System.Windows.Forms with all the classes in this namespace. You can simply use class name directly as shown below: Button myButton;
7.4
.NET NAMESPACES
System
51
QUESTIONS
1. 2. 3. 4. 5. 6. 7. 8. 9. With an example explain class and methods. With an example explain get and set properties in a class. How do we invoke a method in C#? What is nesting of methods? Give an example of typical use of methods nesting? Describe three different ways of providing values to instance variables of a class? Describe two ways of accessing the values of data fields? Compare them. What is property? Why are they referred as smart fields? List at least three important features of properties. Create a class to hold two integer values. Design a method swap that would take two integer object as parameters and swap their contents.
10. What do you mean by name spaces. List the name spaces available in .NET class library.
Chapter 8
WinForms
Windows based applications in .NET is called WinForms. The .NET framework comes with a good number of classes to support Form based application development. A WinForm application will have atleast one Form (window), which would be used for the interaction between the application and user. A Form can contain other controls like TextBox, Label, Button etc. Large WinForms applications will have several Forms, some of them used to capture data from user and some of them used to display data to user. By performing certain actions in each form, user can navigate to other Forms in the application.
8.1
Event Driven programming model is the most commonly used feature in modern programming. In this model, you will write appropriate code for each event. Examples for events are Button Click Mouse Move Mouse Click Key Press In Winforms application, users interact with the application using various actions in the window (like
52
Chapter 8 - WinForms
53
clicking a button, moving mouse, pressing keys in keyboard etc). These actions will generate various events. When an event is generated, the code written for that event will be executed. For example, in a user registration screen, you may have several controls like text boxes where user can enter their name, address, age etc. Once user enter all the information, he may press the Submit button. As a developer, you would have written code in the button click event, to save this user entered data into a database. This is how typically a WinForms based application works in an event driven programming model.
8.2
8.3
Simple MessageBox This chapter and the attached sample application will give you a brief idea about the following: Reading the text value from a textbox Displaying a message box About the sample application This application has 1 textbox and a button. If you type anything in the textbox and press the button, it will display the same text you typed in a MessageBox. Download and unzip the sample application from this page. After you unzip, you will get several files. Some of the important files are :
54
1. Chapter1.csproj - This is the C# project file. Double click this file to open the project. 2. Form1.cs - This is the file for the Form1 in teh sample application. After you open the project, see the Solution Explorer bar on the right side of the Visual Studio. You can click on that to expand it, which will display the list of all files in the project. (Or, you can go to the menu View > Solution Explorer to open the solution explorer. Click on Form1.cs in the solution explorer to open the Form. Now you can see the Form in design mode. Right click on the Form1.cs in the solution explorer and choose View Code to see the source code behind this Form (Or, press F7 from the Form to see the code). Let us analyze the code: The code has lot of Visual Studio generated code. For time being ignore all those code and scroll down to the event handler code in the bottom of the file.
The first line will simply display a messagebox and show the text typed by the user. MessageBox is a class inside the namespace System.Windows.Forms . We have a statement using System.Windows.Forms on top of the source code. This is like a source code. This will help us avoid typing System.Windows.Forms. everytime when we want to use a class inside this namespace. The next few lines of code do a bit more. Here we are displaying a message box, with some additional attributes. The second optional parameter of the Show method is the caption for the messagebox. The third parameter tells that the messagebox will have two buttons - YES and NO. You have several other options like MessageBoxButtons.OK, MessageBoxButtons.OKCancel etc. And, the last parameter says display a question Icon in the messagebox. There are many other types of icons you can display. And another important part is, the MessageBox returns a value when the user press a button to close the messagebox. Our MessageBox asks a question Did you like this application ? and gives two options to the user - YES or NO.
Chapter 8 - WinForms
55
The return value is of type DialogResult and is assigned to the variable result. We are checking the value of the result and depending on whether user pressed the YES button or NO button, appropriate message will be displayed.
QUESTIONS
1. a. b. 2. 3. 4. 5. 6. 7. 8. Write a note on the following. Winform Event Driven Programming Write the steps to create Winform applications. Briefly discuss the various controls available in System.Windows.Froms. Write a C# program to create and display a window. Briefly explain the MessageBox class. Briefly explain the different types of event that can be generated. With the help of an example program explain how to add button control to the window. Write a program to display a message box and read the data entered in the text box. Briefly explain.
Chapter 9
Inheritance
9.1
WHAT IS INHERITANCE?
he concept of inheritance brings something of a real-world view to programming. It allows a class to be defined which has a number of characteristics and then other classes to be created which are derived from that class. The derived class inherits all of the features of the parent class and typically then adds some features of its own. By deriving classes we create what is often referred to as a class hierarchy. The class at the top of the hierarchy is known as the base class and the derived classes as subclasses. Any number of classes may be derived from a class. It is only possible for a derived class to inherit from one class. As such, C# is known as a single inheritance programming language. Classes need not only be derived from a base class. For example, a subclass can also inherit from another subclass.
9.2
AN EXAMPLE OF INHERITANCE
As with most programming concepts the subject of inheritance in C# is perhaps best illustrated with an example. In the previous chapter we created a class called BankAccount:
56
Chapter 9 - Inheritance
57
public class BankAccount { public string accountName; public int accountFee; private int accountBalance; private int accountNumber; public int getAccountNumber() { return accountNumber; } public void setAccountNumber(int newNumber) { accountNumber = newNumber; } }
This class does a good job of defining characteristics common to any type of bank account, such as account holder name, account number and current balance. Imagine, however, that our banking program needs to support a number of specific types of account. For example, the bank might offer its customers an interest bearing savings account. A savings account will have all the characteristics of our BankAccount class but would also need a way to store the prevailing interest rate. One option would be to create a brand new class from the ground up called SavingsAccount which duplicates everything we have in our BankAccount class, plus extra members needed for a savings account. Another, more efficient method is to derive a SavingsAccount class from the BankAccount class and then add in the extra functionality into this subclass.
9.3
CREATING A SUBCLASS IN C#
Now that we have ascertained that we need to create a sub class of our BankAccount class we can take a look at the code necessary to achieve this. Subclasses are declared in the same way as any other class with the exception that the class name is followed by a colon (:) followed by the name of the class from which it is to inherit. With this in mind we can begin by creating our SavingsAccount class:
58
public class BankAccount { public string accountName; public int accountBalance; public int accountNumber; public BankAccount (string name, int number) { accountName = name; accountNumber = number; } public int getAccountNumber() { return accountNumber; } public void setAccountNumber(int newNumber) { accountNumber = newNumber; } } public class SavingsAccount : BankAccount { }
We have now created a sub class of BankAccount called SavingsAccount, but at this point the SavingsAccount class is no different than its parent class. Next we need to add some new members to add the behavior we need:
public class SavingsAccount : BankAccount { public double interestRate; public SavingsAccount (string name, int number, int balance, double rate): base (name, number) { accountBalance = balance; interestRate = rate; } public double monthlyInterest() { return interestRate * accountBalance; } }
Chapter 9 - Inheritance
59
We now have a new class called SavingsAccount which inherits all the members of the BankAccount class and adds some members of its own. In particular we have added a new data member called interestRate which will store the interest rate paid on the account together with a new method to calculate the monthly interest.
9.4
Of particular significance is the constructor. In the BankAccount base class we have a constructor which takes the account name and account number as arguments. In the SavingsAccount subclass we need to accept two additional arguments - the balance and the interest rate. The : base code instructs C# to handle the name and number arguments using the constructor from the base class. The remaining two arguments are then passed to the SavingsAccount constructor. With our subclass complete we can now make use of it:
static void Main() { SavingsAccount saveAccount = new SavingsAccount(Fred Wilson, 123456, 432, 0.02F); Console.WriteLine (Interest this Month= +save Account. monthlyInterest() ); }
This in essence is what inheritance is all about. In the next chapter we will begin looking at Understanding C# Sharp Abstract Classes
9.5
In the examples we have looked at so far in this book we have created classes which could be both instantiated as objects and used as a base class from which to derive classes. Often a base class is not intended to be instantiated and is provided solely for the purpose of providing an outline for subclasses. Such a class is known as an abstract class. An abstract class cannot be instantiated as an object and is only provided for the purpose of deriving subclasses.
A C# abstract class contains abstract members which define what a subclass should contain. These abstract members only declare that a member of a particular type is required, it does not implement the member. Implementation of abstract members takes place within the derived class. A subclass which derives from an abstract class and fails to implement abstract methods will fail to compile.
Abstract member functions and properties are also declared using the abstract keyword. For example to declare an abstract method in our Talk class the following code is required:
public abstract void speak();
We now have an abstract class with an abstract method named speak(). Note that this declaration only states that any class derived from the Hello base class must implement a method called speak() which returns no value (i.e it is declared as void). It does not, however, implement the method.
We now have a class called SayHello which is derived from the abstract Talk class. The next step is to implement the abstract speak() method. When implementing abstract members in a derived class the override modifier must be used. For example:
Chapter 9 - Inheritance
61
We now have a subclass derived from the Talk abstract class which implements the abstract speak() method. We can now bring all of this together into a simple program:
using System; class Hello { public abstract class Talk { public abstract void speak(); } public class SayHello : Talk { public override void speak() { Console.WriteLine(Hello!); } } static void Main() { SayHello hello = new SayHello(); hello.speak(); } }
62
the base class, but may be optionally overriden in the derived class if different behavior is required. For example, the following example implements a virtual method in the Talk class:
using System; class Hello { public abstract class Talk { public abstract void speak();
public virtual void goodbye() { Console.WriteLine(Talk class says goodbye!); } } public class SayHello : Talk { public override void speak() { Console.WriteLine(Hello!); } } static void Main() { SayHello hello = new SayHello(); hello.speak(); hello.goodbye(); } }
When executed, the goodbye() method in the Talk class will be executed resulting in the following output:
Hello! Talk Class says goodbye!
If we decide that the default goodbye() method provided by the Talk class is not suitable for the requirements of the SayHello subclass we can simply implement our own version of the method using the override modifier:
Chapter 9 - Inheritance
63
using System; class Hello { public abstract class Talk { public abstract void speak();
public virtual void goodbye() { Console.WriteLine(Talk class says goodbye!); } } public class SayHello : Talk { public override void speak() { Console.WriteLine(Hello!); } public override void goodbye () { Console.WriteLine (SayHello Class says goodbye!); } } static void Main() { SayHello hello = new SayHello(); hello.speak(); hello.goodbye(); } }
Now when we execute our program the SayHello implementation of the googbye() method will be called:
Hello! Say Hello Class says goodbye!
QUESTIONS
1. 2. With an example program explain the inheritance concept in C#. What is reusability of code? How it is achieved in C#?
64
3. 4. 5. 6. 7. 8. 9. What are two forms of inheritance? Give your own examples. Describe the syntax of single inheritance in C#. Describe improvement characteristics of inheritance.
How does a base class receive its arguments in order to construct its members properly? When do we declare a class abstract? State the characteristics of abstract classes. What are the characteristics of abstract methods?
10. What is virtual method? 11. With an example program explain how to pass arguments to the base class constructors.
12. Write a note on abstract class. 13. Differentiate between abstract and virtual members.
Chapter 10
Exception Handling
xception handling is an in built mechanism in .NET framework to detect and handle run time errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution.
10.1 INTRODUCTION
C# provides three keywords try, catch and finally to do exception handling. The try encloses the statements that might throw an exception whereas catch handles an exception if one exists. The finally can be used for doing any clean up process. The general form try-catch-finally in C# is shown below:
try { // Statement which can cause an exception. } catch(Type x) { // Statements for handling the exception } finally { //Any cleanup code }
65
66
If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally block. But in C#, both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks. If there is no exception occurred inside the try block, the control directly transfers to finally block. We can say that the statements inside the finally block is executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto. In C#, exceptions are nothing but objects of the type Exception. The Exception is the ultimate base class for any exceptions in C#. The C# itself provides couple of standard exceptions. Or even the user can create their own exception classes, provided that this should inherit from either Exception class or one of the standard derived classes of Exception class like DivideByZeroExcpetion ot ArgumentException etc.
The modified form of the above program with exception handling mechanism is as follows. Here we are using the object of the standard exception class DivideByZeroException to handle the exception caused by division by zero.
//C# : Exception Handling Using System;
67
Class MyClient { Public static void Main() { int x=0; int div=0; try { div=100/x; Console.Writeln(this line } Catch(DivideByZeroException { Consloe.Writeln(Exception } Console.Writeln(Result is } }
In the above case the program do not terminate unexpectedly. Instead the program control passes from the point where exception occurred inside the try block to the catch blocks. If it finds any suitable catch block, executes the statements inside that catch and continues with the normal execution of the program statements. If a finally block is present, the code inside the finally block will get also be executed.
//C#: Exception Handling using System; class MyClient { public static void Main() { int x = 0; int div = 0; try { div = 100/x; Console.WriteLine(div); } catch(DivideByZeroException de) { Console.WriteLine (Exception occured);
68
} finally { Console.WriteLine(Finally Block); } Console.WriteLine(the Result is {0},div); }
Remember that in C#, the catch block is optional. The following program is perfectly legal in C#.
class MyClient { public static void Main() { int x = 0; int div = 0; try { div = 100/x; Console.WriteLine(div); } finally { Console.WriteLine(Finally Block); } Console.WriteLine(the Result is {0}; }
But in this case, since there is no exception handling catch block, the execution will get terminated. But before the termination of the program statements inside the finally block will get executed. In C#, a try block must be followed by either a catch or finally block
69
public static void Main() { int x = 0; int div = 0; try { div = 100/x; Console.WriteLine(Not executed line); } catch(DivideByZeroException de) { Console.WriteLine(DivideByZeroException ); } catch(Exception ee) { Console.WriteLine(Exception ); } finally { Console.WriteLine(Finally Block); } Console.WriteLine(Result is {0},div); } }
70
Console.WriteLine(Exception ); } Console.WriteLine(LAST STATEMENT); } }
71
} } class MyClient { public static void Main() { try { throw new MyException (Rajesh); } catch(Exception e) { Console.WriteLine (Exception caught here + e.ToString ()); } Console.WriteLine(Last Statement); } }
QUESTIONS
1. 2. 3. 4. 5. 6. What are compile time errors? Give some examples. How are they detected? What are run time errors? Give some examples. How are they detected? What is exception? Give some examples. Why is it necessary to handle an exception by a special code? Describe the tasks involved in handling exceptions. How do you define the following. a) try block b) catch block c) finally block. 7. What do you my Exceptions? With the help of an example program explain how exception is handled in C#.
72
8. 9. List at least four exceptions that occur in C# programs.
What happens when a try block is neither followed by a try block nor ny a finally block.
10. What is the purpose of using finally block? Give some examples. 11. When do you consider it necessary to define your own exception classes?
12. With an example program explain how to throw your own exceptions. 13. Briefly explain Standard Exceptions. 14. Write a note on user defined Exceptions.
Chapter 11
Arrays
he type of each array declared is given firstly by the type of basic elements it can hold, and secondly by the number of dimensions it has. Single-dimensional arrays have a single dimension (ie, are of rank 1). They are declared using square brackets, eg:
int[] i = new int[100] This line of code declares variable i to be an integer array of size 100. It contains space for 100 integer elements, ranging from i[0] to i[99]. To populate an array one can simply specify values for each element, as in the following code: Int[] i=new int[2]; i[0]=1; i[1]=2; One can also run together the array declaration with the assignment of values to elements using int[] i = new int[] {1,2}; or the even shorter version of this: int[] i = {1,2}; By default, as we have seen, all arrays start with their lower bound as 0 (and we would recommend that you stick with this default). However, using the .NET frameworks System.Array class it is possible to create and manipulate arrays with an alternative initial lower bound.
Chapter 11 - Arrays
73
74
The (read-only) Length property of an array holds the total number of its elements across all of its dimensions. As single-dimensional arrays have just one dimension, this property will hold the length of the single dimension. For instance, given the definition of array i above, i.Length is 2.
A foreach loop can also be used to access each of the elements of an array in turn, but using this construction one doesnt have the same control over the order in which the elements are accessed.
Chapter 11 - Arrays
75
or s
1. 2. 3. for (int i = 0; i < jag.Length; i++) for (int j = 0; j < jag[i].Length; j++) Console.WriteLine(jag[i][j]);
QUESTIONS
1. What do you mean by arrays? Explain how define and initialize arrays in C#.
76
2. 3. 4. 5. 6. 7. 8. 9. Differentiate between Rectangular arrays and Jagged arrays. Explain the need for array variables. What is a variable size array? How is it different from a rectangular array? Give an example of typical use of variable size array. Write a program to add two matrices. Write a program to multiply two matrices. Write a program to find row sum and column sum of a matrix. Write a program to verify whether a given matrix is identity matrix or not.
Chapter 11 - Arrays
Chapter 12
C# Collection Classes
he C# Collection classes are a set of classes designed specifically for grouping together objects and performing tasks on them. A number of collection classes are available with C# and we will be looking at the key classes in this chapter
77
78
using System; using System.Collections.Generic; public class Lists { static void Main() { List<string> colorList = new List<string>(); } }
A list item value can similarly be changed using the index combined with the assignment operator. For example, to change the color from Yellow to Ingido:
colorList[2] = Indigo;
All the items in a list may be accessed using a foreach loop. For example:
79
When compiled and executed, the above code will output each of the color strings in the colorList object.
It is important to note that items in a list may be duplicated. In the case of duplicated items, the Remove() method will only remove the first matching instance.
80
If the item is not found in the List a value of -1 is returned by the IndexOf() method. This technique could be used to replace a specific value with another. For example, without knowing in advance the index value of the Yellow string we can change to Black:
colorList[colorList.IndexOf(Yellow)] = Black;
The LastIndexOf() method returns the index value of the last item in the list to match the specified item. This is particularly useful when a list contains duplicate items.
81
The Clear() method removes the items from the list and sets the Count property to zero. The Capacity property, however, remains unchanged. To remove the capacity of a list follow the Clear() method call with a call to TrimExcess().
QUESTIONS
1. 2. 3. 4. 5. a. b. c. d. e. f. g. What are C# collection classes? Explain briefly. How does an array of ArrayList class different from Array class? When do we decide to use the ArrayList class over the Array class? With an example explain how to create List and ArrayList classes in C#. With an example explain the following. Adding items to list. Accessing list items. Removing items from list. Inserting items into a list Sorting lists. Finding items in a list Clearing the list.
Chapter 13
Introduction to ADO.NET
ADO .NET
Most applications need data access at one point of time making it a crucial component when working with applications. Data access is making the application interact with a database, where all the data is stored. Different applications have different requirements for database access. VB .NET uses ADO .NET (Active X Data Object) as its data access and manipulation protocol which also enables us to work with data on the Internet. Lets take a look why ADO .NET came into picture replacing ADO.
82
83
This lesson is an introduction to ADO.NET. It introduces primary ADO.NET concepts and objects that you will learn about in later lessons. Here are the objectives of this lesson: Learn what ADO.NET is. Understand what a data provider is. Understand what a connection object is. Understand what a command object is. Understand what a DataReader object is. Understand what a DataSet object is. Understand what a DataAdapter object is.
13.2 INTRODUCTION
ADO.NET is an object-oriented set of libraries that allows you to interact with data sources. Commonly, the data source is a database, but it could also be a text file, an Excel spreadsheet, or an XML file. For the purposes of this tutorial, we will look at ADO.NET as a way to interact with a data base. As you are probably aware, there are many different types of databases available. For example, there is Microsoft SQL Server, Microsoft Access, Oracle, Borland Interbase, and IBM DB2, just to name a few. To further refine the scope of this tutorial, all of the examples will use SQL Server.
84
table 1. ADO.NET Data Providers are class libraries that allow a common way to interact with specific data sources or protocols. The library APIs have prefixes that indicate which provider they support.
Provider Name ODBC Data Provider OleDb Data Provider Oracle Data Provider SQL Data Provider Borland Data Provider API prefix dbc
Data Sources with an ODBC interface. Normally older data bases. leDb Data Sources that expose an OleDb interface, i.e. Access or Excel. racle For Oracle Databases. ql dp For interacting with Microsoft SQL Server. Generic access to many databases such as Interbase, SQL Server, IBM DB2, and Oracle.
An example may help you to understand the meaning of the API prefix. One of the first ADO.NET objects youll learn about is the connection object, which allows you to establish a connection to a data source. If we were using the OleDb Data Provider to connect to a data source that exposes an OleDb interface, we would use a connection object named OleDbConnection. Similarly, the connection object name would be prefixed with Odbc or Sql for an OdbcConnection object on an Odbc data source or a SqlConnection object on a SQL Server database, respectively. Since we are using MSDE in this tutorial (a scaled down version of SQL Server) all the API objects will have the Sql prefix. i.e. SqlConnection.
85
86
adapter defined for each table in a DataSet and it will take care of all communication with the database for you. All you need to do is tell the data adapter when to load from or write to the database.
Summary
ADO.NET is the .NET technology for interacting with data sources. You have several Data Providers, which allow communication with different data sources, depending on the protocols they use or what the database is. Regardless, of which Data Provider used, youll use a similar set of objects to interact with a data source. The SqlConnection object lets you manage a connection to a data source. SqlCommand objects allow you to talk to a data source and send commands to it. To have fast forward-only read access to data, use the SqlDataReader. If you want to work with disconnected data, use a DataSet and implement reading and writing to/from the data source with a SqlDataAdapter.
QUESTIONS
1. 2. 3. 4. 5. 6. a. b. c. d. e. Give the overall concept of ADO.NET. Explain in detail ADO.NET architecture. What is a data set? Explain. Write a program to show the demonstration of ADO.NET. What do you mean by ADO.NET data providers? Explain briefly. Briefly explain the following ADO.NET objects. the SqlConnectionObject the SqlCommandObject the SqlDataReaderObject the DataSetObject the SqlDataAdapterObject
Chapter 14
Introduction to ASP.NET
87
88
uses HTML and VBScript (or Jscript) to process and render pages, but because VBScript is a scripting language, you were forced to write spaghetti code (VBScript was entwined in the HTML and ended up rather messy in larger applications). ASP.NET separates code from display, and you can even have pages with no ASP.NET code in them at all. By adding references in your HTML (called controls), you can tell ASP.NET that you want a button here, some text there, and then in your code, you can manipulate what these controls look like, what they display, how big they are, etc. Controls can do more than just display information. You can add events to controls, so that when a visitor clicks on a button, for example, ASP.NET executes a function of your choice.
89
reference on your page to where that DataGrid should go. The DataGrid will be rendered as a table, and will contain all of the data extracted from the database. Microsoft has created an amazingly well designed MSDN library for ASP.NET and all of the other .NET languages. It includes a full class library containing information and examples on every class, function, method, and property accessible through ASP.NET. The MSDN library also includes some tutorials and examples to get you started. It may take you a while to get used to the format and layout of the MSDN ASP.NET library, however, once you do, you will find its an invaluable resource to aid you throughout your ASP.NET learning experience. The .NET MSDN library can be found at http://msdn.microsoft.com/net/
If you take either of the code examples shown above and add the following HTML to them, then they would both run perfectly inside of an ASP.NET page:
90
<head> <title>Hello World example!</title> </head> <body> <asp:Label id=myLabel runat=server /> </body> </html>
QUESTIONS
1. 2. 3. 4. 5. What is a web service ? Explain its working. How does the web service is different from web page? What is ASP.NET? What is use of ASP.NET? Write a program to display Welcome to ASP.NET 8 times in increasing order of their font size using ASP.NET. What is the role of System.Web? Write a program to demonstrate handling of server control programs. Explain briefly the web services provided by ASP.NET. Write a note on ASP.NET class library.
6. 7. 8. 9.
REFERNCES
1. 2. 3. 4. 5. E. Balaguruswamy, Programming in C#, Tata McGrawhill Publication C Xavier, C#, SCITECH publication http://www.dotnetspider.com http://www.csharp-station.com (MSDN Library), www.microsaft.com/msdn