A Radically New Approach: C# and Windows

Total Page:16

File Type:pdf, Size:1020Kb

A Radically New Approach: C# and Windows C HAPTER 1 A Radically New Approach: C# and Windows Microsoft states that “C# is a simple, modern, object-oriented, and type-safe programming language derived from C and C++.” The first thing you will notice when using C# (C sharp) is how familiar you already are with many of the constructs of this language. Object-oriented by design, the C# language provides access to the class libraries available to Visual Basic and Visual C++ programmers. C#, however, does not provide its own class library. C# is implemented by Microsoft in the latest version of the Microsoft Visual Studio and provides access to the Next Generation Windows Services (NGWS). These services include a common execution engine for code development. Visual Studio .NET and C# The latest release of Microsoft’s Visual Studio .NET provides a language-rich environment for developing a variety of applications. Programming can be done in a variety of lan- guages, such as C, C++, C#, Visual Basic, and more. Applications can range from standal- one console (command-line or DOS mode) applications to Microsoft Windows programs. C#, although certainly one of the newest variations of C to hit the market, is just a component of this much larger package. One of Microsoft’s goals, in this release of the Visual Studio .NET, is to allow seamless solutions to project demands. Solutions to a task can include components from C++, Visual Basic, and C# all rolled into one seamless exe- cutable file. This book concentrates on the C# aspect of this package as it applies to creating Win- dows applications. If you are interested in a more detailed treatment of the C# language, we would recommend another of our books, C# Essentials, published by Prentice Hall (ISBN 1 2 Chapter 1 • A Radically New Approach: C# and Windows 0-13-093285-X), 2002. This is just the book if you are the type of programmer who likes to discover all of nuances of a language. Our first task will be to learn how to use Visual Studio to create a simple C# console application. Then we’ll do a quick study of the most important aspects of the C# language. Finally, we’ll turn our attention to our first C# Windows application and see what is in store for us in the remainder of this book. Building C# Applications C# applications fall within two distinct categories: command-line or console applications and Windows applications. By using the AppWizards, you’ll find that both are easy to cre- ate in terms of the template code necessary to outline a project. For our first project we build the familiar Hello World console application. We’ll name this project HelloWorld. The second application, which appears closer to the end of this chapter, is called CircleArea. This is a full-fledged, object-oriented Windows application. Both projects are intended to introduce you to the Visual Studio AppWizards and show you how to build the basic template code that will be part of every project developed in this book. These are good places to set bookmarks and take notes in the margins. Your First C# Console Application To build a console application using C#, start the Visual Studio. Select the File | New | Project sequence to open the New Project dialog box, as shown in Figure 1–1. Your First C# Console Application 3 Figure 1–1 The New Project dialog box allows us to specify a C# console application. Name this project HelloWorld, and specify a subdirectory under the root directory, as shown in Figure 1–1. When you click the OK button, the C# AppWizard creates the template code shown in Figure 1–2. 4 Chapter 1 • A Radically New Approach: C# and Windows Figure 1–2 The AppWizard’s C# template code for a console application. This template code can now be modified to suite your purposes. Figure 1–3 shows how we altered the template code for our HelloWorld project. Examine Figure 1–3 and compare it with the following complete listing. Note the addition of just one line of code: using System; namespace HelloWorld { /// <summary> /// Summary description for Class1. /// </summary> class Class1 { static void Main(string[] args) { Your First C# Console Application 5 // // TODO: Add code to start application here // Console.WriteLine("Hello C# World!"); } } } Examine Figure 1–3, once again. Notice that the Build menu has been opened and the Rebuild option is about to be selected. Clicking this menu item will build the project. Figure 1–3 The template code is altered for the HelloWorld project. 6 Chapter 1 • A Radically New Approach: C# and Windows When you examine this simple portion of code, you notice many of the elements that you are already familiar with from writing C or C++ console applications. Figure 1–4 shows the Debug menu opened and the Start Without Debugging option about to be selected. Make this selection to run the application within the integrated environment of the Visual Studio. Figure 1–4 Running the program from within Visual Studio. When the program is executed, a console (command-line or DOS) window will appear with the programs output. Figure 1–5 shows the output for this application. Now, let’s briefly examine the familiar elements and the new additions. First, the application uses the System directive. The System namespace, provided by the NGWS at runtime, permits access to the Console class used in the Main method. The use of Con- sole.WriteLine() is actually an abbreviated form of System.Console.WriteLine() where System represents the namespace, Console a class defined within the namespace, and WriteLine() is a static method defined within the Console class. C# Programming Elements 7 Figure 1–5 The console window shows the project’s output. Additional Program Details In C# programs, functions and variables are always contained within class and structure def- initions and are never global. You will probably notice the use of “.” as a separator in compound names. C# uses this separator is place of “::” and “->”. Also, C# does not need forward declarations because the order in not important. The lack of #include statements is an indicator that the C# language handles dependencies symbolically. Another feature of C# is automatic memory manage- ment, which frees developers from dealing with this complicated problem. C# Programming Elements In the following sections we examine key elements of the C# language that we use through- out the book. From time to time, additional C# information is introduced, but the material in the following sections is used repeatedly. 8 Chapter 1 • A Radically New Approach: C# and Windows Arrays C# supports the same variety of arrays as C and C++, including both single and multidi- mensional arrays. This type of array is often referred to as a rectangular array, as opposed to a jagged array. To declare a single-dimension integer array named myarray, the following C# syntax can be used: int[] myarray = new int[12]; The array can then be initialized with 12 values using a for loop in the following man- ner: for (int i = 0; i < myarray.Length; i++) myarray[i] = 2 * i; The contents of the array can be written to the screen with a for loop and WriteLine() statement. for (int i = 0; i < myarray.Length; i++) Console.WriteLine("myarray[{0}] = {1}", i, myarray[i]); Note that i values will be substituted for the {0} and myarray[ ] values for {1} in the argument list provided with the WriteLine() statement. Other array dimensions can follow the same pattern. For example, the syntax used for creating a two-dimensional array can take this form: int[,] my2array = new int[12, 2]; The array can then be initialized with values using two for loops in the following manner: for (int i = 0; i < 12; i++) for (int j = 0; j < 2; j++) my2array[i, j] = 2 * i; The contents of the array can then be displayed on the console with the following syn- tax: for (int i = 0; i < 12; i++) for (int j = 0; j < 2; j++) Console.WriteLine("my2array[{0}, {1}] = {2}", i, j, my2array[i, j]); Three-dimensional arrays can be handled with similar syntax using this form: int[,,] my3array = new int[3, 6, 9]; C# Programming Elements 9 In addition to handling multidimensional rectangular arrays, C# handles jagged arrays. A jagged array can be declared using the following syntax: int[][] jagarray1; int[][][] jagarray2; For example, suppose a jagged array is declared as: int[][] jagarray1 = new int[2][]; jagarray1[0] = new int[] {2, 4}; jagarray1[1] = new int[] {2, 4, 6, 8}; Here jagarray1 represents an array of int. The jagged appearance of the structure gives rise to the array’s type name. The following line of code would print the value 6 to the screen: Console.WriteLine(jagarray1[1][2]); For practice, try to write the code necessary to print each array element to the screen. Attributes, Events, Indexers, Properties, and Versioning Many of the terms in this section are employed when developing applications for Windows. If you have worked with Visual Basic or the Microsoft Foundation Class (MFC) and C++ you are familiar with the terms attributes, events, and properties as they apply to controls. In the following sections, we generalize those definitions even more. Attributes C# attributes allow programmers to identify and program new kinds of declarative informa- tion. For example, public, private and protected are attributes that identify the accessibility of a method. An element’s attribute information can be returned at runtime using the NGWS runt- ime’s reflection support. Events Events are used to allow classes to provide notifications about which clients can provide executable code.
Recommended publications
  • Ironpython in Action
    IronPytho IN ACTION Michael J. Foord Christian Muirhead FOREWORD BY JIM HUGUNIN MANNING IronPython in Action Download at Boykma.Com Licensed to Deborah Christiansen <[email protected]> Download at Boykma.Com Licensed to Deborah Christiansen <[email protected]> IronPython in Action MICHAEL J. FOORD CHRISTIAN MUIRHEAD MANNING Greenwich (74° w. long.) Download at Boykma.Com Licensed to Deborah Christiansen <[email protected]> For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. Sound View Court 3B fax: (609) 877-8256 Greenwich, CT 06830 email: [email protected] ©2009 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15% recycled and processed without the use of elemental chlorine.
    [Show full text]
  • Opening Presentation
    Mono Meeting. Miguel de Icaza [email protected] October 24, 2006 Mono, Novell and the Community. Mono would not exist without the community: • Individual contributors. • Companies using Mono. • Organizations using Mono. • Companies using parts of Mono. • Google Summer of Code. Introductions. 2 Goals of the Meeting. A chance to meet. • Most of the Novell/Mono team is here. • Many contributors are here. • Various breaks to talk. Talk to others! • Introduce yourself, ask questions. Talk to us! • Frank Rego, Mono's Product Manager is here. • Tell us what you need in Mono. • Tell us about how you use Mono. 3 Project Status Goals Originally: • Improve our development platform on Linux. As the community grew: • Expand to support Microsoft APIs. As Mono got more complete: • Provide a complete cross platform runtime. • Allow Windows developers to port to Linux. 5 Mono Stacks and Goals. MySMQySQLL//PPosstgtrgesrsess EvEovolluutitioonn# # ASP.NET Novell APIs: MMoozzillala Novell iFolder iFolder, LDAP, Identity ADO.NET ApAapchachee MMonoono DesktoGpTK#: GTK# OpNoevenlOl LfDfAiPce GCneomceil# Windows.Forms JavaJa vCa oCommpaatitbilbitiylity Google APIs Microsoft Compatibility Libraries Mono Libraries Mono Runtime (Implementation of ECMA #335) 6 Platforms, CIL, Code Generation. 7 API space Mono 1.0: July 2004 “T-Bone” Mono 1.2: November 2006 “Rump steak” Mono 1.2 bits. Reliability and C# 2.0, .NET 2.0 scalability: • Complete. • With VM support. • ZenWorks and iFolder • Some 2.0 API support. pushed Mono on the server. • IronPython works. • xsp 1.0: 8 request/second. • xsp 1.2: 250 Debugger: request/second. • x86 and x86-64 debugger. GUI • CLI-only, limited in scenarios (no xsp).
    [Show full text]
  • Demo: Embedding Windows Presentation Foundation Elements Inside a Java GUI Application
    Demo: Embedding Windows Presentation Foundation elements inside a Java GUI application Version 10.1 jnbridge.com JNBridge, LLC jnbridge.com COPYRIGHT © 2002–2019 JNBridge, LLC. All rights reserved. JNBridge is a registered trademark and JNBridgePro and the JNBridge logo are trademarks of JNBridge, LLC. Java is a registered trademark of Oracle and/or its affiliates. Microsoft, Visual Studio, and IntelliSense are trademarks or registered trademarks of Microsoft Corporation in the United States and other countries. Apache is a trademark of The Apache Software Foundation. All other marks are the property of their respective owners. August 13, 2019 Demo: Embedding a WPF element inside a Java GUI application Introduction This document shows how a .NET Windows Presentation Foundation (WPF) control can be embedded inside a Java GUI application (either an AWT, Swing, or SWT application). If you are unfamiliar with JNBridgePro, we recommend that you work through one of the other demos first. We recommend working through the “Java-to-.NET demo,” which will work through the entire process of generating proxies and setting up, configuring, and running an interop project. This current document assumes such knowledge, and is mainly a guided tour of the code and configuration information necessary to embed .NET GUI elements inside GUI-based Java applications. The .NET GUI component In this example, we have provided a Windows Presentation Foundation control, WPFControlDemo.UserControl1. This control is adapted from the example in the first chapter of the book Essential Windows Presentation Foundation, by Chris Anderson (Addison-Wesley). Any WPF component to be embedded inside a Java GUI application must be derived from System.Windows.Controls.Control.
    [Show full text]
  • Using Microsoft Visual Studio to Create a Graphical User Interface ECE 480: Design Team 11
    Using Microsoft Visual Studio to Create a Graphical User Interface ECE 480: Design Team 11 Application Note Joshua Folks April 3, 2015 Abstract: Software Application programming involves the concept of human-computer interaction and in this area of the program, a graphical user interface is very important. Visual widgets such as checkboxes and buttons are used to manipulate information to simulate interactions with the program. A well-designed GUI gives a flexible structure where the interface is independent from, but directly connected to the application functionality. This quality is directly proportional to the user friendliness of the application. This note will briefly explain how to properly create a Graphical User Interface (GUI) while ensuring that the user friendliness and the functionality of the application are maintained at a high standard. 1 | P a g e Table of Contents Abstract…………..…………………………………………………………………………………………………………………………1 Introduction….……………………………………………………………………………………………………………………………3 Operation….………………………………………………….……………………………………………………………………………3 Operation….………………………………………………….……………………………………………………………………………3 Visual Studio Methods.…..…………………………….……………………………………………………………………………4 Interface Types………….…..…………………………….……………………………………………………………………………6 Understanding Variables..…………………………….……………………………………………………………………………7 Final Forms…………………....…………………………….……………………………………………………………………………7 Conclusion.…………………....…………………………….……………………………………………………………………………8 2 | P a g e Key Words: Interface, GUI, IDE Introduction: Establishing a connection between
    [Show full text]
  • Practical ASP.NET Web API
    Practical ASP.NET Web API Badrinarayanan Lakshmiraghavan Practical ASP.NET Web API Copyright © 2013 by Badrinarayanan Lakshmiraghavan This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work. Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its current version, and permission for use must always be obtained from Springer. Permissions for use may be obtained through RightsLink at the Copyright Clearance Center. Violations are liable to prosecution under the respective Copyright Law. ISBN-13 (pbk): 978-1-4302-6175-9 ISBN-13 (electronic): 978-1-4302-6176-6 Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.
    [Show full text]
  • Appendix a and Appendix B
    This PDF contains 2 Appendices: Appendix A and Appendix B. Appendix A Answers to the Test Your Knowledge Questions This appendix has the answers to the questions in the Test Your Knowledge section at the end of each chapter. Chapter 1 – Hello, C#! Welcome, .NET! 1. Why can a programmer use different languages, for example, C# and F#, to write applications that run on .NET? Answer: Multiple languages are supported on .NET because each one has a compiler that translates the source code into intermediate language (IL) code. This IL code is then compiled to native CPU instructions at runtime by the CLR. 2. What do you type at the prompt to create a console app? Answer: You enter dotnet new console. 3. What do you type at the prompt to build and execute C# source code? Answer: In a folder with a ProjectName.csproj file, you enter dotnet run. 4. What is the Visual Studio Code keyboard shortcut to view Terminal? Answer: Ctrl + ` (back tick). Answers to the Test Your Knowledge Questions 5. Is Visual Studio 2019 better than Visual Studio Code? Answer: No. Each is optimized for different tasks. Visual Studio 2019 is large, heavy- weight, and can create applications with graphical user interfaces, for example, Windows Forms, WPF, UWP, and Xamarin.Forms mobile apps, but it is only available on Windows. Visual Studio Code is smaller, lighter-weight, code-focused, supports many more languages, and is available cross-platform. In 2021, with the release of .NET 6 and .NET Multi-platform App User Interface (MAUI), Visual Studio Code will get an extension that enables building user interfaces for desktop and mobile apps.
    [Show full text]
  • Command Line Interface User Guide for Version 11.0 Copyright © 1994-2017 Dell Inc
    Command Line Interface User Guide for Version 11.0 Copyright © 1994-2017 Dell Inc. or its subsidiaries. All Rights Reserved. Contact Information RSA Link at https://community.rsa.com contains a knowledgebase that answers common questions and provides solutions to known problems, product documentation, community discussions, and case management. Trademarks For a list of RSA trademarks, go to www.emc.com/legal/emc-corporation-trademarks.htm#rsa. License Agreement This software and the associated documentation are proprietary and confidential to EMC, are furnished under license, and may be used and copied only in accordance with the terms of such license and with the inclusion of the copyright notice below. This software and the documentation, and any copies thereof, may not be provided or otherwise made available to any other person. No title to or ownership of the software or documentation or any intellectual property rights thereto is hereby transferred. Any unauthorized use or reproduction of this software and the documentation may be subject to civil and/or criminal liability. This software is subject to change without notice and should not be construed as a commitment by EMC. Third-Party Licenses This product may include software developed by parties other than RSA. The text of the license agreements applicable to third-party software in this product may be viewed on the product documentation page on RSA Link. By using this product, a user of this product agrees to be fully bound by terms of the license agreements. Note on Encryption Technologies This product may contain encryption technology. Many countries prohibit or restrict the use, import, or export of encryption technologies, and current use, import, and export regulations should be followed when using, importing or exporting this product.
    [Show full text]
  • CA Plex C# Best Practices
    CA Plex C# Best Practices Example Document Creating packages and code libraries and managing C# source code and application artifacts CA Plex version 6.1 Created by: In collaboration with IIDEA Solutions and CCH, and assistance from CA. Published with the kind permission of the South Carolina Judicial Department . Packages and .NET Assemblies Best Practices for CA Plex. Contents 1. Introduction ......................................................................................................................................... 3 2. Use of assemblies and modules when creating code libraries ............................................................. 3 3. Creating and using assemblies ............................................................................................................. 4 4. Considerations when packaging your model ....................................................................................... 5 5. Software required on the build server .................................................................................................. 6 6. Modelling C# Code Libraries in Plex .................................................................................................. 7 7. Setting up the build server and installing Cruise Control .................................................................. 10 8. Development life cycle ...................................................................................................................... 20 Appendix ..................................................................................................................................................
    [Show full text]
  • Crossplatform ASP.NET with Mono
    CrossPlatform ASP.NET with Mono Daniel López Ridruejo [email protected] About me Open source: Original author of mod_mono, Comanche, several Linux Howtos and the Teach Yourself Apache 2 book Company: founder of BitRock, multiplatform installers and management software About this presentation The .NET framework An overview of Mono, a multiplatform implementation of the .NET framework mod_mono : run ASP.NET on Linux using Apache and Mono The Microsoft .Net initiative Many things to many people, we are interested in a subset: the .NET framework Common Language Runtime execution environment Comprehensive set of class libraries As other technologies, greatly hyped. But is a solid technical foundation that stands on its own merits The .NET Framework .NET Highlights (1) Common Language Runtime : Provides garbage collection, resource management, threads, JIT support and so on. Somewhat similar to JVM Common Intermediate Language, multiple language support: C#, Java, Visual Basic, C++, JavaScript, Perl, Python, Eiffel, Fortran, Scheme, Pascal Cobol… They can interoperate and have access to full .NET capabilities. Similar to Java bytecode .NET Highlights (2) Comprehensive Class Library: XML, ASP.NET, Windows Forms, Web Services, ADO.NET Microsoft wants .NET to succeed in other platforms: standardization effort at ECMA, Rotor sample implementation. P/Invoke: Easy to incorporate and interoperate with existing code Attributes, delegates, XML everywhere Mono Project Open Source .NET framework implementation. Covers ECMA standard plus
    [Show full text]
  • Programming with Windows Forms
    A P P E N D I X A ■ ■ ■ Programming with Windows Forms Since the release of the .NET platform (circa 2001), the base class libraries have included a particular API named Windows Forms, represented primarily by the System.Windows.Forms.dll assembly. The Windows Forms toolkit provides the types necessary to build desktop graphical user interfaces (GUIs), create custom controls, manage resources (e.g., string tables and icons), and perform other desktop- centric programming tasks. In addition, a separate API named GDI+ (represented by the System.Drawing.dll assembly) provides additional types that allow programmers to generate 2D graphics, interact with networked printers, and manipulate image data. The Windows Forms (and GDI+) APIs remain alive and well within the .NET 4.0 platform, and they will exist within the base class library for quite some time (arguably forever). However, Microsoft has shipped a brand new GUI toolkit called Windows Presentation Foundation (WPF) since the release of .NET 3.0. As you saw in Chapters 27-31, WPF provides a massive amount of horsepower that you can use to build bleeding-edge user interfaces, and it has become the preferred desktop API for today’s .NET graphical user interfaces. The point of this appendix, however, is to provide a tour of the traditional Windows Forms API. One reason it is helpful to understand the original programming model: you can find many existing Windows Forms applications out there that will need to be maintained for some time to come. Also, many desktop GUIs simply might not require the horsepower offered by WPF.
    [Show full text]
  • Windows Presentation Foundation Using C# (VS 2013)
    Windows Presentation Foundation Using C#® (VS 2013) This course introduces Windows Presentation Foundation or WPF, the .NET technology from Microsoft for building rich Windows applications. It was originally part of .NET 3.0, previously called “WinFX” by Microsoft. WPF includes an XML-based markup language for defining program elements, Extensible Application Markup Language (XAML). WPF applications can be created using only code or a combination of code and XAML pages. This course covers the essentials of WPF, providing an orientation to this technology and a firm foundation for creating applications. The course is current to .NET 4.5.1 and Visual Studio 2013. WPF is a complex technology that can have a steep learning curve. This course approaches the subject in a practical manner, introducing the student to the fundamentals of creating Windows applications using the features of WPF. It includes coverage of both traditional concepts such as controls and new concepts such as XAML, flexible layout, logical resources, dependency properties, routed events, and the loosely-coupled command architecture of WPF. Data binding is discussed in detail, including visual data binding using Visual Studio 2013 and accessing databases using Entity Framework 6. Course Objectives: Gain an understanding of the philosophy and architecture of WPF. Create Windows applications using the classes provided by WPF. Understand the principles of XAML and create applications using a combination of code and XAML. Use the layout features of WPF to create flexible and attractive user interfaces. Implement event and command-driven applications with windows, menus, dialogs, toolbars, and other common user interface features. Use more advanced features of WPF such as dependency properties, routed events, logical resources, styles, templates, and data binding.
    [Show full text]
  • For Mac OS X
    C More on Stata for Mac Contents C.1 Using Stata datasets and graphs created on other platforms C.2 Exporting a Stata graph to another document C.3 Stata and the Notification Manager C.4 Stata(console) for Mac OS X C.1 Using Stata datasets and graphs created on other platforms Stata will open any Stata .dta dataset or .gph graph file, regardless of the platform on which it was created, even if it was a Windows or Unix system. Also, Stata for Windows and Stata for Unix users can use any files that you create. Remember that .dta and .gph files are binary files, not text (ASCII) files, so they need no translation; simply copy them over to your hard disk as is. Files created on other platforms can be directly opened in the Command window; for example, you can load a dataset by typing use filename or by double-clicking on the file in the Finder. C.2 Exporting a Stata graph to another document Suppose that you wish to export a Stata graph to a document created by your favorite word processor or presentation application. You have two main choices for exporting graphs: you may copy and paste the graph by using the Clipboard, or you may save the graph in one of several formats and import the graph into the application. C.2.1 Exporting the graph by using the Clipboard The easiest way to export a Stata graph into another application is to use drag and drop. You can select the graph in the Graph window and drag it to the location you would like it in another open application.
    [Show full text]