INTRODUCTION

IF YOU WERE TO DESCRIBE THE C# LANGUAGE and its associated environment, the .NET Framework, as the most significant technology for developers available, you would not be exaggerating. .NET is designed to provide an environment within which you can develop almost any application to run on Windows, whereas C# is a programming language designed specifically to work with the .NET Framework. By using C#, you can, for example, write a dynamic web page, a Windows Presentation Foundation application, an XML web service, a component of a distributed application, a database access component, a classic Windows desktop application, or even a new smart client application that enables online and offline capabilities. This book covers the .NET Framework 4.5. If you code using any of the prior versions, there may be sections of the book that will not work for you. This book notifies you of items that are new and specific to the .NET Framework 4.5.

Don’t be fooled by the .NET label in the Framework’s name and think that this is a purely an Internet-focused framework. The NET bit in the name is there to emphasize Microsoft’s belief that distributed applications, in which the processing is distributed between client and server, are the way forward. You must also understand that C# is not just a language for writing Internet or network-aware applications. It provides a means for you to code almost any type of software or component that you need to write for the Windows platform. Between them, C# and .NET have revolutionized the way that developers write their programs and have made programming on Windows much easier than it has ever been before.

So what’s the big deal about .NET and C#?

THE SIGNIFICANCE OF .NET AND C#

To understand the significance of .NET, you must consider the nature of many of the Windows technologies that have appeared in the past 18 years. Although they may look quite different on the surface, all the Windows operating systems from Windows NT 3.1 (introduced in 1993) through Windows 8 and Windows Server 2012 have the same familiar Windows API for Windows desktop and server applications at their core. Progressing through new versions of Windows, huge numbers of new functions have been added to the API, but this has been a process to evolve and extend the API rather than replace it.

The same can be said for many of the technologies and frameworks used to develop software for Windows. For example, Component Object Model (COM) originated as Object Linking and Embedding (OLE). Originally, it was largely a means by which different types of Office documents could be linked so that you could place a small Excel spreadsheet in your Word document, for example. From that it evolved into COM, Distributed COM (DCOM), and eventually COM+—a sophisticated technology that formed the basis of the way almost all components communicated, as well as implementing transactions, messaging services, and object pooling.

Microsoft chose this evolutionary approach to software for the obvious reason that it is concerned about backward compatibility. Over the years, a huge base of third-party software has been written for Windows, and Windows would not have enjoyed the success it has had if every time Microsoft introduced a new technology it broke the existing code base!

Although backward compatibility has been a crucial feature of Windows technologies and one of the strengths of the Windows platform, it does have a big disadvantage. Every time some technology evolves and adds new features, it ends up a bit more complicated than it was before.

It was clear that something had to change. Microsoft could not go on forever extending the same development tools and languages, always making them more and more complex to satisfy the conflicting demands of keeping up with the newest hardware and maintaining backward compatibility with what was around when Windows first became popular in the early 1990s. There comes a point in which you must start with a clean slate if you want a simple yet sophisticated set of languages, environments, and developer tools, which makes it easy for developers to write state-of-the-art software.

This fresh start is what C# and .NET were all about in the first incarnation. Roughly speaking, .NET is a framework—an API—for programming on the Windows platform. Along with the .NET Framework, C# is a language that has been designed from scratch to work with .NET, as well as to take advantage of all the progress in developer environments and in your understanding of object-oriented programming principles that have taken place over the past 25 years.

Before continuing, you must understand that backward compatibility has not been lost in the process. Existing programs continue to work, and .NET was designed with the capability to work with existing software. Presently, communication between software components on Windows takes place almost entirely using COM. Taking this into account, the .NET Framework does have the capability to provide wrappers around existing COM components so that .NET components can talk to them.

It is true that you don’t need to learn C# to write code for .NET. Microsoft has extended C++ and made substantial changes to Visual Basic to turn it into a more powerful language to enable code written in either of these languages to target the .NET environment. These other languages, however, are hampered by the legacy of having evolved over the years rather than having been written from the start with today’s technology in mind.

