an introduction to the microsoft .net framework...

64
CENTRAL OSTROBOTHNIA POLYTECHNIC, 2004 B: AJANKOHTAISTA - AKTUELLT AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK ARCHITECTURE AND TOOLS Supplementary materials for the crash course of software engineering Evgueni V. Pychkine

Upload: others

Post on 12-Apr-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

CENTRAL OSTROBOTHNIA POLYTECHNIC, 2004

B: AJANKOHTAISTA - AKTUELLT

AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK

ARCHITECTURE AND TOOLS

Supplementary materials for the crash course of software engineering

Evgueni V. Pychkine

Page 2: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

PUBLISHER: Central Ostrobothnia Polytechnic Ylivieska Unit,

Vierimaantie 7, 84100 Ylivieska, FINLAND Technical editing and layout: Virve Antinoja Photos: Evgueni V. Pychkine Cover: Paula Salonen, Mika Pajala B: Ajankohtaista – Aktuellt ISBN 952-5107-38-8 ISSN 1239-0755 Printed: multiprint, Vaasa 2003

Page 3: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

CONTENTS 1 INTRODUCTION...................................................................................................................................5

1.1 About the Author ...............................................................................................................5 1.2 Computer Science Faculty, St-Petersburg State Polytechnical University ...........................6 1.3 Presenting the Course .......................................................................................................8

2 UNDERSTANDING THE .NET INITIATIVE ............................................................................................9

2.1 Development of Programming Models and the .NET Vision Statement ...............................9 2.2 The .NET Platform for the Web Services World ..................................................................9 2.3 The .NET is About Many Things .......................................................................................11 2.4 Introducing C#..................................................................................................................13

3 THE .NET FRAMEWORK ARCHITECTURE FOUNDATIONS.................................................................16

3.1 Understanding the Managed Code....................................................................................16 3.2 Assemblies.......................................................................................................................17 3.3 The CLR Execution Model.................................................................................................19 3.4 The Framework Class Library Essentials...........................................................................25

4 THE .NET LANGUAGE INTEROPERABILITY CONCEPTS ....................................................................28

4.1 The Common Type System...............................................................................................28 4.2 The Common Language Specification...............................................................................32

5 .NET APPLICATIONS DEVELOPMENT BY USING VISUAL STUDIO .NET...........................................34

5.1 Hello World “Advanced” (Assemblies Revisited)................................................................34 5.2 C# Standalone Application................................................................................................38 5.3 Customizing user control ..................................................................................................47 5.4 Using Language Interoperability .......................................................................................49 5.5 Building XML Web Service Component and Web Service Client Application.......................52

6 CONCLUSION ....................................................................................................................................62 REFERENCES ........................................................................................................................................63

Page 4: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

TABLE OF FIGURES Figure 2-1. Microsoft .NET platform for Web generation software ...........................................................................................10 Figure 2-2. The .NET Framework architecturally .....................................................................................................................12 Figure 3-1. Compiling source code into .NET managed modules.............................................................................................17 Figure 3-2. Introducing assembly concept ..............................................................................................................................18 Listing 3-1. HelloWorld Console Application C# Source Code ..................................................................................................18 Figure 3-3. The assembly internal structure viewed by ILDasm utility .....................................................................................19 Figure 3-4. CLR execution model............................................................................................................................................20 Figure 3-5. Managed code producers .....................................................................................................................................21 Figure 3-6. Unmanaged code producers .................................................................................................................................22 Table 3-1. The .NET executable codes....................................................................................................................................23 Figure 3-7. Loading the CLR...................................................................................................................................................24 Table 3-2. Some general FCL namespaces.............................................................................................................................25 Table 3-3. Application-specific namespaces...........................................................................................................................26 Listing 3-2. The FCL types vs. language primitive types..........................................................................................................27 Figure 4-1. Usual approach to define languages .....................................................................................................................28 Figure 4-2. The CTS as the storage of core programming abstractions ...................................................................................29 Figure 4-3. The CLR/CTS types graph.....................................................................................................................................30 Table 4-1. The FCL types and corresponding primitive types ..................................................................................................31 Figure 4-4. The CTS and CLS cooperation ..............................................................................................................................32 Figure 4-5. Checking the CLS-compliance..............................................................................................................................33 Listing 5-1. Simple console based user dialogue ....................................................................................................................35 Listing 5-2. Main class of HelloWorldAdvanced.NET console application .................................................................................36 Figure 5-1. HelloWorldAdvanced assembly contents viewed with ILDasm...............................................................................37 Figure 5-2. Creating application window for Safe Multiplication 1.0 .NET application ..............................................................39 Listing 5-3. Actions associated with pushing Go button: parsing values and multiplication......................................................39 Listing 5-4. The full source code of the application “Safe Multiplication 1.0” ..........................................................................41 Figure 5-3. Safe Multiplication: Examples of execution ...........................................................................................................46 Figure 5-4. Improved textbox appearance...............................................................................................................................47 Figure 5-5. Inheritance from the standard user control ...........................................................................................................47 Listing 5-5. Creating non-standard user control that inherits to the FCL user control...............................................................48 Listing 5-6. Checked multiplication implemented as VB component........................................................................................50 Listing 5-7 The fragment of the method button1_Click() .........................................................................................................50 Figure 5-6. The solution explorer window with explored references folder: properties of the CheckedMultiplication assembly 51 Listing 5-8. Web service ASMX-file Service1.asmx .................................................................................................................53 Listing 5-9. C# source code for checked multiplication Web service component .....................................................................53 Figure 5-7. Multiplication Web Service files ............................................................................................................................55 Figure 5-8. Web service testing environment automatically generated by the Visual Studio .NET debugger browsed by the

Internet Explorer ...........................................................................................................................................................55 Listing 5-10. Using Web Service by calling proxy class method ..............................................................................................57 Listing 5-11. Printing message with full description of the server side error............................................................................58 Listing 5-12. Revised fragment of the main() function.............................................................................................................58 Figure 5-9. XML Web Service Infrastructure............................................................................................................................60 Figure 5-10. XML Web Service Infrastructure in details...........................................................................................................61

Page 5: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

5

1 INTRODUCTION

1.1 About the Author

Officially Evgueni V. Pychkine was born in 1969. In 1992 Evgueni V. Pychkine has graduated from the St-Petersburg State Polytechnical University (Honours Diploma) where he continues to work till now. From 2000 he holds PhD in Computer Science and takes post of Associate Professor at the Automation and Computer Science Dept. As the Vice-Dean responsible for international cooperation he takes care about organization of the working program of academic contacts between Computer Science Faculty and Central Ostrobothnia Polytechnic.

Background His background as a lecturer is associated with courses of programming in C++ language, object-oriented programming, software engineering and some related subjects. The main area of interests of him is the programming models development and programming languages as subject of research, as well as the subject of learning. He believes that it’s very difficult to teach languages (both human and machine), but he likes teach to learn languages. As a visiting lecturer he has provided at COP the introductive course of Java-programming and the crash course of software engineering with using Microsoft .Net Framework.

Other interests He speaks English, French and German. His interests to foreign languages are primarily inspired by the interest to the cultures of different lands and peoples. In particular, he is very interested in French literature, music and painting. He plays piano and loves to compose music.

Essential works Automation of the synthesis of multilevel circuits of discrete information transducers on the free surplus set of elements. Ph.D. thesis. St-Petersburg State Polytechnical University, 2000. Sonate No.2 pour piano avec suite d’aquarelles, 1996. Alloquium (d’après Anselmus Cantuariensis) pour piano, 1997.

Page 6: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

6

1.2 Computer Science Faculty, St-Petersburg State Polytechnical University http://www.spbstu.ru

http://www.ftk.spbstu.ru The Computer Science Faculty is the leading Computer Science Department at the St Petersburg State Polytechnical University. The educational activity, scientific and innovative researches cover numerous areas in Information and Computer Technologies. Since its foundation in 1976 this relatively young institution rapidly became a real brand name in field of high level and top quality computer education. Due to the wide range of international mobility programs with foreign educational establishments as well as with various hi-tech enterprises and computer industry giants such as Intel, IBM, Microsoft, Motorola, Altera, Hewlett Packard, Siemens and others we have the possibilities not only to exchange new technologies, but also to share our knowledge in teaching process. We are always open to further cooperation contacts that could be interesting and profitable to all the partners.

Our professors provide high-appreciated courses in foreign high schools and universities. On the whole about 50 professors, more than 130 associate and assistant professors, 10 senior lecturers, 25 academic assistants are teaching inside the walls of their alma mater. We are preparing graduates with BSc and MSc degrees, as well as Dipl. Engineers, PhDs and Dr.Scs. About 300 students enter the faculty each academic year. More than 1500 students are studying simultaneously at the classes and laboratories in several departments of the faculty, specializing in different branches of information technologies, control systems, robotics, engineering cybernetics and hardware and software developments.

We have vast experience of organizing short-term courses in computer science disciplines for international students. As the example of successful active projects the the cooperation program with Central Ostrobothnia Polytechnic may be emphasized. We are also interested in any kind of research cooperation. Among the most significant research trends noticeable nowadays at the faculty the enterprise quality software development, software quality metrics, software-testing methods, distributed software development, software and hardware modeling, simulation and co-simulation systems, software environments and technologies, single chip microcontrollers systems, hybrid systems, cognitive and multi-agent systems, software security and reliability, wireless telecommunication systems could be cited.

Page 7: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

7

The scientific directions being developed at the faculty can be represented in visual form, as a kind of our common mind map:

Page 8: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

8

1.3 Presenting the Course The purpose of this work is to explain in brief how to develop different kind of applications for the .NET Framework and to let students have some supplementary materials to be well prepared for the crash course lectures and practice.

Audience The introduced course is oriented to students and IT professionals that want to learn more about actual trends of software construction. The course provides students with understanding of the leading concepts which software engineering technologies of the day are based on. Students will get the skills to create applications of moderate complexity with using Microsoft .NET platform. The students will learn the C# essentials and get the primary understanding how the language interoperability is supported by the .NET Framework programming model.

At Course Completion At the end of the course, students will understand the object model and its elements, the ways the object model is implemented in different languages and programming technologies. The students will have the understanding of the .NET Framework architecture and the .NET Framework programming model. After completing practical exercises students will be able to create Web applications of moderate complexity, including XML Web services and client applications accessing Web services.

