Using My Coding Books Effectively

A lot of people ask me how to use my books to learn a coding technique quickly.  I recently wrote two articles for New Relic that help explain the techniques for choosing a technical book and the best way to get precisely the book you want. These articles are important to you, the reader, because I want to be sure that you’ll always like the books you purchase, no matter who wrote them. More importantly, these articles help you get a good start with my coding books because you start with a book that contains something you really do need.

Of course, there is more to the process than simply getting the right book. When you already have some experience with the language and techniques for using it, you can simply look up the appropriate example in the book and use it as a learning aid. However, the vast majority of the people asking this question have absolutely no experience with the language or the techniques for using it. Some people have never written an application or worked with code at all. In this case, there really aren’t any shortcuts. Learning something really does mean spending the time to take the small steps required to obtain the skills required. Someday, there may be a technology that will simply pour the knowledge into your head, but that technology doesn’t exist today.

Even reading a book cover-to-cover won’t help you succeed. My own personal experiences tell me that I need to use multiple strategies to ensure I actually understand a new programming technique and I’ve been doing this for a long time (well over 30 years). Just reading my books won’t make you a coder, you must work harder than that. Here is a quick overview of some techniques that I use when I need to discover a new way of working with code or to learn an entirely new technology (the articles will provide you with more detail):

  • Read the text carefully.
  • Work through the examples in the book.
  • Download the code examples and run them in the IDE.
  • Write the code examples by hand and execute them.
  • Work through the examples line-by-line using the debugger (see Debugging as An Educational Tool).
  • Talk to the author of the book about specific examples.
  • Modify the examples to obtain different effects or to expand them in specific ways.
  • Use the coding technique in an existing application.
  • Talk to other developers about the coding technique.
  • Research different versions of the coding technique online.
  • View a video of someone using the technique to perform specific tasks.

There are other methods you can use to work with my books, but this list represents the most common techniques I use. Yes, it’s a relatively long list and they all require some amount of effort on my part to perform. It isn’t possible to learn a new technique without putting in the time required to learn it. In a day of instant gratification, knowledge still requires time to obtain. The wisdom to use the knowledge appropriately, takes even longer. I truly wish there were an easier way to help you get the knowledge needed, but there simply isn’t.

Of course, I’m always here to help you with my books. When you have a book-specific question, I want to hear about it because I want you to have the best possible experience using my books. In addition, unless you tell me that something isn’t working for you, I’ll never know and I won’t be able to discuss solutions for the issue as part of blog post or e-mail resolution.

What methods do you use to make the knowledge you obtain from books work better? The question of how people learn takes up a considerable part of my time, so this is an important question for my future books and making them better. Let me know your thoughts about the question at John@JohnMuellerBooks.com. The same e-mail address also works for your book-specific questions.

 

API Security and the Developer

As our world becomes ever more interconnected, developers rely more and more on code and data sources outside of the environment in which the application runs. Using external code and data sources has a considerable number of advantages, not the least of which is keeping application development on schedule and within budget. However, working with APIs, whether local or on someone else’s system, means performing additional levels of testing. It isn’t enough to know that the application works as planned when used in the way you originally envisioned it being used. That’s why I wrote API Security Testing: Think Like a Bad Guy. This article helps you understand the sorts of attacks you might encounter when working with a third party API or allowing others to use your API.

Knowing the sources and types of potential threats can help you create better debugging processes for your organization. In reality, most security breaches today point to a lack of proper testing and an inability to debug applications because the inner workings of that application are poorly understood by those who maintain them. Blaming the user for interacting with an application incorrectly, hackers for exploiting API weaknesses, or third parties for improperly testing their APIs are simply excuses. Unfortunately, no one is interested in hearing excuses when an application opens a door to user data of various types.