This book can equip you to program in C#, while at the same time provides the necessary background in how the .NET architecture works. You not only cover the fundamentals of the C# language, but also see examples of applications that use a variety of related technologies, including database access, dynamic web pages, advanced graphics, and directory access.

While the Windows API just evolved and was extended since the early days of Windows NT in 1993, and the .NET Framework offered a major change on how programs are written since the year 2002, now in the year 2012 are the days of the next big change. Do such changes happen every 10 years? Windows 8 now offers a new API: the Windows Runtime (WinRT) for Windows Store apps. This runtime is a native API (like the Windows API) that is not build with the .NET runtime as its core, but offers great new features that are based on ideas of .NET. Windows 8 includes the first release of this API available for modern-style apps. While this is not based on .NET, you still can use a subset of .NET with Windows Store apps, and write the apps with C#. This new runtime will evolve in the next years to come with upcoming releases of Windows. This book will also give you a start in writing Windows Store apps with C# and WinRT.

ADVANTAGES OF .NET

So far, you’ve read in general terms about how great .NET is, but it can help to make your life as a developer easier. This section briefly identifies some of the features of .NET.

  • Object-oriented programming — Both the .NET Framework and C# are entirely based on object-oriented principles from the start.
  • Good design — A base class library, which is designed from the ground up in a highly intuitive way.
  • Language independence — With .NET, all the languages—Visual Basic, C#, and managed C++—compile to a common Intermediate Language. This means that languages are interoperable in a way that has not been seen before.
  • Better support for dynamic web pages — Though Classic ASP offered a lot of flexibility, it was also inefficient because of its use of interpreted scripting languages, and the lack of object-oriented design often resulted in messy ASP code. .NET offers an integrated support for web pages, using ASP.NET. With ASP.NET, code in your pages is compiled and may be written in a .NET-aware high-level language such as C# or Visual Basic 2010. .NET now takes it even further with outstanding support for the latest web technologies such as Ajax and jQuery.
  • Efficient data access — A set of .NET components, collectively known as ADO.NET, provides efficient access to relational databases and a variety of data sources. Components are also available to enable access to the file system and to directories. In particular, XML support is built into .NET, enabling you to manipulate data, which may be imported from or exported to non-Windows platforms.
  • Code sharing — .NET has completely revamped the way that code is shared between applications, introducing the concept of the assembly, which replaces the traditional DLL. Assemblies have formal facilities for versioning, and different versions of assemblies can exist side by side.
  • Improved security — Each assembly can also contain built-in security information that can indicate precisely who or what category of user or process is allowed to call which methods on which classes. This gives you a fine degree of control over how the assemblies that you deploy can be used.
  • Zero-impact installation — There are two types of assemblies: shared and private. Shared assemblies are common libraries available to all software, whereas private assemblies are intended only for use with particular software. A private assembly is entirely self-contained, so the process to install it is simple. There are no registry entries; the appropriate files are simply placed in the appropriate folder in the file system.
  • Support for web services — .NET has fully integrated support for developing web services as easily as you would develop any other type of application.
  • Visual Studio 2012 — .NET comes with a developer environment, Visual Studio 2012, which can cope equally well with C++, C#, and Visual Basic 2012, as well as with ASP.NET or XML code. Visual Studio 2012 integrates all the best features of the respective language-specific environments of all the previous versions of this amazing IDE.
  • C# — C# is a powerful and popular object-oriented language intended for use with .NET.

You look more closely at the benefits of the .NET architecture in Chapter 1, “.NET Architecture.”

WHAT’S NEW IN THE .NET FRAMEWORK 4.5

The first version of the .NET Framework (1.0) was released in 2002 to much enthusiasm. The .NET Framework 2.0 was introduced in 2005 and was considered a major release of the Framework. The major new feature of 2.0 was generics support in C# and the runtime (IL code changed for generics), and new classes and interfaces. .NET 3.0 was based on the 2.0 runtime and introduced a new way to create UIs (WPF with XAML and vector-based graphics instead of pixel-based), and a new communication technology (WCF). .NET 3.5 together with C# 3 introduced LINQ, one query syntax that can be used for all data sources. .NET 4.0 was another major release of the product that also brought a new version of the runtime (4.0) and a new version of C# (4.0) to offer dynamic language integration and a huge new library for parallel programming. The .NET Framework 4.5 is based on an updated version of the 4.0 runtime with many outstanding new features.

