COSC 1336 Assignment 06 PDF

Title COSC 1336 Assignment 06
Author Chris Hernandez
Course Programming Fundamentals I
Institution Lone Star College System
Pages 30
File Size 2.3 MB
File Type PDF
Total Downloads 41
Total Views 144

Summary

Download COSC 1336 Assignment 06 PDF


Description

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

Unit Assignment #6 – Exceptions, Extensions, Text, and Recursion

Objectives for this assignment • • • •

Exceptions: system errors and crashes Extensions: extending Microsoft’s basic classes Advanced text – RegEx Recursion: a method calling itself in repetitive manner

Why this assignment is important Although the content is quite diverse, each item is individually important to all well rounded developers.

Expectations for successful completion The individual elements are demonstrated through a Windows environment – not through console applications as previous.

Vocabulary and Terms     

© Mark Reynolds, 2003-2017

Exception Try-Catch-Finally Extension method RegEX Recursion

Page 193 of 325

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

As Assign sign signme me ment nt Back Backgro gro groun un und d Exc Excepti epti eption on Ha Handli ndli ndling ng Exceptions are program errors; also known as bugs, crashes, and crappy software (pardon my French). Typically, an application crash will originate from:    

unexpected disconnect – e.g. an external resource suddenly becomes unavailable unexpected value – e.g. a Canadian zip code (such as G1H-0D2) is entered in a text field expecting conventional US formatted zip codes mathematical overflow – e.g. 100,000 × 100,000 or 3 ÷ 0 memory saturation – i.e. extending the previous StringBuilder project too large

Per Microsoft:29 When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception. If the currently executing method does not contain such a catch block, the CLR looks at the method that called the current method, and so on up the call stack. If no catch block is found, then the CLR displays an unhandled exception message to the user and stops execution of the program. Found online:30

29 30

https://msdn.microsoft.com/en-us/library/0yd65esw.aspx http://www.bccfalna.com/csharp-try-catch-finally/#.WAEJqSRrWZg © Mark Reynolds, 2003-2017

Page 194 of 325

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

Regardless of the error, the developer must consider all variations of error and exception. Paraphrasing Donald Rumsfeld31, there are   

‘known knowns’: Error conditions that we know we should expect and should undertake proactive prevention ‘known unknowns’: Error conditions that we do not know but we should nevertheless be proactive ‘unknown unknowns’: Error conditions that are totally unexpected and unplanned.

A good developer prepares for and proactively addresses errors that were never considered.32

31

https://video.search.yahoo.com/yhs/search?fr=yhs-mozilla-004&hsimp=yhs004&hspart=mozilla&p=donald+rumsfeld+known+and+unknown#id=1&vid=3da0ef8a1bc16e027c249276d8f742e5&action=click 32 Mark Reynolds’ Houston Techfest presentation “Defensive Programming – Addressing the Unknown Unknowns” https://lnkd.in/eEfueNX © Mark Reynolds, 2003-2017

Page 195 of 325

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

As Assign sign signme me ment nt IInstr nstr nstruct uct uctio io ions ns Pre Pre-Pr -Pr -Projec ojec ojectt Create a new solution named Assignment 06. Remember to create the Blank Solution first, then add the projects.

Pro Projec jec jectt #1 #1:: Ex Except cept ception ion hhan an andlin dlin dling g Create a new WinForms application: Project01_ExceptionHandling Set these properties on the form:   

Title (using your name) An icon (suggest IconArchive.com) Minimum Size = 500,300

Add a menu strip and add menu items as shown.

© Mark Reynolds, 2003-2017

Page 196 of 325

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

Know Known n Kn Knowns owns These are the errors you know you will encounter. The static class Convert does not anticipate invalid source parameters. After this assignment, never use it again!

The Convert.ToXxx() is a dangerous construct! Any error will toss an error. Never use a Convert.To if there is any way around it.

Demonstrate Understanding! Add comments explaining why this line never executes.

© Mark Reynolds, 2003-2017

Page 197 of 325

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

Know Known n Un Unknow know knowns ns The .TryParse will safely attempt to convert an object into a specific value type and provide a success Boolean.33 TryParse will address and handle issues and challenges. The ‘out’ parameter is a value returned through the calling stack, not as a function result.

Demonstrate Understanding! Add comments providing a recommendation for a sourceString that will successfully convert. Try these values for sourceString and tell me what happens: 12 12.34 2300000000 Twelve Null 0

33

https://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx © Mark Reynolds, 2003-2017

Page 198 of 325

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

Unkn Unknown own Unk Unknown nown nownss Finally, sometimes the developer cannot anticipate some faults and must use the try-catch construct.

This DivideByZero exception will not be known until runtime.

Demonstrate Understanding! Try these values for sourceString and tell me what happens: 12 12.34 2300000000 Twelve Null 0

Demonstrate Understanding! Google the exception object and explain (in comments) the .Message and .InnerMessage.

© Mark Reynolds, 2003-2017

Page 199 of 325

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

