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.