It was serendipity that I was asked to review the recent Snapchat debacle and write an article about it. My editorial appears as Security Lessons Courtesy of Snapchat. The problems with Snapchat are significant and they could have been avoided with proper testing procedures, QA, and debugging techniques.This vendor is doing precisely all the wrong things—I truly couldn’t have asked for a better example to illustrate the issues that can occur when APIs aren’t tested correctly and fully. The results of the security breach are truly devastating from a certain perspective. As far as I know, no one had their identity stolen, but many people have lost their dignity and privacy as a result of the security breach. Certainly, someone will try to extort money from those who have been compromised. After all, you really don’t want your significant other, your boss, or your associates to see that inappropriate picture.

The need to test APIs carefully, fully, and without preconceived notions of how the user will interact with the API is essential. Until APIs become more secure and developers begin to take security seriously, you can expect a continuous stream of security breaches to appear in both the trade press and national media. The disturbing trend is that vendors now tend to blame users, but this really is a dead end. The best advice I can provide to software developers is to assume the user will always attempt to use your application incorrectly, no matter how much training the user receives.

Of course, it isn’t just APIs that require vigorous testing, but applications as a whole. However, errors in APIs tend to be worse because a single API can see use in a number of applications. So, a single error in the API is spread far wider than a similar error in an application. Let me know your thoughts on API security testing at John@JohnMuellerBooks.com.

Understanding the Effects of REM Sleep on Writing

A lot of people wonder how authors sometimes make the creative leaps they do in books. Of course, part of it is natural gift. Writing does involve some element of innate ability—a requirement that has been proven to my satisfaction more than a few times. Another part of the creative leap is mindset. When you spend a great deal of energy looking for something, you’re bound to eventually find it. We can target how our minds process information and therefore, control the resulting output to some degree. Hard work also comes into play—the best authors research their topic heavily (even in the fiction arena).

However, the obvious factors alone can’t account for the creative leap. Something more is at work than these elements. Over the years I’ve come to understand that part of what makes me a good author is my subconscious. An ability to take information stored during my waking hours and turn it into patterns as I sleep is part of the writing process for me and most likely many other authors as well (whether they realize it or not).

Sleep alone isn’t enough to generate the informational patterns, however. Over the years I’ve read articles such as REM Sleep Stimulates Creativity and Sleeping on it – how REM sleep boosts creative problem-solving. In fact, because the topic interests me so much, I’ve probably read a hundred or so such articles and a few books as well (such as, A Whack on the Side of the Head: How You Can Be More Creative). Getting sufficient Rapid Eye Movement (REM) sleep is an essential part of the creative process. In graphing my own productivity over the years, I’ve found a correlation between the quantity of REM sleep (and most especially, remembered dreams) and the quality of my output. Sometimes quantity is also affected by REM sleep, but the best writing I’ve done is when I’ve had enough REM sleep.

The onset of REM sleep usually occurs about 90 minutes after falling asleep. The sleep cycle varies between light and REM sleep depending on the person. A number of other factors also seem to play a role in my own personal sleep cycle. For example, I tend to get more REM sleep after a day of moderate physical exertion, mixed with plenty of research time (non-writing time). Eating no more than two hours before I go to bed is also a factor and I also try to create a restful environment conducive to sleep. In fact, more than once I’ve taken a two hour nap after performing research to overcome writer’s block. The technique works quite often. (Shorter nap times don’t appear to provide any advantage because the REM sleep cycle may not even occur or is of insufficient length to derive a solution to the problem at hand.)

As part of the dreaming cycle, I’m often able to employ lucid dreaming techniques (or what is commonly called directed dreaming). However, more often than not I simply wake with the answers to the questions I had when I went to sleep and quickly write them down. It’s a technique authors have used successfully over the centuries to great effect.

The point is that REM sleep is a required component for many creative endeavors. It’s not just authors who require REM sleep, but anyone who is involved in any sort of creative effort. A lack of REM sleep may be why engineers on a team are unable to create a useful solution to problems or why developers write buggy code. There is certainly nothing mysterious about the process, except why more people don’t employ it.