Final thought: if you know of specific errors that cannot be identified and accommodated ahead of time, this is a better try-catch solution: catch (DivideByZeroException ex) { MessageBox.Show(“You must be careful not to use 0 as a denominator”); } catch (Exception ex) { MessageBox.Show(ex.Message); }

There is no comprehensive list of exceptions, or even common exceptions that I found. Incorporate these ‘better’ catch blocks in lieu pf the prior example.

© Mark Reynolds, 2003-2017

Page 200 of 325

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

Real Exa Example mple 1st: You will probably want to use a defensive and safe conversion into integer every time the conversion is required. This means you will need a method to make the conversion. First, create a new method in the Form1 code (after the previously added methods). This method could be used every time the conversion to an integer is needed: The OBJECT type is the core, base type of every other type or class. As such string, int, datetime, double, everything will be acceptable.

The DBNull is a value seen in certain database designs. It is not a pure and true null. It cannot be checked using ==. Always check for known knowns.

Check for unknown unknowns.

Demonstrate Understanding! Add comments to this method explaining why each part is the basis for defensive programming.

© Mark Reynolds, 2003-2017

Page 201 of 325

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

Second, add the event method for the Real Example menu option:

This is an example of a developer’s mistake. I’ve seen this in commercial programs. If you offer Cancel and No as two options, they should do different things!

This rejection of anything not correct is more robust than rejection of explicitly incorrect values incorrect values. For example: If (okToProceed == DialogResult.No) return;

Always use the natural null / empty value for the respective object type. As a developer, you must know when these exists. There is no checklist.

If not made clear previously, the var type is not unknown. As the developer, you know the type. And the computer does too. So why get bogged down in typing it out? The destinationInput type is not know at this point in the application.

© Mark Reynolds, 2003-2017

Page 202 of 325

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

Fina Finall Out Output put

© Mark Reynolds, 2003-2017

Page 203 of 325

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

Pro Projec jec jectt #2 #2:: Bef Befor or oree w wee gget et sstart tart tarted, ed, ppau au ause se an and d re rearra arra arrang ng ngee tthe he m menu enu The menu in Project #1 was messy. This side-task will replicate Project #2, reset the namespace, and rearrange the menu. We will replicate and rename Project #1. This requires renaming the folder and project name, changing the properties and assembly information, and changing the namespace throughout the project.

Cre Create ate a new projec projectt Do NOT create a new project – yet.

Unlo Unload ad PProjec rojec rojectt #1

© Mark Reynolds, 2003-2017

Page 204 of 325

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

Open File Explo Explorer rer in in the sol solution ution spa space ce

Repl Replicate icate the previo previous us p project roject Drag and drop (while holding the ctrl key) to make a copy:

Ren Rename ame the ne new w fol folder der and th the eo old ld pro project ject n name ame

Rename the folder and the project to: ProjectX

© Mark Reynolds, 2003-2017

Page 205 of 325

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

Relo Reload ad th the e fist proje project ct Return Visual Studio and reload the project.

Add an ex existin istin istingg proj project ect

© Mark Reynolds, 2003-2017

Page 206 of 325

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

Bro Browse wse aand nd fin find d it

Fix tthe he As Assemb semb sembly ly an and d nam namesp esp espace ace Open the Properties in the solution: Change these to ProjectX

Open the Asse Assembly mbly mbly.cs .cs an and d fix it too Open the Assembly.cs found in the project Properties folder. Change these to ProjectX

© Mark Reynolds, 2003-2017

Page 207 of 325

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

Fix tthe he na names mes mespace pace In each .cs file, change the namespace to ProjectX (three times)

If this process failed, you can always restart and create a ProjectX following the same steps as seen in Project 1 – hopefully not necessary.

© Mark Reynolds, 2003-2017

Page 208 of 325

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

Cre Create ate ne new w me menus nus

Remo Remove ve the ol old d cod code e

Do not double click anything!

