Solution - Challenge Epic Spies Asset Tracker

Tutorial Series: Free C# Fundamentals via ASP.NET Web Apps

Previous Article  |  Next Article


Get GitHub Code

This is the solution to the ChallengeEpicSpiesAssetTracker, where you are tasked with creating a system for Epic Spies, inc. that keeps track of all their assets' statistics. This was a tricky challenge, because we haven't touched on the exact method to use in order to complete it, but it's ultimately a combination of array-based functionality we've used up to this point. Read on only as much as you need in order to get past the issue you're facing, then try and solve the rest on your own if possible.

Step 1: Default.aspx Page

To begin, create a new ASP.NET Web Forms Project and set up the Default.aspx Page as we've done throughout this series. Then, switch to the design view and add the following controls to your web form:


finalPage


The programmatic IDs for the controls are as follows:

  1. assetTextBox
  2. electionsTextBox
  3. actsTextBox
  4. addButton
  5. resultLabel

The Epic Spies logo should be only 150px tall. To set the size, move your cursor over the bottom right-hand corner of the image, click and drag to resize the image:


Logo


Step 2: Creating the Arrays

Next, double-click the addButton to open the addButton_Click event in Default.aspx.cs. What we need to do first is create a set of arrays to hold the different values that the user inputs into the TextBoxes. We also know that we need to retain their values between post backs to the server, so we need to initialize these arrays in the Page_Load event:


Arrays


Now that we have our arrays initialized, we need to add them to the ViewState so that we can save them between posts back to the server:


ViewState


Tip:

Adding objects to the ViewState requires that a key is assigned so that we can access those objects by referencing that key. In this case, the key is the upper-case version of the array we're adding to ViewState. Not only is this easier to remember, but it's easier to read for others looking at your code later.

Now that we have these arrays initialized and added to the ViewState, we're almost ready to begin adding items to them. However, we need to wrap the Page_Load code in a conditional to ensure that we don't initialize these values over and over:


PostBack


Step 3: Retrieving Arrays from ViewState

Next, we need to retrieve the arrays' values from the ViewState so that we can modify them in the addButton_Click. We can do this by creating locally-scoped arrays that take on the value of their counterparts held in ViewState. For instance, we create a new string array called assets that holds the ViewState["Assets"] value. We do this for all three arrays:

NewArrays

Tip:

The values in ViewState are generic objects, which cannot be implicitly converted to arrays, nor will a helper method such as ToString() work. We need to cast them not only to the appropriate data type, but to an array of that data type. Failing to cast like this results in the following error:


Error


Step 4: Resizing the Arrays

Now that we've retrieved the arrays we created, we need to resize them before adding the information the user input. In order to do this, use the Array.Resize() method, which takes in two parameters:

  1. An array reference
  2. The new length

Obviously, the array reference will be the array you're trying to resize, such as assets or elections. But how do you determine the new length? In Lesson 23, we simply used myArray.Length + 1, but since we have multiple arrays, using this method for each creates a lot of redundant and unnecessary code. Because all three arrays will be the same length, what we can do is create an integer variable equal to one more than the length of one of the arrays:


newLength


Now that we know the length the new arrays need to be, we can proceed by using the Resize() method for each array:


Resize


Step 5: Adding Values to the Arrays

Before we can begin to add values to the arrays, we need to make sure that we add them at the appropriate location, in the newest index we just created. To do this, create a new int variable called newIndex that holds that value:


newIndex


Note: Remember that the GetUpperBound() method takes in the dimension of the array that you're evaluating. Because we're dealing with single-dimension, zero-based arrays, this will be 0.

Now, we can add the user-input values to the arrays at the appropriate index. Make sure to use the int.Parse() method for the integer arrays:


addArray


Now that the arrays are updated, they need to be saved back to the ViewState to be preserved between post backs. To do this, simply assign the appropriate ViewState to the array:


newViewState


Step 6: Formatting the resultLabel

The final step is to display the result to the resultLabel. In order to meet the requirements for the challenge, use the String.Format() method and type the following:


StringFormat


In order to retrieve the values needed, we can make use of the helper methods for the arrays. For {0}, we can use elections.Sum() to add all the integers stored in the elections array. For the average acts, we can use acts.Average(), and the last asset can be retrieved by simply using assets[newIndex]:


FinalStringFormat


To correctly format the average to display two decimal places, postfix it with N2:


Asset


Finally, clear out the text from the TextBoxes before the page refreshes:


ClearTextbox


Save and run your project to see the result:


finalPage


Conclusion

This completes the solution for ChallengeEpicSpiesAssetTracker. There was a lot required in order to complete this challenge, but hopefully you're beginning to see how all you've learned so far about C# works together to create useful applications. Remember, repetition is key to learning, so keep on working with these concepts and practicing them. Hopefully you were able to complete most or all of this on your own. If not, that's ok. Come back later and try it again. Great job!


Related Articles in this Tutorial:

Lesson 1 - Series Introduction

Lesson 2 - Installing Visual Studio 2015

Lesson 3 - Building Your First Web App

Lesson 4 - Understanding What You Just Did

Lesson 5 - Working with Projects in Visual Studio

Lesson 6 - Simple Web Page Formatting in Visual Studio

Challenge 1

Solution 1

Lesson 7 - Variables and Data Types

Lesson 8 - Data Type Conversion

Lesson 9 - Arithmetic Operators

Lesson 10 - C# Syntax Basics

Challenge 2 - ChallengeSimpleCalculator