What is your take on REM sleep? Do you ever stuff your head full of information and then go take a nap to solve problems? If not, would you be willing to give the technique a try after reading this article? Let me know your thoughts (and the results of any experiments) at John@JohnMuellerBooks.com.

 

Entering Data in a Code::Blocks Window

Sometimes it isn’t very obvious how to enter data into a Code::Blocks window. One of the windows that seems to be causing problems for a number of readers is the Watches window. You open this window by choosing Debug | Debugging Windows | Watches. The purpose of this window is to let you view the content of variables in your application, which is an essential part of the debugging process. In order to view the variable (or other expression) content, you must enter it in the Watches window. Book III of C++ All-In-One Desk Reference For Dummies tells you all about debugging.

One technique for entering the variable is to select it in the editing window and the drag it to the Watches window. The variable will appear in the Watches window along with its value. However, this approach only works for variables and expressions that actually appear in your code. You might want to enter some other expression (or manually enter the variable, rather than drag and drop it). The Watches window consists of rows and columns as shown here.

WatchEntry01

The name of the variable or the expression you want to view appears in the first column. To enter a new value into the Watches window, click directly in the first empty left column cell. The row will turn blue and you’ll see a red insertion point appear in the cell as shown in the screenshot. Now you can type the variable name or expression you want to work with and press Enter. Let’s say your variable is named i. It might look like this:

WatchEntry02

Notice that the row is now white because it isn’t selected. However, you can see the name of the variable, i, it’s value 1983844706, and it’s type int. The row is in red because the value of i has just changed (unchanged values appear in black so you can see them easier). As you debug your application, you can now watch the value of i for changes.

Sometimes it isn’t obvious how to enter information into Code::Blocks (or any other application for that matter). When that happens, the focus turns to the application, rather than the work you need to do, and the experience becomes frustrating. Let me know about your book-related Code::Blocks questions at John@JohnMuellerBooks.com and I’ll do my best to answer them. Because I don’t have a direct connection to the vendor, my ability to answer other sorts of questions is limited.

 

Debugging As an Educational Tool

One of the questions I get asked quite often is how I learn new programming techniques. After all, I work with a broad range of languages and IDEs in my pursuit of new programming environments. Let’s face it—I like to play with code. For me, it’s not really a job to write application code. I like to see how different things work and what’s possible with a given language. In order to accomplish my goals, however, I need to learn techniques quickly. The debugger is my secret to learning how to code quickly and easily. In fact, I’ve written an article on the topic, “Improve Your Coding Skill by Listening to the Debugger.” You also see this technique emphasized in a number of my books, especially LINQ for Dummies and Start Here! Learn Microsoft Visual C# 2010 Programming.

The main reason that I use the debugger as an educational tool is that I can see the code in action. It’s possible to see how the code actually works, rather than envision what the code is supposed to do. The difference is important. For me, seeing the code actually work demonstrates that the theory behind the code is sound. Many theories sound good until you actually try to use them—using the debugger proves the theory as you work through the code.

From a personal perspective, the biggest hindrance that I face in using the debugger as an educational tool is the lack of good comments. In fact, comments are such a problem that I write about them in Creating Useful Comments. When the code lacks comments, I need to look up the calls myself and then determine how the developer is using them. It’s time consuming and a somewhat painful way to learn at times because I can see the code work, but I don’t know how it works or why the developer chose a particular approach. Even worse is when the code contains misleading comments. Worse still are comments that are outright incorrect because they reflect a previous state of the code or the developer didn’t actually understand why a technique works (the sheer dumb luck approach to coding).

Make sure you check out my article on the topic and get back to me about it. I’d like to hear your views on using the debugger as an educational aid. For that matter, I’d like to hear your viewpoint on debuggers as a class of application. Do you feel they need work or are debuggers as useful as they need to be? You may even feel that debuggers have become encumbered by way too many features. Whatever your viewpoint, let me know at John@JohnMuellerBooks.com.

 

Are Enforced Updates a Good Idea?