With each release of the Framework, Microsoft has always tried to ensure that there were minimal breaking changes to code developed. Thus far, Microsoft has been successful at this goal.

The following section details some of the changes that are new to C# 2012 and the .NET Framework 4.5.

Asynchronous Programming

Blocking the UI is unfriendly to the user; the user becomes impatient if the UI does not react. Maybe you’ve this experience with Visual Studio as well. Good news: Visual Studio has become a lot better in reacting faster in many scenarios.

The .NET Framework always offered calling methods asynchronously. However, using synchronous methods was a lot easier than calling their asynchronous variant. This changed with C# 5. Programming asynchronously has become as easy as writing synchronous programs. New C# keywords are based on the .NET Parallel Library that is available since .NET 4. Now the language offers productivity features.

Windows Store Apps and the Windows Runtime

Windows Store apps can be programmed with C# using the Windows Runtime and a subset of the .NET Framework. The Windows Runtime is a new native API that offers classes, methods, properties, and events that look like .NET; although it is native. For using language projection features, the .NET runtime has been enhanced. With .NET 4.5, the .NET 4.0 runtime gets an in-place update.

Enhancements with Data Access

The ADO.NET Entity Framework offered important new features. Its version changed from 4.0 with .NET 4.0 to 5.0 with .NET 4.5. After the release of .NET 4.0, the Entity Framework already received updates with versions 4.1, 4.2, and 4.3. New features such as Code First, spatial types, using enums, and table-valued functions are now available.

Enhancements with WPF

Programming Windows desktop applications, WPF has been enhanced. Now you can fill collections from a non-UI thread; the ribbon control is now part of the framework; weak references with events have been made easier; validation can be done asynchronously with the INotifyDataErrorInfo interface; and live shaping allows easy dynamic sorting and grouping with data that changes.

ASP.NET MVC

Visual Studio 2010 included ASP.NET MVC 2.0. With the release of Visual Studio 2012, ASP.NET MVC 4.0 is available. ASP.NET MVC supplies you with the means to create ASP.NET using the model-view-controller model that many developers expect. ASP.NET MVC provides developers with testability, flexibility, and maintainability in the applications they build. ASP.NET MVC is not meant to be a replacement for ASP.NET Web Forms but is simply a different way to construct your applications.

WHERE C# FITS IN

In one sense, C# is the same thing to programming languages that .NET is to the Windows environment. Just as Microsoft has been adding more and more features to Windows and the Windows API over the past 15 years, Visual Basic 2012 and C++ have undergone expansion. Although Visual Basic and C++ have resulted in hugely powerful languages, both languages also suffer from problems because of the legacies left over from the way they evolved.

For Visual Basic 6 and earlier versions, the main strength of the language was that it was simple to understand and made many programming tasks easy, largely hiding the details of the Windows API and the COM component infrastructure from the developer. The downside to this was that Visual Basic was never truly object-oriented, so large applications quickly became disorganized and hard to maintain. As well, because Visual Basic’s syntax was inherited from early versions of BASIC (which, in turn, was designed to be intuitively simple for beginning programmers to understand, rather than to write large commercial applications), it didn’t lend itself to well-structured or object-oriented programs.

C++, on the other hand, has its roots in the ANSI C++ language definition. It is not completely ANSI-compliant for the simple reason that Microsoft first wrote its C++ compiler before the ANSI definition had become official, but it comes close. Unfortunately, this has led to two problems. First, ANSI C++ has its roots in a decade-old state of technology, and this shows up in a lack of support for modern concepts (such as Unicode strings and generating XML documentation) and for some archaic syntax structures designed for the compilers of yesteryear (such as the separation of declaration from definition of member functions). Second, Microsoft has been simultaneously trying to evolve C++ into a language designed for high-performance tasks on Windows, and to achieve that, it has been forced to add a huge number of Microsoft-specific keywords as well as various libraries to the language. The result is that on Windows, the language has become a complete mess. Just ask C++ developers how many definitions for a string they can think of: char*, LPTSTR, string, CString (MFC version), CString (WTL version), wchar_t*, OLECHAR*, and so on.