Prerequisites Before attending the course students must have some experience in programming with at least one language such as C++, Java or Object Pascal; basics of procedural, object-oriented and component programming; basics of data flows, control flows and structural programming fundamentals; primary understanding of what is Web and basic conception of client/server computing. The experience in using Microsoft Windows operating systems family and Microsoft Visual Studio developer’s tools is desired. Being familiarized with XML and related technologies is helpful, but not required.

Acknowledgements I’d like to thank all listeners and readers of the draft versions of this work, among them: Juha Huumonen, the chief of international department of COP (Ylivieska unit), some students specializing in media technologies at COP after guidance of Veikko Brax, my students at the Computer Science Faculty of the St-Petersburg State Polytechnical University (SPbSPU), Alexander Pavlov (completed his M.Sc. work after my guidance) for his help in preparing some application examples dealing with Web Services, Anna Besstrashnova for her helpful notes regarding to language usage, and, of course, my wife Galina who is one of the first listeners and critiques of my works. I’m especially grateful to Veikko Brax for his constant help in organizing these courses in the framework of the cooperation between Central Ostrobothnia and St-Petersburg Polytechnics and all necessary arrangements and preparations.

Page 9: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

9

2 UNDERSTANDING THE .NET INITIATIVE

2.1 Development of Programming Models and the .NET Vision Statement Somewhat about 2000 Microsoft’s chiefs Bill Gates and Steve Ballmer declared that they have had changed the company and since that time it is “no more just about personal computers, but about empowering people through great software, any time, any place and on any device” [Miller, 2002]. From the philosophical point of view, the .NET platform can be understood as some implementation of this vision statement. From more practical and more technical prospective, the .NET Framework programming model is one of the possible answers to the actual needs of software producers and software customers. To see this clearly let us make a brief historical look at the development of programming models. In over than 15-20 years we’ve known multiple different programming models that have been mainly associated with sorts of hardware of the day. Some of these models are still being used; some of them are rather archaic. One of the first programming models we’ve known is mainframe-programming model, based on time and resources sharing. With expansion of relatively cheap personal computers available for end customers a desktop programming model appeared, firstly for so called monolithic applications (that in general are totally separate entities), and then for shared memory Windows-like applications. Another level of representing data exchange and resource access abstractions was implemented by the client/server architecture (that in general is not tightly integrated with operating systems where applications run). In some sense, the client/server architecture oriented programming can also be distinguished as one of the ways to program. Then we’ve seen at least a couple of versions of the Web usage: we’ve seen so called printing on the Web, basically just putting HTML code out on the Web-site (eventually integrated with script code providing a client located functionality); we’ve seen a dynamic Web-pages creation, based on the server-side solutions using e.g. ASP and databases access.

2.2 The .NET Platform for the Web Services World

Web Generation Programming A lot of IT-professionals and software developers really believe we’re going to a new programming model that is often called the third generation of the Web [Risse, 2001]. Following Risse’s definition, this model is response to the users’ needs to standardize the way to program the Web that works within the company (that is often called the Intranet), that works outside of the company (that is usually called “business-to-business”, B2B, or simply the Extranet) or the web that works for consumers (generally called the Internet that provides “business-to-client” communication schema, or B2C).

Page 10: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

10

One of assumptions which this new generation Web programming model is being derived from is that a user may want to get information from the Web by using any device at any time: by using a cell phone or a palm, by using a simple desktop browser, or a rich desktop, etc. The Internet is then introduced as a standard networking environment, where the idea of delivering software as a service (not obligatorily as an end product) is exposed. The way to create such kind of service-oriented applications is then called Web services programming model.

Web Services What is a Web service? From the developer’s prospective, Web service is a programmable application component that can be called similar way you use to make a function call, or a DLL-method call, or an API-function call. Web services are accessible as URL-addressed resources via ubiquitous Internet protocols. As a rule, Web services are very small reusable application components that can be shared seamlessly among Web sites as services. From the user prospective, Web service programming model implements the earlier discussed idea of software as a service, software accessible when users need it. It’s important to note that Web services programming model is not a Microsoft-centric model. We know, for example, Java-based implementation of Web services programming model.

The .NET Platform for the Web Generation Software The .NET platform is then Microsoft offer to the Web services world (see Figure 2-1). It includes aspects of mobile users support, home clients as well as the work place based clients, accessing software components by using different kinds of devices. So, the .NET Framework is aimed to connect devices.

Figure 2-1. Microsoft .NET platform for Web generation software

Page 11: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

11

It includes a set of experiences that around what people do: do they work on the Web at home, or in the office, do they work on information documents, do they work as busyness analysts or as developers. Hence, the .NET Framework is aimed to connect user experiences, i.e. to connect people. It includes a set of so called core services, such as Microsoft .NET Passport service that is already well known to those who has Hotmail account. And this could be called as “connecting information systems”. Finally it includes server infrastructure that is aimed to provide the ability of the services to be available 24/7 in scalable and reliable infrastructure. This server applications also take care about integration of the Web services world with the systems that users already have.

2.3 The .NET is About Many Things The thing, we should touch before going further, is the understanding that the .NET is not only about Web services. The presentation of an approach to program the Web with Web services is surely the key strength used to mobilize developers to start learning the .NET Framework architecture and tools (and it’s exactly what we do), and thinking this way, it is some kind of marketing. But the .NET Framework supports all kinds of applications. As Chappell said, “the .NET is about Web services, certainly, but it’s also about many other things” [Chappell, 2002]. So, in the framework of this course we should try to talk about “many other things”, not only or mainly about Web services.