I currently have a system running Windows 98 in my home because there are some older games and other applications that I still enjoy using on that platform. The system isn’t connected to the Internet or any other machine because I consider the system a security hazard. I’ve set this system up for the sheer pleasure of seeing some of my old applications come to life again and to make use of some older hardware that still works just fine. The system has our movie database on it and a few other non-business items. However, the fact remains that this system would be unsafe to use to browse the Internet. It would probably be infected to the point of being unusable in a matter of hours (if it lasted that long).

Generally, when it comes to my Internet-connected systems, I use the latest software available to keep my systems secure. The software isn’t allowed to languish until it reaches an unprotected state either. I test every available update on one machine. If it works and I don’t see any major problems, I deploy it to all of the other systems I own on the same day. One of the major ways to keep your systems safe is to ensure you’re running the latest version of the software—the one with all of the latest bug fixes.

For most developers, debugging is an ongoing process. Although it seems is if it would be possible to squash every bug in the application after one carefully conducted review, the reality is that most applications are complex enough that even a team of developers can’t find every bug in multiple reviews, much less one. It also doesn’t help that many companies rush products to market long before they’re ready because they need to generate money from that product in order to remain solvent. So, from a certain perspective, we’re all beta testers and those bug updates are a requirement if we want to keep our systems running properly in the hostile environment of the Internet.

Unfortunately, not everyone is as conscientious as I am and some people are downright suspicious of updates. So, I can understand
Microsoft’s perspective about employing forced updates of some of their
products when those products are attached to an unfriendly Internet.
Just in case you haven’t heard it, Microsoft is going to start automatically updating Internet Explorer users. However, Microsoft is hardly the first one to the party with enforced updates. A lot of other vendors use this tactic as well. Many products today include a forced update feature. Most allow the user to opt out of the forced update, but the default setup relies on forced updates to keep less skilled user’s machines updated.

There are many advantages to using forced updates. The most important is that using forced updates keeps everyone on the Internet safer. The fewer machines that nefarious individuals can exploit, the better. Forced updates also reduce vendor support calls and could therefore help keep software costs lower. Using forced updates can also improve the user experience and make users more productive. For all these reasons, and more, I see forced updates as a big win for the less experienced user, especially the home user who is currently susceptible to every sort of virus and intrusion out there.

However, there is a down side to using forced updates. All users find them intrusive. Even if the update is silent, it uses resources during the update process. As a result, the user’s system suddenly slows down, which could actually cause some number of support calls when the update process is a resource hog. Forced updates are also a cause for concern in corporate environments where running untested software can cause a host of interoperability problems with custom software. Expert users also find forced updates a problem because the update can (and usually will) cause problems with the user’s custom configuration.

I’d also like to see forced updates provide a wait feature. Some users will apply unauthorized fixes to repair a bug until an update comes out. These unauthorized fixes tend to cause problems with the update. Giving the user a chance to remove the unauthorized fix before the update occurs will keep the update from actually trashing the user’s system. Personally, I never use these unauthorized fixes simply because they do have such a huge potential for causing more problems than they fix. However, some users don’t have the option to wait for the update to come out and must rely on an unauthorized fix.

So, what is your opinion about forced updates?  Are they a good idea? Generally, I see them as a win for novice and home users, but less helpful to corporate and expert users. Let me know your opinion at John@JohnMuellerBooks.com.

 

Creating Useful Comments

A major problem with most applications today is that they lack useful comments. It’s impossible for anyone to truly understand how an application works unless the developer provides comments at the time the code is written. In fact, this issue extends to the developer. A month after someone writes an application, it’s possible to forget the important details about it. In fact, for some of us, the interval between writing and forgetting is even shorter. Writing good comments is a main topic in C# Design and Development as part of Chapter 13, but I make the topic part of every application development book I write. Despite my best efforts and those of many other authors, many online examples lack any comments whatsoever, making them nearly useless to anyone who lacks time to run the application through a debugger to discover how it works.