Now enters .NET—a completely revolutionary environment that has brought forth new extensions to both languages. Microsoft has gotten around this by adding yet more Microsoft-specific keywords to C++ and by completely revamping Visual Basic to the current Visual Basic 2012, a language that retains some of the basic VB syntax but that is so different in design from the original VB that it can be considered, for all practical purposes, a new language.

It is in this context that Microsoft has provided developers an alternative—a language designed specifically for .NET and designed with a clean slate. C# is the result. Officially, Microsoft describes C# as a “simple, modern, object-oriented, and type-safe programming language derived from C and C++.” Most independent observers would probably change that to “derived from C, C++, and Java.” Such descriptions are technically accurate but do little to convey the beauty or elegance of the language. Syntactically, C# is similar to both C++ and Java, to such an extent that many keywords are the same, and C# also shares the same block structure with braces ({}) to mark blocks of code and semicolons to separate statements. The first impression of a piece of C# code is that it looks quite like C++ or Java code. Beyond that initial similarity, however, C# is a lot easier to learn than C++ and of comparable difficulty to Java. Its design is more in tune with modern developer tools than both of those other languages, and it has been designed to provide, simultaneously, the ease of use of Visual Basic and the high-performance, low-level memory access of C++, if required. Some of the features of C# follow:

  • Full support for classes and object-oriented programming, including interface and implementation inheritance, virtual functions, and operator overloading.
  • A consistent and well-defined set of basic types.
  • Built-in support for an automatic generation of XML documentation.
  • Automatic cleanup of dynamically allocated memory.
  • The facility to mark classes or methods with user-defined attributes. This can be useful for documentation and can have some effects on compilation (for example, marking methods to be compiled only in debug builds).
  • Full access to the .NET base class library and easy access to the Windows API (if you need it, which will not be often).
  • Pointers and direct memory access are available if required, but the language has been designed in such a way that you can work without them in almost all cases.
  • Support for properties and events in the style of Visual Basic.
  • Just by changing the compiler options, you can compile either to an executable or to a library of .NET components that can be called up by other code in the same way as ActiveX controls (COM components).
  • C# can be used to write ASP.NET dynamic web pages and XML web services.

Most of these statements, it should be pointed out, also apply to Visual Basic 2012 and Managed C++. Because C# is designed from the start to work with .NET, however, means that its support for the features of .NET is both more complete and offered within the context of a more suitable syntax than those of other languages. Although the C# language is similar to Java, there are some improvements; in particular, Java is not designed to work with the .NET environment.

Before leaving the subject, you must understand a couple of limitations of C#. The one area the language is not designed for is time-critical or extremely high-performance code—the kind where you are worried about whether a loop takes 1,000 or 1,050 machine cycles to run through, and you need to clean up your resources the millisecond they are no longer needed. C++ is likely to continue to reign supreme among low-level languages in this area. C# lacks certain key facilities needed for extremely high-performance apps, including the capability to specify inline functions and destructors guaranteed to run at particular points in the code. However, the proportions of applications that fall into this category are low.

WHAT YOU NEED TO WRITE AND RUN C# CODE

The .NET Framework 4.5 can run on the client operating systems Windows Vista, 7, 8, and the server operating systems Windows Server 2008, 2008 R2, and 2012. To write code using .NET, you need to install the .NET 4.5 SDK.

In addition, unless you intend to write your C# code using a text editor or some other third-party developer environment, you almost certainly also want Visual Studio 2012. The full SDK is not needed to run managed code, but the .NET runtime is needed. You may find you need to distribute the .NET runtime with your code for the benefit of those clients who do not have it already installed.

WHAT THIS BOOK COVERS

This book starts by reviewing the overall architecture of .NET in Chapter 1 to give you the background you need to write managed code. After that, the book is divided into a number of sections that cover both the C# language and its application in a variety of areas.

Part I: The C# Language

This section gives a good grounding in the C# language. This section doesn’t presume knowledge of any particular language; although, it does assume you are an experienced programmer. You start by looking at C#’s basic syntax and data types and then explore the object-oriented features of C# before looking at more advanced C# programming topics.