The .NET Framework as a Development Platform The kernel of the .NET Initiative is the .NET Framework as a development platform for developing such kind of .NET applications as XML Web Services, Web Forms applications, Win32 GUI-based applications, Win32 console applications, Windows services and utilities. The .NET Framework can be installed on all 32-bits versions of Windows family operating systems (Windows 98, Windows 98 SE, Windows Me, Windows NT 4.0, Windows 2000), and on all versions of Windows XP and Windows .NET Server Family. Windows Server 2003 ships already with Microsoft .NET Framework 1.1. Additionally Microsoft has developed a rich software developer’s kit (the .NET Framework SDK) that is distributed for free and includes compilers for all .NET languages implemented by Microsoft (C#, Visual Basic .NET, C++ with Managed Extensions .NET, JScript .NET, J#) as well as collection of utilities and documentation files. The .NET Framework SDK requires Windows NT 4.0, Windows 2000, Windows XP, or Windows .NET Server family OS.

The Common Language Runtime As to architecture, the .NET Framework is based on two foundation parts (see Figure 2-2): the Common Language Runtime (CLR) and the Framework Class Library (FCL).

Page 12: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

12

Figure 2-2. The .NET Framework architecturally

The Common Language Runtime is the execution environment where all .NET applications are run. The CLR is firstly implemented for Windows family operating systems. Distribution of CLR elements as open source will support the implementation of the CLR for other system architectures. The essential parts of the CLR specification together with C# language and the portions of the FCL are already standardized by the European Computer Manufacturers Association (ECMA). All this opens doors (or “windows”☺) for implementation of the .NET Framework on different system platforms and architectures. Let us briefly analyze the common reasons of using special execution environment instead of direct source code compilation into native code executed by a processor. The increasing of the software size and complexity, often requiring reusable code components accessible by the Web, caused the necessity to develop programming systems oriented to produce mobile, safe and stable code. The code mobility assumes that it’s possible to execute the code on different platforms and architectures. The code safety is in strong relation to the language facilities guaranteeing that the code has no unauthorized access to the resources of the computer where the code run on. The code stability depends in great part on possibility to detect errors as early as possible in development time or in runtime and on total exclusion of some classes of errors (such as memory management errors, uncaught exception errors, uninitialized objects errors, etc.) [Pychkine, 2003-2]. The standard mechanism making able to deal with code having such characteristics, is based on the idea of using a special execution system working with some kind of intermediate code instead of direct compilation of a source code into a set of processor instructions. The common language runtime is an implementation of this idea in the .NET Framework programming architecture.

Page 13: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

13

The Framework Class Library The Framework Class Library contains definitions of thousands .NET types used while constructing .NET components. The FCL is also one of the most important constituent parts of the .NET Framework. By definition, the FCL is the common base class library available for all .NET languages. Certainly, different languages may have features that are not directly mapped to each other. This problem is resolved by the common language specification (CLS). CLS-compliance of a component means that this component can produce or/and consume code originally written in other .NET language.

The .NET Compact Framework The light (or “lite” as Richter named [Richter, 2002]), version of .NET Framework called the .NET Compact Framework for pocket PCs and mobile devices is also realized.

Visual Studio .NET As a development environment the Visual Studio .NET is realized. The last chapter of this work shows in some details how to use Visual Studio .NET tools to create different kinds of .NET applications. The last release of the .NET development environment is Visual Studio .NET 2003 edition that provides support development, debugging, emulation and testing applications for portable and mobile devices among others features.

2.4 Introducing C# Despite having a lot of languages ported to the .NET platform, for many people C# is one of the most visible aspects of the .NET initiative. The reasons of this are the following:

• It expresses the .NET concepts better than other .NET languages. • It supports component programming at the language level. • It is widely used by Microsoft professionals in their presentations and

marketing campaigns regarding the .NET Framework programming. • It is immediately familiar to C++ developers. • Many C# underlying concepts closely match to Java ones. This helps

developers understand the genesis of C# and the ways C# use to implement concepts of object-oriented and component programming.

Generally said, each programming language is a tool that is a product of software development conceptions, the tool that clothes the essential contents of the conceptions in syntax form [Pychkine, 2003-2]. Subsequently, it is clear that from the developer’s prospective, learning the language is the shortest way to have a good understanding of the new programming infrastructure. At first sight C# programs match very closely to Java ones. Just as Java, C# is strictly object-oriented language that supports single inheritance with interfaces (and don’t support multiple inheritance). C# has a lot of similar features (but not total equality) to Java in thread processing and exception handling.

Page 14: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

14

C# has also a strong type system where all type casts are checked to be safe during a compilation stage as well as in runtime. C# has documentation comments (with embedded XML instead of using embedded HTML in Java documenting model). By the way, Chappell believes that if Microsoft had no licensing problems for free changing of Java, C# would probably not exist today [Chappell, 2001-1]. But now it exists and it’s about useless to suffer about hypothetic circumstances, and no one knows would Java .NET be better implementation of the .NET conceptions than C# is or not. Although C# is to some extend a copy of Java (with using C++ syntax to express Java compatible semantics), it has important features that don’t exist in Java. The good example of such kind of features is attribute concept support, which allow developers to control the code’s external behavior directly from within the code. Another example is full support for value types such as primitive types and structures. Some features existing in Java have been implemented in C# differently. For example, class names may not correspond to the file names (although it’s often so); namespaces may be “reopened” in other files and they don’t match to the internal structure of an assembly; exceptions don’t have to be caught in the client code, etc. At last, in contrast to first implementations of Java, C# is compiled language from the beginning (as well as all other .NET languages). Some C# features are virtual answers to possible demands of C++ developers, among them are the following:

• operator overloading that is really one of the habits of many C++ programmers;

• possibility to write code that uses pointers and direct access to the memory (i.e. to write unsafe code);

• rich type system that contains structures (struct) and enumerations (enum); • passing function arguments by reference (also for value types); • flexible memory control that makes possible to have objects allocated on the

stack; • syntax appearance, etc.

In addition, C# syntax wraps for features that can be programmed in other languages, but that mainly are not directly language-implemented. The list of some of them follows:

• Component-based programming with properties and events; • Delegates as method types; • Indexers as custom specified operations that can be used as indexes; • Boxing / unboxing mechanism which allows treating value type instances as

objects; • Attributes which allow attaching metadata to the source code and therefore

extending the language.

Page 15: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

15

In his speech at the St-Petersburg Polytechnic in 2001 Chappell said that C++ is the way to complicate things. If I have correctly understood the idea, strict explanation of this is the following: complicating things means that data and process models built by using C++ abstractions are often more complex than they actually could be. In this sense, Java would be qualified as the language that simplifies things. This means that models built by using Java abstractions are often simpler than they actually should be. C# is probably the good compromise between C++ and Java approaches to program with correspondence of the leading idea of the object-oriented programming allowing developers to express the problem and the essential part of software project in terms of the problem [Pychkine, 2003-1].

Page 16: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

16

3 THE .NET FRAMEWORK ARCHITECTURE FOUNDATIONS We will shortly describe here two levels of the .NET Framework architecture (see Figure 1-2), the CLR execution model and the FCL contents.

3.1 Understanding the Managed Code

Managed Code as a Concept To understand better the way to program under the umbrella of the .NET Framework, we should begin from the managed code concept. When we say “managed code” we think about the code, where correctness and safety is checked at runtime (i.e. when the execution environment manages the code’s lifetime and execution). To guarantee that the executed code is “safe” and secure the CLR provides the following features [Pavlov, 2002]:

• Type safety verification; • Allocation and releasing memory resources management – Garbage Collector

(GC) takes care about objects deletion; • Exceptions handling as the main consistent approach to errors handling; • Two levels of security: code level and user roles level.

The code is supposed to be type safe, if the following conditions are true:

• A reference to a type is strictly compatible with the type being referenced; • Only appropriately defined operations are invoked for the object instance; • Identities are what they claim to be. It means that if, for example, some

method is defined to accept 4-byte value, the CLR detects and blocks the operation required accessing parameters as 8-byte value.

During verification, managed code is examined for confirmation that the code accesses memory locations and calls methods only through properly defined types. Here are examples of such examined situations:

• Out-of-bounds referencing; • Attempts to read memory that has not been primarily written; • Uncaught exceptions.

As a concept, an idea to verify code during execution isn’t new. At the same time, we should remark that the .NET implementation of this idea uses some relatively new approaches.

.NET Managed Modules A managed module is the main output of any .NET compiler (Figure 2-1). The managed module is the standard Windows PE file that requires the CLR to execute. Thinking so, we can group the parts of a managed module into two sections. First section is in relation to PE internal structure and information interpreted by the CLR and utilities (we are leaving details for the classroom, see also [Richter, 2002]). The second section is the most interesting for us because it is strongly related to the application source code and to the .NET execution model.

Page 17: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

17

This section consists of two parts. First one is the intermediate language (IL) code that is produced by the .NET language compilers and that will be later (in runtime) compiled by the CLR JIT-compiler into native processor instructions set. The second one is the metadata section. Metadata tables contain information about types and members defined in the module as well as about types and members defined in the referenced modules. Thus, metadata guarantee the verification of the IL code. Due to the metadata, the IL code executed by the CLR can be checked for correctness of memory usage, method arguments, type casts and branches control. The integration of metadata with the code constitutes more productive and extensible model in comparison with type libraries and IDL-files. Compilers don’t need any kind of header files since all information can be received directly from modules. IntelliSense tools in Visual Studio .NET allow developers getting hints about methods signatures and type structures deduced from the corresponding metadata. Metadata is also used to provide development time check of method calls. Garbage collector uses metadata to control object lifetime. Metadata allows to have object serialization on remote computer.

Figure 3-1. Compiling source code into .NET managed modules

As you see, metadata is used almost on every stage of the .NET Framework development and execution process, so Gunnerson called metadata “glue” joining together all .NET runtime elements [Gunnerson, 2000].

3.2 Assemblies The CLR doesn’t actually work directly with managed modules, it works with assemblies. Assembly is a set of logically grouped modules and resource files (Figure 3-2). An assembly is defined in the .NET abstracts as a reusing, deployment, versioning and security policy smallest unit. Depending on the situation, either .NET language compiler, or IL assembly linker play the role of a linkage tool.

Page 18: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

18

Figure 3-2. Introducing assembly concept

Each assembly contains information about all modules of the assembly and about referenced assemblies, therefore assemblies are self-describing (by their manifests). It means that the CLR gets all information used in process of runtime verification directly from the assembly, no additional information is required neither from the OS registry, nor from the Active Directory [Richter, 2002]. This simplifies the .NET applications deployment. As a result, since all the .NET components are types and therefore need no registration, the installation procedure is often just copying files. The .NET Framework SDK contains special utility called ILDasm (Intermediate Language code DisASseMbler) which allows programmer to “explore” an assembly. We take as an example the C# source code of the console application used in every teaching book “Hello. World!” that can be implemented in the .NET Framework as Listing 3-1 shows. // HelloMain.cs using System; namespace HelloWorld { /// <summary> /// Main class of the console application printing "Hello, World!" /// </summary> class CMain { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { Console.WriteLine( "Hello, World!" ); } } }

Listing 3-1. HelloWorld Console Application C# Source Code

Page 19: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

19

After building the .NET managed module we can view the contents of the assembly code by using the ILDasm utility so to get the information about internal structure of this assembly as shown in Figure 3-3.

Figure 3-3. The assembly internal structure viewed by ILDasm utility

Here we see that an assembly always contains the manifest (in fact, it’s special file where basically the names of the files that are the part of the assembly are stored, but also the assembly’s attributes, version information, security information associated with it, culture, publisher, publicly exported types description). Also we see the class and members structure of the managed module and we may “explore” the IL-code of each method of the class (as shown for the method main() in Figure 3-3). As mentioned by Richter, the reason of introducing this new assembly concept is to allow developers to decouple the logical and physical notions of reusable types [Richter, 2002].

3.3 The CLR Execution Model Now we are ready to discuss how the managed code is executed in the CLR environment in details (see Figure 3-4). To execute the method presented as a set of IL instructions, IL code must be converted to the code that can be executed by the processor installed on the machine (as noted above, this code is usually called native CPU code, or, shortly, native code). The translation of the IL code into machine commands is the task of JIT compiler.

Page 20: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

20

Figure 3-4. CLR execution model

JIT Compilation Model The process of JIT compilation (just-in-time compilation) is based on the idea of compiling the code when it is called instead of total compilation of the code as a whole. Because the CLR supplies a JIT compiler for each supported CPU architecture, developers can write a set of IL instructions that can be JIT-compiled and executed on computers with different architectures (instead of writing IL instructions developers often use a high-level .NET language that is compiled into IL instructions by the corresponding compiler). Of course, the code using specific operating system facilities or calling platform-specific or native API methods can run only on the specific platform it uses. The reason for using JIT compilation instead of ordinary compilation takes into account the fact that some methods or functions might never be invoked during execution. Rather than spending time and memory to convert all the IL code into the native code, it converts the IL as required during execution and stores the resulting native code so that it is accessible for subsequent calls.

Page 21: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

21

At the beginning of execution, the class loader creates a stub and attaches it to each of a type's methods when the type is loaded. When a method is initially called, JIT compiler starts functioning and perform the following actions:

1. Loads metadata of the assembly containing IL code of called method; 2. Verifies and compiles the IL code into native processor instructions; 3. Saves the native code in a dynamically allocated block of memory; 4. Modifies the stub, replacing it by the address of the native code location in the

memory; 5. Jumps to the code in the allocated block.

On the subsequent calls of this method, neither the compilation, nor the verification is no more needed, because the native code is already loaded to the memory, the JIT-compiled method proceeds directly to the native code that was previously generated.

Some Details About Code Safety The safe code concept should not be mixed with the managed code concept. Generally speaking, the .NET managed code is an IL code which is verified to be safe. In MSDN documents a type-safe code is defined as a code that accesses types only in well-defined, allowable ways. Code that is proven during verification to be type-safe is called verifiably type-safe code.

Figure 3-5. Managed code producers

Page 22: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

22

Visual Basic .NET, Visual C# .NET, Visual J# compilers and IL Assembler always produce verifiably type-safe code in managed modules (Figure 2-5). But not all languages are type-safe. Some language compilers, such as Microsoft Visual C++, cannot generate verifiably type-safe managed code. Moreover, even Microsoft C++ with Managed Extensions compiler generates unmanaged code by default. C++ compiler is unique, as C++ is a kind of language that allows developers writing both managed and unmanaged code (Figures 3-5, 3-6). This gives developers possibilities to use earlier developed unmanaged C++ code without rewriting it in strict concordance to the CLR requirements. Among this, using C#, C++ with Managed Extensions or IL assembly language blocks of code, marked by the unsafe keyword, programmer can mark blocks of code that contains operations qualified unsafe. This means, that this code can’t be verifiably safe, because it’s not possible to guarantee type safety of such code due to the limitations of the verification process or to the compiler limitations. In reality, this unsafe code might have no dangerous or incorrect operations (i.e. be safe, in fact), but it’s impossible to prove it during the CLR verification stage.

Figure 3-6. Unmanaged code producers

The Microsoft .NET Framework SDK contains PEVerify tool which helps developers who generate IL code (such as compiler writers, script engine developers, and so on) to determine whether their IL code with associated metadata meets type safety requirements.

Page 23: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

23

Table 3-1 lists the summarized descriptions of different kinds of code just discussed:

Table 3-1. The .NET executable codes

Code category Description Examples of code

producers Verifiably type-safe managed code

IL based code that is created in strict concordance to the “type safety contract” (see chapter “Managed Code as a Concept” of this work). Managed code supplies the metadata required to provide runtime services such as memory management, cross-language integration, code access security, and automatic lifetime control of objects.

C# VB.NET J#

Not verifiably type- safe managed code

IL based code that is created with concordance to the “type safety contract”, but that can’t be proven by the CLR during verification. Examples of such code are the following:

• code containing pointers or direct memory access,

• code containing allocation resources on some external memory and manual freeing these memory blocks, etc.

The safety of such code is supposed to be checked by other tools (e.g. PEVerify tool) that are not in direct relation with the CLR verification procedure.

C++ C# with unsafe blocks

Not verifiably type- safe unmanaged code

Code stored in DLLs, or in COM-components, or in WinAPI based application components, or other external code (i.e. not IL code). This code is supposed to be created with concordance to type safety requirements, but its type safety can’t be proven in runtime.

C++ without explicitly used pointers

Unmanaged unsafe code

Code that is created without regard to the conventions and requirements of the CLR. Such code is executed by the CLR with minimal services (no garbage collection, limited debugging, and so on). Unmanaged code can be originally stored in DLLs, or in COM-components, or in WinAPI based application components that is supposed to be unsafe, i.e. not checked for type safety (but that might actually be safe).

C C++ with pointers

By default, code that is not type-safe is only allowed to be run if it originates from the local computer. Therefore, mobile code should be type-safe.

Page 24: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

24

Loading the CLR One question aside may interest some .NET Framework programmers: how the CLR starts functioning within Windows execution environment, or, more specifically, what the process of loading the CLR executing managed assembly consists of. In general, Windows loader recognizes this PE managed code as a usual unmanaged PE file. As discussed earlier, at the structural level PE file can be considered as a combination of two parts: PE header and PE contents (as Figure 3-7 demonstrates).

Figure 3-7. Loading the CLR

Into the “.text” part of the PE header the special stub function is inserted. The only action it provides is to pass control to _CorExeMain that is realized in the “main .NET Framework DLL” MSCorEE.dll. This DLL’s name is acronym from the “Microsoft Component Object Runtime Execution Engine”. The Windows loader finds the reference to this DLL in the “.idata” section of PE Header, so this call of the _CorExeMain is justified. The MSCorEE.dll is now loaded to the process memory. Subsequent actions are the following:

1. The _CorExeMain function takes care about the initialization of the CLR. 2. It checks the CLR header and finds the IL entry point (shown as Main Entry

at the picture). 3. It runs JIT-compiler that compiles IL code into native code. 4. Finally the control is passed to IL-Main as main thread.

Page 25: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

25

3.4 The Framework Class Library Essentials

The FCL as a Hierarchy of Namespaces The FCL is organized as a factored and extensible hierarchy of namespaces that contains type definitions. The FCL is one of the .NET products that aimed to unify application models. It is the FCL structure and the regular approaches to use FCL types that in great part supports the possibility to write code which uses redistributable components implemented in different .NET languages without hard code’s complication. Most namespaces contain general types used for any kind of application. Some of them are listed in Table 3-2.

Table 3-2. Some general FCL namespaces

FCL Namespace Description System Basic types used in every application System.Collections Types providing organization and management

of collections of objects, such as lists, queues, arrays, hash tables, and dictionaries

System.Globalizaion Support for internationalization and globalization of code and resources: string compares, formatting cultural depending data (dates, times, calendar)

System.IO Basic data stream access and management, including file and folder processing and memory input/output

System.NET Support for network communication, including simple programming interfaces for common network protocols

System.Runtime.InteropServices Types allowing managed code to call unmanaged code such as COM provided facilities or functions in Win32 DLLs, or other unmanaged code

System.Reflection Access to type metadata and dynamic creation and invocation of types

System.Text Character encoding, character conversion, and string manipulation

System.Xml Standards-based support for processing XML, including XML Schemas processing

Some namespaces are application-specific. This means that the functionality provided by the definitions contained in these namespaces is required to construct in easier and reliable way the different kind of .NET applications.

Page 26: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

26

Table 3-3 lists some application-specific FCL namespaces.

Table 3-3. Application-specific namespaces

FCL Namespace Description System.Web.Services Support for Web server and client management,

communication, and design. Provides core infrastructure for ASP.NET, including Web Forms support

System.Web.UI Classes and interfaces that allow you to create ASP.NET server controls and pages that will appear in your Web applications as user interface elements

System.Windows.Forms Rich user interface features for Windows-based applications System.ServiceProcess Classes that allow you to implement, install, and control

Windows service applications

The System Namespace Types and Primitive Types The only namespace used in every application is System namespace containing data types which are in general usage. These types are commonly supported by different languages that use specific syntax to implement the data representing concepts. These implementations may differ as listed below:

• Implementing data that are differently represented at the binary code level by using the same syntax. For example, long keyword used in C# source code means 64-bit signed integer value in complementary binary code, while the same keyword in C++ source code corresponds to platform specific binary code (containing either 32-bit, or 64-bit value).

• Implementing equal data representing concepts by different syntax. For example, to represent Boolean value bool keyword is used in C# syntax, while boolean keyword is used in Java syntax.

• Implementing different concepts by the same syntax. For example, char type in Java is used to represent 16-bits Unicode characters, while the same keyword in C++ is used to represent signed 8-bits integers considered as ASCII table codes.

• Some FCL types may be supported at the language level in some languages, and may not be supported at the language level in other languages. For example, Visual Basic don’t work with unsigned types, while C# does.

Page 27: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

27

The value types from the System namespace strictly correspond to declared data representing concepts and therefore they are not platform or language specific. As noted above, some primitive types of a language may map to the FCL types, some types may not. C# language specification force programmers to use C# keywords in favor of using FCL type names “as a matter of style”. In contrast to this, Richter believes that using FCL type names is better than using language primitive type names because of the following reasons [Richter, 2002]:

• The earlier mentioned difference between implementation of different data representing concepts by the same syntax in different languages: in C# long map to the FCL type System.Int64 (64-bit signed integer value in complementary binary code), but in other languages, long could map to the FCL type System.Int32 or even to System.Int16. “Someone reading source code in one language could easily misinterpret the code’s intention if they were used to programming in a different programming language”.

• Many FCL types offer numbers of useful methods. These methods are defined to accept arguments or to return values of the FCL types. “As a matter of style” passing the arguments or assigning return values for such methods by using variables of primitive type looks a bit unnatural like (although it’s legal – see Listing 3-2):

static int Main(string[] args) { // Check command line argument if( args.Length != 1 ) { Console.WriteLine( "Error. Command line argument needed" ); return 1; } // Parse argument that should be integer value int argVal1 = Int32.Parse( args[0] ); // Correct, feels unnatural, because Parse() // returns System.Int32 value (not int value) Int32 argVal2 = Int32.Parse( args[0] ); // Correct, feels good // ... return 0; }

Listing 3-2. The FCL types vs. language primitive types

Although the Richter’s opinion sounds quite reasonable, you should be aware of the fact that many developers have a habit to use language types instead of fully qualified FCL types.

Page 28: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

28

4 THE .NET LANGUAGE INTEROPERABILITY CONCEPTS The .NET Framework is a multilanguage platform, so developers can leverage their existing skills and inherit their successful solutions, or integrate their current solutions into the .NET application infrastructure. Microsoft delivers some .NET languages (C#, Visual Basic .NET, J#, JScript). 3rd parties also develop a lot of .NET compilers (Cobol, Eiffel, SML, etc.). The foundation infrastructure for the multilanguage environment and interoperability support is provided by the CLR, or, being more specific, by with the Common Type System together with the Common Language Specification.

4.1 The Common Type System The usual approach used by language designers is to define language’s semantics (strongly related to the underlying abstractions) tied to the language syntax (Figure 4-1). Then we call the process of source code translation as the syntax oriented translation (when the semantics “is computed” in accordance of recognized syntax).

Figure 4-1. Usual approach to define languages

The other possibility is to define core programming abstractions without mapping them to a particular syntax. If the abstractions are general enough, they could then be used in different languages. In this case syntax and semantics are kept separate, that allows different languages to be defined on the same underlying abstractions [Chappell, 2001-2] (Figure 4-2).

Page 29: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

29

This is exactly what the Common Type System is aimed to. The CTS defines how types are declared, used, and managed during runtime, or being more detailed:

• The CTS establishes a framework that enables cross-language integration, type safety, and high performance code execution,

• The CTS provides an object-oriented model that supports the complete implementation of many programming languages,

• The CTS defines rules that languages must follow to ensure that objects written in different languages can interact with each other.

Figure 4-2. The CTS as the storage of core programming abstractions

Thus, as a fundamental part of the CLR, the CTS specifies no particular syntax, but defines a common set of types instead. This set of types can be used to define language syntaxes (Figure 4-3). In fact, the only language that supports CTS integrally is IL assembly language.

Page 30: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

30

Figure 4-3. The CLR/CTS types graph

The common type system supports two general categories of types, and each could be further divided into following subcategories:

• Value types that directly contain their data. Value type instances are either allocated on the stack or allocated inline in a structure. Value types can be built-in (implemented by the runtime), user-defined, or enumerations. Table 3-1 lists built-in value types with the corresponding primitive types implemented by some different languages.

• Reference types that store a reference to the value's memory address. Reference type instances are allocated on the heap.

All types are implicitly derived from the System.Object FCL base type (the only reference type included into the System namespace).

Page 31: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

31

So, the CTS is a mechanism that allows interacting software components originally written in different .NET languages. All FCL types can be used in every .NET program, but not all of them map directly to the language types. For example, in C# language you can use both FCL types (i.e. CTS types) and C# types that are all mapped to the FCL types (see Table 3-1). Java built-in types listed in Table 4-1 let us to compare the C# and Java type systems (note that Java language is not directly supported by the .NET platform, but there is J# language created for the migration of Java application to the .NET world).

Table 4-1. The FCL types and corresponding primitive types

FCL types CLS-compliance C# types C++ types Java types

System.Boolean Yes bool bool boolean

System.Char Yes char wchar_t char

System.SByte No sbyte char -

System.Int16 Yes short short short

System.Int32 Yes int int int

System.Int64 Yes long long long

System.Byte Yes byte unsigned char byte

System.UInt16 No ushort unsigned short -

System.UInt32 No uint unsigned int -

System.UInt64 No ulong unsigned long -

System.Single Yes float float Float

System.Double Yes double double Double

System.Decimal Yes decimal - -

System.Object Yes object - Object

System.String Yes string - String

The grey colored type names in italic in C++ column show that in C++ some built-in types depend on architecture, therefore they don’t strictly map to the FCL types (although they might map to the FCL types for specific platforms).

Page 32: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

32

4.2 The Common Language Specification As noted in the MSDN materials, “to fully interact with other objects regardless of the language they were implemented in, objects must expose to callers only those features that are common to all the languages they must interoperate with. For this reason, a set of language features has been defined, called the Common Language Specification (CLS), which includes basic language features needed by many applications”. Thus, the CLS is a minimal set of features that should be implemented by the language to integrate it with the CLR. CLS-compliance of the type guarantees that this type will be correctly used by the client component. If your component uses only CLS features in the API that it exposes to other code (including derived classes), the component is guaranteed to be accessible from any programming language that supports the CLS. Mathematically, the CLS is the subset of the CTS that is product of multiplication CTS subsets implemented by different .NET languages (Figure 4-4).

Figure 4-4. The CTS and CLS cooperation

In other words, a subset of interfaces that each CLS-compliant .NET language implements forms the CLS. The .NET language should be able to consume any CLS API at least (example of such CLS consumers are JScript.NET and COBOL.NET). Some languages can produce and consume any CLS API (C#, VB, C++). So, it’s non-trivial to be a CLS consumer, and hard to be a CLS producer. Note that not all FCL types are CLS-compliant (take a look at Table 4-1 again).

Page 33: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

33

It’s possible to check CLS-compliance at the compilation stage by using special attribute CLSCompliance(true) either on the assembly level, or on the type level (Figure 4-5).

Figure 4-5. Checking the CLS-compliance

As Figure 4-5 shows, the C# code containing such definitions does not compile. In this case the first error is explained by the fact that the CLR type UInt32 is not supported in all .NET languages, for example, Visual Basic .NET doesn’t support unsigned primitive types. The second error is caused by the fact that not all the languages are case sensitive (e.g. Visual Basic, COBOL, Fortran).

Page 34: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

34

5 .NET APPLICATIONS DEVELOPMENT BY USING VISUAL STUDIO .NET In this section the development process of different kinds of .NET applications is described. We emphasize concepts and facilities that each example application is related to. We only shortly touch upon the “how-to-do” aspects in favor of more detailed analysis of the development process at the conception level because of the following reasons:

• Using such Visual Studio .NET tools as wizards, designers, debuggers and so on can be the subject of practical sessions: it is surely more productive to do this by hands during lab works, or hands-on seminars then reading the routine and monotone written description of this process.

• Nevertheless there are a lot of books concentrated on this side of development: there is no reason to repeat it.

So, our task is not only to surf comfortably on a code generated by the .NET design tools, but to dive into the code and to see what is hidden behind the external surface.

5.1 Hello World “Advanced” (Assemblies Revisited)

The Task We begin from a kind of advanced HelloWorld simplest console application that prints not only traditional “Hello, World!” message, but also asks user for his name and prints hello message addressed to the user. Despite the fact that this task may easily be solved by one function, we use this example to illustrate the object-oriented design (concerning data modeling) and the component programming (concerning .NET application structure).

Page 35: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

35

Data and Behavior Model Constructing data and behavior model, we define (as relatively separate entities) the structure representing user information (in our example this information is restricted only by a user name) and the class providing functionality of simple console based user dialogue as Listing 5-1 demonstrates. // File: ConsoleUserDialog.cs // Assembly: HelloWorldAdvanced // // Implementing console based user dialog // // Copyright (C) Evgueni V. Pychkine, 2003 using System; namespace HelloWorldAdvanced { // Struct representing user information // (only user name is supported in this version) public struct UserInfo { // Property to store user name with checking // that it consists only of letters // // Throws FormatException if not all characters are letters public string name { set { foreach( char ch in value ) { if( !Char.IsLetter( ch ) ) throw new FormatException( "Not all characters are letters" ); } _name = value; } get { return _name; } } private string _name; // Internal storage for user name } // Class for simple console user dialog class ConsoleUserDialog { // Constructor: Reads user name and prints hello to user public ConsoleUserDialog() { Console.Write( "Please enter you name=>" ); try { // Here the "get" method of the // <user.name> property is implicitly called: // Possible throwing FormatException object user.name = Console.ReadLine(); Console.WriteLine( "Hello, {0}!", user.name ); } catch( FormatException fe ) { // FormatException caught: // Not all characters are letters Console.WriteLine( "Is it really your name?" ); Console.WriteLine( "({0})", fe.Message ); } } private UserInfo user; // User information (name) } }

Listing 5-1. Simple console based user dialogue

Page 36: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

36

Using Property Concept Note that to represent a user name class member we have used the property concept. It gives a programmer opportunity to use the name field “naturally” as it is an ordinary string variable (see the class ConsoleUserDialog constructor source code). Each attempt to write value into this variable passes control to the “set” method of the property that allows to check, let’s say, whether the name consists only of letters. The respective IL code is automatically generated by the C# compiler.

The Application Source Code The source code using the developed class would be as following (Listing 5-2): // File: HelloMain.cs // Assembly: HelloWorldAdvanced // // Copyright (C) Evgueni V. Pychkine, 2003 using System; namespace HelloWorldAdvanced { class CHelloMain { // The main entry point for the application: // Prints "Hello, World!" message and starts dialog [STAThread] static void Main(string[] args) { Console.WriteLine( "Hello, World!" ); ConsoleUserDialog userDlg = new ConsoleUserDialog(); } } }

Listing 5-2. Main class of HelloWorldAdvanced.NET console application

The Assembly Now let us return to the discussion about assemblies. This simple application is the example of an assembly created after two source code files have been successfully compiled into IL code. Exploring the EXE file with ILDasm utility we will see all the objects defined in this assembly as shown in Figure 5-1.

Page 37: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

37

Figure 5-1. HelloWorldAdvanced assembly contents viewed with ILDasm

JIT Compilation Revisited This example gives us also the opportunity to talk more about JIT compilation. Let’s look at the method WriteLine() provided by the Console class in System namespace. This method is called at least twice during runtime (or even three times if the incorrect format exception is thrown). However this method is verified to be type safe and compiled into native CPU code only once (at its fist call from the method main()). The consequent calls go directly to the block of dynamic memory where the native code has been already placed.

Summary The following list summarizes the main .NET concepts and facilities illustrated in this example:

• .NET C# console application construction • IL code JIT compilation • Using properties as class members • Handling exceptions • Building single-file assembly • Console based text input/output implementation

Page 38: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

38

5.2 C# Standalone Application

The Task Now let’s take a look at more complex application based on Windows graphic user interface (GUI). We continue with a standalone C# Windows application that is based on a Windows form class. The development process is dramatically facilitated by using the Visual Studio. Net application wizard and the Windows form designer. The task is the following. We should develop Windows .NET application that enables to multiply two long integer values, entered to the text boxes placed on the application window. We should implement the checked computation, i.e. our application should be able to recognize the following fault cases:

• Impossible to pares entered data as integer values, • Impossible to store entered value in memory as 32-bit signed integer

value, • Impossible to store computation result in memory as 32-bit signed

integer value (i.e. the application should be able to detect an overflow situation).

Creating Windows Form with the Visual Studio .NET Tools To create the application we choose the main menu item File and then the command New and the command Project in the pop-up menu associated with the New menu item. In the windows which appears, we choose the project type (Visual C# Project) and the Windows application as template. We use “Safe Multiplication” as a project name. After the Visual Studio .NET application wizard creates the application infrastructure for us, we develop our application window by drag-and-dropping the necessary items from the toolbox to obtain the window form as shown in Figure 5-2. We use Textbox component for the first multiplier entering field (textBox1), another Textbox component for the second multiplier (textBox2), two Button components: one – for “Go” button that starts the computation (button1), another – for “Reset” button that resets the application state into initial position (button2). Two Label components are required to represent the names of entering fields: “First multiplier” (label1) and “Second multiplier” (label2) respectively. Another two labels (that are slightly visible at the form as initially empty blocks at textboxes’ left side) are used to signalize the status of each entered datum (“OK”, if the entered value is correct, otherwise the error message). These labels are named label3 and label4 by the form designer. In this example we keep the component names given by the form designer, but it is recommended to students to change them in order to make them more readable and able to express their meanings in the program explicitly, for example goButton instead of button1, label1Status instead of label3 and so on. At last, we change the application window title into “Safe Multiplication 1.0” to obtain the window appearance as shown in Figure 5-2.

Page 39: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

39

Figure 5-2. Creating application window for Safe Multiplication 1.0 .NET application

The Business Logic of the Application After double clicking on the Go button component at the form, the control passes to the source code window where the title of the function associated with pushing this button appeared, and we should only add the custom functionality needed as Listing 5-3 shows. private void button1_Click(object sender, System.EventArgs e) { int a, b; // Multipliers try { // Parse first multiplier a = Int32.Parse( textBox1.Text ); // Display Ok status label3.ForeColor = Color.Green; label3.Text = "Ok"; } catch( FormatException ) { // Display "Non integer value" status label3.ForeColor = Color.Red; label3.Text = "ERROR: This is not integer value!"; return; } catch( OverflowException ) { // Display "Too large value" status label3.ForeColor = Color.Red; label3.Text = "ERROR: Too large by absolute value!"; return; }

Page 40: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

40

try { // Parse second multiplier b = Int32.Parse( textBox2.Text ); // Display Ok status label4.ForeColor = Color.Green; label4.Text = "Ok"; } catch( FormatException ) { // Display "Non integer value" status label4.ForeColor = Color.Red; label4.Text = "ERROR: This is not integer value!"; return; } catch( OverflowException ) { // Display "Too large value" status label4.ForeColor = Color.Red; label4.Text = "ERROR: Too large by absolute value!"; return; } // Prepare resulting text to display on "Go" button // after completion of the computation string sResult=a.ToString()+" * "+b.ToString()+" = "; // Multiplication try { // Checked multiplication int result; checked { result = a * b; } // Complete and display resulting text sResult += result.ToString(); button1.Text = sResult; } catch( OverflowException ) { // Complete and display overflow result sResult += "Overflow"; button1.Text = sResult; return; } }

Listing 5-3. Actions associated with pushing Go button: parsing values and multiplication

This method is automatically registered by the form designer to be associated with the event “Pushing Go button” during runtime. As followed from the code (see Listing 5-3), if the entered value is not successfully parsed as correct 32-bit integer value, the corresponding text colored in red appears as status label text (label3 for the first multiplier, label4 – for the second one). If both multiplication operands are parsed successfully, the checked block implements the multiplication. Using keyword checked allows us to catch the overflow exception if the result value is too large to be represented as 32-bit integer value. As you see, the computation result is printed directly on the Go button.

Page 41: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

41

The Application in a Whole Listing 5-4 shows the full source code of the application. From the source code we can see that a lot of work has been done by the form designer. It includes GUI support, and association of the business logic of the application with the events conditioned by the user actions. Some portions of manually written code are all bodies of the methods implementing the application business logic. using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace Safe_Multiplication { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code // after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { 11 this.textBox1 = new System.Windows.Forms.TextBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label();

Page 42: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

42

this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // textBox1 // this.textBox1.Font = new System.Drawing.Font( "Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(204))); this.textBox1.Location = new System.Drawing.Point(168, 32); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(152, 29); this.textBox1.TabIndex = 0; this.textBox1.Text = "0"; 22 this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged); // // textBox2 // this.textBox2.Font = new System.Drawing.Font( "Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(204))); this.textBox2.Location = new System.Drawing.Point(168, 80); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(152, 29); this.textBox2.TabIndex = 1; this.textBox2.Text = "0"; this.textBox2.TextChanged += new System.EventHandler(this.textBox2_TextChanged); // // label1 // this.label1.Font = new System.Drawing.Font( "Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point ((System.Byte)(204))); this.label1.Location = new System.Drawing.Point(16, 40); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(144, 24); this.label1.TabIndex = 2; this.label1.Text = "First muptiplier"; // // label2 // this.label2.Font = new System.Drawing.Font( "Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point ((System.Byte)(204))); this.label1.Location = new System.Drawing.Point(16, 80); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(144, 24); this.label2.TabIndex = 2; this.label2.Text = "Second muptiplier"; // // label3 // this.label3.Font = new System.Drawing.Font(

Page 43: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

43

"Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point ((System.Byte)(204))); this.label3.Location = new System.Drawing.Point(336, 32); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(160, 32); this.label3.TabIndex = 3; // // label4 // this.label4.Font = new System.Drawing.Font( "Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point ((System.Byte)(204))); this.label4.Location = new System.Drawing.Point(336, 80); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(160, 32); this.label4.TabIndex = 3; // // button1 // this.button1.Font = new System.Drawing.Font( "Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point ((System.Byte)(204))); this.button1.Location = new System.Drawing.Point(24, 136); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(472, 72); this.button1.TabIndex = 4; this.button1.Text = "Go"; 33 this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.Location = new System.Drawing.Point(24, 232); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(472, 24); this.button2.TabIndex = 5; this.button2.Text = "Reset"; this.button2.Click += new System.EventHandler(this.button2_Click); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(6, 13); this.ClientSize = new System.Drawing.Size(512, 273); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.button2, this.button1, this.label3, this.label1, this.textBox2, this.textBox1, this.label2, this.label4}); this.Font = new System.Drawing.Font( "Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, S((System.Byte)(204))); this.Name = "Form1"; this.Text = "Safe Multiplication 1.0"; this.ResumeLayout(false); } #endregion

Page 44: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

44

/// <summary> /// The main entry point for the application. /// </summary> [STAThread] 44 static void Main() { Application.Run(new Form1()); } 55 private void button1_Click( object sender, System.EventArgs e ) { int a, b; // Multipliers try { // Parse first multiplier a = Int32.Parse( textBox1.Text ); // Display Ok status label3.ForeColor = Color.Green; label3.Text = "Ok"; } catch( FormatException ) { // Display "Non integer value" status label3.ForeColor = Color.Red; label3.Text = "ERROR: This is not integer value!"; return; } catch( OverflowException ) { // Display "Too large value" status label3.ForeColor = Color.Red; label3.Text = "ERROR: Too large by absolute value!"; return; } try { // Parse second multiplier b = Int32.Parse( textBox2.Text ); // Display Ok status label4.ForeColor = Color.Green; label4.Text = "Ok"; } catch( FormatException ) { // Display "Non integer value" status label4.ForeColor = Color.Red; label4.Text = "ERROR: This is not integer value!"; return; } catch( OverflowException ) { // Display "Too large value" status label4.ForeColor = Color.Red; label4.Text = "ERROR: Too large by absolute value!"; return; } // Prepare resulting text to display on "Go" button // after completion of the computation string sResult=a.ToString()+" * "+b.ToString()+" = "; // Multiplication try { // Checked multiplication int result; 66 checked {

Page 45: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

45

result = a * b; } // Complete and display resulting text sResult += result.ToString(); button1.Text = sResult; } catch( OverflowException ) { // Complete and display overflow result sResult += "Overflow"; button1.Text = sResult; return; } } 77 private void textBox1_TextChanged( object sender, System.EventArgs e ) { label3.Text = ""; button1.Text = "Go"; } private void textBox2_TextChanged( object sender, System.EventArgs e ) { label4.Text = ""; button1.Text = "Go"; } 88 private void button2_Click( object sender, System.EventArgs e ) { label3.Text = ""; label4.Text = ""; button1.Text = "Go"; textBox1.Text = "0"; textBox2.Text = "0"; } } }

Listing 5-4. The full source code of the application “Safe Multiplication 1.0”

Some lines of the source code which merit special comments are marked by the red figures. Here are our comments:

1. Initializing of all the components existing in the framework of the application window (the components that we have placed on the window from the toolbox).

2. Registration of the method textBox1_TextChanged() as the method associated with the event: “Changing text in the Textbox for the first multiplier”. Here the delegate concept is used (it will be the subject of our special attention while studying advanced C# features).

3. Registration of the method button1_Click() as the method associated with the event “Clicking Go button” (as you have just seen, the essential business logic of the application is, in fact, placed to this method).

4. The main entry point to the application: starting Windows application with the Form1 object as the main application window.

5. The method button1_Click() that has been just discussed.

Page 46: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

46

6. Checked multiplication. By default (if the keyword checked is not used), the arithmetic operations are not checked for overflow. By using special syntax, the programmer demands generating code where all the operations within the checked block are checked for overflow with possible throwing the exception OverflowException.

7. Method textBox1_TextChanged() restores the “Go” button initial appearance and clears respective status label. Similar is the method textBox2_TextChanged().

8. Method button2_Click() restores the initial appearance of all the GUI components on the form.

Application Test and Summary Figure 5-3 shows the examples of different executions of the developed application.

Figure 5-3. Safe Multiplication: Examples of execution

Text below lists the concepts of the .NET Framework programming illustrated by this example:

• Construction of the System.Windows.Forms based C# application • Working with window toolbox, and GUI design simplification • Changing properties of window form elements • Checked computation implementation • Handling exceptions • Parsing strings

Page 47: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

47

5.3 Customizing user control In next three applications the application architecture is the main object of changes. We don’t change the application business logic to let students concentrate on the details of creating different kind of .NET applications and on the concepts essentials that we are talking about. It means that from the user’s prospective, the applications work almost or exactly in the same manner as the standalone “Safe multiplication” application that has been just presented.

The Task Let’s start our improvement from the idea of changing the textboxes appearance making them in some way “more interactive”. For example, let’s change the textbox background to, let’s say, light-green color if the user input is correct, and, to light-pink color, if the user input is wrong (Figure 5-4). For initial state we use some soft color, for example, light steel blue color (or another color you like).

Figure 5-4. Improved textbox appearance

The Solution in General To use the existing textbox functionality we inherit our new user control from the existing user control component defined in the FCL (Figure 5-5).

Figure 5-5. Inheritance from the standard user control

Page 48: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

48

After we have inherited a custom class from som FCL class, we can use all open functionality provided by the base class, but in addition we can change behavior of the derived class objects the way we want to.

Creating the Non-Standard User Control Component We can create our custom user control either as separate project (in this case we should create new .NET project by choosing “Windows control library” as a project type), or add a new item to the existing project (by using command Add User Control in the menu Project). The next step is to define our new user control component as the class that inherits to the class System.Windows.Forms.TextBox. To provide checking correctness of the user input “on the fly” (as described some lines above) we should override the base class method OnTextChanged(). In case if we would like our text to appear in some desired color when the handle is just created (as you probably remember we have chosen the light steel blue background color), we should also override the base class method OnHandleCreated(). In both cases to use the functionality provided by the base class, developers should not forget to call the base class method before implementing some additional functionality (of course, except the rare cases when you would like to rewrite some method totally). After everything is done, we obtain the source code that is similar to the code that Listing 5-5 demonstrates. using System; using System.Windows.Forms; namespace MyControl { // AdvancedTextBox inherits to the FCL class public class AdvancedTextBox : System.Windows.Forms.TextBox { // Overriding OnTextChange() method protected override void OnTextChanged(System.EventArgs e) { // Using functionality provided by the base class base.OnTextChanged( e ); // Add new functionality try { // Parsing entered text to check whether // it looks like integer value Int32.Parse( this.Text ); // OK: Set the background color to light green this.BackColor = Color.LightGreen; } catch // Error: the text isn’t integer value { // Set the background color to light pink this.BackColor = Color.LightPink; } } // Overriding OnHandleCreated() method protected override void OnHandleCreated(System.EventArgs e) { // Using functionality provided by the base class base.OnHandleCreated( e );

Page 49: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

49

// Set initial state of the background color this.BackColor = System.Drawing.Color.LightSteelBlue; } } }

Listing 5-5. Creating non-standard user control that inherits to the FCL user control

After the IL code is built, we can use our AdvancedTextBox in the application the same way as the standard user control component has been used. What is more, by using the command Customize Toolbox, appearing in the pop-up menu invoked by the clicking of the right button of the mouse when the mouse pointer points to the toolbox window, we can start dialogue that lets us to include our newly created component directly to the toolbox. After that we are able to use this textbox component in every future application as it would be an ordinary FCL textbox component. Thus, our steps to customize a user control component are the following:

1. Create a user control (a new item in the existing project or a new project). 2. Inherit from System.Windows.Forms.TextBox class. 3. Override the method OnTextChanged(). 4. Override the method OnHandleCreated() (optionally). 5. Customize Visual Studio .NET toolbox. 6. Use created non-standard user control in design.

Using Non-Standard User Control in the Application To use just created non-standard user control (which is not in the standard FCL assemblies) you should add reference to the assembly containing the AdvancedTextBox class definition. To add a reference you can use the command Add Reference of the main menu item Project. Then browse your files to find the DLL module of the needed assembly, select it and press OK button (another way to add reference to the assembly is exposed in the next section “Language Interoperability Example”).

Summary Summarizing the application description, we list the.NET Framework programming concepts illustrated in this example:

• Creating a non-standard user control as a redistributable component • Customizing Visual Studio .NET toolbox • Elements of component programming

5.4 Using Language Interoperability

The Task In this section we overview the componentized application architecture, making changes in the multiplication example so that the library component (written in Visual Basic) is used in the client module (written in C#). This component containing the multiplication method is placed into the separate assembly that therefore should be referenced from the client assembly. Thus such application architecture illustrates how to use the .NET language interoperability.

Page 50: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

50

The Library Component VB Source Code To develop the library component, we create the new Visual Basic project, choosing “Class Library” as a project type. Our class library is very simple and contains only one class that provides functionality for 32-bit integer values checked multiplication. Listing 5-6 shows the implementation. Note that in Visual Basic arithmetic computations are checked for overflow by default (i.e. no any instruction required).

Imports Microsoft.VisualBasic Namespace CheckedComputation Public Class CheckedMult // Multiplication method Public Function Mult( ByVal a As Int32, ByVal b As Int32 ) As Int32 Dim result As Int32 result = a * b // NB! May throw overflow exception Return result End Function End Class End Namespace

Listing 5-6. Checked multiplication implemented as VB component

The resulting IL module is stored therefore in the corresponding assembly DLL file named, let’s say, CheckedComputation.dll.

The Client Application C# Source Code The only place of the client application that needs to be rewritten is the portion of the code in the method button1_Click() body (Listing 5-7, compare with Listing 5-4):

// Use class name CheckedMult defined within the namespace // CheckedComputation (in the CheckedComputation.dll assembly) CheckedComputation.CheckedMult cm = new CheckedComputation.CheckedMult(); // cm – “Computation Machine” – object able to realize // checked multiplications // String to present computation results string sResult = a.ToString() + " * " + b.ToString() + " = "; try { int result = cm.Mult( a, b ); // Call method Mult(), // defined in the class // CheckedMult sResult += result.ToString(); button1Go.Text = sResult; } catch( OverflowException ) // Exception handling: it works // through modules and languages { sResult += "Overflow"; button1Go.Text = sResult; return; }

Listing 5-7 The fragment of the method button1_Click()

Page 51: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

51

To perform the multiplication we have now used the method Mult() of the class CheckedMult. Note that this method may throw an OverflowException that is caught in the method button1_Click() placed in another module that is originally written in another .NET language. So, the exception handling mechanism works through the modules and through the languages.

Building the Application To bind all modules together, the external assembly (which contains Visual Basic component) should be referenced from the client assembly. To do this in Visual Studio .NET development environment it’s sufficient to click the right button of the mouse when the solution or project name, or reference folder is highlighted in the solution explorer window and choose command Add Reference in the pop-up menu. Then find the required assembly simply by browsing the contents of the folders of the hard drive: in our case we should find the CheckedComputation.dll file, generated by the Visual Basic .NET compiler by browsing. Then select the found assembly name and press OK button. After that the new assembly name (CheckedComputation) will be added to the Reference folder as Figure 5-6 shows.

Figure 5-6. The solution explorer window with explored references folder: properties of the CheckedMultiplication assembly

Page 52: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

52

Summary Summarizing the concepts this example illustrates, the following points could be emphasized:

• Construction of the library component • Referencing the library component from the client application • Exceptions handled through modules and languages

5.5 Building XML Web Service Component and Web Service Client Application

The Task To introduce the Web generation programming model based on using Web services, we implement the multiplication method as an application component accessible by the web. Then this little Web service is called from the client application near as simple as ordinary library component.

Understanding a Web Service To be able to create a Web service located on your computer you should be sure that your computer is configured to be a Web Server. Follow installation instruction when installing Microsoft .NET Framework and tools or consult your system administrator if you have no administrative rights to do this. If your computer is configured as a Web Server you may create an application of “XML Web Service” type. Note that all files of the Web service project are located in the specified folder that is in the root folder of your Web server. For the local host computer with the Microsoft Internet Information Server (IIS) installed and configured it could be, for example, the folder c:\Inetpub\wwwroot\MultiplicationService that maps on the Internet-folder http://localhost/MultiplicationService. A Web service can be understood as special form of Web application that have no user interface. Instead of this, Web service provides methods, available for other applications of different types: Web applications with rich GUI, Web library components, or even console applications. Web Services are standardized on the base of open Internet-protocols such as HTTP or SOAP (Simple Object Access Protocol), therefore using Microsoft .NET Framework is not obligatory to develop Web services or to access them. But the .NET Framework tools really facilitate these tasks, isolating developers from the low level details of interaction between client applications and Web services, such as HTTP-requests containing SOAP-messages to the Web methods, sending the Web service responses as SOAP-messages to the client application. The SOAP is the XML based language developed for standard calls of remote procedures by the Web (see http://www.w3.org/TR/SOAP for detailed description of the SOAP). Note that exactly as all other .NET applications, .NET Web services need the CLR to execute, therefore they are all managed applications.

Page 53: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

53

The Web Service Application Architecture After we created Web service project, the Visual Studio .NET generates the complete Web service definition presented as ASMX-file (see Listing 5-8). The ASMX extension is an ASP.NET registered file extension for the Web Services.

<%@WebService Language = "c#" Codebehind = "Service1.asmx.cs" Class = "MultiplicationService.Service1" %>

Listing 5-8. Web service ASMX-file Service1.asmx

This little file shows the usage of some important elements of the .NET Framework based Web service architecture. The ASMX-file starts with @WebService directive containing the following attributes:

• Attribute Language specifies the language which the Web service source code is developed in.

• Attribute Codebehind specifies the file where the source code of the Web service is located.

• Attribute Class specifies the full class name (with namespace) which contains Web service method(s).

Note that HTTP, XML, SOAP and other low level details are hidden: this caused the simplification of the Web service development within the .NET Framework. At the source code level Web methods are declared simply by applying to them standard attribute WebMethod as Listing 5-9 shows. using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Web; using System.Web.Services; namespace MultiplicationService { /// <summary> /// The only Web service in our example. /// </summary> public class Service1 : System.Web.Services.WebService { public Service1() { //CODEGEN: This call is required by the ASP.NET //Web Services Designer InitializeComponent(); } #region Component Designer generated code //Required by the Web Services Designer private IContainer components = null; /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent()

Page 54: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

54

{ } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if(disposing && components != null) { components.Dispose(); } base.Dispose(disposing); } #endregion // WEB SERVICE EXAMPLE // Checked multiplications of two Int32 values [WebMethod] public Int32 Mult( Int32 a, Int32 b ) { Int32 result; checked { result = a*b; } return result; } } }

Listing 5-9. C# source code for checked multiplication Web service component

The text after this attribute is the only text that should be written manually, all the rest is generated automatically by the Web Service Designer. The whole folder structure corresponding to the developed Web service viewed by Windows Explorer is shown in Figure 5-7.

Page 55: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

55

Figure 5-7. Multiplication Web Service files

Debugging the Developed Web Service The Visual Studio .NET allows developers to debug their Web services by using command Start of the main menu item Debug. The debugger dynamically creates an HTML-document providing testing environment for the just developed Web service (Figure 5-8).

Figure 5-8. Web service testing environment automatically generated by the Visual Studio .NET debugger browsed by the Internet Explorer

Page 56: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

56

After entering values into the textboxes corresponding to the Web method arguments and pushing Invoke button we will see XML-document corresponding to the Web Service’s HTTP response. So, developers can immediately test their Web services without writing sample client code.

The Client Application Construction Now let’s take a look at the client side. The client component developer wishing to use the Web service should know at least the following:

• The URL-address of the Web service, in our case it’s http://localhost/MultiplicationService/Service1.asmx.

• The namespace where the class containing the Web service is defined, in our case it’s MultiplicationService namespace.

• The name of the class, containing the Web method, in our case it’s the class Service1 (thus, the full name of the Web service component is MultiplicationService.Service1).

• The signature of the Web method, in our case it’s the method Mult() that needs two arguments of System.Int32 FCL type (which correspond to C# type int) and returns the System.Int32 value or throws the exception System.OverflowException.

Web Service Description in WSDL and Creating Web Service Proxy Class To simplify and unify the ways to provide the information required for a Web service usage the WSDL (Web Service Description Language) was developed. The WSDL is XML-based language that was recently standardized (see http://www.w3.org/tr/wsdl for details of the WSDL specification). To see the WSDL-description of an existing Web service you should simply tape into the address line of your browser the URL-address of the Web service followed by the WSDL-request: http://localhost/MultiplicationService/Service1.asmx?wsdl. This WSDL-file establishes contract that defines whole functionality provided by the Web service to allow client developers using this Web services in their applications. As a rule, developers don’t need to read the WSDL-contract, instead of this they pass it to the special tool creating a proxy class containing all necessary elements to call the Web service. The .NET Framework provides such tool named wsdl.exe. The proxy class supports two principal things:

• Representing a remote Web service at the local level so that it can be used as an ordinary method of the local class;

• Hiding low level details to simplify client code construction. The proxy class instance is created in the client application domain, but all calls to the proxy are passed by the proxy class to the remote methods of the Web service. In other words, the proxy class wraps the contents of the Web service class: if the Web Service class contains the method Mult(), the generated local proxy class will also contain it. To create the proxy for the Web Service MultiplicationService.Service1 we should call the utility wsdl.exe as following: wsdl http://localhost/MultuplicationService/Service1.asmx

Page 57: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

57

Calling the Web Service Method As a result, the source file Service1.cs is created. We add this file to the project where we want to use the Web service, and after that we can use the proxy class Service1 defined in this file to call Web service method as shown in the following simple console application (Listing 5-10): using System; using System.Web.Services.Protocols; namespace WebMultClient { class MultClient { [STAThread] static void Main(string[] args) { Int32 a, b; // Multipliers Int32 result; // Multiplication result try { Console.Write( "Enter first multiplier:" ); a = Int32.Parse( Console.ReadLine() ); Console.Write( "Enter second multiplier:" ); b = Int32.Parse( Console.ReadLine() ); } catch( FormatException ) { Console.WriteLine("This is not integer value"); return; } catch( OverflowException ) { Console.WriteLine("Too large absolute value"); return; } try { // Creating an instance of the proxy class // Service1, defined in the source file // Service1.cs generated by the wsdl.exe Service1 ws = new Service1(); // Calling the method of the proxy class result = ws.Mult( a, b ); // From within the proxy class method // the Web service method is called // in its turn Console.WriteLine( "Result: {0}", result ); } catch( SoapException ) { Console.WriteLine( "Overflow" ); } } } }

Listing 5-10. Using Web Service by calling proxy class method

Page 58: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

58

As you see, the only moment here differs from the interoperability example code examined earlier. The exception handled in the client code now has the type SoapException which is defined within the namespace System.Web.Services.Protocols. This exception type is used by the following reason. When some XML Web service throws an unhandled exception, the ASP.NET catches the exception and throws the SoapException object. This object is serialized into an XML representation and then can be parsed and recognized by any computer on which the Web service client application runs. This allows interoperating of a Web service and its client: at the client side the XML code is deserialized into a SoapException object and this new object is thrown in the client’s thread (and therefore can be caught within the client running code). To print the message containing the full description of the server side fault, we could rewrite the code for catching exception as following (Listing 5-11):

catch( SoapException se ) { Console.WriteLine( "Web Service error:" ); Console.WriteLine( se.Message.ToString() ); }

Listing 5-11. Printing message with full description of the server side error

In case if overflow situation occured at the server side, the client application yields the output that is similar to the following:

WebServiceError: System.Web.Services.Protocols.SoapException: Service was unable to process request ---> System.OverflowException: Arithmetic operation resulted in an overflow at MultiplicationService.Service1.Mult(Int32 a, Int32 b) in c:\inetpub\wwwroot\multiplicationservice\service1.asmx.cs:line 60 --- End of inner exception stack trace ---

Note, that the exact message may differ at your computer. As you see, creating Web Service clients is not very hard. But Visual Studio .NET provide features that simplify client components development even more.

Another Way to Call the Web Service In fact, instead of generating a proxy class by the wsdl.exe utility and adding it to the project you may simply add a Web reference to the project (the similar way you use to add a reference to an external local assembly). In this case the proxy class is implicitly created by the development environment so that you can call the Web service methods as they are. To add a Web reference you should choose the command Add Web Reference of the main menu item Project and tape the URL-address of the Web-service and then, after the Web service methods are found, push Add Reference button. After that the client application is automatically configured so that you may call the Web service methods by indicating the namespace of the WebService, as Listing 5-12 shows (note that the namespace localhost may differ from the namespace at your configuration).

localhost.Service1 ws = new localhost.Service1(); result = ws.Mult( a, b ); Console.WriteLine( "Result: {0}", result );

Listing 5-12. Revised fragment of the main() function

Page 59: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

59

Web Services in Real World As it goes from the idea, an XML Web service can be used either internally by a single application (as the above example shows) or exposed externally over the Internet for use by any number of applications. Because it is accessible through a standard interface, an XML Web service allows heterogeneous systems to communicate and therefore provides an alternative solution for data and system interoperability instead of pursuing the generic capabilities of code portability. In the above example we have exactly known the URL-address of the Web Service as well as the way to use it correctly. In real world where there are a lot of servers that could provide some functionality as software services it would be virtually impossible to find a particular service without special means for searching it. We see here an apparent analogy with finding different resources on the Internet by using so called search engines. XML Web services directories provide bases where XML Web service providers can publish information about services available at their Web servers. Such directories may even be XML Web services themselves, accessible programmatically and providing search results as responses to from potential XML Web service clients’ queries (Figure 5-9). Microsoft in cooperation with some other companies proposed the UDDI (Universal Description, Discovery and Integration) specification that defines a standardized way to publish and to discover such information about XML Web services as:

• Business information (what is the Web Service publisher and what field this service may be used in),

• Service information (what functionality does this service provide), • Binding information (how to access this Web Service), and • Information about specifications for services (see http://uddi.microsoft.com/

for more information).

Page 60: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

60

Figure 5-9. XML Web Service Infrastructure

XML Web service discovery is the process of locating and interrogating XML Web service descriptions, which is the preliminary step for accessing an XML Web service. Through the discovery process, XML Web service clients can learn at design time that an XML Web service exists, what its capabilities are, and how to properly interact with it. Programmatic discovery can be enabled when an XML Web service publishes a .disco file, which is an XML document that can contains links to other discovery documents, XSD schemas, and service descriptions through WSDL-contract. If XML Web service clients know the location of the service description, they can bypass the discovery process (as the previous example shows). To understand how to interact with a particular XML Web service, it is necessary to provide a service description that defines what kind of interactions the XML Web service supports. The service description is an XML document written in WSDL that defines the format of messages the XML Web service understands. The service description serves as an agreement that defines the behavior of an XML Web service and instructs potential clients in how to interact with it. Thus, in full version, to build an XML Web Service client there are four basic steps should be accomplished (as Figure 5-10 illustrates):

1. Find the XML Web service by looking in an XML Web Service directory and get a URL at the vendor’s Web server.

2. Discover an XML Web service, i.e. get XML Web service discovery as a set of files containing the specific information about each XML Web service available at that URL. Information about each XML Web service is returned to the client in form of a WSDL-contract.

3. On the base of the given WSDL-contract, create a Web Service proxy class (as discussed above).

Page 61: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

61

4. Create a client application, which invokes methods of the proxy class. The methods of the proxy class can communicate with the XML Web service methods by using the industry standard Internet protocols like SOAP.

Figure 5-10. XML Web Service Infrastructure in details

Summary Here is the summary of the .NET programming elements, illustrated in this section:

• Creating an XML Web service by using Microsoft Visual Studio .NET tools • Testing the just created Web service • Creating a Web Service proxy class • Synchronous calls to the Web Service method through the proxy class • Configuring client application which uses the Web service

Page 62: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

62

6 CONCLUSION This paper contains the preliminary materials aimed to help listeners understand what the Microsoft .NET Framework programming mdel. All the crash course attendees could use these materials to be well prepared for the lectures concentrated on the advanced subjects as well as for practical seminars. This work could also be useful for those who want to understand better the .NET Framework architecture and tools available for .NET developers, as well as development of .NET applications by using Microsoft Visual Studio .NET tools. This work is the continuations of the series of works for the software engineering crash course at COP started with the article “Understanding the object model” [Pychkine, 2003-1].

Page 63: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work

63

REFERENCES [Chappell, 2001-1]. Chappell, David. Questions and Answers About C#. Inform IT-Columns. 20/8/2001. [Chappell, 2001-2]. Chappell, David. Understanding .NET’s Common Type System. Inform IT-Columns. 14/12/2001. [Chappell, 2002]. Chappell, David. .NET & Beyond: Confronting .NET myths. Application Development Trends Columns. 3/1/2002. [Gunnerson, 2000]. Gunnerson, Eric. A Programmer’s Introduction to C#. Apress. 2000. [Miller, 2002]. Miller, Jim. The .NET Vision. Talk at Microsoft .NET Crash Course for Faculty and PhDs. Conference materials. Cambridge, 2001. [Pavlov, 2002]. Павлов А.M., Пышкин Е.В. Обзор архитектуры платформы Microsoft. Net для разработки программного обеспечения // XXX Юбилейная Неделя науки СПбГТУ. Ч.VII: Материалы межвузовской научной конференции. СПб.: Изд-во СПбГТУ, 2002. с.39-41. (Pavlov Alexander, Pychkine, Evgueni V. The .NET Framework Architecture Overview. Proceedings of the XXXth Week of Science at St-Petersburg State Polytechnical University, 2002. Part VII, pp.39-41.- In Russian). [Pychkine, 2003-1]. Pychkine, Evgueni V. Understanding the Object Model. Prerequisites for the crash course of software engineering. Ajankohtaista-aktuellt. Central Ostrobothnia Polytechnics. 2003. ISBN 952-5107-33-7. [Pychkine, 2003-2]. Пышкин Е.В. Основные концепции объектно-ориентированного программирования. Учебное пособие. СПб.: Изд-во СПбГТУ, 2003, 302 с., ил. (Pychkine, Evgueni V. Main Concepts of the Object-Oriented Programming. St-Petersburg, State Polytechnical University, 2003, 302 p.- In Russian). [Richter, 2002]. Richter, Jeffrey. Applied Microsoft .NET Framework Programming. Microsoft Press. 2002. [Risse, 2001]. Risse, Michael. Introducing Microsoft .NET. Talk at Microsoft .NET Developer Conference. Conference materials. Copenhagen, 2001.

Page 64: AN INTRODUCTION TO THE MICROSOFT .NET FRAMEWORK …kspt.ftk.spbstu.ru/media/files/people/pyshkin/books/cop... · 2012-01-31 · 8 1.3 Presenting the Course The purpose of this work