Solution - ChallengeSimpleCalculator

Lesson 11 - Conditional If Statements

Lesson 12 - The Conditional Ternary Operator

Challenge 3 - ChallengeConditionalRadioButton

Solution - Challenge Conditional RadioButton

Lesson 13 - Comparison and Logical Operators

Lesson 13 Challenge - First Papa Bob's Website

Solution - Challenge First Papa Bob's Website

Lesson 14 - Working with Dates and Times

Lesson 15 - Working With Spans of Time

Lesson 16 - Working with the Calendar Server Control

Challenge 4 - Challenge Days Between Dates

Solution - Challenge Days Between Dates

Lesson 17 - Page_Load and Page.IsPostBack

Lesson 18 - Setting a Break Point and Debugging

Lesson 19 - Formatting Strings

Challenge 5 - Challenge Epic Spies Assignment

Solution - Challenge Epic Spies Assignment

Lesson 20 - Maintaining State with ViewState

Lesson 21 - Storing Values in Arrays

Lesson 22 - Understanding Multidimensional Arrays

Lesson 23 - Changing the Length of an Array

Challenge 6 - Challenge Epic Spies Asset Tracker

Solution - Challenge Epic Spies Asset Tracker

Lesson 24 - Understanding Variable Scope

Lesson 25 - Code Blocks and Nested If Statements

Lesson 26 - Looping with the For Iteration Statement

Challenge 7 - Challenge For Xmen Battle Count

Solution - Challenge For Xmen Battle Count

Lesson 27 - Looping with the while() & do...while() Iteration Statements

Lesson 28 - Creating and Calling Simple Helper Methods

Lesson 29 - Creating Methods with Input Parameters

Lesson 30 - Returning Values from Methods

Lesson 31 - Creating Overloaded Methods

Lesson 32 - Creating Optional Parameters

Lesson 33 - Creating Names Parameters

Lesson 34 - Creating Methods with Output Parameters

Challenge 8 - Challenge Postal Calculator Helper Methods

Solution - Challenge Postal Calculator Helper Methods

Mega Challenge Casino

Solution - Mega Challenge Casino

Lesson 35 - Manipulating Strings

Challenge 9 - Phun With Strings

Solution - Challenge Phun With Strings

Lesson 36 - Introduction to Classes and Objects

Challenge - Hero Monster Classes Part 1

Solution - Hero Monster Classes Part 1

Challenge - Hero Monster Classes Part 2

Solution - Challenge Hero Monster Classes Part 2

Lesson 37 - Creating Class Files Creating Cohesive Classes and Code Navigation

Lesson 38 - Understanding Object References and Object Lifetime

Lesson 39 - Understanding the .NET Framework and Compilation

Lesson 40 - Namespaces and Using Directives

Lesson 41 - Creating Class Libraries and Adding References to Assemblies

Lesson 42 - Accessibility Modifiers, Fields and Properties

Lesson 43 - Creating Constructor Methods

Lesson 44 - Naming Conventions for Identifiers

Lesson 45 - Static vs Instance Members

Challenge 10 - Challenge Simple Darts

Solution - Challenge Simple Darts

Lesson 46 - Working with the List Collection

Lesson 47 - Object Initializers

Lesson 48 - Collection Initializers

Lesson 49 - Working with the Dictionary Collection

Lesson 50 - Looping with the foreach Iteration Statement

Lesson 51 - Implicitly-Typed Variables with the var Keyword

Challenge 11 - Challenge Student Courses

Solution - Challenge Student Courses

Mega Challenge War

Solution - Mega Challenge War

Lesson 52 - Creating GUIDs

Lesson 53 - Working with Enumerations

Lesson 54 - Understanding the switch() Statement

Lesson 55 - First Pass at the Separation of Concerns Principle

Lesson 56 - Understanding Exception Handling

Lesson 57 - Understanding Global Exception Handling

Lesson 58 - Understanding Custom Exceptions

Lesson 59 - Creating a Database in Visual Studio

Lesson 60 - Creating an Entity Data Model

Lesson 61 - Displaying the DbSet Result in an ASP.NET GridView

Lesson 62 - Implementing a Button Command in a GridView

Lesson 63 - Using a Tools-Centric Approach to Building a Database Application

Lesson 64 - Using a Maintenance-Driven Approach to Building a Database Application

Lesson 65 - Creating a New Instance of an Entity and Persisting it to the Database

Lesson 66 - Package Management with NuGet

Lesson 67 - NuGet No-Commit Workflow

Lesson 68 - Introduction the Twitter Bootstrap CSS Framework

Lesson 69 - Mapping Enum Types to Entity Properties in the Framework Designer

Lesson 70 - Deploying the App to Microsoft Azure Web Services Web Apps

Papa Bob's Mega Challenge

Papa Bob's Mega Solution Part 1 - Setting up the Solution

Papa Bob's Mega Solution Part 2 - Adding an Order to the Database

Papa Bob's Mega Solution Part 3 - Passing an Order from the Presentation Layer

Papa Bob's Mega Solution Part 4 - Creating the Order Form

Papa Bob's Mega Solution Part 5 - Adding Enums

Papa Bob's Mega Solution Part 6 - Creating an Order with Validation

Papa Bob's Mega Solution Part 7 - Calculating the Order Price

Papa Bob's Mega Solution Part 8 - Displaying the Price to the User

Papa Bob's Mega Solution Part 9 - Creating the Order Management Page


Comments

Please login or register to add a comment