Part II: Visual Studio

This section looks at the main IDE utilized by C# developers worldwide: Visual Studio 2012. The two chapters in this section look at the best way to use the tool to build applications based on the .NET Framework 4.5. In addition, this section also focuses on the deployment of your projects.

Part III: Foundation

In this section, you look at the principles of programming in the .NET environment. In particular, you look at security, threading, localization, transactions, how to build Windows services, and how to generate your own libraries as assemblies, among other topics. One part is interaction with native code and assemblies using platform invoke and COM interop. This section also gives information how the Windows Runtime differs from .NET and how to start writing Windows 8–style programs.

Part IV: Data

Here, you look at accessing data using ADO.NET and learn about the ADO.NET Entity Framework. You can use core ADO.NET to get the best performance; the ADO.NET Entity Framework offers ease of use with mapping objects to relations. Now, different programming models with Model First, Database First, and Code First are available that are all discussed. This part also extensively covers support in .NET for XML, using LINQ to query XML data sources.

Part V: Presentation

This section starts by showing you how to build applications based upon the Windows Presentation Foundation. Not only different control types, styles, resources, and data binding are covered, but you can also read about creating fixed and flow documents, and printing. Here, you can also read about creating Windows Store apps, use of pictures for a nicer UI, grids, and contracts to interact with other applications. Finally, this section includes coverage of the tremendous number of features that ASP.NET offers, building websites with ASP.NET Web Forms, ASP.NET MVC, and dynamic data.

Part VI: Communication

This section is all about communication. It covers services for platform-independent communication using Windows Communication Foundation (WCF) and WCF to access data with WCF Data Services. With Message Queuing, asynchronous disconnected communication is shown. This section looks at utilizing the Windows Workflow Foundation and peer-to-peer networking.

CONVENTIONS

To help you get the most from the text and keep track of what’s happening, a number of conventions are used throughout the book.


WARNING Warnings hold important, not-to-be-forgotten information that is directly relevant to the surrounding text.


NOTE Notes indicate notes, tips, hints, tricks, or and asides to the current discussion.

As for styles in the text:

  • We highlight new terms and important words when we introduce them.
  • We show keyboard strokes like this: Ctrl+A.
  • We show filenames, URLs, and code within the text like so: persistence.properties.
  • We present code in two different ways:
We use a monofont type with no highlighting for most code examples.
We use bold to emphasize code that’s particularly important in the present context or to show changes from a previous code snippet.

SOURCE CODE

As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. All the source code used in this book is available for download at http://www.wrox.com. When at the site, simply locate the book’s title (either by using the Search box or by using one of the title lists) and click the Download Code link on the book’s detail page to obtain all the source code for the book.


NOTE Because many books have similar titles, you may find it easiest to search by ISBN; this book’s ISBN is 978-1-118-31442-5.

After you download the code, just decompress it with your favorite compression tool. Alternately, you can go to the main Wrox code download page at http://www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.

ERRATA

We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty piece of code, we would be grateful for your feedback. By sending in errata you may save another reader hours of frustration, and at the same time you can help provide even higher quality information.

To find the errata page for this book, go to http://www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On this page you can view all errata that has been submitted for this book and posted by Wrox editors. A complete book list including links to each book’s errata is also available at www.wrox.com/misc-pages/booklist.shtml.

If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. We’ll check the information and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions of the book.

P2P.WROX.COM

For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a web-based system for you to post messages relating to Wrox books and related technologies and interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.

At http://p2p.wrox.com you can find a number of different forums to help you not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps:

1. Go to p2p.wrox.com and click the Register link.
2. Read the terms of use and click Agree.
3. Complete the required information to join and any optional information you want to provide, and click Submit.
4. You will receive an e-mail with information describing how to verify your account and complete the joining process.

NOTE You can read messages in the forums without joining P2P but to post your own messages, you must join.

After you join, you can post new messages and respond to messages other users post. You can read messages at any time on the web. If you want to have new messages from a particular forum e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.

For more information about how to use the Wrox P2P, read the P2P FAQs for answers to questions about how the forum software works as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset