Thursday, October 29, 2009

Hack 28. Package Your Toolbox Settings











 < Day Day Up > 





Hack 28. Package Your Toolbox Settings





If you want to be able to deploy the same

toolbox settings on a bunch of different machines, you can write a

program to add custom controls or code snippets to the toolbox
.





One of the big challenges of

team development is creating consistent code across all developers.

One way to encourage consistent code is to provide each developer

with the same set of controls and code snippets. This way, each

individual developer has all the same tools as the other developers

(whether they use them is another matter).





In Section 4.5Customize the

Toolbox" [Hack

#27]
, we covered a method

for moving toolbox settings, but using this as a method of

distribution is not a good idea. The method outlined involved copying

a user-specific file to another system. This is a great solution for

moving your own personal settings, but trying to use this method as a

means of distribution would result in the overwriting of any custom

controls or code snippets each developer may have created.





A better method for adding custom controls and code snippets to each

developer's system is to create a small program that

adds these controls and snippets through the



Visual Studio Common Environment Object

Model. In this hack, you are going to learn how to create just such a

program.





For simplicity's sake, we are going to create a

Windows Forms application that, upon the press of a button, will add

a number of custom controls to the Visual Studio toolbox. In

practice, you may find it easier to create an installation package or

command-line tool, but the code will be the same. The first thing you

need to do is create a Windows Forms Project in Visual Studio using

your favorite .NET language. (I am using C# for these examples, but a

version of VB.NET is available for download from

the book's web site, which is described in the

Preface.) Next, you will need to create a reference to the

envdte.dll



assembly�this assembly contains the objects we will work with

to modify the Visual Studio environment. This is called the Common

Environment Object Model and can be used to modify just about every

aspect of the Visual Studio IDE [Hack #86] .





After you create the obligatory using or

Imports statement for the

EnvDTE namespace, you can start to work with

the Visual Studio environment.









When working with EnvDTE, you may run across frequent

"Call was rejected by the Callee"

errors. These are due to timeouts and occur more frequently on slow

machines, but they can pop up on fast machines as well. To prevent

these errors refer to [Hack #87] .








The next thing you need to do is to get an instance of the current

DTE (see [Hack #87] ). This is not as easy as it

sounds. Because the DTE objects for Visual Studio .NET 2002 and

Visual Studio .NET 2003 are exactly the same, we have to get the

class using the progid, as shown here:





Type latestDTE = Type.GetTypeFromProgID("VisualStudio.DTE.7.1");

EnvDTE.DTE env = Activator.CreateInstance(latestDTE) as EnvDTE.DTE;











You can get a reference to the currently executing instance of Visual

Studio using this line of code:





EnvDTE.DTE dte = 

(DTE)Marshal.GetActiveObject("VisualStudio.DTE.

7.1");







This will return a reference to the currently executing instance of

Visual Studio as opposed to a reference to a new instance of Visual

Studio.








The DTE object can be used to modify

many different parts of Visual Studio. To get the toolbar window, you

need to access the Windows collection of the DTE object using the

vsWindowKindToolBox constant, then you need to cast the

object to the ToolBox type as shown in this code:





Window win = env.Windows.Item(Constants.vsWindowKindToolbox);



ToolBox toolBox = (ToolBox) win.Object;







The next thing you need to do is check to see if the



tab you want to add is already there.

If it is not already there, you will want to add it:





ToolBoxTab tab = null;



// Loop through the tab collection and see if the tab already exists

foreach (ToolBoxTab tb in toolBox.ToolBoxTabs)

{

if (tb.Name = = "Our Controls")

{

tab = tb;

}

}



// The tab does not exist so add it

if(tab = = null)

{

tab = toolBox.ToolBoxTabs.Add("Our Controls");

}







Now there is a little dirty work. The following things need to be

done because working with the DTE object can often be an adventure in

bugs. Rather than simply adding the control to the Toolbox tab, first

you need to show the property window, activate the tab, and then

select the first item. All of this is necessary to get the process to

run correctly, though admittedly does not make a lot of sense:





// Show the PropertiesWindow for bugs sake

env.ExecuteCommand("View.PropertiesWindow","");



// Activate the tab

//(Because the Add method will only add to the active tab)

tab.Activate( );



// Select the first item

//(Because this is the only way to make it work)

tab.ToolBoxItems.Item(1).Select( );







Then you need to add the toolbox item to the tab by calling the Add

method and passing in the path to the .dll that

contains your controls and the type of item you are adding. When

adding a code snippet, the first string is

the name of the snippet and the second is the value of the snippet.

When adding controls, the first string is not

used; the name of the control is used instead. Visual Studio uses the

assembly specified in the second string and looks inside it to

determine the name of the control.





In this example, I am using

System.Web.dll

,

which will add all of the controls in that assembly to the toolbox.

In practice, you will want to point to the assembly that contains

your custom controls.





// Add new toolbox items for our custom controls

ToolBoxItem tbi1 = tab.ToolBoxItems.Add("not used", _

@"C:\windows\Microsoft.NET\Framework\v1.1.4322\System.Web.dll",

vsToolBoxItemFormat.vsToolBoxItemFormatDotNETComponent);







The last thing you need to do is close the

environment:





// Close the environment

env.Quit( );







After running this code, whether in an installation procedure or a

simple Windows Form, you can open Visual Studio and you will see all

of the controls in System.Web.dll added to your

new Toolbox tab. (You may need to right-click on the toolbox and

select Show All Tabs to see the new tab.)









At the time of this writing, attempting to add code snippets to the

toolbox in this manner works for only Visual Studio .NET

2002�all attempts to get this working in Visual Studio .NET

2003 and VIsual Studio .NET 2005 have ended with only the tab being

added and no code snippets being saved. Hopefully this will be fixed

before the final release of Visual Studio 2005.








If you are shipping your own custom controls, or even using a set of

custom controls internally, this code presents a great way to install

these controls in the toolbox for all of your users. The complete

application can be downloaded in both C# and VB.NET from this

book's web site (see

http://www.oreilly.com/catalog/visualstudiohks).

















     < Day Day Up > 



    Chapter 21.&nbsp; I/O and PL/SQL









    Chapter 21. I/O and PL/SQL


    Many, perhaps most, of the PL/SQL programs we write need to interact only with the underlying Oracle RDBMS using SQL. However, there will inevitably be times when you will want to send information from PL/SQL to the external environment, or read information from some external source (screen, file, etc.) into PL/SQL. This chapter explores some of the most common mechanisms for I/O in PL/SQL, including the following built-in packages:



    DBMS_OUTPUT


    For displaying information on the screen


    UTL_FILE


    For reading and writing operating system files


    UTL_MAIL and UTL_SMTP


    For sending email from within PL/SQL


    UTL_HTTP


    For retrieving data from a web page


    It is outside the scope of this book to provide full reference information about the built-in packages introduced in this chapter. Instead, in this chapter, we'll demonstrate how to use them to handle the most frequently encountered requirements. Check out Oracle's documentation for more complete coverage. You will also find Oracle Built-in Packages (O'Reilly) a helpful source for information on some of the older packages; we have put several chapters from that book on this book's web site.









      Examples








       

       














      Examples



      Many times you can determine the meaning of a term from examples. If you use your common sense, experience, and background knowledge to figure out what the examples have in common, you should have a good idea about the meaning of the main word or phrase.



      Signals That an Example Is Coming



      The signal words and phrases for example, for instance, examples include, such as, and including are usually accompanied by one or more examples. Sometimes the word like is also used as a signal of example.





      • Be sure to label all containers with inflammable contents, such as gasoline, alcohol, kerosene, or natural gas.





      Gasoline, alcohol, kerosene, and natural gas all catch fire easily. They are examples of things that are inflammable. In this example, inflammable contents means contents that can catch fire easily.





      WHAT DO YOU KNOW?



      Try the next two examples yourself. Circle the letter next to the answer that best defines the italicized word. Use common sense and the context clues of example to help you decide.



      1:

      That group of architects is known for designing many edifices, including houses, office high rises, hotels, and apartment complexes.





      (a) cabins



      (b) hospitals



      (c) buildings



      (d) roads







      A1:

      All of the examples are buildings. Edifices are buildings.



      2:

      The committee made many amendments to the agreement. For example, they increased the minimum pay, decreased the minimum hours, restricted the telephone service, and expanded the sales territories.





      (a) changes



      (b) provisions



      (c) additionschanges



      (d) amenitiesprovisions







      A2:

      All of the examples are changes; amendments are changes.











      More Signals



      Other example clues are signaled by the terms especially, particularly, in particular, and specifically. Also, watch for phrases like among the most (least, best, etc.) or signals of number.





      WHAT DO YOU KNOW?



      Circle the letter next to the answer that best defines the italicized word.



      1:

      The company appreciated all the employees' endeavors to meet the deadline, especially the hours they worked nights and weekends.





      (a) efforts



      (b) positions



      (c) thresholds



      (d) entreatiespositions









      A1:

      This sentence gives working nights and weekends as an example of an endeavor; an endeavor is an effort.





      2:

      Among the most important benefits to the new employee were good health insurance coverage and sick leave.





      (a) advantages or "extras" provided by an employer



      (b) day care for workers' children



      (c) compositions



      (d) nurses in the building









      A2:

      The benefits listed are examples of advantages or "extras" provided by an employer.













      A List as an Example



      Sometimes, instead of a signal word, a list of examples is itself the signal.





      WHAT DO YOU KNOW?



      Circle the letter next to the answer that best defines the italicized word. Use common sense and the context clues of example to help you decide.



      1:

      The most common forms of remuneration for work in that company are weekly salary and cash bonuses.





      (a) vacation



      (b) recognition



      (c) pay



      (d) schedule









      A1:

      The examples of remuneration are salary and bonuses. Remuneration is pay.





      2:

      The firm bought new machinery, new delivery vans, and a piece of property for a larger building. These acquisitions were costly and used all the firm's savings.





      (a) positions



      (b) trucks



      (c) bills to pay



      (d) newly obtained items









      A2:

      Machinery, vans, and property that are all new are listed as examples of acquisitions. Acquisitions are newly obtained items.













      More on Examples



      Like the other contextual clues you have learned, examples can help you decide between two or more meanings of a word that may already be familiar.





      WHAT DO YOU KNOW?



      The following examples use the word deductions with different meanings. Example clues will help you understand which way the word is being used. Circle the letter next to the answer that best defines the way deductions is used in each sentence. Use common sense and the context clues of example to help you decide.



      1:

      The deductions from her paycheck included a health insurance premium, a charitable contribution, and income tax withholding.





      (a) additions of money



      (b) decisions



      (c) hours worked



      (d) amounts of money taken out









      A1:

      The examples of deductions are all amounts of money taken out of the check.





      2:

      Watsmith looked over the evidence. "From these clues, I have concluded that the thief was a man. I have figured out that the thief worked alone and that he wore gloves."





      "Wonderful deductions, Watsmith!" exclaimed his friend.







      (a) amounts taken out



      (b) suit of clothes



      (c) conclusions



      (d) mystery









      A2:

      The examples of deductions are the conclusions that Watsmith reached based on the clues.




























         

         


        Task Two: Filling In Missing Labels













        Task Two: Filling In Missing Labels


        When the order-processing system produces a summary report, it enters a label in a column only the first time that label appears. Leaving out duplicate labels is one way to make a report easier for a human being to read, but for the computer to sort and summarize the data properly, you need to fill in the missing labels.





        You might assume that you need to write a complex macro to examine each cell and determine whether it’s empty, and if so, what value it needs. In fact, you can use Excel’s built-in capabilities to do most of the work for you. Because this part of the project introduces some powerful worksheet features, start by going through the steps before recording the macro.




        Select Only the Blank Cells


        Look at the places where you want to fill in missing labels. What value do you want in each empty cell? You want each empty cell to contain the value from the first nonempty cell above it. In fact, if you were to select each empty cell in turn and put into it a formula pointing at the cell immediately above it, you would have the result you want. The range of empty cells is an irregular shape, however, which makes the prospect of filling all the cells with a formula daunting. Fortunately, Excel has a built-in tool for selecting an irregular range of blank cells.




        1. In a copy of the Nov2007 worksheet in the Chapter02 workbook, select cell A1.




        2. On the Home tab of the Ribbon, in the Editing group, click the Find & Select arrow, and then click Go To Special.




        3. In the Go To Special dialog box, click Current region, and then click OK.




          Excel selects the current region-the rectangle of cells including the active cell that is surrounded by blank cells or worksheet borders.






          Tip 

          You also can press Ctrl+* to select the current region. Press and hold the Ctrl key while pressing either * on the numeric keypad or Shift+8 on the regular keyboard.





        4. Once again, click the Find & Select arrow on the Ribbon, and then click Go To Special.




        5. In the Go To Special dialog box, click the Blanks option, and then click OK.


          Excel subselects only the blank cells from the selection. These are the cells that need new values.





          Excel’s built-in Go To Special feature can save you-and your macro-a lot of work.







        Fill the Selection with Values


        You now want to fill each of the selected cells with a formula that points to the cell above. Normally when you enter a formula, Excel puts the formula into only the active cell. You can, however, if you ask politely, have Excel put a formula into all the selected cells at once.




        1. With the blank cells selected and D3 as the active cell, type an equal sign ( = ), and then press the Up Arrow key to point to cell D2.


          The cell reference D2-when used in a formula in cell D3-actually means “one cell above me in the same column.”




        2. Press Ctrl+Enter to fill the formula into all the currently selected cells.


          When more than one cell is selected, if you type a formula and press Ctrl+Enter, the formula is copied into all the cells of the selection. (If you press the Enter key without pressing and holding the Ctrl key, the formula goes into only the one active cell.) Each cell with the new formula points to the cell above it.







        3. Press Ctrl+* to select the current region.




        4. Right-click any selected cell, and click Copy. Right-click any selected cell, click Paste Special, click the Values option, and then click OK.




        5. Press the Esc key to get out of copy mode, and then select cell A1.




        Now the block of cells contains all the missing-label cells as values, so the contents won’t change if you happen to re-sort the summary data.





        Record Filling In the Missing Values


        In this section, you’ll select a different copy of the imported worksheet and follow the same steps, but with the macro recorder turned on.




        1. Select a copy of the Nov2007 worksheet (one that doesn’t have the labels filled in), or run the ImportFile macro again.




        2. Click the Record Macro button, type FillLabels as the name of the macro, and then click OK.




        3. Select cell A1 (even if it’s already selected), and press Ctrl+* to select the current region.




        4. Click the Find & Select arrow on the Ribbon, click Go To Special, click the Blanks option, and then click OK.




        5. Type an equal sign ( = ), press the Up Arrow key, and press Ctrl+Enter.




        6. Press Ctrl+*, right-click, and click Copy. Then right-click, click Paste Special, click the Values option, and then click OK.




        7. Press the Esc key to get out of copy mode, and then select cell A1.




        8. Click the Stop Recording button, and then save the Chapter02 workbook.


          You’ve finished creating the FillLabels macro.







        Watch the FillLabels Macro Run


        Now read the macro while you step through it.




        1. Select (or create) another copy of the imported worksheet.




        2. On the View tab of the Ribbon, click the View Macros button, select the FillLabels macro, and then click Step Into.


          The Visual Basic editor window appears, with the header statement of the macro highlighted.




        3. Press F8 to move to the first statement in the body of the macro:


          Range("A1").Select

          This statement selects cell A1. It doesn’t matter how you got to cell A1-whether you clicked the cell, pressed Ctrl+Home, or pressed various arrow keys-because the macro recorder always records just the result of the selection process.




        4. Press F8 to select cell A1 and highlight the next statement:


          Selection.CurrentRegion.Select

          This statement selects the current region of the original selection.




        5. Press F8 to select the current region and move to the next statement:


          Selection.SpecialCells(xlCellTypeBlanks).Select

          This statement selects the blank special cells of the original selection. (The word SpecialCells is a method that handles many of the options in the Go To Special dialog box.)




        6. Press F8 to select just the blank cells and move to the next statement:


          Selection.FormulaR1C1 = "=R[-1]C"

          This statement assigns =R[-1]C as the formula for the entire selection. When you entered the formula, the formula you saw was =C2, not =R[-1]C. The formula =C2 really means “get the value from the cell just above me,” but only if the active cell happens to be cell C3. The formula =R[-1]C also means “get the value from the cell just above me,” but without regard for which cell is active.


          You could change this statement to Selection.Formula = "=C2" and the macro would work exactly the same-provided that the order file you use when you run the macro is identical to the order file you used when you recorded the macro and that the active cell happens to be cell C3 when the macro runs. However, if the command that selects blanks produces a different active cell, the revised macro will fail. The macro recorder uses R1C1 notation so that your macro will always work correctly.






          See Also 

          For more information about R1C1 notation, see the section titled “R1C1 Reference Style” in Chapter 4, “Explore Range Objects.”





        7. Press F5 to execute the remaining statements in the macro:



          Selection.CurrentRegion.Select
          Selection.Copy
          Selection.PasteSpecial Paste:=xlPasteValues, _
          Operation:=xlNone, SkipBlanks:=False, Transpose:=False Application.CutCopyMode = False
          Range("A1").Select


          These statements select the current region, convert the formulas to values, cancel copy mode, and select cell A1.






          See Also 

          The final statements in this macro are identical to the PasteSpecial macro from the section titled “Convert a Formula to a Value by Using a Macro” in Chapter 1, “Make a Macro Do Simple Tasks.”





        You’ve completed the macro for the second task of your month-end project. Now you can start a new macro to carry out the next task-adding dates.















        Chapter 10.&nbsp; Dates and Timestamps









        Chapter 10. Dates and Timestamps


        Most applications require the storage and manipulation of dates and times
        . Dates are quite complicated: not only are they highly formatted data, but there are myriad rules for determining valid values and valid calculations (leap days and years, national and company holidays, date ranges, etc.). Fortunately, the Oracle RDBMS and PL/SQL provide a set of true datetime
        datatypes that store both date and time information using a standard, internal format.


        For any datetime value, Oracle stores some or all of the following information:


        Support for true datetime datatypes
        is only half the battle. You also need a language that can manipulate those values in a natural and intelligent manneras actual dates and times. To that end, Oracle provides you with support for SQL standard interval arithmetic, datetime literals, and a comprehensive suite of functions with which to manipulate date and time information.









          Lab 11.1 Exercise Answers



          [ Team LiB ]





          Lab 11.1 Exercise Answers


          This section gives you some suggested answers to the questions in Lab 11.1, with discussion related to how those answers resulted. The most important thing to realize is whether your answer works. You should figure out the implications of the answers here and what the effects are from any different answers you may come up with.


          11.1.1 Answers


          a)

          What output was printed on the screen?

          A1:

          Answer:



          Course 10 has 1 student(s)
          Course 20 has 6 student(s)
          Course 25 has 40 student(s)
          Course 100 has 7 student(s)
          Course 120 has 19 student(s)
          Course 122 has 20 student(s)
          Course 124 has 3 student(s)
          Course 125 has 6 student(s)
          Course 130 has 6 student(s)
          Course 132 has 0 student(s)
          Course 134 has 2 student(s)
          Course 135 has 2 student(s)
          Course 140 has 7 student(s)
          Course 142 has 3 student(s)
          Course 144 has 0 student(s)
          Course 145 has 0 student(s)
          Course 146 has 1 student(s)
          Course 147 has 0 student(s)
          Course 204 has 0 student(s)
          Course 210 has 0 student(s)
          Course 220 has 0 student(s)
          Course 230 has 2 student(s)
          Course 240 has 1 student(s)
          Course 310 has 0 student(s)
          Course 330 has 0 student(s)
          Course 350 has 9 student(s)
          Course 420 has 0 student(s)
          Course 430 has 0 student(s)
          Done…

          PL/SQL procedure successfully completed.



          Notice that each course number is displayed a single time only.


          b)

          Modify this script so that if a course has more than 20 students enrolled in it, an error message is displayed indicating that this course has too many students enrolled.

          A2:

          Answer: Your script should look similar to the script shown. All changes are shown in bold letters.



          -- ch11_1b.sql, version 2.0
          SET SERVEROUTPUT ON
          DECLARE
          CURSOR course_cur IS
          SELECT course_no, section_id
          FROM section
          ORDER BY course_no, section_id;
          v_cur_course SECTION.COURSE_NO%TYPE := 0;
          v_students NUMBER(3) := 0;
          v_total NUMBER(3) := 0;
          BEGIN
          FOR course_rec IN course_cur LOOP
          IF v_cur_course = 0 THEN
          v_cur_course := course_rec.course_no;
          END IF;

          SELECT COUNT(*)
          INTO v_students
          FROM enrollment
          WHERE section_id = course_rec.section_id;

          IF v_cur_course = course_rec.course_no THEN
          v_total := v_total + v_students;
          IF v_total > 20 THEN
          RAISE_APPLICATION_ERROR (-20002, 'Course '||
          v_cur_course||' has too many students');
          END IF;
          ELSE
          DBMS_OUTPUT.PUT_LINE ('Course '||v_cur_course||
          'has '||v_total||' student(s)');
          v_cur_course := course_rec.course_no;
          v_total := 0;
          END IF;
          END LOOP;
          DBMS_OUTPUT.PUT_LINE ('Done...');
          END;



          Consider the result if you were to add another IF statement to this script, one in which the IF statement checks whether the value of the variable exceeds 20. If the value of the variable does exceed 20, the RAISE_APPLICATION_ERROR statement executes, and the error message is displayed on the screen.


          c)

          Execute the new version of the script. What output was printed on the screen?

          A3:

          Answer: Your output should look similar to the following:



          Course 10 has 1 student(s)
          Course 20 has 6 student(s)
          DECLARE
          *
          ERROR at line 1:
          ORA-20002: Course 25 has too many students
          ORA-06512: at line 21



          Course 25 has 40 students enrolled. As a result, the IF statement





          IF v_total > 20 THEN
          RAISE_APPLICATION_ERROR (-20002, 'Course '||
          v_cur_course||' has too many students');
          END IF;

          evaluates to TRUE, and the unnamed user-defined error is displayed on the screen.


          d)

          Generally, when an exception is raised and handled inside a loop, the loop does not terminate prematurely. Why do you think the cursor FOR loop terminates as soon as RAISE_APPLICATION_ERROR executes?

          A4:

          Answer: When the RAISE_APPLICATION_ERROR procedure is used to handle a user-defined exception, control is passed to the host environment as soon as the error is handled. Therefore, the cursor FOR loop terminates prematurely. In this case, it terminates as soon as the course that has more than 20 students registered for it is encountered.



          When a user-defined exception is used with the RAISE statement, the exception propagates from the inner block to the outer block. For example:





          -- outer block
          BEGIN
          FOR record IN cursor LOOP
          -- inner block
          BEGIN
          RAISE my_exception;
          EXCEPTION
          WHEN my_exception THEN
          DBMS_OUTPUT.PUT_LINE ('An error has occurred');
          END;
          END LOOP;
          END;

          In this example, the exception my_exception is raised and handled in the inner block. Control of the execution is passed to the outer block once the exception my_exception is raised. As a result, the cursor FOR loop will not terminate prematurely.


          When the RAISE_APPLICATION_ERROR procedure is used, control is always passed to the host environment. The exception does not propagate from the inner block to the outer block. Therefore, any loop defined in the outer block will terminate prematurely if an error has been raised in the inner block, with the help of the RAISE_APPLICATION_ERROR procedure.





            [ Team LiB ]



            What's a Browser?













            What’s a Browser?

            You read the World Wide Web by using a browser. If you use X Windows, you can use a graphical browser such as Mozilla, Konqueror, or Opera. With a graphical browser, you get to see all the cool stuff as well as the text. (Does this type of browser make the browsing experience any more educational or enriching? In some cases, maybe, but mostly it just makes browsing more fun.) If you’re familiar with a browser on Windows, you’ll find browsing on UNIX quite familiar, and if you use Mozilla, Netscape, or Opera on Windows, you’ll find their UNIX versions nearly identical. This chapter describes both Mozilla and Konqueror.








            When you start your browser, you can begin with the Web page it suggests and find your way to the information you want by following the hypertext links. (Don’t worry — we tell you how.) Alternatively, you can jump directly to a Web page if you know its name. These names are called URLs (for Uniform Resource Locators) — see the nearby sidebar, “URL!” to read about them.











            Represented Conflict











             < Day Day Up > 











            Represented Conflict


            We are beginning to understand how procedural representations work to simulate phenomena through dynamic depictions. But there is a question that precedes a discussion of how games create such representations. It is the question of what phenomena a dynamic system can depict. Can a game designer pick anything to simulate, or are there inherent limitations? Are there certain things that games are predisposed to simulate, certain subjects that lend themselves naturally to games? Game designer Warren Robinett seems to think that just about anything might be simulated:



            Many provocatively complex phenomena await interpretation …trains and other vehicles which move cargo through spaces, kayaks in swirling river currents, planets orbiting their stars, competing creatures in evolving ecologies, visible melodies smeared upon harmonic wallpaper, looping programs in throbbing execution, and human thought darting across a tangled network of knowledge....


            The real world offers a vast set of phenomena to simulate—animals behaving, plants growing, structures buckling, traffic jamming, snowflakes forming. Any process is a candidate. Every verb in the dictionary suggests an idea.[3]



            Since Robinett originally penned this challenge, games have been designed to simulate some of the phenomena he describes: Sim Life attempted to simulate evolving ecologies of creatures; the shareware game Bridge Builder simulates structures buckling under the weight of a train. However, many of the phenomena on his list are still waiting to find themselves in games. As Robinett points out, "every verb in the dictionary suggests an idea" for a simulation. Why then, do games seem to focus on a narrow range of processes to simulate? Why do we see the same genres of games over and over: fighting, racing, war, sports, and so on? Of course, economic and business concerns greatly influence game content. But is there something else, something deeper about the underlying structure of games that determines the kinds of processes they can and cannot depict?


            Our definition of a game describes them as systems in which players engage in an artificial conflict, defined by rules, that results in a quantifiable outcome. The part of the definition relevant to our present discussion of simulation and representation is conflict. Games are contests of power: they are systems of conflict. Conflict is not only a product of the game's rules, but of its system of representation as well. Every game, on some level, dynamically represents conflict. The elements of a game—the players, the pieces, the rules—all have a role in generating the representation. The insight that games represent conflict through a dynamic process might help to explain the prevalence of certain content in games: perhaps some forms of conflict are simply easier to model than others. At the same time, understanding the kinds of conflict that games most often depict also helps us to strategize new kinds of subjects for games to simulate.


            What are the forms of conflict we find dynamically represented in games? If the game has a strong narrative component, the conflict is easy to spot. The Lord of the Rings Board Game clearly simulates the struggle of the players, as the Fellowship hobbits, to reach Mount Doom at Mordor and destroy the One Ring. But in many games, it is more difficult to pin down the simulated conflict. What is the conflict in Baseball, Checkers, or Jeopardy? The key to comprehending the form of conflict simulated by a game is to figure out what is being contested. In what kind of arena is the conflict being held? Over what is the conflict being waged? How is the progress of the conflict measured? What aspects of the conflict are dynamically represented?


            In order to answer these questions we distill the range of game conflict into three general categories: territorial conflict, economic conflict, and conflict over knowledge. These three categories are neither discrete nor mutually exclusive: many games incorporate two or all three of them at once within their design. Rather than a strict typology, they are instead conceptual frames for looking at the kinds of conflict that games can dynamically represent. Next, we explore each of these three categories in more detail.




            Conflict Over Territory


            Conflict over territory is perhaps the most intuitive of the three categories. Board games such as Chess, in which pieces are moved on a limited playing field, are a common game of this sort. In games of territorial conflict, players strategically position their units to capture enemies and gain ground. Conflicts of this kind are abstract representations of war: the pieces depict military units, and the play area dynamically represents the territory over which the battle is waged.


            Go is another good example of a game focused on capturing territory. As players lay down their stones, their primary goal is to surround areas of the playfield to secure the captured space. At the end of the game, each player receives a point for each grid intersection secured (plus a point for each captured enemy piece).The game originated as a military simulation—in feudal Japan, Go was considered a martial art. As a territorial conflict, Go is a strikingly elegant representation.


            There are many other games that simulate the process of territorial conflict. Tic-Tac-Toe is a simple territorial conflict where players attempt to strategically occupy territory in a pattern that will lead to victory. Ball-based sports such as Football and Soccer entail moving a team or a special marker across a stretch of terrain into the opponent's end zone or goal: the enemy invaded. Tabletop games such as Warhammer offer incredibly complex representations of warfare dynamically enacted, with dozens of different kinds of units, large detailed maps, and thick rulebooks controlling the particulars of interaction. The U.S. military uses even more complex war games as training exercises, in which hundreds or even thousands of troops play vast games of laser tag in real and simulated environments.



            Economic Conflict


            Economic conflict is another common form of conflict in games. Within simulations of economic conflict, it is not terrain that is contested, but a unit of value.The word "economic" does not necessarily refer to money, but to any collection of pieces, parts, points, cards, or other items that form a system through which the conflict takes place. In a pinball game, you are trying to rack up a high score. In Magic: The Gathering, you are trying to reduce your oppo-nent's life to zero. In these game economies, the rules give each unit a value, and progress through the game is measured according to the values assigned by this economy.


            An economy in a game is generally a limited economy. This means that the units that make up the economy are finite, and usually the players know the composition of the economy. In Poker, it is crucial that all players understand the limited economy of a deck of playing cards. Knowledge about which cards appear in the deck allows them to understand which hands are more difficult to build. Four-of-a-kind is harder to build than a pair; a straight flush harder still. The other economy of Poker—the betting money—might or might not be a limited economy. Each player might start with the same amount of chips, in which case all players know the parameters of the chip economy. If players can use money in their pockets or other valuables for betting, the players don't know the full extent of the economy—although the economy is ultimately limited by the capital each player possesses outside the magic circle. On the other hand, if players are not betting "real money" but are instead playing for fun using an endless supply of chips, the normally limited betting economy becomes unlimited.


            Because economic conflict is generally reducible to numbers and points, and games are intrinsically mathematical, we can frame almost any game in this way. For example, a race game, in which players roll a die and move a marker down a track, might at first seem to be a territorial conflict.


            However, the same game could also be played by throwing dice and adding up the points that players receive each turn, making the game more of an economic conflict. Since the two games would have similar constituative rules, the operational rules would help determine what kind of conflict the game represents. Yet some games combine categories: Is Quake a territorial conflict or an economic one? It is clearly a hybrid. The play takes place within the representation of a space, in which relative position at each moment is quite important. However, much of the game consists of managing economies of resources such as health, armor, ammo, weapons, and kills.


            Even the strongly territorial games of Chess and Go can be seen as procedural representations of economic conflict. In Chess, the pieces represent an economy, and the use-value of each piece is derived from the total set of relationships on the board. Of course, one unit—the King— has a special value, which determines the winner of the game. Similarly, at the end of a game of Go, territory is translated into points, and as with the race game example, Go could be interpreted as an economy—of contested points. Remember that the three kinds of conflict are not hard and fast categories; they are merely frames we use to understand the kinds of conflict that games traditionally simulate.



            Conflict Over Knowledge


            Conflict over knowledge offers a different model for understanding the way games simulate conflict. In Trivial Pursuit, for example, it is true that pieces move about on the spatial territory of a board. It is also true that the players acquire a set of colored plastic pieces within an economy of parts in order to win the game. But these ways of framing Trivial Pursuit seem to leave out the key component of the game conflict: the process of asking and answering trivia questions.


            In Trivial Pursuit, as with many other games in which information itself forms the arena of conflict, the contested "terrain" of the game is knowledge. Game shows such as Hollywood Squares, computer trivia games such as You Don't Know Jack, and even games about translation of information from one form to another such as Charades, can all be understood as games in which the conflict is one of knowledge. Conflicts over knowledge are inherently cultural, because the game conflict itself engages with a cultural space that lies outside the game. In a game of conflict over knowledge, the outcome of a game action is dependent on whether or not the player knows the right answer to a question of some kind. This is quite different than representation of territorial or economic conflict: the process being simulated is the conflict of acquiring and sharing cultural knowledge. Games designed with factual knowledge as part of the system of conflict cross over the border of the magic circle, creating a game contingent on information brought into the game from external sources.



            Games represent conflict as acquisition of and contestation over territory, economy, and knowledge. These three rather abstract categories don't tell us exactly what games are capable of simulating, but describe the general sorts of processes that games most often simulate. Identifying these three categories also helps explain why we see the same kinds of conflict being modeled over and over in games. For example, why is it that video games often seem to focus on simulating military conflict: fighting, shooting, and conquering? Or that so many games overflow with collectable item economies: magic coins, money, or other precious objects? Like it or not, the tendency toward military and economic representation in games has a long history, directly linked to the processes of territorial and economic conflict intrinsic to most games.


            There is a relatively clear line of descent, for example, from Go and Chess to Kriegspiel, wargaming miniatures, and role-play-ing games, and from these non-digital games to today's RPGs,


            FPSs, and RTSs (role-playing games, first-person shooters, and real-time strategy games). A tremendous amount of design thinking regarding wargaming, military simulation, and other forms of territorial conflict has accumulated over the centuries. Simulating the difference between mounted units and infantry units; between melee and ranged weapons; between attacks that spread damage and attacks that penetrate; between size and maneuverability, strength and speed, and so on, have become well-worn design problems of game representation over the years. In this sense, today's highly detailed military games are the inheritors of millennia of design thinking.


            Happily, this long history in no way limits what it is possible to simulate in games, even when it comes to forms of conflict. An important question for today's game designer is: What other kinds of conflict can games simulate? For example, what about Robinett's wish list? How could a game be designed to simulate social conflict, psychological conflict, or interpersonal conflict? These are truly tough design challenges. As we will see in the following pages, part of the challenge lies in the fact that simulations require radical simplification and stylization. Sid Meier's Civilization series are wonderful strategy games that tackle the Herculean task of simulating cultural development. But because cultural knowledge in the game is necessarily stylized into abstract units ("Do you trade Monotheism for Iron Working?") the game never comes close to representing the subtlety of its subject matter.


            The history of games contains many robust examples for simulating military and economic conflict. A design lexicon for simulating social or cultural conflict may take generations to develop. Of course, these unsolved challenges are part of what makes game design as a field so remarkable. Despite the fact that games are a truly ancient phenomenon, there are still countless avenues for representational innovation—as long as you are ready to question long-standing assumptions about what games are and what they can be.







            [3]Warren Robinett, Inventing the Adventure Game, unpublished manuscript.



















             < Day Day Up > 



            USING TESTSUITE









































            Prev don't be afraid of buying books Next






























            USING TESTSUITE



            As mentioned earlier, TestSuites are
            used to collect a selection of Tests so that they can be
            run as a unit. Note that a TestSuite may recursively
            contain other TestSuites.



            When you start out with JUnit you will likely be
            using TestSuites without even knowing it. The framework
            uses reflection to find and collect all of the test methods in a
            given TestCase whose signatures match:




            public void testWhatever()






            When you use this facility, you have no control
            over or any guarantee of the order in which the test methods will
            be run. Tests should be written in such a way that they are order
            independent, so this should not be a problem. If, however, you have
            a situation where you want or need tests to run in a specific order
            you can supply a public static Test suite() method which
            builds the TestSuite as required. Here is an example:




            public static Test suite() {
            suite.addTest(new TestMovieList("testEmptyList"));
            suite.addTest(new TestMovieList("testAdding"));
            return suite;
            }






            I can't stress enough that test methods within a
            TestCase should be completely independent. You should
            seldom have to resort to writing your own suite() method.
            In xUnit for languages that lack a reflection mechanism, you will
            have to build suites by hand, as it were.



            If you find that you want or need to have test
            methods run in a specific order you should see if there is a way to
            remove that requirement. It may be that you are relying on an
            external resource whose state is modified by each subsequent test.
            Try to find a way to tease apart those dependencies, setting up the
            appropriate fixture individually for each test. You might be able
            to do this by mocking such an external resource. For more on mock
            objects, see Chapter 7.



            Another more valid use of TestSuite, in
            my opinion, is to create smaller TestSuites which include
            a specific subset of the tests. There are two main reasons to do
            this:











            1. You can create custom suites of tests that
              relate directly to the task you are working on. By doing this you
              can save time running tests by focusing the tests that are run on
              the area of the code you are working on. But always keep that suite
              and the code it tests in sync. As you find yourself needing to
              involve code that your suite doesn't test, be sure to add the tests
              for that code to your suite so that you can proceed, protected and
              confident.











            2. You will most likely want to have a
              TestSuite that tests a complete package or module. My
              practice is to have a suite in each package called TestAll
              that includes all tests in that package and all subpackages. By
              doing this, I can easily test any subtree of a project. Here's an
              example:




              package com.saorsa.nowplaying.pd.tests;

              import junit.framework.Test;
              import junit.framework.TestSuite;

              public class TestAll extends TestSuite {

              public TestAll() {
              super();
              }

              public static Test suite() {
              TestSuite suite = new TestSuite();
              suite.addTestSuite(TestMovie.class);
              suite.addTestSuite(TestMovieList.class);
              return suite;
              }
              }


























































            Amazon






            Recipe 6.8 Checking Projects Out of a CVS Repository











             < Day Day Up > 







            Recipe 6.8 Checking Projects Out of a CVS Repository







            6.8.1 Problem





            Someone wants to check out a project

            of yours from the CVS repository.









            6.8.2 Solution





            In Eclipse, right-click a file in the CVS Repositories view, and

            click Check Out As. Then use the Check Out dialog to check out the

            item.









            6.8.3 Discussion





            If other people want to check out a module that

            you've stored in a CVS repository, they have to

            create a connection to the repository as we did earlier in this

            chapter. To do this, they should right-click the CVS Repositories

            view; select New Repository Location; and enter the name of

            the CVS server, the location of the repository, the username, the

            password, and the type of connection.





            They can then open the CVS Repositories view to explore the files in

            the repository. To check out the GreetingApp

            module, they can right-click the module in the Repositories view and

            click Check Out As from the context menu. Eclipse will open the New

            Project dialog and automatically create a new project corresponding

            to the CVS module.





            If you're sharing an Eclipse project, and each CVS

            module has its own Eclipse .project file, you

            can select Check Out As Project from the Repositories

            view's context menu, which checks out an Eclipse

            project and adds it to the Package Explorer. Note that if your code

            isn't in a project of a kind that Eclipse can

            recognize, it will ask you what type of project to create.









            6.8.4 See Also





            Chapter 4 of Eclipse (O'Reilly).



















               < Day Day Up > 



              Hack&nbsp;3.&nbsp;Deny All Access in One Second or Less










              Hack 3. Deny All Access in One Second or Less




              Here's a safe way to keep out all users while doing temporary maintenance or troubleshooting.


              All administrators eventually need to have a machine running in full multiuser mode, with all services running, but at the same time completely deny login access to the machine. This is usually for the purpose of troubleshooting a problem, testing a new software installation, or performing maintenance or software upgrades. There are a couple of really quick ways to do this.


              The first method is by far the quickest. Just run the following command (as root):



              # touch /etc/nologin



              This will deny access to anyone trying to log in to the machine. You'll want to be sure to keep an active login session on the machine after you create this file or make sure that root is allowed to log in on the local console or via SSH, since a root login will bypass this mechanism. You'll know it's working because the logs for some services will tell you that access was denied because of the presence of the nologin file. Others will just say "failed password."


              This method can be improved through the use of a nologin.txt file, where you can put some text that users will see when they try to log in. If you have a scheduled downtime, for instance, you can put the details into this file so that users will get a friendly reminder that the machine is unavailable during the downtime window.


              The second method works only if the services you're running are linked against libwrap, in which case you can very quickly cut off all access to the machine. To check that a service is linked against libwrap, use the ldd command on the binary for the service. For example, to make sure my SSH service is linked against libwrap, I've done the following:



              # ldd /usr/sbin/sshd
              linux-gate.so.1 => (0x004ab000)
              libwrap.so.0 => /usr/lib/libwrap.so.0 (0x0072f000)
              …(lots deleted)



              The above output shows all the libraries sshd is linked against, and the path to the library file being used. Clearly, libwrap is linked here. Once you've confirmed that this is the case for the other services you're running, you're ready for the next step.


              Create a file called /etc/hosts.deny.ALL, which should consist of only one line:



              ##### /etc/hosts.deny.ALL
              ALL:ALL@ALL



              Now, whenever you need to shut down access to the machine, you simply move your /etc/hosts.allow and hosts.deny files out of the way and move your hosts.deny.ALL file into place. Here's a command line that'll handle it nicely:



              # cd /etc; mv hosts.allow hosts.allow.bak; mv hosts.deny hosts.deny.bak
              # mv hosts.deny.ALL hosts.deny



              Now you're left with only a single hosts.deny file, which denies access to everything. Note that it would not help you to just move both files out of the way, because tcpwrappers treats the absence of a file just like an empty file. If there are no files, tcpwrappers acts as though you have two files that have not addressed access controls for a given service, and by default it will grant access to the service!



              1.4.1. See Also


              • "Allow or Deny Access by IP Address" [Hack #64]













              Section 5.6. DOM Stuff for Tables







              5.6. DOM Stuff for Tables

              XHTML tables have methods and properties that the other XHTML elements do not have. These special methods and properties are specifically designed for manipulating parts of the table in a more precise manner. To use these methods and properties, however, you must think of a table in the full XHTML specification. An XHTML table contains a <caption>, a <thead>, a <tfoot>, and any number of tbodies:


              caption

              References the <caption> of a table


              thead

              References the <thead> of a table, if there is one


              tfoot

              References the <tfoot> of a table, if there is one


              tbodies

              Reference a collection with one entry for every <tbody> that exists for the table (there is usually just one <tbody>, table.tbodies[0])

              A rows collection corresponds to all the rows in each <thead>, <tfoot>, and <tbody> node. Each row has a cells collection, which contains every <td> or <th> element in that given row. Every cell contains all of the normal DOM methods and properties associated with an XHTML element. Consider the following table, which is displayed in Figure 5-7:


              <table id="oreillyBooks" summary="Some O'Reilly books on Ajax">
              <caption>O'Reilly Ajax Books</caption>
              <thead>
              <tr>
              <th>Title</th>
              <th>Author(s)</th>
              <th>Published Date</th>
              </tr>
              </thead>
              <tfoot>
              <tr>
              <td colspan="3">Ajax books from oreilly.com</td>
              </tr>
              </tfoot>
              <tbody>
              <tr>
              <td>Ajax Design Patterns</td>
              <td>Michael Mahemoff</td>
              <td>June 2006</td>
              </tr>
              <tr>
              <td>Ajax Hacks</td>
              <td>Bruce W. Perry</td>
              <td>March 2006</td>
              </tr>
              <tr>
              <td>Head Rush Ajax</td>
              <td>Brett McLaughlin</td>
              <td>March 2006</td>
              </tr>
              <tr>
              <td>Programming Atlas: Rough Cuts</td>
              <td>Christian Wenz</td>
              <td>March 2006</td>
              </tr>
              </tbody>
              </table>




              Figure 5-7. An XHTML table to be manipulated by the DOM


              Using the DOM properties to reference elements in the table, here are some examples of how to reference table nodes:


              var table = $('oreillyBooks');

              x = table.tBodies[0].rows[0].cells[1].firstChild.value; // Michael Mahemoff
              x = table.tHead.rows[0].cells[2].firstChild.value; // Published Date
              x = table.tBodies[0].rows[2].cells[0].firstChild.value; // Ajax Design Patterns
              x = table.tFoot.rows[0].cells[0].firstChild.value; // Ajax books from oreilly.com




              Tables, along with their child elements, have methods that you can use for creating, inserting, and deleting, as shown in Table 5-16.

              Table 5-16. DOM table methods
              MethodDescriptionElement
              createCaption( )Creates a new table caption object, or returns an existing one.HTMLTableElement
              createTFoot( )Creates a table footer row, or returns an existing one.HTMLTableElement
              createTHead( )Creates a table header row, or returns an existing one.HTMLTableElement
              deleteCaption( )Deletes the table caption, if one exists.HTMLTableElement
              deleteCell(index)Deletes a cell from the current row at the passed index. If the index is -1, the last cell in the row is deleted.HTMLTableRowElement
              deleteRow(index)Deletes a table row found at the passed index. If the index is -1, the last row in the table is deleted.HTMLTableElement, HTMLTableSectionElement
              deleteTFoot( )Deletes the footer from the table, if one exists.HTMLTableElement
              deleteTHead( )Deletes the header from the table, if one exists.HTMLTableElement
              insertCell(index)Inserts an empty cell into this row at the passed index. If the index is -1 or is equal to the number of cells, the new cell is appended.HTMLTableRowElement
              insertRow(index)Inserts a table row found at the passed index. If the index is -1 or is equal to the number of rows, the new row is appended to the last row.HTMLTableElement, HTMLTableSectionElement


              The methods are easy to use, as the descriptions in the table of methods show. The following is an example of the createCaption( ) method:


              var x = $('myTable').createCaption( );

              x.appendChild(document.createTextNode('This is my table caption'));


              Likewise, it's easy to use methods such as insertRow( ) and insertCell( ), as the following illustrates:


              var x = $('myTable').insertRow(2);
              var a = x.insertCell(0);
              var b = x.insertCell(1);
              var c = x.insertCell(2);

              a.appendChild(document.createTextNode('New data in column one'));
              b.appendChild(document.createTextNode('New data in column two'));
              c.appendChild(document.createTextNode('New data in column three'));


              Using the table of O'Reilly books that produced Figure 5-7, this code would produce Figure 5-8. That's all there really is to manipulating tables using DOM methods and properties. Of course, most of the normal DOM properties and methods could accomplish the same things, but the DOM table methods and properties make things simpler.

              Figure 5-8. The DOM manipulated table









              Recipe 21.3. Getting Input One Character at a Time










              Recipe 21.3. Getting Input One Character at a Time





              Problem


              You're writing an interactive application or a terminal-based game. You want to read a
              user's input from standard input a single character at a time.




              Solution


              Most Ruby installations on Unix come with the the Curses extension installed. If Curses has the features you want to write the rest of your program, the simplest solution is to use it.


              This simple Curses program echoes every key you type to the top-left corner of the screen. It stops when you hit the escape key (\e).[1]

              [1] This code will also work in irb, but it'll look strange because Curses will be fighting with irb for control of the screen.



              #!/usr/bin/ruby -w
              # curses_single_char_input.rb
              require 'curses'
              include Curses

              # Setup: create a curses screen that doesn't echo its input.
              init_screen
              noecho

              # Cleanup: restore the terminal settings when the program is exited or
              # killed.
              trap(0) { echo }

              while (c = getch) != ?\e do
              setpos(0,0)
              addstr("You typed #{c.chr.inspect}")
              end



              If you don't want Curses to take over your program, you can use the HighLine library instead (available as the highline gem). It does its best to define a get_
              character
              method that will work on your system. The get_
              character
              method itself is private, but you can access it from within a call to ask:



              require 'rubygems'
              require 'highline/import'

              while (c = ask('') { |q| q.character = true; q.echo = false }) != "\e" do
              print "You typed #{c.inspect}"
              end



              Be careful; ask echoes a newline after every character it receives.[2] That's why I use a print statement in that example instead of puts.

              [2] This actually happens at the end of HighLine.get_response, which is called by ask.


              Of course, you can avoid this annoyance by hacking the HighLine class to make get_character public:



              class HighLine
              public :get_character
              end
              input = HighLine.new
              while (c = input.get_
              character) != ?\e do
              puts "You typed #{c.chr.inspect}"
              end





              Discussion


              This is a huge and complicated problem that (fortunately) is completely hidden by Curses and HighLine. Here's the problem: Unix systems know how to talk to a lot of historic and modern terminals. Each one has a different feature set and a different command language. HighLine (through the Termios library it uses on Unix) and Curses hide this complexity.


              Windows doesn't have to deal with a lot of terminal types, but Windows programs don't usually read from standard input either (much less one character at a time). To do single-
              character input on Windows, HighLine makes raw Windows API calls. Here's some code based on HighLine's, which you can use on Windows if you don't want to require HighLine:



              require 'Win32API'

              def getch
              @getch ||= Win32API.new('crtdll', '_getch', [], 'L')
              @getch.call
              end

              while (c = getch) != ?\e
              puts "You typed #{c.chr.inspect}"
              end



              HighLine also has two definitions f get_character for Unix; you can copy one of these if you don't want to require HighLine. The most reliable implementation is fairly complicated, and requires the termios gem. But if you need to require the termios gem, you might as well require the highline gem as well, and use HighLine's implementation as is. So if you want to do single-character input on Unix without requiring any gems, you'll need to rely on the Unix command stty:



              def getch
              state = `stty -g`
              begin
              `stty raw -echo cbreak`
              $stdin.getc
              ensure
              `stty #{state}`
              end
              end

              while (c = getch) != ?\e
              puts "You typed #{c.chr.inspect}"
              end



              All of the HighLine code is in the main highline.rb file; search for "get_character".




              See Also


              • Recipe 21.5, "Setting Up and Tearing Down a Curses Program"

              • Recipe 21.8, "Changing Text Color"