Dou Doublebleble-click click ea each ch m menu enu it item em aand nd ad add d th the e code back (copy it from Project #1)

© Mark Reynolds, 2003-2017

Page 209 of 325

COSC 1336 – Programming Fundamentals I

Fall 2017

Course Syllabus

Professor Reynolds

Pro Projec jec jectt #2 (co (cont) nt) nt):: Ex Exten ten tension sion M Metho etho ethods ds Now that the new Project 2 is ready to go… An extension method will extend an existing type or class with new functionality. The class added here is normally created in a separate project to enable reuse.

Addi Adding ng tthe he firs firstt ext extension ension First, Add a new class file named Extensions. Then change the class to public static Extensions: public static class Extensions { }

Next, copy the ToInt code into this class, making changes as noted: (the rest is unchanged)

public static int ToInt(this object sourceValue, int defaultValue)

The this means whenever a type class of object (or inherits from object (all of them) is encountered, add this method to the class as if it were always there.

(More may be added; I use close to a hundred in my projects.)

© Mark Reynolds, 2003-2017

Page 210 of 325

COSC 1336 – Programming Fundamentals I

Fall 2017

Course Syllabus

Professor Reynolds

Cha Changing nging the o origin rigin riginal al code to accom accommo mo modate date the ext extens ens ension ion Finally, remove the ToInt method from the main form and make these changes to the Real Example method:

This is all it takes!

We will use Extension Methods several times during the balance of the semester. The previous code

The code using the new Extension method

var sourceString = string.Empty;

var sourceString = string.Empty;

var defaultValue = -1; int destinationInt;

var destinationInt = sourceString.ToInt(0);

destinationInt = ToInt(sourceString, defaultValue);

Test the application:

© Mark Reynolds, 2003-2017

Page 211 of 325

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

Fina Finall Out Output put

Pro Projec jec jectt #3 #3:: Re RegEx gEx Sys Syste te tem mC Clas las lasss Deleted - skip

© Mark Reynolds, 2003-2017

Page 212 of 325

COSC 1336 – Programming Fundamentals I

Fall 2017

Course Syllabus

Professor Reynolds

Pro Projec jec jectt #4 #4:: Re Recur cur cursion sion aand nd the Dire Directo cto ctory ry SSys ys ystem tem Cl Class ass Add a new menu item and a TreeView as shown. In the TreeView, set:  

the width (look in the size property) to 200 the Dock property to Right

The event method will setup and then call another method to perform a directory recursion on your computer. That second method will call itself. The main event method should address these preliminary setup: Reset the treeview nodes

Select the starting location

Create the root treeview node

Then parse the initial folder! Then create the recursive folder private void ParseFolders(string currentFolder, TreeNode currentTreeNode)

The recursive folder will undertake three functions using the framework: Application.DoEvents(); try { // Look for folders under the current folder // Look for files under the current folder } catch { } // just skip any access authorization issues

A list of the folders within a folder is available with this command: (you should always use informative variable names) var xxx = Directory.GetDirectories(currentFolder)

© Mark Reynolds, 2003-2017

Page 213 of 325

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

Since the Directories.GetDireectories function returns a collection of path names, each may be examined like any other collection. Each sub folder should perform something like this: var newTreeNode = new TreeNode(subFolder); currentTreeNode.Nodes.Add(newTreeNode); ParseFolders(subFolder, newTreeNode);

The files within any given folder may be retrieved into a string collection with: var filesInCurrentFolder = Directory.GetFiles(currentFolder);

Similarly, each file should be parsed like any other collection: var nameWithoutPath = Path.GetFileName(fileNameWithFullPath); var newTreeNode = new TreeNode(nameWithoutPath); currentTreeNode.Nodes.Add(newTreeNode);

Fina Finall Out Output put

© Mark Reynolds, 2003-2017

Page 214 of 325

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

Tic TicTacT TacT TacToe oe Pa Part rt 4 (inc w/ w/Ass Ass Assignm ignm ignmen en entt ##6) 6) Ho House use usekee kee keeping ping an and dR Ref ef efacto acto actorin rin ring g Code Re Refactori factori factoring ng Let’s refactor.34

Cod Codee refac refactor tor toring ing is the process of restructuring existing computer code—changing the factoring—without changing its external behavior. Refactoring improves nonfunctional attributes of the software. Advantages include improved code readability and reduced complexity; these can improve source-code maintainability and create a more expressive internal architecture or object model to improve extensibility. Typically, refactoring applies a series of standardized basic micro-refactorings, each of which is (usually) a tiny change in a computer program's source code that either preserves the behavior of the software, or at least does not modify its conformance to functional requirements. Many development environments provide automated support for performing the mechanical aspects of these basic refactorings. If done extremely well, code refactoring may also resolve hidden, dormant, or undiscovered bugs or vulnerabilities in the system by simplifying the underlying logic and eliminating unnecessary levels of complexity. If done poorly it may fail the requirement that external functionality not be changed, introduce new bugs, or both. There are two general categories of benefits to the activity of refactoring. 1. Ma Maintain intain intainabili abili ability. ty. It is easier to fix bugs because the source code is easy to read and the intent of its author is easy to grasp.[4] This might be achieved by reducing large monolithic routines into a set of individually concise, well-named, single-purpose methods. It might be achieved by moving a method to a more appropriate class, or by removing misleading comments. 2. Ext Extensibili ensibili ensibility ty ty. It is easier to extend the capabilities of the application if it uses recognizable design patterns, and it provides some flexibility where none before may have existed.[1]

34

https://en.wikipedia.org/wiki/Code_refactoring © Mark Reynolds, 2003-2017

Page 215 of 325

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

TicTa TicTacToe cToe cToeCell Cell

Rename XorY to CellOwner. Be sure the Intellisense comments (with the ///) are properly added and the syntax is correct. Do not use // nor /*…*/ for Intellisense comments.

© Mark Reynolds, 2003-2017

Page 216 of 325

COSC 1336 – Programming Fundamentals I Course Syllabus

Fall 2017 Professor Reynolds

Tic TicTac Tac TacToeG ToeG ToeGam am amee The TicTacToeGame class will contain the game information including information about each square. Implement this class:

The collection is declared here.

The collection is reset here.

The collection is loaded here.

ticTacToeCell must be added to _ticTacToeCells.

© Mark Reynolds, 2003-2017

Page 217 of 325

COSC ...


Similar Free PDFs