Good application code comments help developers of all stripes in a number of ways. As a minimum, the comments you provide as part of your application code provides these benefits.

 

  • Debugging: It’s easier to debug an application that has good comments because the comments help the person performing the debugging understand how the developer envisioned the application working.
  • Updating: Anyone who has tried to update an application that lacks comments knows the pain of trying to figure out the best way to do it. Often, an update introduces new bugs because the person performing the update doesn’t understand how to interact with the original code.
  • Documentation: Modern IDEs often provide a means of automatically generating application documentation based on the developer comments. Good comments significantly reduce the work required to create documentation and sometimes eliminate it altogether.
  • Technique Description: You get a brainstorm in the middle of the night and try it in your code the next day. It works! Comments help you preserve the brainstorm that you won’t get back later no matter how hard you try. The technique you use today could also solve problems in future applications, but the technique may become unavailable unless you document it.
  • Problem Resolution: Code often takes a circuitous route to accomplish a task because the direct path will result in failure. Unless you document your reasons for using a less direct route, an update could cause problems by removing the safeguards you’ve provided.
  • Performance Tuning: Good comments help anyone tuning the application understand where performance changes could end up causing the application to run more slowly or not at all. A lot of performance improvements end up hurting the user, the data, or the application because the person tuning the application didn’t have proper comments for making the adjustments.


I had previously mentioned the need for good comments. Some developers write comments that are nearly useless. Although it’s hard to encapsulate the substance of a good comment, developers who answer these sorts of questions are well on their way to writing good comments.

 

  • Who is affected by the code?
  • What is the code supposed to do?
  • When is the code supposed to perform this task?
  • Where does the code obtain resources needed to perform the task?
  • Why did the developer use a particular technique to write the code?
  • How does the code accomplish the task without causing problems with other applications or system resources?


There are many other questions you could ask yourself, but these six questions are a good start. You won’t answer every question for every last piece of code in the application because sometimes a question isn’t pertinent. As you work through your code and gain experience, start writing down questions you find yourself asking. Good answers to aggravating questions produce superior comments. Whenever you pull your hair out trying to figure out someone’s code, especially your own, remember that a comment could have saved you time, frustration, and effort. What is your take on comments? Let me know at John@JohnMuellerBooks.com.

 

Debugging a CodeBlocks Application with Command Line Arguments

Most application environments provide a means of setting command line arguments and CodeBlocks is no exception. The example shown in Listing 4-12 on page 107 of C++ All-In-One Desk Reference For Dummies requires that you set command line arguments in order to see anything but the barest output from the debugger. This post discusses the requirements for setting command line arguments for debugging purposes.

Let’s begin with the example without any configuration. Every application has one command line argument—the path and application executable name. So, when you run the example shown in Listing 4-12 you’ll see the path and executable name as a minimum, as shown here.

CommandLineArguments01

If you run this example, you may see a different path, but the command line executable should be the same. The point is that you see at least one argument as output. However, most people will want to test their applications using more than one argument. In order to do this, you must pass command line arguments to the application. The following steps tell how to perform this task.

 

  1. Choose Project | Set Program’s Arguments. You’ll see the Select Target dialog box shown here.
    CommandLineArguments02
  2. Select Debug as the target, as shown in the figure.
  3. Type the arguments you want to use, such as Hello Goodbye, in the Program Arguments field and click OK. The IDE is now set to provide command line arguments to the application when you’re using the specified target, which is Debug in this case.

To see how this works, set a breakpoint at the line that reads (you’ll find a discussion of how to set breakpoints on page 375 of the book):

for (int index=0; index < argc; index++)

You also want to create a watch that shows the command line arguments in action. In this case, you want to see the particular argument that the application is processing. Use these steps to set the watch.

 

  1. Choose Debug | Edit Watches. You’ll see the Edit Debugger Watches dialog box shown here.
    CommandLineArguments03
  2. Click Add. You’ll see the Add Watch dialog box shown here.
    CommandLineArguments04
  3. Type argv[index] and click OK. You’ll see the new watch added to the Edit Debugger Watches dialog box.
  4. Click OK. The new watch is ready for use.

