ebook img

C#.NET 3: Advanced Algorithms and Database Access PDF

414 Pages·2015·2.41 MB·English
by  
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview C#.NET 3: Advanced Algorithms and Database Access

C#.NET 3: Advanced Algorithms and Database Access Lesson 1: Introduction and Multidimensional Arrays Understanding the Learning Sandbox Environment Visual Cues Code Snippets The OST Plug-In Arrays Revisited Multidimensional Arrays Declaring, Allocating, and Initializing Multidimensional Arrays Accessing Multidimensional Array Elements Debugging Classes Matching Game - A Coding Tutorial Matching Game User Interface Prototypes Creating the User Interface Adding the Code Lesson 2: Jagged Arrays and Array Class Methods Jagged Arrays Declaring, Allocating, and Initializing Jagged Arrays Accessing Jagged Array Elements Mixing Jagged Arrays and Multidimensional Arrays The Array Object Array Length Versus GetLength() Array Rank Clearing Array Element Contents Copying an Array Resizing an Array Other Class Array Properties and Methods Math Drop - A Coding Tutorial Math Drop Game User Interface Prototypes Creating the User Interface Adding the Code Lesson 3: Array Indexers and Sorting Indexers Sorting Arrays Tiler - A Coding Tutorial Tiler Game User Interface Prototypes Creating the User Interface Adding the Code Lesson 4: Object Relationships and the Object Class Inheritance The Object Base Class DrawShapes - A Coding Tutorial Draw Shapes User Interface Prototypes Creating the User Interface Adding the Code Lesson 5: Abstract and Sealed Classes Conceptualizing Abstract Classes Calling Base Class Constructors Sealed Classes PopIt - A Coding Tutorial PopIt User Interface Prototypes Creating the User Interface Adding the Code Lesson 6: Struct Data Type, Enums, and Casting Structs Enums Casting ColorMatch - A Coding Tutorial User Interface Prototypes Creating the User Interface Adding the Code Lesson 7: Interfaces and Interface Casting Interfaces What is an Interface? Multiple Inheritance Interfaces Versus Abstract Classes Creating an Interface Shape Capture - A Coding Tutorial User Interface Prototypes Object Identification and Discussion Creating the User Interface Adding the Code Lesson 8: Delegates and Events Delegates What is a Delegate? Working with Delegates Anonymous Delegate Methods Multicast Delegate Instances Why Delegates? Events Events are delegates .NET Events Subscriber and Publisher Balloons - A Coding Tutorial User Interface Prototypes Creating the User Interface Adding the Code Lesson 9: Lambda Expressions Lamba Expressions What is a Lambda Expression? Lambda Expression Syntax Lambda Statements and Expressions Lambda Expressions and Event Handlers Usage Lambda Expressions as Algorithms Lambda Expression Trees Targets - A Coding Tutorial User Interface Prototypes Creating the User Interface Adding the Code Lesson 10: Exceptions and Exception Handling Introduction Creating an Exception Try/Catch/Finally Block Throwing an Exception Nested Exceptions Extending Exceptions Custom Exceptions To Catch or Not Exceptions and the Using Syntax Coding Tutorial Lesson 11: Collections and Generics Collections and Generics Introduction ArrayList vs. List Generic Other Generic Collection Classes Creating Generic Classes Coins - A Coding Tutorial User Interface Prototypes Creating the User Interface Adding the Code Lesson 12: Creating and Manipulating Strings Strings Immutability and Empty Versus Null StringBuilder Regular Expressions Lesson 13: Introduction to Database Access Using .NET What are Databases? Data Sources Window Working with Datasets Lesson 14: Working With Databases and Visual Data Components Making the Connection Modifying Database Data Working With Datasets Lesson 15: A Database GUI Application Course Project The Assignment User Interface Class Design Diagram TOE Chart Use Cases - MainForm Use Cases - CategoriesForm Use Cases - CategoryBreakdownForm DataSet Designer Coding Requirements Application Development Steps First Steps Categories ComboBox Populating the Register DataGridView Inserting a New Record Register Balance and Nullable Data Types Deleting a Register Entry Update Categories Category Breakdown Reports Tab Order Copyright © 1998-2014 O'Reilly Media, Inc. This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information. Introduction and Multidimensional Arrays Welcome to the O'Reilly School of Technology's C# .NET 3: Advanced C# Programming course! Course Objectives When you complete this course, you will be able to: create and represent more complex data using enumerations, structs, arrays and classes. enhance structs and classes using indexers, casting, interfaces, abstraction and sealing. handle and create custom events using delegates and lambda expressions. create custom exceptions. use generics with collections. overcome performance limitations and the immutability of strings by using the StringBuilder class. Use regular expressions for concise pattern matching and replacement. Access data in a database, and use visual data components. In this course, you will go deeper into many advanced programming concepts such as multidimensional and jagged arrays, array indexers, abstract and sealed classes, structs, enums, casting, interfaces, delegates, events, lambda expressions, generics, the StringBuilder class, regular expressions, and advanced exception handling. You'll also get an introduction to working with databases and visual data components. You will create several applications throughout the course, which will enhance your professional portfolio and also contribute toward certificate completion. Lesson Objectives When you complete this lesson, you will be able to: use the Learning Sandbox Environment use Arrays use Multidimensional Arrays Debug Classes create a Matching Game - A Coding Tutorial Learning with O'Reilly School of Technology Courses As with every O'Reilly School of Technology course, we'll take a user-active approach to learning. This means that you (the user) will be active! You'll learn by doing, building live programs, testing them and experimenting with them— hands-on! To learn a new skill or technology, you have to experiment. The more you experiment, the more you learn. Our system is designed to maximize experimentation and help you learn to learn a new skill. We'll program as much as possible to be sure that the principles sink in and stay with you. Each time we discuss a new concept, you'll put it into code and see what YOU can do with it. On occasion we'll even give you code that doesn't work, so you can see common mistakes and how to recover from them. Making mistakes is actually another good way to learn. Above all, we want to help you to learn to learn. We give you the tools to take control of your own learning experience. When you complete an OST course, you know the subject matter, and you know how to expand your knowledge, so you can handle changes like software and operating system updates. Here are some tips for using O'Reilly School of Technology courses effectively: Type the code. Resist the temptation to cut and paste the example code we give you. Typing the code actually gives you a feel for the programming task. Then play around with the examples to find out what else you can make them do, and to check your understanding. It's highly unlikely you'll break anything by you can make them do, and to check your understanding. It's highly unlikely you'll break anything by experimentation. If you do break something, that's an indication to us that we need to improve our system! Take your time. Learning takes time. Rushing can have negative effects on your progress. Slow down and let your brain absorb the new information thoroughly. Taking your time helps to maintain a relaxed, positive approach. It also gives you the chance to try new things and learn more than you otherwise would if you blew through all of the coursework too quickly. Experiment. Wander from the path often and explore the possibilities. We can't anticipate all of your questions and ideas, so it's up to you to experiment and create on your own. Your instructor will help if you go completely off the rails. Accept guidance, but don't depend on it. Try to solve problems on your own. Going from misunderstanding to understanding is the best way to acquire a new skill. Part of what you're learning is problem solving. Of course, you can always contact your instructor for hints when you need them. Use all available resources! In real-life problem-solving, you aren't bound by false limitations; in OST courses, you are free to use any resources at your disposal to solve problems you encounter: the Internet, reference books, and online help are all fair game. Have fun! Relax, keep practicing, and don't be afraid to make mistakes! Your instructor will keep you at it until you've mastered the skill. We want you to get that satisfied, "I'm so cool! I did it!" feeling. And you'll have some projects to show off when you're done. Understanding the Learning Sandbox Environment Most of the time we'll be working in Visual Studio, Microsoft's Integrated Development Environment (IDE) for working with C#. Visual Cues CODE TO TYPE: In boxes like this, we'll ask you to type code (or remove code)in Visual Studio. Code to add will look like this, and code to remove will look like this. These boxes signal that it's time to experiment! OBSERVE: Similarly, when we want you to simply observe some code or result, we will put it in an "OBSERVE" box like this. We might use color highlighting to help explain the code. You are not expected to type anything from these boxes. Text that corresponds to the color of the code in an OBSERVE box will explain that particular code in more detail. When you see this icon , go ahead and save your work. You can save whenever you like; we want you to get into the habit of saving your projects frequently. In fact, whenever you pause to think, move your cursor over to the on the Toolbar and click on it. Code Snippets Whenever we present snippets of code, you'll want to create a sample project where you can enter that code. We'll prompt you to create test project(s) for each lesson. As we progress through each lesson, you'll create methods and call those methods from the Form constructor under the InitializeComponent() line of code. Eventually you'll create more topic-specific methods, and comment out the call to the methods that you're not using. The OST Plug-In We've added a new menu item to the Visual Studio system that we think you'll like. You can now use the OST menu to get to your syllabus for this course at any time. Your menu may display other courses you've enrolled in as well. If your Visual Studio menus start to get confusing in the course of your work, you can always get Tip back to the default view by selecting this course from the OST menu. Arrays Revisited For this lesson, create a test project using File | New | Project, change the Name of the project to MultiDimensionalArrays, and click OK. You may recall that an array is a reference data type that holds multiple values or elements of a specific data type. Even though an array can hold multiple values, each value is referenced through a single variable name. Array reference variables are stored on the stack, but the values they reference are stored on the heap. Remember that although we allocate memory for arrays on the heap using the C# new keyword, we may Note omit the new keyword when declaring and initializing an array. If we are reallocating memory for an already declared keyword, we still need to use the new keyword. Let's try an example that shows how we can declare, allocate, and initialize arrays. Modify Form1.cs as shown: CODE TO TYPE: . . . public Form1() { InitializeComponent(); ArraysReview1(); } private void ArraysReview1() { // Integer array declaration with a value of null. int[] declaredArray; // Integer array declaration with pre-allocated space for five integer elements, // all values initialized to default value for integers (0). int[] declaredAllocatedWithDefaultInitializationArray = new int[5]; // Changing the number of array elements to 25, all values initialized to default // value for integers (0). // Note that any previously stored values in the array elements are erased. declaredAllocatedWithDefaultInitializationArray = new int[25]; // Integer array declaration with pre-allocated space for five integer elements, // with array element initialization. int[] initializedArray = new int[5]{ 1, 2, 3, 4, 5 }; // Integer array declaration with pre-allocated space for five integer elements, // with array element initialization, omitting array size. int[] initializedSizeOmittedArray = new int[]{ 1, 2, 3, 4, 5 }; // Integer array declaration with pre-allocated space for five integer elements, // with array element initialization, omitting new keyword. int[] initializedAbbreviatedSyntaxArray = { 1, 2, 3, 4, 5 }; } . . . Make sure to add breakpoints to enable stepping through the code to clarify the code behavior. To add a breakpoint, click in the left margin next to the line of code where you want to include a break. When you run the program, execution will pause at that point. Click to save your changes, and then click to run the program; note how the values and types change for the arrays we created. We typically refer to the number of elements an array can hold as its size; we can also call it dimension. So far, we've used only one-dimensional arrays.—we'll introduce multidimensional arrays next. Multidimensional Arrays Arrays can have more than one dimension. You can visualize a one-dimensional array as a single column of data elements, a two-dimensional array as a spreadsheet of rows and columns, or as a plane that can be represented by x and y values, and a three-dimensional array as a cube. Beyond three dimensions, you might be able to imagine the fourth dimension is time, or maybe a property of the element at a specific location. Here's an example of multi-dimensional data tht may help you get a handle on multidimensional arrays. Suppose you're a movie mogul. In the next year, you plan to make three different movies: one about alien shark zombies, one a feel-good love story, and the third, a superhero action movie. You begin to work out your budget by calculating what you will need to spend for one month of work on just the alien shark zombies movie. You create a list of budget items: costumes, pay for crew members, food and transportation for everyone, and so on. We could consider this task to be one-dimensional. Next, when you budget for all of these things for more than one month, you'll add a second dimension. When you budget for your other movies, that's a third dimension of your movie studio budget. After a month goes by, you need to track your actual expenses for all of the costs for each of the movies for all of the preceding months—a fourth dimension. If you want to compare the budgeted costs to actual costs, that could be considered a fifth dimension. Now if your movie studio has other divisions, say for documentaries, shorts, corporate films, and television productions, you might need to add a sixth dimension! If you do want to know more about visualizing n-dimension arrays, there is an excellent discussion on Note stackoverflow. Declaring, Allocating, and Initializing Multidimensional Arrays So, how do we declare, allocate, and initialize a two-dimensional array? Modify Form1.cs as shown (add breakpoints to enable stepping through the code to clarify the code behavior): CODE TO TYPE: . . . public Form1() { InitializeComponent(); ArraysReview1(); ArraysReview2(); } . . . private void ArraysReview2() { // Two-dimensional array declaration with a value of null. int[,] declared2DArray; // Two-dimensional array declaration with pre-allocated space for // one row and two columns, // all values initialized to default value for integers (0). int[,] declaredAllocatedWithDefaultInitialization2DArray = new int[1, 2]; // Two-dimensional array declaration with pre-allocated space for // two rows and three columns, with array element initialization. int[,] initialized2DArray = new int[2, 3] { { 987, 876, 654 }, { 543, 432, 321 } }; // Two-dimensional array declaration with pre-allocated space for // two rows and three columns, with array element initialization, // omitting arrray size int[,] initializedSizeOmitted2DArray = new int[ , ] { { 987, 876, 654 }, { 543 , 432, 321 } }; // Two-dimensional array declaration with pre-allocated space for // two rows and three columns, with array element initialization, // omitting new keyword int[,] initializedAbbreviatedSyntax2DArray = { { 987, 876, 654 }, { 543, 432, 321 } }; } . . . Click to save your changes, and then click to run the program. The values and types change for the arrays we created. When initializing two-dimensional arrays, note that you group each row of column values within separate curly braces {}, separated by commas. How do you visualize or represent the elements of a two-dimensional array? Modify Form1.cs as shown: CODE TO TYPE: . . . public Form1() { InitializeComponent(); ArraysReview1(); ArraysReview2(); ArraysReview3(); } . . . private void ArraysReview3() { // Two-dimensional array initialized with values to help visualize the structu re string[,] spreadsheet2DArray = { {"A1 or R1C1", "B1 or R1C2", "C1 or R1C3"}, {"A2 or R2C1", "B2 or R2C2", "C2 or R2C3"}, {"A3 or R3C1", "B3 or R3C2", "C3 or R3C3"}, {"A4 or R4C1", "B4 or R4C2", "C4 or R4C3"} }; } . . . Click to save your changes, and then click to run the program. The values and types change for the arrays we created. In the code snippet above, A1 (column A, row 1) and R1C1 (Row 1 Column 1) represent a standard spreadsheet referencing convention to help you visualize the assignment of values to the two-dimensional array elements; it would look like this in a spreadsheet: Remember, array indexes start at zero (0), not one (1)! The first row in the first column would Note actually be referenced as 0, 0. In order to create arrays beyond two dimensions, we'll continue the pattern. Modify Form1.cs as shown (always make sure to add breakpoints to enable stepping through the code to clarify the code behavior):

Description:
create a Matching Game - A Coding Tutorial Most of the time we'll be working in Visual Studio, Microsoft's Integrated Development Environment
See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.