You’re ready to test out the new setup. Choose Debug | Start or press F8. The debugger will start. If you don’t see the Watches window, choose Debug | Debugging Windows | Watches. Click Next Line and you’ll see the first command line argument as shown here.

CommandLineArguments05

Notice that the value of index is in red because it has changed to 0. In this case, argc contains 3 arguments (including the first one that you’re seeing now) and that argument is in argv, which is pointed to at the memory address shown. The argument at that first index value is the path and command line executable name, just as expected.

Click Next Line twice. Now you’ll see the second argument, as shown here.

CommandLineArguments06

If you followed the instructions earlier, you should be seeing Hello as the second argument as well. Click Run and you’ll see the output shown here.

CommandLineArguments07

Testing for command line arguments in a CodeBlocks application consists of telling the IDE what to pass in the Select Target dialog box and then setting the correct watches so that you can see how the command line arguments work. Let me know if you have any questions about this process at John@JohnMuellerBooks.com.

 

New Book Announcement: Start Here! Learn Microsoft Visual C# 2010 Programming

Have you ever attended a college course and found that you just didn’t understand what the teacher was trying to say? Worse yet, you found yourself dosing during a lecture? Many people require a hands-on approach to learning—they just don’t learn well using the college approach. Start Here! Learn Microsoft Visual C# 2010 Programming is designed to answer needs of anyone who has quickly become disenchanted with the way that colleges teach programming. You’ll start coding in Chapter 1 and won’t stop coding until you’ve completed the book!

Start Here! Learn Microsoft Visual C# 2010 Programming takes an entirely new approach to learning how to write code. You begin by writing some codeimagine that! Then, you use a special tracing technique to see how the code workswhat it does and how it does it. Instead of mind numbing sessions involving the discussion of keywords from a purely theoretical view, you jump right into using those keywords to do something useful.

You also don’t waste your time with silly Hello World applications. You get right into techniques that will prove useful later when you’re creating applications on your own. Chapter 1 starts things off right by showing you how to display an image from a Web site on the local desktop. Instead of spending hours trying to figure out looping mechanisms, you use the modern techniques provided by Language INtegrated Query (LINQ) to achieve your goals. You’ll do things like access a Web service and request weather information from it. There are even Silverlight and Windows Presentation Foundation (WPF) examples. Here is a quick overview of the book’s content:

  • Chapter 1: Getting to Know C#
  • Chapter 2: Developing a Web Project
  • Chapter 3: Using Simple Data Manipulation Techniques
  • Chapter 4: Using Collections to Store Data
  • Chapter 5: Working with XML
  • Chapter 6: Accessing a Web Service
  • Chapter 7: Using the Windows Presentation Foundation
  • Chapter 8: Working with Libraries
  • Chapter 9: Creating Utility Applications
  • Chapter 10: Using LINQ in Web Applications
  • Chapter 11: Working with Silverlight Applications
  • Chapter 12: Debugging Applications


You’ll also gain knowledge that many people spend years learning. For example, the tracing technique you use throughout the book naturally leads into the debugging information in Chapter 12. Debugging won’t be a mystery to youit’ll actually be a natural part of your work process so you’ll find it much easier to locate the bugs in your applications.

There is even a chapter on writing command line utilities. More and more administrators are returning to the command line because the GUI is simply too slow in today’s competitive world. Unfortunately, many developers don’t know how to write a really good command line utility, but you’ll gain this skill at the outset.

This book (my 88th) is truly designed for the complete novice. You do need to know how to work with Windows and perform basic tasks such as installing applications. However, you don’t need to know anything about coding to start using this book. In fact, people who already have a good starting knowledge of programming may find that some of the material is a little too simple. If you have any questions at all about my new book, please let me know at John@JohnMuellerBooks.com.

Understanding the Connection Between Application Output and ErrorLevel

Many readers have a disconnect between application output and the ErrorLevel variable found in batch files. I’ve received more than a few e-mails where readers don’t quite understand the whole concept behind the ErrorLevel variable. They think it actually signifies some sort of mystical operating system derived error, when it isn’t anything of the sort.

A large part of the problem is that those readers who commonly work with batch files aren’t developers and many developers don’t work with batch files. In fact, even though many administrators are moving back to command line utilities because working with the GUI is time consuming and inefficient, many developers have decided to eschew the console application in favor of GUIs with fancier user interfaces.

Another problem is that ErrorLevel is inappropriately named. It should really be named ApplicationOutput. I’m sure that at one time the intention truly was to convey some sort of error information, but even Microsoft uses ErrorLevel for other purposes.

Let’s take a practical look at the whole concept of ErrorLevel beginning with a simple C# application to generate the codes. When working with C#, you’ll find that the output is now called an ExitCode as shown here.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace GenerateOutput
{
    class ExitCode
    {
        static void Main(string[] args)
        {
            // Create a variable to hold the exit
            // value.
            Int32 Value;
 
            // Make sure there is a variable provided as input.
            if (args.Count() > 0)
            {
 
                // Determine whether the input is actually a number.
                if (Int32.TryParse(args[0], out Value))
 
                    // If it is, then exit using that number.
                    Environment.Exit(Value);
                else
 
                    // Otherwise, exit with an error value of -2.
                    Environment.Exit(-2);
            }
            else
 
                // Exit with an error value of -1
                Environment.Exit(-1);
        }
    }
}

The only purpose of this application is to generate exit codes given certain circumstances. The first check determines whether the user has supplied any sort of input at all. If not, if the user simply types GenerateOutput without any arguments at all, then the application exits with a value of -1 to indicate an error. Likewise, if the user types something other than a number, such as GenerateOutput Hello, the application exits with a value of -2 to indicate a different sort of error. Only when the user supplies a number does the application exit with a numeric value.

The batch file used to test this application is equally simple. All it does is call GenerateOutput with the value (if any) that the user provides to the batch file, TestOutput.bat. Here’s the batch file code.

@Echo Off
 
REM Run the application.
GenerateOutput %1
 
REM Most application output are status indicators.
If ERRORLEVEL 2 GOTO HighOutput
 
REM You can perform specific actions for a specific status.
If ERRORLEVEL 1 GOTO ValueOne
 
REM Applications can also provide a success indicator.
If ERRORLEVEL 0 GOTO Success
 
REM Errors are normally negative numbers, but can be anything.
If ERRORLEVEL -1 GOTO Error1
If ERRORLEVEL -2 GOTO Error2
 
:HighOutput
ECHO The value you provided is higher than 1.
GOTO End
 
:ValueOne
ECHO You provided an input of precisely 1.
GOTO End
 
:Success
ECHO An output value of 0 indicates success!
GOTO End
 
REM Here is the beginning of the various messages.
:Error1
ECHO You must supply a number as an argument!
GOTO End
 
:Error2
ECHO You must supply a number and not text or special characters!
GOTO End
 
REM Here is the ending point.
:End

As you can see, the tests check for errors, success messages, and non-error application output. Any combination of console application and batch file can do the same thing provided the developer and administrator get together to work out the details or the developer at least documents the exit codes.

The process is the same each time. Test for an ErrorLevel value, then go to the label specified, execute the directions, and then go to the end of the batch file. The ErrorLevel values must appear in order from greatest to least in order to work correctly. Here is some test output from this test application and batch file pair.

ErrorLevel01

The point of this exercise is to ensure that developer and administrator alike realize the importance of the exit code (ErrorLevel). The application should use it to provide some sort of status information that the administrator can then use to track how well the application works in an automated setting. Let me know if you have any questions at John@JohnMuellerBooks.com.