text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
Hi, I have downloaded and testing these two mapping libraries. I wrote a program which has 100000 iterations and maps the beans of the same class: public class IntBean { @JMap private int int1; @JMap private int int2; @JMap private int int3; @JMap private int int4; @JMap private int int5; @JMap private int int6; @JMap private int int7; @JMap private int int8; @JMap private int int9; @JMap private int int10; } Mappers are created BEFORE iterations start: private JMapper jmapper = new JMapper(IntBean.class, IntBean.class); private MapperFactory orikaFactory = new DefaultMapperFactory.Builder().build(); private MapperFacade orikaFacade = null; What is in each iteration: this.orikaFacade.map(a1, a2); or a2 = (A) this.jmapper2.getDestination(a1); I know, that Orika and Jmapper are great libraries from Google and they use reflection in a different way than for example Dozer, which is much slower, they se reflection to generete code somehow.. I have 3 questions: 1) How they work - when the code is generated, during maven build, in runtime - everytime when I create mapper in code? Are they change class code byte dynamically? 2) Why there is this speed difference that I noticed? 3) Which library would you choose and why? Both have the same capabilities? Why both come from Google? Why Google didnt develop Orika and created Jmapper instead? PS: Hand mapping: 1ms Orika mapping: 32ms Hand mapping: 6ms GREAT SPEED !!! Dozer: 1140ms You need to post your questions to Google or a forum for those third party libraries. This forum is for Java programming questions only and you have not ask any such questions. Please mark your thread ANSWERED and repost it in an appropriate forum.
https://community.oracle.com/thread/3522723
CC-MAIN-2017-43
refinedweb
273
64.3
Use a loop to execute a group of statements, called the loop body, more than once. In C, you can introduce a loop by one of three iteration statements : while, do ... while, and for. In each of these statements, the number of iterations through the loop body is controlled by a condition, the controlling expression . This is an expression of a scalar type; that is, an arithmetic expression or a pointer. The loop condition is true if the value of the controlling expression is not equal to 0; otherwise, it is considered false. A while statement executes a statement repeatedly as long as the controlling expression is true: while ( expression ) statement The while statement is a top-driven loop: first the loop condition (i.e., the controlling expression) is evaluated. If it yields true, the loop body is executed, and then the controlling expression is evaluated again. If the condition is false, program execution continues with the statement following the loop body. Syntactically, the loop body consists of one statement. If several statements are required, they are grouped in a block. Example 6-1 shows a simple while loop that reads in floating-point numbers from the console and accumulates a running total of them. /* Read in numbers from the keyboard and * print out their average. * -------------------------------------- */ #include <stdio.h> int main( ) { double x = 0.0, sum = 0.0; int count = 0; printf( "\t--- Calculate Averages ---\n" ); printf( "\nEnter some numbers:\n" "(Type a letter to end your input)\n" ); while ( scanf( "%lf", &x ) == 1 ) { sum += x; ++count; } if ( count == 0 ) printf( "No input data!\n" ); else printf( "The average of your numbers is %.2f\n", sum/count ); return 0; } In Example 6-1, the controlling expression: scanf( "%lf", &x ) == 1 is true as long as the user enters a decimal number. As soon as the function scanf( ) is unable to convert the string input into a floating-point numberwhen the user types the letter q, for examplescanf( ) returns the value 0 (or -1 for EOF, if the end of the input stream was reached or an error occurred). The condition is then false, and execution continues at the if statement that follows the loop body. Like the while statement, the for statement is a top-driven loop, but with more loop logic contained within the statement itself: for ( [expression1]; [expression2]; [expression3] ) statement The three actions that need to be executed in a typical loop are specified together at the top of the loop body: expression1 : Initialization Evaluated only once, before the first evaluation of the controlling expression, to perform any necessary initialization. expression2 : Controlling expression Tested before each iteration. Loop execution ends when this expression evaluates to false. expression3 : Adjustment An adjustment, such as the incrementation of a counter, performed after each loop iteration, and before expression2 is tested again. Example 6-2 shows a for loop that initializes each element of an array. #define ARR_LENGTH 1000 /* ... */ long arr[ARR_LENGTH]; int i; for ( i = 0; i < ARR_LENGTH; ++i ) arr[i] = 2*i; Any of the three expressions in the head of the for loop can be omitted. This means that its shortest possible form is: for ( ; ; ) A missing controlling expression is considered to be always true, and so defines an infinite loop . The following form, with no initializer and no adjustment expression, is equivalent to while ( expression ): for ( ; expression; ) In fact, every for statement can also be rewritten as a while statement, and vice versa. For example, the complete for loop in Example 6-2 is equivalent to the following while loop: i = 0; // Initialize the counter while ( i < ARR_LENGTH ) // The loop condition { arr[i] = 2*i; ++i; // Increment the counter } for is generally preferable to while when the loop contains a counter or index variable that needs to be initialized and then adjusted after each iteration. In ANSI C99, a declaration can also be used in place of expression1. In this case, the scope of the variable declared is limited to the for loop. For example: for ( int i = 0; i < ARR_LENGTH; ++i ) arr[i] = 2*i; The variable i declared in this for loop, unlike that in Example 6-2, no longer exists after the end of the for loop. The comma operator is often used in the head of a for loop in order to assign initial values to more than one variable in expression1, or to adjust several variables in expression3. For example, the function strReverse( ) shown here uses two index variables to reverse the order of the characters in a string: void strReverse( char* str) { char ch; for ( int i = 0, j = strlen(str)-1; i < j; ++i, --j ) ch = str[i], str[i] = str[j], str[j] = ch; } The comma operator can be used to evaluate additional expressions where only one expression is permitted. See "Other Operators" in Chapter 5 for a detailed description of the comma operator. The do ... while statement is a bottom-driven loop: do statement while ( expression ); The loop body statement is executed once before the controlling expression is evaluated for the first time. Unlike the while and for statements, do ... while ensures that at least one iteration of the loop body is performed. If the controlling expression yields true, then another iteration follows. If false, the loop is finished. In Example 6-3, the functions for reading and processing a command are called at least once. When the user exits the menu system, the function getCommand( ) returns the value of the constant END. // Read and carry out an incoming menu command. // -------------------------------------------- int getCommand( void ); void performCommand( int cmd ); #define END 0 /* ... */ do { int command = getCommand( ); // Poll the menu system. performCommand( command ); // Execute the command received. } while ( command != END ); Example 6-4 shows a version of the standard library function strcpy( ), with just a simple statement rather than a block in the loop body. Because the loop condition is tested after the loop body, the copy operation includes the string terminator '\0'. // Copy string s2 to string s1. // ---------------------------- char *strcpy( char* restrict s1, const char* restrict s2 ) { int i = 0; do s1[i] = s2[i]; // The loop body: copy each character while ( s2[i++] != '\0' ); // End the loop if we just copied a '\0'. return s1; } A loop body can be any simple or block statement, and may include other loop statements. Example 6-5 is an implementation of the bubble-sort algorithm using nested loops. The inner loop in this algorithm inspects the entire array on each iteration, swapping neighboring elements that are out of order. The outer loop is reiterated until the inner loop finds no elements to swap. After each iteration of the inner loop, at least one element has been moved to its correct position. Hence the remaining length of the array to be sorted, len, can be reduced by one. // Sort an array of float in ascending order // using the bubble-sort algorithm. // ----------------------------------------- void bubbleSort( float arr[ ], int len ) // The array arr and { // its length len. int isSorted = 0; do { float temp; // Holder for values being swapped. isSorted = 1; --len; for ( int i = 0; i < len; ++i ) if ( arr[i] > arr[i+1] ) { isSorted = 0; // Not finished yet. temp = arr[i]; // Swap adjacent values. arr[i] = arr[i+1]; arr[i+1] = temp; } } while ( !isSorted ); } Note that the automatic variables temp, declared in the do ... while loop, and i, declared in the head of the for loop, are created and destroyed again on each iteration of the outer loop.
http://books.gigatux.nl/mirror/cinanutshell/0596006977/cinanut-CHP-6-SECT-3.html
CC-MAIN-2018-43
refinedweb
1,244
61.87
The hypersonic SQL database, whose official name was later changed to HSQLDB, is a pure-Java embedded relational database server that you can use in stand-alone mode (using direct file access) or in client/server mode, accepting many concurrent users. Although not as powerful as DB2 and not as popular as MySQL, HSQLDB can satisfy the needs of a wide range of Java applications, because of its extensibility and low memory/processor requirements. HSQLDB is a convenient Java development database because it features a rich subset of Structured Query Language (SQL), and because Java programmers won't need to install a processor, memory, and disk-hungry database server into their development workstation. It's an ideal tool for integration into the Eclipse IDE, providing useful tools for both novice and experienced developers. This article and the ones to follow in this series will show you how to build a set of Eclipse plug-ins that bring HSQLDB into the Eclipse Workbench. You'll see a real-world example of how to develop such a plug-in, considering API and user interface (UI) issues, and also how to evaluate alternative ways to bring desired functionality to a user. This article assumes you are using the Eclipse SDK distribution, not the Platform Runtime-Binary plus JDT. The latter would be well suited if the goal were just to develop a regular Java application. In this series, we'll create and expand the plug-in set using three steps, according to the rationale described in "Levels of Integration" (see the Resources later in this article for a link): - Launching existing tools from Eclipse, providing easy access to desired pre-existing tools from Workbench menus - Exploring how other Eclipse features can be used to add value to the pre-existing set of tools, improving Java developer productivity - Rewriting the tools using SWT for seamless integration into the Eclipse Workbench You can download HSQLDB, including sources and documentation, from SourceForge (hsqldb.sourceforge.net; see the link in Resources). This should not be confused with the original SourceForge project, hsql.sourceforge.net, which has been frozen. The binary distribution is a standard ZIP file, and all you need to do is to unzip it somewhere on your hard drive. All HSQLDB components -- the database engine, server processes, JDBC driver, documentation, and a handful of utilities -- are provided in a single JAR package, installed in lib/hsqldb.jar, and about 260 KB. The database engine needs just 170 KB of RAM to run, making it adequate for PDAs, such as Zaurus from Sharp, and the entire download, including sources and documentation, is small enough to fit on a standard 1.44 MB floppy disk. You can start the database server and utilities from the command prompt by invoking convenience classes such as org.hsqldb.Server and org.hsqldb.util.DatabaseManager, each of which accepts a small set of command-line options like "-url" (for remote connections), "-database" (for direct file access), and "-user". Also accepted is the "-?" option to provide help on valid command-line syntax. The key to HSQLDB's simplicity is the serialization of SQL statement execution. That is, although many concurrent users can be connected to the database (when running in server mode), all SQL statements are placed in a queue and executed one at a time. Thus, there is no need to implement complicated locking and synchronization algorithms. In spite of that, HSQLB implements ACID (Atomicity, Consistency, Isolation, and Durability) semantics. In other words, it is a transactional database, but only at the read uncommitted level, without transaction isolation. HSQLDB was really created for embedded applications, not for the corporate data center. If you want triggers, aggregated functions, outer joins, views, and other SQL features, they are all there (something you won't get from most lightweight relational databases). You can implement stored procedures by adding your Java classes do the HSQLDB classpath. Then you issue a CREATE FUNCTION statement and you're done. In fact, many standard SQL functions like SQRT and ABS are implemented as direct mappings to standard Java classes such as java.lang.Math. HSQLDB modes of operation The HSQLDB engine can be run in many modes to suit different application scenarios: In-memory mode All database tables and indexes are kept in memory and never saved to disk. Before you ask why anyone would want a database that is lost at application termination, think about having a local cache for database data that you can query, sort, group, and update using standard SQL statements. Stand-alone mode The application creates a database connection using JDBC, and the HSQLDB engine runs inside the application, accessing the database files directly. There can be no concurrent users (the application has exclusive access to the database files), but there are no additional threads nor TCP connection overhead. Stand-alone is the preferred mode for many embedded applications. Server mode This is the standard client/server database configuration similar to other relational databases, allowing concurrent connections using TCP sockets. Most developers will want this mode as it allows any JDBC client to connect and query/update tables while the main application is still running. Web server mode HSQLDB can act as a Web server, accepting SQL queries though HTTP, or can run as a servlet inside any standard Web container, passing though firewalls or installed on a Web hosting service without involving the provider support team (and expensive database hosting options). As HTTP is stateless, there are no transactions in this mode. HSQLDB database file structure HSQLDB keeps all table and index data in memory, saving all SQL statements issued into a file named database.script, which also acts as the transaction log. When the engine is initialized, this file is read and all SQL statements are processed, thus recreating the entire database. During shutdown, the HSQLDB engine will generate a new database.script file with the minimum set of statements for fast database startup. Besides the default memory tables, HSQLDB also supports "cached" and "text" tables. Data for all cached tables is kept in a file named database.data, while text table data is kept in any delimited text file (like CSV files) named by the set table source non-standard SQL statement. While cached tables provide support for data sets bigger than available RAM, text tables are a convenient way to import and export data. Besides the database.script and database.data files, any HSQLDB database may include a database.properties file, on which the administrator can set many parameters that affect ANSI SQL compatibility. All database files (except for text table data files) must be kept in the same directory. There's no explicit way to create HSQLDB databases. If you ask the engine to open a non-existent database file (using either server mode -database option or a stand-alone mode JDBC URL), the file and containing directory will be created. So, if you are sure there was data in that empty database, check for typing errors. Let's now start developing the plug-in! Creating the HSQLDB Eclipse set of plug-ins Putting an existing application inside a powerful tool like Eclipse is not a trivial task. Fortunately, both HSQLDB and Eclipse ease the task, since HSQLDB is embeddable in other applications, and since Eclipse provides a clean, easy-to-understand plug-in infrastructure and a robust development environment for creating new plug-ins, the PDE. Even if you have no previous exposure to Eclipse plug-in development, the PDE makes the task very easy. See the articles covering Eclipse basics in the Resources section later in this article. These instructions assume you are using the Eclipse SDK distribution, not the Platform Runtime-Binary plus JDT. The latter would be well suited if your goal were just to develop a regular Java application. You can use your preferred operating system, as we'll only use Java code and no native code at all. We'll start with the minimum effort to create a useful set of plug-ins and write the smallest amount of code. Later, in the next parts of this series, we'll see how Eclipse features can be leveraged to provide added value to HSQLDB. In this article, we'll focus on the following functionality for our code: - Start the HSQLDB engine in server mode, so both the user application and an SQL console (like HSQLDB's own DatabaseManager utility) can run SQL statements at the same time. - Stop the HSQLDB database cleanly. - Invoke the DatabaseManager utility so developers can enter SQL statements interactively from the Workbench. - Run SQL script files using the HSQLDB ScriptTool utility. Over the years, I have kept many *.sql files in my project folders, to create database tables and insert test data, and have long wished for an easy way to run them. - Configure HSQLDB connection properties, such as TCP port and administrator password. How will these functions be made available to the Workbench? The easiest way to accomplish the first three is to provide an actionSet, added to a new top-level menu and also accessible from its own toolbar. The action to run SQL script files must be tied only to files with a "*.sql" extension, so this will be an objectContribution, added by the Workbench to the pop-up menus on any views that display these files. Finally, the connection parameters fit nicely into a plug-in preferences page, accessible from the Workbench Window menu. Figure 1 shows the new menu and toolbar, while Figure 2 shows the new entry in the pop-up menu for the Navigator view, and Figure 3 shows the property page, so you can get a glimpse of what the first release of our plug-in set will look like. Figure 1. HSQLDB menu and associated toolbar Figure 2. Pop-up menu item added to *.sql files Figure 3. HSQLDB connection properties Turning HSQLDB into an Eclipse plug-in The first step in building our set of plug-ins is to package HSQLDB itself as an Eclipse plug-in. This plug-in will contain only hsqldb.jar and the needed plugin.xml file required by the Workbench. If you've browsed the standard Eclipse plug-ins directory, you've already found that JUnit, Xerces, Tomcat, and other popular Java packages are isolated in their own plug-ins, unchanged, and that all Eclipse specifics are encapsulated in other plug-ins. This compartmentalization makes it easy to update these third-party tools, which don't necessarily require changes to Eclipse itself. Another benefit is the ease of sharing these common libraries with many plug-ins. Open your Eclipse SDK installation and create a new plug-in project; name it hsqldb.core. (I know the recommended name would be org.hsqldb.core, but I won't pretend to take the HSQLDB namespace. Perhaps HSQLDB developers reading this will like this idea and recommend it as the "official" Eclipse integration plug-in; in that case the name would probably be changed.) Be sure to select the "Empty Plugin" option instead of any plug-in template; otherwise, you'll get a useless top-level plug-in class, which can be safely deleted if you were anxious and already created it. Copy hsqldb.jar from your HSQLDB installation to the project directory and add it to the Runtime of the project. You can do this by using the PDE Plugin Manifest Editor or by simply copying the contents from Listing 1. Listing 1. plugin.xml manifest file for the hsqldb.core plug-in Adding Workbench extensions Next, create a second plug-in project named hsqldb.ui. This will contain all Eclipse extensions for the first revision of the plug-in set: an action set containing three actions, an object contribution associated to *.sql files, and a property page. Name its main class ( Plugin class) PluginUi, accepting the default package name hsqldb.ui. Open the plugin.xml file using the Plugin Manifest Editor, and select the Extensions tab. Rename the contributed menu to HSQLDB and change the sample action so it displays the label "Runs HSQLDB Database Manager". Add two other actions to the same actionSet with labels "Stops HSQLDB database server" and "Starts HSQLDB database server", providing each with a unique action id and implementation class. Please note that the actions will be displayed on the menu and toolbar in the reverse order of creation (that is the reverse order of appearance in the plugin manifest file). Click the Add button to add two new extensions using the Extension templates, a pop-up menu and a property page. The pop-up menu should be associated with the *.sql file pattern, but the property page fields will be set programmatically. Figure 4 shows how the Plugin Manifest editor should appear at the end, displaying all plug-in extensions; Figure 5 displays the properties for the object contribution (note the filter for *.sql files), and Figure 6 shows the properties for the "Run SQL Script" action for the file resources pop-up menu. The icons are in the source code for this article (see Resources), but I'm sure you know a graphics expert who can draw better ones! Figure 4. HSQLDB actions on the manifest editor Figure 5. HSQLDB object contribution on the manifest editor Figure 6. Run SQL Script action on the manifest editor Before code can be added to our actions, we need to tell this UI plug-in about the corresponding core plug-in, otherwise it won't have access to HSQLDB classes. Change to the "Dependencies" page on the Plugin Manifest Editor and add a plug-in dependency, as shown in Figure 7. Some dependencies, like "eclipse.ui", were configured automagically by the PDE, while others, like "org.eclipse.debug.core" will be added when the actions are coded. If you prefer to edit XML code directly, Listing 2 shows the complete plugin.xml file for the hsqldb.ui plug-in. To complete the plug-in setup, add a new Class to the hsqldb.ui package, and name it HsqldbUtil. This class will contain all code that deals directly with HSQLDB, keeping the contributed extensions code simple. Figure 7. hsqldb.ui plug-in dependencies Listing 2. plugin.xml manifest file for the hsqldb.ui plug-in It's easy to start the HSQLDB engine in server mode using the class org.hsqldb.Server. As command-line arguments, it gets the database name (path + base name for database files), TCP port to listen for connection requests, and a flag telling if it should call System.exit() at shutdown. The following command line would be typical of running HSQLDB: java -cp /opt/hsqldb/hsqldb.jar org.hsqldb.Server -database /tmp/bd -port 9001 -system_exit=true The above line creates database files /tmp/db.script, /tmp/db.properties, and /tmp/db.data. We can just use the Server class main method and pass the arguments as an array of Strings. But we have to do this inside a new thread; otherwise, we'll lock the entire Workbench. The plugin class, which is a singleton, keeps a reference to this thread so it can check if there's a server that started running before trying to connect to it, and also to check if it's actually running, because any client can connect and submit the SHUTDOWN statement, terminating the server. The code in Listing 3 shows the run method for hsqldb.ui.actions.HsqldbStartAction, and Listing 4 shows the code for the startHsqldb from hsqldb.ui.HsqldbUtil, which actually starts the server. Later, we'll discuss the techniques for managing user feedback. The most interesting part of this code is how we find a location to keep the database files. A project named .hsqldb is created, if it does not exist, and inside it the engine will look for database.script and other database files. Eclipse provides all plug-ins in a standard directory where any configuration file can be saved. Such a directory can be obtained by calling plugin.getStateLocation, but I don't feel that database files are actually plug-in configuration files. They look more like user data files, and, as such, they should be inside a project in the developer workspace. Listing 3. Action to start HSQLDB in server mode, from hsqldb.ui.actions.HsqldbStartAction Listing 4. Code that really starts HSQLDB in server mode, from hsqldb.ui.HsqldbUtil To stop the HSQLDB server, all that's needed is a SHUTDOWN command as an SQL statement. The method stopHsqldb from hsqldb.ui.HsqldbUtil, shown in Listing 5, does just that. The code for the corresponding action will be much the same as that described for starting the server, so it won't be listed here. Exceptions ClassNotFoundException (from Class.forName) and SQLException are thrown so that the action code can provide adequate feedback to the user. Listing 5. Code to stop the HSQLDB server Running the HSQL Database Manager Running the Database Manager utility from HSQLDB is a bit more involved than running the server itself. While the server was created to be embeddable in other applications, the utility was intended to be run as a stand-alone application or as a Java applet. Although both modes accept command-line arguments (or applet parameters), we do not want the extra overhead of starting a new Java VM just to get a Window where the user can type SQL statements. Calling the class static void main(String[] args) directly won't work as expected, because it would invoke System.exit() and so terminate the Workbench. Browsing the org.hsqldb.util.DatabaseManager source code, we find that it could be easily instantiated and initialized with a JDBC connection, but the required methods are not public. So we can create a class named org.hsqldb.util.PatchedDatabaseManager inside the HSQLDB source tree and use the supplied Ant build script to generate a new hsqldb.jar containing our patched Database Manager. Just two methods need to have their visibility changed to public: void main() and void connect(Connection con). Using them, Listing 6 shows how the plug-in runs the patched class. The Database Manager is an AWT application (see Figure 8), which will create its own event thread (independent of the Eclipse SWT one) and be terminated by closing the Workbench, which calls System.exit(). There's no problem running multiple instances of the utility, except for the lack of ties to the Workbench window. That's fine for the first revision of our HSQLDB plug-in, but before this series is finished, we'll have to change it to be an SWT application, hosted as an Eclipse view. Figure 8. HSQLDB Database Manager Listing 6. Starting the patched Database Manager utility The HSQLDB Script Tool reads plain text files and executes the included SQL statements against a provided JDBC URL. Batches of SQL statements are separated by the go command, and scripts can also use the Developers familiar with other database systems may create scripts containing just SQL statements delimited by semicolons (;), but this makes HSQLDB run all scripts in a single batch, returning just the last statement results. You need to include the go command between SQL statement to receive results from each one. The easiest way to let the user browse script results is to put then in a console view, just like Java applications and Ant build scripts invoked from the Workbench. This requires creating a Java Launch configuration, which in turn creates another Java VM. As SQL scripts are short-lived, we can consider the overhead to be acceptable, and if you think the Database Manager should also be invoked in its own VM, you can use the runScriptTool method presented in Listing 7 as an example. Listing 7 is the longest listing in this first article, and most of it is related to setting up a classpath containing the correct JRE bootstrap classes (which must be set explicitly) and hsqldb.jar from the hsqldb.core plug-in. Check the Resources section at the end of this article for more information about the launch framework provided by Eclipse and extensions provided by the JDT. To developers familiar with other GUI toolkits, it's not obvious how to get the path for the selected SQL script file. The IObjectActionDelegate interface, which is implemented by object contributions that extend resource pop-up menus, receives on its run method just a reference to the action itself, just like a top-level menu action, containing no information about the selected resource or the originating control. The resource reference is actually provided to selectionChanged method and has to be saved as an instance variable so it can be used used later -- see Listing 8. Listing 7. Running the HSQLDB Script Tool Listing 8. How to get the SQL Script to be executed, from hsqldb.ui.popup.actions.HsqldbRunScript With most of the functionality of our plug-in set now in place, it's only missing a way to configure server connection parameters: the TCP port it listens to, administrator user name, and administrator user password. The TCP port may have to be changed so it won't conflict with other applications installed on the developer's machine; the user and password can be changed by SQL statements from any client. These parameters can be put into a C-like structure (or pascal-like record) class named HsqldbParams, which is shown in Listing 9. It also declares constants used by the Plugin Preferences Store and Property Page to fetch and save the parameters (preferences) values. Listing 9. Preferences structure for HSQLDB server connection parameters Unfortunately, the preference page class generated by the PDE New Extension Wizard is a bit misleading, including a method to set default preference values that won't be used by the plugin preferences store. The correct place for initializing defaults is the main Plugin class itself. Otherwise, all preferences that are at their default values will be returned by the preferences store as 0 or null. Thus, the preferences page class becomes much simpler, as shown in Listing 10, and the method initializeDefaultPreferences is added to the PluginUi class as shown in Listing 11. Note the default values for each preference are defined by the preferences structure, not the plugin class nor the preference page class. Listing 10. Preferences page for HSQLDB plug-in Listing 11. Changed methods from the generated Plugin class Providing feedback to the user As the plug-in set provides neither a view nor an editor to the Workbench, there are limited ways to provide user feedback on the actions. We can use the status line of the Workbench window, and also an SWT MessageDialog so that important events (mostly errors) aren't missed by the user. The visibility and enablement model for Workbench actions is focused on workspace resource selection, but most plug-in actions (starting HSQLDB server, stopping it, and starting the Database Manager) don't depend on resource selection, but rather on whether the server is running or not running -- conditions that have to be explicitly checked by each action run method. Caveat: plugin and action classes are not instantiated until absolutely required to lower Workbench memory requirements. The manifest file contents are used to present menu choices and to enable/disable them, but as the HSQLDB server is not a workspace resource, it can't enable actions. You can, as described for the manifest code in Listing 2, (see the <enablement> element) enable/disable an action based on plug-in activation, so at startup just the "Start HSQLDB server" action is enabled, but after that there's no easy way to, say, disable this action if the server is already running, and then re-enable it when it's stopped. Note the code used to put an hourglass cursor on the Workbench window, and the code used to set the status line message. These are not easy to find in PDE documentation or Eclipse.org articles. The plugin class overrides the shutdown method so it can cleanly shut down the server when the Workbench is closed, and we're finished. Of course, a complete plug-in set would require additional tasks not covered here, such as: - Package the two plug-ins as a feature, so that all are installed, removed, enabled, and disabled as a unit. - Provide help docs for the plug-in itself, and include HSQLDB docs in a format suitable for the Workbench help manager. This article showed how to create a set of plug-ins that bring the HSQLDB database into the Eclipse Workbench, adding the ability to start and stop the database server, as well as running SQL statements and scripts. We've seen how the PDE makes creating this plug-in easy, via wizards and editors for most tasks, leaving the developer with little more than the task of creating the code that actually implements the desired functionality. In the next part of this series, you'll learn how to leverage the Workbench features to add value to HSQLDB development, instead of simply running pre-existing tools. Information about download methods - by Jim Amsden's "Levels of Integration" explains how to integrate a tool into the Eclipse Workbench. - Download the HSQLDB binary and source distribution. - Download the source code discussed in this article. - "Developing Eclipse plug-ins" (developerWorks, December 2002) walks though a simple "Hello, World" plug-in creation, without using the PDE wizards and editors. - "PDE Does Plug-ins" walks though a simple "Hello, World" plug-in creation, but this time teaching how to use PDE wizards and editors. - "Contributing Actions to the Eclipse Workbench" teaches everything about actions, actionSets, objectContributions, etc. - "Preferences in the Eclipse Workbench UI" talks about preferences and PreferenceStores. - "Simplifying Preferences Pages with Field Editors" shows an easier way to create preference pages (which is the one used in this article). - "Notes on the Eclipse Plug-In Architecture" is another article you should read to gain a better understanding about the Eclipse Platform. - "Launching Java Applications Programmatically" demonstrates the infrastructure provided by the JDT to launch Java applications similar to running the HSQLDB ScriptTool. - "Plug a Swing-based development tool into Eclipse" (developerWorks, October 2002) talks about how to integrate Swing and AWT tools into the (SWT based) Workbench. - "Extend Eclipse's Java Development Tools" (developerWorks, July 2003) walks though the process of creating Eclipse plug-ins using the PDE. - Visit the HSQLDB SourceForge Project for source code and binary distributions. - The Hypersonic SQL original project Web site is now discontinued. - JFaceDBC is a nice SQL console, built as an Eclipse plug-in. - Find more articles for Eclipse users in the Open source projects zone on developerWorks. Also see the latest Eclipse technology downloads on alphaWorks..
http://www.ibm.com/developerworks/opensource/library/os-echsql/
crawl-003
refinedweb
4,461
52.8
mdr_e_l_e_a_s_en_o_t_e_s Changes in version 1.0.7 - Fixed potential login deadlock in OnlineAccountClient. - Increased upper timeout limits to 60s to assist scope-harness testing on slow builders. - Fixes for building with Florian Boucault's crossbuilder. - Fixed incorrect generation of shlib files. - Marked the push(Filters const&, FilterState const&) method of SearchReply and SearchListenerBase as deprecated and provided push methods which take the Filters argument only. - Fixed Yakkety build by adding missing #includes - Fixed arm64 build by temporarily disabling SmartScopesClient_test Changes in version 1.0.6 - Got rid of category header background, as per design (Bug #1446216). - Re-enabled license/copyright test for xenial+. - Removed libjson-cpp and replaced with json-glib based implementation (Bug #1360247). - Fixed Yakkety build. Changes in version 1.0.5 - Simplify debian/control munging. - Look for clang-format as opposed to clang-format-3.x. - Added missing initializations to TypedScopeFixture (Bug #1542906). - Allow clients to specify authentication parameters (Bug #1554040). - Fixed incorrect generation of Replaces: and Conflicts: entries in debian/control for xenial. Changes in version 1.0.4 - New RangeInputFilter. - Changed ABI compliance testing to use abigail. Changes in version 1.0.3 - No-change rebuild for zeromq3 transition. Changes in version 1.0.2 - Changed version number generation to use a common script. - Removed symbols files because we are now using abi-compliance-checker. - Replaced global dummy loggers for testing with heap-allocated instances to avoid crash due to global destructor ordering (LP: #1472755). - Store scopes package version in /var/lib/.../version file for fast retrieval from the shell plugin. - Loop through each argument of the custom scope runner command and ensure that all path arguments are absolute. - Protect all JsonCppNode::get_node() methods with a "if (!root_) throw;" check (Bug #1494796). Changes in version 1.0.1 - Consolidate debian packaging for Vivid and Wily, so we don't need to keep to separate series for the gcc 5 ABI break. - Add docs for the table widget - Added support for preview widget updates via ActivationResponse. Changes in version 1.0.0 - Changed package name and soname for toolchain update to gcc 5.0. Changes in version 0.6.20 - Support preview widget updates via ActivationResponse. - Consolidated build for gcc 4.9 and 5.0 so we can build both Vivid and Wily packages from the same tree. All the debian files are now generated from the debian/rules clean target. Changes in version 0.6.19 - Support UNITY_SCOPES_CONFIG_DIR environment variable. Changes in version 0.6.18 - Allow child_scopes() and set_child_scopes() methods more time to execute as they read from and write to disk. - Added ChildScopes.Timeout configuration parameter to Zmq.ini - Added API for activation of in-card result actions - see ScopeBase::activate_result_action() and ActivationResponse::Status::UpdateResult. Changes in version 0.6.17 - Added is_account_login_result() method to Result class. Changes in version 0.6.16 - Added support for attaching arbitrary data to CannedQuery. - Added ENABLE_QT_EXPERIMENTAL guard to qt headers until that library is finalized. Further changes in the unity::scopes::qt namespace are expected at this point. - Added DateTimePickerFilter into experimental namespace. Changes in version 0.6.15 - Renamed "child_scopes()" to "find_child_scopes()" - Renamed "child_scopes_ordered()" to "child_scopes()" - Added is_aggregated() and aggregated_keywords() to SearchMetaData Changes in version 0.6.14 Added push_surfacing_results_from_cache() to Reply proxy. This allows a scope to reply the results of the last succesful surfacing query from an on-disk cache. This is useful to prevent the user being presented with an empty screen when swiping to the scope while the device has no network access, or the scope's data source is off-line. Note: This is change is ABI compatible with gcc and clang despite the addition a new virtual function. Changes in version 0.6.13 - Return keywords as a set rather than a vector. Changes in version 0.6.12 - Introduced child_scopes() methods for aggregators to return their list of child scopes at runtime. - Added missing virtual destructor to AbstractScopeBase. (LP: #1360266) - Removed deprecated Runtime::run_scope() method. - Prevent query from looping indefinitely if a query is forwarded among aggregators and loops back to an earlier aggregator. Changes in version 0.6.11 - The JSON for a CategoryRenderer now supports a "fallback" field in the "art" and "mascot" entries of the "components" dictionary. This allows a scope to specify a category-specific fallback image in case the artwork for a result cannot be retrieved. - PreviewWidget now supports a "fallback" field for the "image", "gallery", and "header" widget types. This allows the scope to specify a fallback image in case the artwork for a widget cannot be retrieved. Changes in version 0.6.10 - Renamed "Tags" scope .ini option to "Keywords". - Added support for IsAggregator scope .ini option. - Implemented BufferedResultForwarder API in utility namespace. Changes in version 0.6.9 - Added support for ChildScopes scope .ini option to list scopes ids of aggregated scopes. - Added support for Version attribute in scope.ini file, and added version() accessor to ScopeMetadata. - Added app_directory() method ScopeBase for scopes that are installed from the same click package as an app. This allows the app to share data with its scope (but not vice versa). - Added missing methods for settings_definitions(), location_data_needed(), and child_scope_ids() to testing::ScopeMetadataBuilder. - Added support for Tags scope .ini option. Changes in version 0.6.8 - Replaced dbus-send with "list updated" pub/sub to invalidate smart scopes. Changes in version 0.6.7 - OnlineAccountClient fixes: run the internal event loop within its own context to avoid clashing with external main loop (LP: #1377147). - Introduced new dependencies on dbus-test-runner and libdbustest1-dev. - Fix for Zmq infinite reconnection problem (LP: #1374206) Changes in version 0.6.6 - Added support for online accounts (via new OnlineAccountClient class). Changes in version 0.6.5 - Implemented support for expandable preview widgets. See the documentation of PreviewWidget for details of the new widget type. Changes in version 0.6.3 - Fix scope cache path for confined scopes. Changes in version 0.6.2 - Move scope configuration to ~/.config/unity-scopes/ - New setting to enable/disable of location data being fed to scopes. - New DebugMode scope configuration option. Changes in version 0.6.1 - Clear any signal masks inherited from the parent process when forking. - Allow timeout value of -1 to disable the scope idle timeout, reaper timeouts, and two-way invocation timeout. Changes in version 0.6.0 - Added tmp_directory() method to ScopeBase, so a scope can find out where it can write temporary files. - Added cache_directory() method to ScopeBase, so a scope can find out where it can write its files. - Upgraded finished() callback to be more flexible and expandable. - Refactored scoperunner and ScopeLoader. ScopeLoader no longer knows about the registry and scoperunner now calls RuntimeImpl::run_scope() to set the scope running, instead of duplicating lots of functionality. - Removed registry parameter from ScopeBase::start(). The registry is now available via a registry() accessor on ScopeBase. The original start() method is still present, but deprecated. The default implementation of the new start() method forwards to the old one so, if a scope implements only the old one but not the new one, things still work. - Made methods on ScopeBase virtual, so the testing framework can override them in a test scope. - Added support for additional query reply info. - Introduced QueryMetadata base for shared functionality of *Metadata classes. - Added set_internet_connectivity() and internet_connectivity() to QueryMetadata. Changes in version 0.5.2 - Added CannedQuery parameter to Category. - Added support for scope settings. - Added Registry.Timeout configuration parameter to Zmq.ini. Changes in version 0.5.1 - Support nested dictionaries in appearance attributes of scope metadata. To define nested dictionary, use dots in key names in [Appearance] section of scope .ini file, e.g. "PageHeader.Logo" = "logo.svg" creates "Logo" attribute inside "PageHeader" dictionary of appearance attributes. Changes in version 0.5.0 - Changed ScopeBase::start() method to return void instead of int, and made both start() and stop() methods virtual instead of pure virtual. - Moved all filter classes except for OptionSelectorFilter into experimental namespace, since they are not currently supported by the Shell and their API may get changed. - Moved Annotation class into experimental namespace. Annotations are not currently supported by the shell and should not be used as their API may change or get removed. - removed deprecated SearchReply::register_annotation() method. - Changes to departments API: SearchReply::register_departments() method now takes parent department argument only, and uses Department::SCPtr for it. SearchListenerBase::push() method for departments got changed to match as well. Removed constructors of Department and added static create() methods instead. Changed DepartmentList to hold Department pointers instead of values. Changed Department::set_has_subdepartments() method to take bool value (true by default). - Changed parameter type for pushing categories on SearchListenerBase to Category::SCPtr const&. - Changed constructor of SearchQueryBase to take CannedQuery and SearchMetadata arguments. Changed constructor of PreviewQueryBase to take Result and ActionMetadata arguments. Changed ActivationQueryBase constructor to take Result, widget id and action id argument. All the constructor arguments are then available via respective getters of the base classes. Changes in version 0.4.8 - Introduced Dir/ScopesWatcher classes to watch for updates to the scope install directories, and added API to subscribe to changes in registry. Changes in version 0.4.7 - Implemented RatingFilter and RadioButtonsFilter. - changed create() methods of OptionSelectorFilter and RangeInputFilter to return unique_ptr (UPtr) instead of shared pointers. Changes in version 0.4.6 - Added method to get and set display hints for filters (at this moment the only display hint available is Primary hint). - Added has_subdepartments flag and alternate label to Department class. - Added TTL option for scope results. Changes in version 0.4.5 - Implemented RangeInputFilter. Changes in version 0.4.4 - The register_annotation() method of SearchReply is now deprecated - push(Annotation const&) should be used instead. The display order of annotations with respect to results and categories got updated in the documentation of that method. - Simplified configuration with sensible defaults for all values. - scoperunner, scoperegistry, and smartscopesproxy are now install in /usr/lib/<arch> (instead of in a subdirectory of <arch>). - Runtime::run_scope() now has an overload to accept a path to Runtime.ini. If no file name is passed, the system-wide Runtime.ini is used. - UNIX domain sockets for Zmq are now placed under /user/run/<uid>/zmq by default. Changes in version 0.4.2 - Made the scope search, activate, perform_action, and preview methods non-blocking. A (fake) QueryCtrl is returned immediately from these methods now. Calling cancel() before the server has finished creating the query remembers the cancel and sends it to the server once the server has returned the real QueryCtrl. This change should be transparent to application code (the only difference being that these methods complete faster now). - CannedQuery class can now be converted to and from a scopes:// uri with to_uri() and from_uri() methods. These methods replace to_string() and from_string() methods that got removed. Changes in version 0.4.0 - Re-factored proxy class implementation. These changes are API compatible, but not ABI compatible. Renaming of various API elements for consistency and clarity: PreviewWidget::add_attribute() -> PreviewWidget::add_attribute_value() PreviewWidget::attributes() -> PreviewWidget::attribute_values() PreviewWidget::add_component() -> PreviewWidget::add_attribute_mapping() PreviewWidget::components() -> PreviewWidget::attribute_mappings() ActivationListener -> ActivationListenerBase ActivationListenerBase::activation_response() -> ActivationListenerBase::activated() PreviewListener -> PreviewListenerBase SearchListener -> SearchListenerBase PreviewQuery -> PreviewQueryBase SearchQuery -> SearchQueryBase ActivationBase -> ActivationQueryBase ReplyBase -> Reply RegistryBase -> Registry Query -> CannedQuery CannedQuery::scope_name() -> CannedQuery::scope_id() ScopeMetadata::scope_name() -> CannedQuery::scope_id() Scope::create_query() -> Scope::search() ScopeBase::create_query() -> ScopeBase::search() SearchQuery::create_subquery() -> SearchQuery::subsearch() Variant::Type: changed ordinal values of enumerators Changes in version 0.3.2 - ActivationResponse::set_scope_data(Variant const&) and scope_data() methods have been added; they are meant to replace setHints() and hints() and use Variant instead of VariantMap for arbitrary scope data. The existing ActivationResponse::setHints(VariantMap const&) and hints() methods have been marked as deprecated and for removal in 0.4.0. Changes in version 0.3.1 - Scope::activate_preview_action() and ScopeBase::activate_preview_action() were renamed to perform_action(). They now also require widget identifier along with action id and hints. - Added SearchMetadata and ActionMetadata classes; these classes are now passed to create_query(), activate(), perform_action(), preview() methods of ScopeBase and Scope (ScopeProxy) instead of a plain VariantMap. - The 'Handled' state was removed from ActivationResponse::Status and two new values were added instead: ShowDash and HideDash. - Annotation API changes: annotations of 'Card' type were removed and Annotation doesn't support category attribute anymore. SearchReply::push() method for annotations was renamed to register_annotation(). Annotations are now going to be displayed in the order they were registered by scopes. - Result::activation_scope_name() method was renamed to target_scope_proxy() and it now returns ScopeProxy instead of a string. Client code can now use that proxy for result activation or preview calls, instead of having to do an extra registry lookup. Changes in version 0.3.0 - Preliminary API for filters has been added via OptionSelectorFilter and FilterState classes. This part of the API is not yet supported by Unity shell and should be considered highly experimental. - ScopeBase::create_query() method now takes Query object instance instead of just a search query string. Search query string is now encapsulated in the Query class and can be retrieved via Query::query_string(). - ScopeProxy class provides overloaded create_query methods for passing filter state and department id. Note: departments are not yet supported across the API. The scoperegistry allows extra scopes to be added on the command line now: $ scoperegistry some/path/Runtime.ini some/other/path/Fred.ini Joe.ini This loads Fred and Joe scopes in addition to any scopes picked up via the normal configuration. If Fred or Joe appear in configuration as well as on the command line, the config file on the command line takes precedence. The .so for additional scopes is expected to be in the same directory as the corresponding .ini file.
https://phone.docs.ubuntu.com/en/scopes/api-cpp-development/md__r_e_l_e_a_s_e__n_o_t_e_s
CC-MAIN-2021-04
refinedweb
2,270
52.46
I have written a simple program that reverses an array. For example, the string 'hello' would be printed out as 'olleh'. However, when I input something like 'hello', it prints out half the string reversed, followed by some cryptic characters and other nonsense that shouldn't be there. My source code is as follows: #include <stdio.h> #include <string.h> int main() { char str[100], temp; int i = 0, j = 0; printf("Enter a string:\n"); fgets(str, 100, stdin); // scanf("%s", &str); j = strlen(str) - 1; while (i < j) { temp = str[i]; str[i] = str[j]; str[j] = str[temp]; i++; j--; } printf("The reversed string is: %s", str); return (0); } Lets take a closer look at these two lines: temp = str[i]; ... str[j] = str[temp]; In the first you set temp to the character in str[i]. The other you use temp as the index into str. But temp is not an index, it's a character. So the last line should be str[j] = temp;
https://codedump.io/share/PAIb3aVRf2SK/1/why-is-my-array-being-printed-incorrectly
CC-MAIN-2017-51
refinedweb
169
81.83
Conor MacNeill wrote: > Cost. My 'itch' is to have pluggable support for component creation. If nobody -1 the ComponentHelper - then any antlib can be implemented as an optional task. I'll probably be ok with any "official" solution ( if it isn't too complex ), and probably I'll do my own experiments. Having a simple ComponentHelper plugin that uses the XML namespace to load a simple properties descriptor is one reasonable solution. Certainly not the only one. >>. My point was that naming conflicts are not the biggest problem we are facing. The only way I know to avoid naming conflicts is to use a namespace. Not using the XML namespace if we do need a namespace ( and inventing our own ) would be a very bad idea IMO. I don't think that the antlib concept will directly increase the number of tasks or the likelyhood of conflicts. Renaming tasks is a very different issue. Renaming existing tasks is yet another issue ( and see no reason for it to happen - I think we agree on this). >. How is that different from tomcat shiping a properties file ( and using taskdef resource=... ) ? People and companies are already shipping ant tasks and libs. If we want to use XML namespaces to reduce the chance of conflicts - and this can be optional, so "simple" build files will not have to do it - then the syntax is pretty clear. <project xmlsns: <tomcat:deploy ... > I don't see too many choices for that ( the URL of the NS is the only big issue ). Do you see any other option on resolving name conflicts in xml files ? > Let's talk about what the build file looks like and work from there. I think we should agree on some basic issues: 1. If a namespace will be used to resolve conflicts - it will be XML namespace ( i.e. we won't invent our own ). 2. Existing files will not have to change. ( i.e. the default namespace will be used for the core tasks ). 3. If you don't need namespaces, you'll not have to use them. I.e. if you have a simple project and use few libs - you can still use the simpler syntax.. Costin -- To unsubscribe, e-mail: <mailto:ant-dev-unsubscribe@jakarta.apache.org> For additional commands, e-mail: <mailto:ant-dev-help@jakarta.apache.org>
http://mail-archives.apache.org/mod_mbox/ant-dev/200301.mbox/%3Cav83cj$7la$1@main.gmane.org%3E
CC-MAIN-2017-30
refinedweb
392
75.2
This article is written by Arkadiusz Merta and was originally published in the February 2005 issue of the Software 2.0 magazine. You can find more articles at the SDJ website. The .NET technology opened a new world of possibilities for highly distributed applications. .NET Remoting and Web services enable them to communicate all over the world. Language independency, seamless integration with databases, Web interfaces as easy to build as regular Windows applications – a new world of possibilities is ready to be discovered by developers. This article presents possibilities for development of .NET applications running on operating systems other than Windows, using the MONO platform. Advantages and challenges will be presented. The paper also presents some common issues encountered while developing applications using the .NET technology. The primary idea is to show whether the same C# code samples can be compiled under .NET and MONO (using the Microsoft C# compiler – csc, or the MONO compiler – mcs), executed under either .NET or MONO, and run under either Windows or Linux. In the .NET Framework, one of the primary ideas was to isolate the application (assembly) from the operating system. This is achieved by compiling .NET source code into an executable that contains Microsoft Intermediate Language (MSIL), which does not depend upon the operating system or the target processor. During execution, MSIL is translated into native code for the particular processor, and linked with the appropriate operating system libraries, and executed as a ‘regular’ application. So, in this context, the .NET Framework builds a functional abstraction layer for .NET applications. For example, Windows Forms, a standard graphical interface for .NET applications, is translated by the .NET Framework into a series of calls to the .NET Framework’s Common Library (CL). This is very different to the approach previously used in Visual C++ Microsoft Foundation Classes (MFC), which actually executed direct calls to the Win32 API. .NET assemblies are executed against the .NET Framework, while Win32 applications are calling the operating system directly. This feature promises operating system independency. The trick is that the .NET Framework is a single vendor solution; although some ports to mobile devices are available (SmartPhone) – they are really bound to Microsoft's offerings. The biggest competitor of .NET – the Java Virtual Machine – has one feature that gives it an advantage: true system independency. Java was developed much earlier than Microsoft .NET, and from the very beginning, it was meant to be an Open Source product. No wonder that the community accepted it and developed ports for the Java Virtual Machine for many different platforms. When .NET was released, Java was already quite popular, ported to many operating systems, with a rich set of free development tools already available (e.g., IBM Sun ONE Studio and Eclipse). The .NET Framework is given away for free, but the .NET development tools are quite expensive – Visual Studio .NET is sold for more than $2000. To be able to compete with Sun’s Java, Microsoft (together with Hewlett-Packard and Intel) published C# and the Common Language Infrastructure (CLI) specifications and submitted them to the international standardisation organization, ECMA. As a result, ECMA-334 (C#) and ECMA-335 (CLI) standards were ratified late December 2001. This way, the .NET Framework was now on track to become really portable. The MONO project started in 2001, but the first stable release, 1.0, was issued in Q2 2004. The work was initiated by Ximiana (and based upon the research project ROTOR), which was further bought by Novell. The aim was quite clear: to move the .NET Framework from the one vendor solution into a wide and portable standard for a number of platforms and operating systems. Versions for x86, SPARC, and PowerPC platforms are available. Unix, Linux, FreeBSD and Windows are supported. C# (stable) and eventually Basic (unstable) can be used for development. System, Web, Remoting, security, Web services, and XML packages are ready. Some data components are ready (Oracle), some are unfortunately unstable (including Microsoft SQL client; the full list of packages can be found in the section MONO components). This article refers to MONO 1.0.1. In this article, the terms ".NET Framework" refer to the Microsoft product, and "MONO Framework" refers to the MONO implementation of the CLI. Please install Windows MONO to: c:\mono\Mono-1.0 which will save you a lot of effort while compiling packages (there are some bugs within the packager configuration). Furthermore, the PATH variable must be updated with the path to the MONO bin directory (here: c:\mono\Mono-1.0\bin). PATH Installing MONO under Windows with .NET Framework actually means that two execution engines will work side-by-side. Please be aware that simply double-clicking an assembly (or running it from the command line) will execute it using the .NET Framework, which is the default for the system. In order to execute an assembly under MONO, a command must be used: mono <assembly_name> The easiest way to do this is to use the MONO command prompt. Let us try to write a small .NET console application, compile it under Windows using Microsoft as well as MONO tools, and execute it under Windows. The piece of C# code shown in Listing 1 outputs Hello World! to the standard console. using System; namespace FirstHomeWork{ class First{ [STAThread] static void Main(string[] args){ System.Console.WriteLine(“Hello World!”); System.Console.ReadLine(); } } } Let us save it under first.cs and compile it using csc (Microsoft’s .NET C# compiler) into first_ms.exe: >csc /out:first_ms.exe first.cs >first_ms.exe Hello World! As expected, the execution outputs the programmers' beloved string on the standard console and waits until Enter is pressed. Let us do the same with MONO, using msc (MONO C# compiler): >msc -out:first_mono.exe first.cs As a result we get first_mono.exe file. Trying to run it we will receive the same result as for first_ms.exe file: >first_mono.exe Hello World! But what actually happened here? We just executed the C# source code compiled using the MONO msc compiler, under ... the Microsoft .NET Framework! To execute first_mono.exe under the MONO Framework, we will have to use: >mono first_mono.exe Hello World! The result is (as hoped) the same. The assembly files produced by mcs and csc have the same size. However, when we compare them byte-by-byte, it will appear that some byte codes differ. One important note here is how the MONO assemblies are executed. For the latter example, we used a mono command to run them. This command uses a Just in Time (JIT) compiler to translate the code from intermediate language into the target platform native, stores the result in memory, and executes from there afterwards. A copy of the JIT-compiled code stays in memory for subsequent use. One MONO feature should be introduced here: mint. Mint is an interpreter. In order to execute a MONO application using mint, we can call the following from the command line: mint first_mono.exe The output will be quite the same. But under the hood, execution will be done in a different way. Mint, as an interpreter, does not use JIT at all, it just walks through the compiled code, interprets each of the ECMA-CLI bytes, and executes them against the x86 instruction set. Because interpretation is done at each step, overall, applications run by mint tend to be slower than the ones run under mono. However, JIT compilation takes some time at the beginning, and small applications can be faster with mint than when they are run with mono. But, because mint interprets the code, the C# compiler can be used for debugging purposes. Additionally, by avoiding JIT, compilation allows for execution on platforms where JIT is not available yet (OS X). We now know some basic principles of MONO; now let us try to write a simple dialog application. The application will be created using Visual Studio .NET (see Figure 1 and Figure 2). Figure 1. Simple dialog application – a label and a ‘Say Hello’ button Figure 2. Simple dialog application after clicking ‘Say Hello’ We have the source code, let us try to compile it under MONO: mcs –out:form_mono.exe form.cs form.cs(13) error CS0246: Cannot find type ‘System.Windows.Forms.Form’ Compilation failed: 1 error(s), 0 warnings No luck? The reason for our failure is quite simple: the MONO Framework implements CLI functionality, but not fully. Unfortunately, some of the packages are still marked as unstable or unimplemented (a list of packages included in MONO 1.0 can be found in the section Mono components). Moreover, some packages probably won’t be implemented at all. Let us try to concentrate on the GUI. As stated in the introduction, the MONO project's aim is to create frameworks based upon CLI specifications, for platforms other than x86 and MS Windows. The .NET Framework for building Windows applications uses Windows Forms (System.Windows.Forms namespace). But it contains a set of controls designed especially for Microsoft Windows. Does it mean that there is no possibility to build GUIs with MONO? Of course not. The difference is that Unix / Linux – based systems have their own, widely accepted graphical package: Gtk. System.Windows.Forms Gtk was, from the beginning, created to support GIMP – a graphical tool for X-Windows systems. After that, it became an important builder of graphical interfaces operating under Unix / Linux. Now, its managed version called Gtk# is also distributed with the MONO project under the Gtk and GtkSharp namespaces (gtk-sharp.dll). Gtk GtkSharp The assemblies compiled with MONO will be executable under the .NET Framework (not: MONO Framework) as long as only .NET Framework namespaces implemented in MONO are used. So, to create MONO GUI applications that will work under either Windows or Linux, Gtk# has to be used. Once again, there is, for now, no possibility to compile stable .NET Windows Forms applications under MONO (and execute them across platforms). The good thing is that Gtk# is quite easy to learn, and a lot of functionality is the same as in Windows Forms. Let’s try to test this conclusion (Listing 2). We save it to form_mono.cs file and compile using mcs: mcs –out:form_mono.exe –pkg:gtk-sharp form_mono.cs Please note that a reference to the gtk-sharp package must be added (-pkg:gtk-sharp). Let us execute the application over the MONO Framework by calling: mono form_mono.exe. The result can be seen in Figure 3. using System; using Gtk; using GtkSharp; namespace FirstDialogMONOApp{ public class form_mono{ private static Label lbl; static void onWindowDelete( object obj, DeleteEventArgs args){ Application.Quit(); } static void onBtnClick(object obj, EventArgs args){ lbl.Text = "Hello to you!"; } static void Main() { Application.Init(); Window win = new Window("First Form - mono"); win.DeleteEvent+= new DeleteEventHandler(onWindowDelete); VBox vbox = new VBox(false,1); lbl = new Label("???"); vbox.PackStart(lbl,false,false,1); Button btn = new Button ("Say Hello"); btn.Clicked+=new EventHandler(onBtnClick); vbox.PackStart(btn,true,true,1); win.Add(vbox); win.ShowAll(); Application.Run(); } } } Figure 3. Simple dialog application – MONO version If we compare the source code of the Windows and MONO versions, a lot of similarities would be found. Some widget names are quite the same (Label, Button), some methods and attributes are the same (e.g. Label constructor, Label.Text attribute), and events also match (DeleteEvent – DeleteEventHandler, Clicked – EventHandler). Label Button Label.Text OK, we now know that to build a GUI application in MONO, Gtk# must be used, because MONO 1.0 does not contain an implementation of System.Windows.Forms. That’s why a .NET application won’t compile directly using MONO. A question emerges: can a MONO GUI application that uses Gtk# be executed over a .NET Framework? Let us check by calling: form_mono.exe. As a result, we will receive a Just-In-Time Debugging dialog with an exception (Figure 4). Looking more closely at Figure 4, we will discover that the exception type is a System.IO.FileNotFoundException. By allowing the debugger to run, the extended message will provide us with some more details (Figure 5). System.IO.FileNotFoundException Figure 4. JIT exception dialog Figure 5. Debugger exception window glib-sharp is known to us now – we referenced it while compiling our MONO dialog application. It seems, however, that during application execution, it can no longer be found. Since this library will be used for several applications – let us try to make it accessible. The best place to put a .NET (or .NET compatible) assembly that must be shared with many applications is the Global Assembly Cache (GAC). GAC is a special, isolated storage area, where applications can be stored and executed with policies assigned to them. The contents of the .NET Framework GAC can be listed via Administrative Tools/Microsoft .NET Framework Configuration (Figure 6). By clicking View List of assemblies in the Assembly Cache, we will receive a list of assemblies that reside in GAC. Since our task is rather to add gtk-sharp to GAC, we choose Add an Assembly to the Assembly Cache, find gtk-sharp.dll (should be in Mono-1.0/lib/mono/gtk-sharp), and add it. Let's check whether it has been added, using View List of assemblies in the Assembly Cache option this time (Figure 7). The contents of the GAC can also be listed from the command line, using the gacutil tool: gacutil /lr Other command line switches enable GAC manipulations. Figure 6. .NET configuration Figure 7. .NET GAC containing the ‘gtk-sharp’ assembly Let us try to execute our MONO application again by calling: form_mono.exe. Still no luck? We will receive the same error message. The exception message, however, contains the statement that either gtk-sharp or one of its dependencies was not found. Since we put gtk-sharp into GAC already, we can assume that the first condition has been satisfied. We have to check what kind of dependencies are required for Gtk#. The .NET executable files differ very much from regular Windows executables. Besides the content of intermediate code instead of system native, their organisation is a bit different. What’s most important at this point is that they contain a manifest. Manifest data contains information about the assembly and a list of assemblies that it depends upon. It also contains all the publicly exposed types and resources. Investigating it is a good way of gathering knowledge of how the module can be used. Let us check the dependencies using Microsoft’s ildasm tool (Figure 8). The ILDSAM tool parses any .NET Framework EXE/DLL module and shows the information in an easily-readable format. It allows the user to browse a manifest that contains the used .NET namespaces, types, and dependencies. MONO provides a command line disassembler: monodis. Figure 8. Ildasm tool lists the contents of the manifest of gtk-sharp.dll As we can see, the gtk-sharp assembly depends upon several other assemblies: As we did with gtk-sharp above – let us add atk-sharp, gdk-sharp, glib-sharp, and pango-sharp to the GAC (Figure 9). Figure 9. GAC updated with Gtk# and its dependencies The final step – running the application – should succeed now. This proves that Gtk# and its dependencies are fully compliant with the Microsoft .NET Framework. I believe that we know enough at this point to try to make our application distributed. As seen in MONO components, the MONO Framework implements the System.Web and System.Web.Services namespaces – we will try to use them in order to build an application that takes some data out from the Web server using Web services. The Hello dialog application will be extended here to use the Web service to get a welcome string value. We will test whether MONO can create a Web service that will be used either by an application written in .NET or MONO. System.Web System.Web.Services MONO comes with its own small Web server which is called XSP. It can be run in batch using: c:\mono\Mono-1.0\bin\startXSP.bat By default, it resides on port 8088. To see its start page, an address like: should be entered in a Web browser. First, let us create hello.asmx and place it in the Web server root: <%@ WebService Language="c#" Class="helloServices.hello" Codebehind="hello.asmx.cs" %> The header specifies that: helloServices hello Now, let us create the Web service implementation (Listing 3). using System; using System.Web.Services; namespace helloServices{ public class hello:System.Web.Services.WebService { [WebMethod] public string getHello(){ return "Hello (from the Web Service)"; } } } The Web service code – behind file (as in Listing 3), contains a Web method called getHello which returns a welcome string. Now we will compile the code–behind file, adding a reference to System.Web.Services (/r: switch) and specifying the target as library (/t: switch): getHello >mcs /r:System.Web.Services.dll /t:library hello.asmx.cs The output file (hello.asmx.dll) should be stored in the Web server /bin directory. Let us try to use a Web browser to see whether the Web service works (Figure 10). Figure 10. Hello Web service called from within a Web browser And it worked! We can now invoke a method, clicking on the getHello link and Invoke after that. OK – we wrote a Web service, compiled it under MONO using mcs, and that works even when invoked from IIS. But how about using it in our application? Let's start with the easier solution: using MONO’s Web service inside a .NET application. To do this, a Web reference in a Visual Studio .NET solution to the hello service must be added, and the button click handler modified as shown in: private void btn_Click(object sender, System.EventArgs e){ localhost.hello helloService = new localhost.hello(); lbl.Text = helloService.getHello(); } Since I operated on a single machine, a reference to localhost has been added. By doing this, Visual Studio generates a proxy for the service (localhost.hello class), which is further instantiated and the getHello Web method invoked. The result is as expected (Figure 11). localhost.hello Figure 11. Dialog app that acquired the welcome string from the Web service created using MONO How about our MONO application? As mentioned, Visual Studio creates a proxy automatically. Since there is no special development tool for MONO under Windows yet – we have to do it ourselves using a tool called wsdl (included in the MONO package): >wsdl.exe –n:helloWS This will generate the hello.cs file containing the proxy code. Please always specify the namespace of the proxy using the -n switch (here: namespace was set to helloWS). Let’s modify the Say Hello button handler: helloWS static void onBtnClick(object obj, EventArgs args){ helloWS.hello helloService = new helloWS.hello(); lbl.Text = helloService.getHello(); } The web server XSP, included in the MONO distribution, enables proxy generation too. Let’s compile everything, adding a reference to the Web service: > mcs -out:form_mono.exe -pkg:gtk-sharp -r:System.Web.Services.dll form_mono.cs hello.cs ...and run under MONO using: mono form_mono.exe, achieving the results as can be seen in Figure 12. Figure 12. MONO application calling the Web service Thanks to adding Gtk# to GAC, the application executed under the .NET Framework also works fine! So now, we can build Web services and proper clients using MONO. We saw that the code can be compiled by either .NET or MONO, and executed against both frameworks. This is, of course, because the MONO Framework implements a System.Web namespace. A key reason for using MONO instead of Microsoft .NET is MONO’s ability to operate over different platforms. For a Linux platform, a Red Hat 9 Server with GNOME desktop will be used here as our test machine. In order to install MONO under Red Hat Linux: Download mono_all.zip from here. I’ve managed to install MONO under SuSE Linux 9.1 Personal with success. The MonoDevelop tool didn’t run though, because of unresolved package dependencies (SuSE uses KDE instead of GNOME, by default). Figure 13. MonoDevelop under Red Hat 9 A GUI based development tool has been created for the MONO platform. MonoDevelop is not as sophisticated as Visual Studio .NET. It contains a simple editor with syntax highlighting, context help, code auto-completion, and it enables applications to be compiled. It organises files into projects and solutions, and several project templates are available. In order to test MONO portability, we will try to execute applications compiled under Windows using MONO mcs against RedHat with MONO 1.0. To do this, the assembly is simply copied to a Linux machine and executed there (Figure 14). Figure 14. Dialog application executed under Linux And it worked again! Looking more closely at Figure 14, we can see that the application looks a bit different to the one executed on Windows. This is because Gtk# for Windows uses the Windows look & feel – Linux desktop widgets differ slightly. One of the issues specific for enterprise-level applications is that they perform a lot of processing, cooperating closely with databases. Microsoft’s .NET improves on the great Microsoft SQL client, with DataSets that significantly improve work with databases. The DataSet is one of the major components of ADO.NET. A DataSet is the result of querying a database against views, tables, or rows (using either stored procedures or an SQL query). It can be considered a snapshot of the queried data. It not only provides data, but incorporates the functionality of synchronisation with the data source (insert, delete, and update). DataSet MONO can interact with a variety of commercial and open source databases using ADO.NET (and some third-party tools), as listed in Table 1. Table 1. Databases or database engines supported by MONO Database/ Engine Namespace Assemblies to reference with ‘-r’ option Notes .NET MySQL ByteFX.Data System.Data.dll ByteFX.Data.dll A third-party package distributed with MONO ODBC System.Data.Odbc Yes Microsoft SQL System.Data.SqlClient Support for ver. 7 and 2000 Oracle System.Data.OracleClient System.Data.dll System.Data.OracleClient.dll PostgreSQL Npgsql Npgsql.dll Firebird/ Interbase FirebirdSql.Data.Firebird FirebirdSql.Data.Firebird.dll IBM DB2 IBM.Data.DB2 IBM.Data.DB2.dll OLE DB System.Data.OleDb Using Gnome DB, i.e., Access SQL Lite Mono.Data.SqlliteClient Mono.Data.SqliteClient.dll Embeddable SQL database engine Sybase Mono.Data.SybaseClient System.Data.dll Mono.Data.SybaseClient.dll As can be seen, the number of databases supported by the MONO Framework is far richer than the number offered by Microsoft. Of course, libraries for databases missing in .NET also exist – but they are not distributed along with Visual Studio .NET. A sample use of the Microsoft SQL database engine is given in Listing 4. using System; using System.Data; using System.Data.SqlClient; namespace SQLClient{ class sqlclient{ [STAThread] static void Main(string[] args){ SqlConnection conn; conn = new SqlConnection(); conn.ConnectionString = "user id=sa;data source=192.168.89.176;" + "persist security info=False; initial catalog=MONOTest"; SqlCommand sel = new SqlCommand(); sel.Connection = conn; sel.CommandText = "SELECT id, Name, Surname FROM people"; SqlDataAdapter dataAdapter = new SqlDataAdapter(); dataAdapter.SelectCommand = sel; DataSet ds = new DataSet(); dataAdapter.Fill(ds, "people"); DataTable table = ds.Tables[0]; for(int row = 0; row < table.Rows.Count; row++){ System.Console.Write("{0}: ", row+1); for(int col = 1; col < table.Columns.Count; col++) System.Console.Write("{1}:{2}, ", row+1, table.Columns[col].ColumnName, table.Rows[row].ItemArray[col].ToString()); System.Console.WriteLine(""); } System.Console.ReadLine(); } } It can be compiled under .NET (using csc) or MONO (using mcs; add the -r:System.Data switch). It can be executed under .NET or the MONO (calling mono) Framework, and it works well under either Windows or Red Hat (Figure 15). Figure 15. SQL client executed in Red Hat A comparison of any two platforms cannot be seen as complete without a performance test. As a sample test, I chose an application from the previous section, and augmented it with insert and delete operations. The test database contained 2500 rows to select. ‘Insert’ added another 500 rows. ‘Delete’ removed them. As a test machine, a Pentium III 500 with 64 MB of RAM was used. The results are shown in Table 2. The table shows that applications executed against MONO tend to be much slower than the ones executed against the .NET Framework. Actually, it is not surprising that Microsoft’s framework connecting to Microsoft’s database is faster than MONO. What is actually surprising is that a MONO application executed against the .NET Framework was as fast as Microsoft’s native. Table 2. Comparison of application performance compiled using MONO and .NET run under Windows 2000 MS Windows 2000 Platform MONO Platform .NET MONO app* [ms] .NET app** MONO app*** NET app**** Connection Creation 1071 891 111 Select 2500 rows 2667 2353 781 Insert 500 rows 2072 2125 719 713 Delete 500 rows 2720 2754 663 662 * Application compiled under MONO (using mcs) and executed against MONO platform (using mono). ** Application compiled under .NET (using csc) and executed against MONO platform (using mono). *** Application compiled under MONO (using mcs) and executed against .NET platform. **** Application compiled under .NET (using csc) and executed against .NET platform. One important note here is that both MONO and .NET assemblies executed at almost the same speed. For accurateness, let us have a quick look at the test made by executing the application under the mint interpreter (Table 4). The comparison shows that, for some operations, the interpreter can be quicker; for others though, they can be even four times slower! Table 3. Comparison of application performance compiled using MONO and .NET, run under Red Hat 9 Red Hat 9 MONO/Win app* MONO/Linux app** .NET/Win app*** 510 509 664 626 652 2039 2061 2770 2726 2859 * Application compiled under Windows MONO (using mcs) and executed against MONO platform under RedHat 9 (using mono). ** Application compiled under RedHat MONO (using mcs) and executed against MONO platform under RedHat 9 (using mono). *** Application compiled under Windows .NET (using csc) and executed against MONO platform under RedHat 9 (using mono). Table 4. A comparison of MONO applications run using the ‘mono’ command (i.e. using JIT) and the ‘mint’ command (i.e. interpreted) Windows 2000 mono <>* mint <>** mint <>*** Connection creation 1106 807 3620 1419 5491 5932 9720 10889 * Application compiled under MONO (using mcs) and executed against MONO platform (using mono) hosted by Windows (for comparison). ** Application compiled under MONO (using mcs) and executed against MONO platform (using mint) hosted by Windows. *** Application compiled under MONO (using mcs) and executed against MONO platform (using mint) hosted by RedHat. A MONO package also contains and supports a set of third-party tools, one of which is called IKVM.NET. IKVM.NET is an implementation of the Java Virtual Machine for .NET or MONO runtimes (see Figure 13 – one of the project template-type nodes is called Java). IKVM.NET has ambitions to join what are considered as mutually exclusive technologies of Sun and Microsoft to allow seamless execution against one runtime framework. The project is still under active development, and a lot of functionality needs to be implemented (e.g., AWT and Swing components!). However, some key points for the future should be mentioned: A promise of taking advantage of legacy systems written in Java and interoperability of .NET is quite interesting. Still, this is for the future. One of the interesting parts of MONO is called glade. The Glade classes give applications the ability to load user interfaces from XML files at runtime. So, generally, changes in the application’s look and feel can be performed without the need to recompile it! Let’s implement our dialog application using Glade. First of all, we will create a GUI outline. As stated above, it is defined inside an XML text file. It can, of course, be written manually, but several freeware builders are available. Here, Glade for Windows will be used (Figure 16). Glade for Windows can be downloaded from SourceForge. A Linux version can be found here. Figure 16. ‘Glade for Windows’ while building a sample application A generated gui.glade XML file that defines a GUI, looks like the one shown in Listing 5 (some lines were removed for clarity). Listing 5. XML file with GUI definition <?xml version="1.0" standalone="no"?> <!--*- mode: xml -*--> <!DOCTYPE glade-interface SYSTEM ""> <glade-interface> <widget class="GtkWindow" id="window1"> <property name="title" translatable="yes"> First Form</property> ... <property name="resizable">False</property> ... <signal name="delete_event" handler="OnWindowDeleteEvent" /> <child> <widget class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="homogeneous">False</property> <property name="spacing">0</property> <child> <widget class="GtkLabel" id="lbl"> <property name="label" translatable="yes">???</property> ... </widget> </child> ... <child> <widget class="GtkButton" id="btn"> <property name="label" translatable="yes"> Say Hello</property> ... <signal name="clicked" handler="onBtnClick"/> </widget> </child> ... </widget> </child> </widget> </glade-interface> Please take a look at the lines: signal and property. They set basic properties (e.g. name), or define signals connected to them. A Glade signal is actually an event, which will be further handled by a specified method. We will create a Glade client application (glade.cs; Listing 6). The client code shows the main class that triggers an application and two event handlers (for button click and window close) specified in the respective signal XML statements. Furthermore, a Glade.XML.GetWidget is used to get a reference to the label element. The XML file is given as a Glade.XML constructor parameter. Glade.XML.GetWidget Glade.XML Listing 6. C# application that uses GUI definition from an XML file using System; using Gtk; using Glade; public class GladeApp { private Glade.XML gxml; public static void Main (string[] args) { new GladeApp (args); } public GladeApp (string[] args) { Application.Init(); gxml = new Glade.XML (null, "gui.glade", "window1", null); gxml.Autoconnect (this); Application.Run(); } public void onBtnClick(object obj, EventArgs args){ helloWS.hello helloService = new helloWS.hello(); Gtk.Widget wg = gxml.GetWidget("lbl"); if(wg != null ) ((Label)wg).Text = helloService.getHello(); } public void OnWindowDeleteEvent (object o, DeleteEventArgs args) { Application.Quit (); args.RetVal = true; } } Now, let us compile everything as shown in Listing 6: >mcs –pkg:gtk-sharp –pkg:glade-sharp –r:System.Web.Services –linkresource:gui.glade glade.cs hello.cs Please note that: And run by calling: mono glade.exe The application does not differ from the one shown in previous samples. This is because Glade uses Gtk# widgets. The beauty of this solution can be seen when we try to edit gui.glade (using, for example, Notepad). For example – a label name can be changed from ??? into Waiting...; running glade.exe again will display these changes – without the need to recompile anything. Of course, there are several disadvantages to such a solution. Obviously, an event (signal) handler must be bundled inside the compiled assembly, so if functionality changes, the application will have to be rebuilt anyway. Furthermore, XML, despite being in a text format, is hard to read, and a good tool for creating and editing it is required. Another interesting feature of MONO is the possibility to embed it within other programs: you can write C code (unmanaged), which calls a MONO assembly (managed). Although it seems to be quite an academic discussion – let us try this out (just to be aware of the possibilities). C definitely lacks interoperability routines. Wouldn’t it be nice to have Web services accessible? As a Web service, the known hello will be used. We will create a C client and a managed assembly that will call a Web service. Let us first create an exposeWS.cs file that will perform a call to a Web service (Listing 7). Listing 7. C# application that calls a Web service using System; class helloStub{ static void Main(){ Console.WriteLine("Contacting WebService..."); helloWS.hello helloService = new helloWS.hello(); String answer = helloService.getHello(); Console.WriteLine("Web service answer: {0}", answer); } } And compile it under MONO, by calling: mcs –r:System.Web.Services exposeWS.cs hello.cs. As a result, the exposeWS.exe assembly will be created. Now, we will write a client.c file containing a C client (Listing 8). We will compile our C client using gcc and linker parameters obtained from the pkg-config tool: gcc client.c -o:client .exe `pkg-config –cflags –libs mono` Listing 8. C application that uses the MONO application #include <mono/jit/jit.h> int main(int argc, char* argv[]){ //Create domain for assembly MonoDomain *domain; domain = mono_jit_init ("exposeWS.exe"); if(!domain)error(); //Load assembly into domain MonoAssembly *assembly; assembly = mono_domain_assembly_open(domain, "exposeWS.exe"); if( !assembly )error(); //Execute assembly mono_jit_exec(domain,assembly,0,argv); //Clean up mono_jit_cleanup(domain); return 0; } The last thing to do is to run the client: >client.exe Contacting WebService... Web service answer: Hello (from the Web service) We have just run a C client that connected with the Web service! One of the basic functionalities of each programming framework is its ability to debug assemblies run against it. As is normal, two features will be examined: tracing and debugging. Tracing outputs a log whenever the assembly has reached a particular point of execution. MONO assemblies can be traced at runtime using the -trace option. Let us try to trace calls to the getHello method from the hello.cs proxy used by the previous exposeWS.exe assembly. > mono –trace=’M:helloWS.hello:getHello’ exposeWS.exe Contacting WebService... EXCEPTION handling: FormatException EXCEPTION handling: FormatException EXCEPTION handling: FormatException EXCEPTION handling: FormatException Web service answer: Hello (from the Web Service) ENTER: helloWS.hello:getHello () (this:0x80d8f00[helloWS.hello exposeWS.exe], ) LEAVE: helloWS.hello:getHello () [STRING:0x83bf9b0:Hello (from the Web Service)] Please note that a -trace=’M:helloWS.hello:getHello’ switch has been added to the mono command line. The switch specifies that the method getHello from the class hello stored in the namespace helloWS will be traced. Some exceptions have been logged – four lines such as EXCEPTION handling: FormatException have been outputted. Let us try to check where they were thrown. To do this, we will trace all calls to the helloWS namespace. > mono –trace=’N:helloWS’ exposeWS.exe Contacting WebService... ENTER: (wrapper remoting-invoke-with-check) helloWS.hello:.ctor () (this:0x80d8f00[helloWS.hello exposeWS.exe], ) . ENTER: helloWS.hello:.ctor () (this:0x80d8f00[helloWS.hello exposeWS.exe], ) EXCEPTION handling: FormatException EXCEPTION handling: FormatException EXCEPTION handling: FormatException EXCEPTION handling: FormatException Web service answer: Hello (from the Web Service) . LEAVE: helloWS.hello:.ctor () LEAVE: (wrapper remoting-invoke-with-check) helloWS.hello:.ctor () ENTER: helloWS.hello:getHello () (this:0x80d8f00[helloWS.hello exposeWS.exe], ) LEAVE: helloWS.hello:getHello () [STRING:0x83c1a00:Hello (from the Web Service)] Contacting WebService... ... LEAVE: helloWS.hello:getHello () [STRING:0x83bf9b0:Hello (from the Web Service)] Please note that a -trace=’N:helloWS’ switch has been added to the mcs command line. As has been seen, exceptions were logged in the hello class constructor. Since this one does nothing special (Listing 9), we can suspect that the exception was thrown somewhere in the super class constructor. Let’s try to trace the whole namespace first: Listing 9. hello class constructor public class hello : System.Web.Services.Protocols.SoapHttpClientProtocol { public hello () { this.Url = ""; } } > mono –trace=’N: System.Web.Services.Protocols’ exposeWS.exe Contacting WebService... ENTER: System.Web.Services.Protocols.SoapHttpClientProtocol: .ctor ()(this:0x80d8f00[helloWS.hello exposeWS.exe], ) . ENTER: System.Web.Services.Protocols.HttpWebClientProtocol: .ctor ()(this:0x80d8f00[helloWS.hello exposeWS.exe], ) ... . . . . . . ENTER: System.Web.Services.Protocols.SoapExtension: InitializeGlobalExtensions ()() EXCEPTION handling: FormatException EXCEPTION handling: FormatException EXCEPTION handling: FormatException EXCEPTION handling: FormatException . . . . . . LEAVE: System.Web.Services.Protocols.SoapExtension: InitializeGlobalEx As can be seen, the exception occurred in the method InitializeGlobalExtensions() of the class System.Web.Services.Protocols.SoapExtension. So – is it a bug? Actually, no – as the logger output – not an exception, but an act of exception handling happened. An exception was thrown, but also caught (and handled). InitializeGlobalExtensions() System.Web.Services.Protocols.SoapExtension The full list of tracing options is accessible by calling: mono –help-trace. One more thing should be pointed out here, and that is that the presented code does not contain any TRACE methods at all. The output has been generated on the basis of the operational stack. TRACE Another feature that is worth mentioning, common to both MONO and .NET, are trace switches. The idea is quite clear: to enable output trace information being toggled on or off, by setting the proper flag in the external configuration file. This can be used whenever a deployed application requires some investigation at some future period as to what is actually happening during execution. An external flag can be set, trace logs gathered, and after that – unset again (and no logs will be output anymore). Let us update exposeWS.cs as in Listing 10. First of all, a BooleanSwitch has been created and named as infoWS. Because the output of the trace must be specified, a trace listener has been set-up to use the default console. Furthermore, several Trace.Writeif instructions have been added in order to clarify the execution process. They will output values to the standard console only if the switch sw is enabled. BooleanSwitch infoWS Trace.Writeif sw Listing 10. C# application with trace switches using System; using System.Diagnostics; class helloStub{ private static BooleanSwitch sw = new BooleanSwitch("infoSW", "Info trace:"); static void Main(){ Trace.Listeners.Add( new TextWriterTraceListener(Console.Out)); Console.WriteLine("Contacting WebService...",); Trace.WriteIf( sw.Enabled, "Instantializing Web service proxy..."); helloWS.hello helloService = new helloWS.hello(); Trace.WriteIf( sw.Enabled, "OK\r\nQuerying for hello string..."); String answer = helloService.getHello(); Trace.WriteIf( sw.Enabled, "OK\r\nDisplaying hello string...\r\n"); Console.WriteLine("Web service answer: {0}", answer); Trace.WriteIf(infoSW.Enabled, "OK\r\nLeaving..."); } As previously pointed out, an external configuration file will be required here (exposeWS.exe.config; Listing 11). The configuration file defines a switch named infoWS and sets its value to 0 (please note the similarities between the BooleanSwitch constructor parameters and the add element name attribute in the configuration file). The configuration file must be stored in the same directory as the assembly. Furthermore, configuration files must be named as: <assembly_name_with_extension ><.config>. E.g., for exposeWS.cs compiled into exposeWS.exe, the configuration file must be named exposeWS.exe.config. add name Let us try to compile: >mcs –r:System.Web.Services.dll –d:TRACE exposeWS.cs hello.cs Please note that the -d:TRACE option has been added to the mcs command line. This is because trace instructions are, by default, removed from the code during compilation. The -d option will prevent this. Run by calling: mono exposeWS.exe Anything changed? Of course not – we specified the infoSW value to be 0 (false). Let’s try setting that value to 1. infoSW By executing the application using mono exposeWS.exe, we will see several additional lines added by Trace.WriteIf() calls. Trace.WriteIf() Listing 11. Application configuration file with trace switches definition <?xml version="1.0" encoding="utf-8"?> <configuration> <system.diagnostics> <switches> <add name="infoSW" value="0"/> </switches> </system.diagnostics> </configuration> Trace switches can be of two types: true false TraceSwitch 0 TraceError TraceWarning TraceInfo TraceVerbose OK, now we know enough about tracing and trace switches, but what about debugging? At this point, I am afraid that I have to disappoint everyone who just started to be potential MONO freaks. According to the MONO manual, in order to run an assembly in debug mode, it must first be compiled with the --g option that generates *.gdb files that contain debugger symbols. Under Windows, such attempts result in the error that Mono.CSharp.Debugger.dll cannot be found. This is logged as one of the known bugs and it is supposed to be fixed in newer releases. The Linux version of mcs from MONO 1.0 (also MONO 1.0.1 or MONO 1.0.2) also cannot generate debugger symbols. The output assembly is bigger than the one compiled without them, but this is all that actually happens. The MONO team promised to provide a debugger by the beginning of 2004. I will keep you informed about the progress of this work. There are some ways around these problems (e.g., use of gdb under Linux), but I have concentrated on the package as-is. An interesting initiative was started by Martin Baulig. He wrote a debugger that can be downloaded from here. The current version is 0.9. The last version of IDE that was released, was version 0.4; the next releases will integrate with MonoDevelop. Based on the considerations listed in this article, several conclusions can be drawn: System.Data SQLClient Still, we have to take into account that MONO is under development. It is a promising alternative where portability is required. However, current releases can be used only for smaller projects. The list below presents the status of particular modules: Commons.RelaxNG Cscompmgd Mono.Data Mono.Data.Tds Mono.Posix Mono.Security Mono.Security.Win32 System.Configuration.Install System.DirectoryServices System System.Drawing System.Runtime.Remoting System.Security System.XML Mono.Cairo Mono.CSharp.Debugger Mono.Data.DB2Client Mono.Data.SqlLite Mono.GetOptions System.Web.Mobile System.Design System.Drawing.Design Formatters.Soap Mono.Data.TdsClient System.EnterpriseServices System.Management System.Messaging System.ServiceProcess System.Web.RegularExpressions This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) [DllImport("wdapi1130", CharSet = CharSet.Ansi)] private static extern IntPtr WD_DriverName(StringBuilder sName); General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. News on the future of C# as a language
http://www.codeproject.com/Articles/13434/MONO-an-alternative-for-the-NET-framework?fid=280342&df=90&mpp=25&sort=Position&spc=Relaxed&noise=1&prof=True&view=None
CC-MAIN-2014-10
refinedweb
6,964
51.34
A basic (?) problem with addresses (gcc) Discussion in 'C Programming' started by Piotrne, Dec Basic question about casting and addressesdrowned, Aug 2, 2003, in forum: C++ - Replies: - 4 - Views: - 429 - Rolf Magnus - Aug 3, 2003 gcc 2.95 and gcc 3.2, Mar 14, 2005, in forum: C++ - Replies: - 8 - Views: - 503 Problem with basic templates on GCCWinbatch, Mar 16, 2005, in forum: C++ - Replies: - 13 - Views: - 621 - HappyHippy - Mar 16, 2005 C99 structure initialization in gcc-2.95.3 vs gcc-3.3.1Kevin P. Fleming, Nov 6, 2003, in forum: C Programming - Replies: - 2 - Views: - 726 - Kevin P. Fleming - Nov 6, 2003 Physical Addresses VS. Logical Addressesnamespace1, Nov 29, 2006, in forum: C++ - Replies: - 3 - Views: - 978
http://www.thecodingforums.com/threads/a-basic-problem-with-addresses-gcc.740181/
CC-MAIN-2015-18
refinedweb
119
63.8
JPA: Creating a object from a query The JPA allow us to create objects inside a query, just with the values that we need: package com.model; public class PersonDogAmountReport { private int dogAmount; private Person person; public PersonDogAmountReport(Person person, int dogAmount) { this.person = person; this.dogAmount = dogAmount; } public int getDogAmount() { return dogAmount; } public void setDogAmount(int dogAmount) { this.dogAmount = dogAmount; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } } package com.main; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; import com.model.PersonDogAmountReport; public class Page13 { @SuppressWarnings('unchecked') public static void main(String[] args) { CodeGenerator.startConnection(); CodeGenerator.generateData(); EntityManager em = CodeGenerator.getEntityManager(); Query query = em.createQuery('select new com.model.PersonDogAmountReport(p, size(p.dogs)) from Person p group by p.id'); List<PersonDogAmountReport> persons = query.getResultList(); for (PersonDogAmountReport personReport : persons) { System.out.println(personReport.getPerson().getName() + ' has: ' + personReport.getDogAmount() + ' dogs.'); } CodeGenerator.closeConnection(); } } Notice that inside our query we create a new object. The good news is that you can create any object, it does not need to be an entity. You just need to pass the full path of the class and the JPA will handle new class instantiation. This is a very useful functionality to use with reports that you need of specifics fields but those fields do not exists in the entity. JPQL: Bulk Update and Sometimes we need do execute an operation to update several rows in a table database. E.g. update all persons with the age higher than 70 and define than as elderly. You can run a Bulk Update/Delete like this: package com.main; import javax.persistence.EntityManager; import javax.persistence.Query; import com.model.Person; public class Page14 { public static void main(String[] args) { CodeGenerator.startConnection(); CodeGenerator.generateData(); EntityManager em = CodeGenerator.getEntityManager(); em.clear(); Query query = em.createQuery('update Person p set p.name = 'Fluffy, the destroyer of worlds!''); query.executeUpdate(); query = em.createQuery('select p from Person p where p.id = 4'); Person person = (Person) query.getSingleResult(); System.out.println('My new name is: ' + person.getName()); query = em.createQuery('delete from Person p where p.dogs is empty'); query.executeUpdate(); query = em.createQuery('select p from Person p'); System.out.println('We had 6, but was found ' + query.getResultList().size() + ' persons in the database'); CodeGenerator.closeConnection(); } } The cascade option will not be triggered in this scenario; you will not be able to delete an object and hope that the JPA will delete the cascaded objects in the relationship. The database data integrity belongs to the Developer once we talk about bulk operations. If you want to remove an object from the database and its relationships you need to update the object setting the relationship to null before executing the delete. We can define this kind of operation as a very dangerous operation. If we comment the line 17 (“em.clear(); “), we will see that the name of the person stills the same after the update. The “problem” is that the Persistence Context keeps all the data in memory “attached”, but these kinds of bulk operations do not update the Persistence Context. We will have an operation done in our database but was not reflected at our Persistence Context yet. This kind of situation could give us synchronization problems. Picture the following scenario: - A transaction is started. - Person A is persisted in the database through the method em.persist(). - Person B has its name updated to “Louanne” through the method em.merge(). - Person A will be removed by a bulk delete. - Person B has its name updated to “Fernanda” by a bulk update. - Transaction finishes. What would happen in this scenario? The Person A was removed by the bulk operation but the Persistence Context will try to persist it the database. The Person B had its name updated to Fernanda but the Persistence Context will try to update to Louanne. There is no default behavior for kind of situation, but there are solutions that we can use to avoid these problems: - Start a new transaction before the bulk operation: With a new transaction started just to the bulk operation, when this operations finishes the updates/deletes will be executed in the database. You will not have an entity manager trying to use data that has not been written to the database yet. - Call the “entityManager.clear()” method before the bulk operation: if you invoke this method you will force the Persistence Context to release all cached data. After the bulk operation if you use the find method, the Persistence Context will get the data from the database because you cleaned the cached data before the bulk operation. Invoke the clear() method is not a silver bullet, if you use it too many times it can give you performance problems. If your Persistence Context has a lot of cached objects and you invoke the clear() method, your Persistence Context will have to do a lot of “trips” to get the needed data again. The Persistence Context has a wonderful data cache control and should take advantage of it. The bulk operations are an option that will help us in several situations, but you must use it carefully. JPA: Criteria JPA is a good framework do run your queries, but Criteria it is not a good way of doing queries with JPA. JPA Criteria is too much verbose, complicated and it need too much code to do some basic queries. Unfortunately it is not easy as Hibernate Criteria. The code bellow will show an easy Criteria code, but we will not see more of this subject. I already read 3 books about EJB/JPA and not a single one book talked about it. The code bellow has a criteria code: package com.main; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaQuery; import com.model.Person; public class Page15 { @SuppressWarnings({ 'unchecked', 'rawtypes' }) public static void main(String[] args) { CodeGenerator.startConnection(); CodeGenerator.generateData(); EntityManager em = CodeGenerator.getEntityManager(); CriteriaQuery criteriaQuery = em.getCriteriaBuilder().createQuery(); criteriaQuery.select(criteriaQuery.from(Person.class)); List<Person> result = em.createQuery(criteriaQuery).getResultList(); System.out.println('Found ' + result.size() + ' persons.'); CodeGenerator.closeConnection(); } } I am sorry to say what I think about Criteria like this here, but at this point I do not see simplicity to use Criteria in your code unless for A ListALL. The code above code easily applied to a Generic DAO, it would be easier to list all objects by it. The following link shows a Generic DAO in an application: Full WebApplication JSF EJB JPA JAAS. The end! I hope this post might help you. You will not need to edit any configuration to run the code of this post, just import it to the Eclipse. If you got any doubt/comment just post it bellow. See you soon. Useful Links: - - - Pro EJB 3: Java Persistence API, Mike Keith, Merrick Schincariol - Enterprise JavaBeans 3.0 – Richard Monson-Haefel, Bill Burke Reference: JPA Queries and Tips from our JCG partner Hebert Coelho at the uaiHebert blog. The reason why I like to use CriteriaQuery is when you need to generically create SQL based on multiple filtering rules. Criteria beats hand-written JPA queries hands down in those cases Hello Milan, do you know EasyCriteria? Is a framework (Open Source) that helps with JPA Criteria. It makes easier to handle the JPA Criteria and keep you code cleaner and less verbose. =D Thanks for sharing your knowledge. I have read the full series and i had learned new ways to create queries, but i dont know how you are avoiding SQL injection with the code that you provide. I think i need to learn more! thanks anyway
http://www.javacodegeeks.com/2012/07/ultimate-jpa-queries-and-tips-list-part_7092.html/comment-page-1/
CC-MAIN-2016-07
refinedweb
1,281
51.24
TimerAlarm(), TimerAlarm_r() Send an alarm signal Synopsis: #include <sys/neutrino.h> int TimerAlarm( clockid_t id, const struct _itimer * itime, struct _itimer * otime ); int TimerAlarm_r( clockid_t id, const struct _itimer * itime, struct _itimer * otime ); Arguments: - id - The timer type to use to implement the alarm;. - itime - NULL, or a pointer to a _itimer structure that specifies the length of time to wait. - otime - NULL, or a pointer to a _itimer structure where the function can store the old timer trigger time. Library: libc Use the -l c option to qcc to link against this library. This library is usually included automatically. Description:. Returns: The only difference between these functions is the way they indicate errors:.
https://developer.blackberry.com/playbook/native/reference/com.qnx.doc.neutrino.lib_ref/topic/t/timeralarm.html
CC-MAIN-2020-34
refinedweb
114
63.7
RSI Strategy RSI Strategy Hey, nice work. Two suggestions: 1. Try mean-reversion strategies for other equities than SPY? The reason for this is that SPY in particular is somewhat slow-moving. Maybe try an equity with a bit more volatility, and you could see much greater returns. 2. Are you sure that 10/200 are the best long/short windows? I suggest you try something like this to find the best. Sorry, I actually meant that you should try your RSI strategy with equities other than SPY. But mean-reversion is good too. :-) The results should be similar, I think. Hello I'm new. I'm looking to run your strategy but i got an error : Runtime exception: NameError: name 'ta' is not defined LINE 8 Where I'mwrong? Thanks That algorithm was written on the old version of Quantopian, which is why it won't run as is. Here it is compatible with Qver2 You can see from 2012 it has 1+ beta and no alpha -- it simply goes long SPY and uses a little bit of leverage to outpace it until Oct 20, 2014 when it makes a mistake and shorts SPY while SPY is still bullish. Out of sample, it performed well -- it went to cash to avoid 2015 and 2016 drawdown periods, which is good -- most algorithms fail out of sample -- but it also doesn't make any gains there either. I wouldn't recommend trading this algo, but its signal might be useful to determine how much market exposure or risk to allow another algorithm to take, or to dynamically adjust its parameters. (IE, if algorithm performs well in a bull market with one set of settings, and performs well in uncertain markets with another set of settings.) Then again, this algorithm buys and sells so infrequently it's hard to draw any strong statistical conclusions. Viridian Hawk, Almost the same, but long only plus bond: import talib def initialize(context): schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_open(minutes = 1)) def my_rebalance(context, data): # ----------------------------------------- stock, bond = symbol('SPY'), symbol('IEF') ma_f, ma_s, rst_period, LB = 10, 200, 3, 10 # ----------------------------------------- if get_open_orders(): return price = data.current(stock,'price') mavg_f = data.history(stock, 'price', ma_f,'1d').mean() mavg_s = data.history(stock, 'price', ma_s,'1d').mean() hist_rsi = data.history(stock, 'price', rst_period + 1,'1d') rsi = talib.RSI(hist_rsi, rst_period)[-1] stock_position = context.portfolio.positions[stock].amount if all(data.can_trade([stock, bond])): if price > mavg_s and rsi < LB and stock_position == 0: order_target_percent(stock, 1.0) order_target(bond, 0) elif price > mavg_f and (mavg_f < mavg_s*1.015) and stock_position > 0: order_target(stock, 0) order_target_percent(bond, 1.0) record(leverage = context.account.leverage) ''' Total Returns 393.1% Benchmark Returns 268.2% Alpha 0.09 Beta 0.25 Sharpe 1.01 Sortino 1.44 Volatility 0.11 Max Drawdown -17.11% 100000 START 11/01/2002 END 08/03/2017 '''
https://www.quantopian.com/posts/rsi-strategy
CC-MAIN-2018-17
refinedweb
478
61.33
How WINS Technology Works Updated: March 28, 2003 Applies To: Windows Server 2003, Windows Server 2003 R2, Windows Server 2003 with SP1, Windows Server 2003 with SP2 In this section - NetBIOS Overview - WINS Architecture - WINS Protocol - WINS Processes and Interactions - Related Information Windows Internet Name Service (WINS) is a name resolution service that maps NetBIOS names to IP addresses in networks that use NetBIOS over TCP/IP (NetBT). As such, the primary purpose of WINS is to support clients that run older versions of Windows and applications that use NetBIOS. In earlier versions of Microsoft operating systems, NetBIOS names were required for locating network resources. In Microsoft Windows NT 4.0, for example, clients used NetBIOS to locate Windows NT 4.0 domain controllers, as well as for file and print sharing. Therefore, WINS is required for name resolution in network environments that include computers running Windows versions earlier than Windows 2000. WINS is not required in a network that consists entirely of computers running Windows 2000, Windows XP, Windows Server 2003, or other TCP/IP-based systems, such as most versions of UNIX, that fully support the use of Domain Name System (DNS) names. If NetBIOS and, consequently, WINS are eliminated from such an environment, however, any applications and services that depend on NetBIOS, such as the Computer Browser service, will not function. Organizations that need to continue to support older versions of Windows still rely on NetBIOS and WINS. WINS can be used in conjunction with DNS, which resolves domain names, to connect to any network resource by referencing the resource’s user-friendly name. Used in conjunction with Dynamic Host Configuration Protocol (DHCP), WINS supports dynamic IP address assignments, thus eliminating the administrative burden of maintaining static IP addresses. This section describes how WINS works in a properly configured environment, which includes the following: - NetBT is enabled. - DNS is configured correctly. - DHCP is configured correctly. - The network, including routers, is configured to handle name resolution traffic. - WINS-configured servers are designed with sufficient CPU, memory, and hard disk space to handle WINS activity. The following sections describe WINS components, how they fit in a network environment, and how NetBIOS name resolution processes work. NetBIOS Overview An understanding of NetBIOS is essential to understanding WINS. In the OSI reference model, NetBIOS is a session-layer protocol. Applications use this protocol to communicate over NetBIOS-compatible transports. NetBIOS and applications that use NetBIOS can run over both TCP/IP and Internetwork Packet Exchange (IPX). When it runs over TCP/IP, NetBIOS is commonly referred to as NetBT. RFCs 1001 and 1002 define the functions and features of three NetBIOS services in a TCP/IP environment: name service, session service, and datagram service. The name service encompasses registering NetBIOS names, renewing and releasing names, and resolving NetBIOS names to IP addresses. WINS is the Microsoft implementation of a NetBIOS name server (NBNS), as defined by the RFCs. The other two services are beyond the scope of this section. NetBIOS Names RFCs 1001 and 1002 provide for 16-byte NetBIOS names. The first 15 characters of a NetBIOS name are user-definable. Windows reserves the sixteenth character for a name suffix. The user-definable portion of a NetBIOS name cannot begin with an asterisk (*). Use of extended characters, the underscore (_) and period (.) in particular, can result in name resolution errors in environments that also use DNS name resolution. NetBIOS names are not case-sensitive. The name suffix, the final byte of a NetBIOS name reserved by Windows, specifies the resource type. A WINS client can use the suffix to identify the specific service it needs to access. That is, a WINS client can construct the NetBIOS name based on a computer, user, or domain name and append the suffix to locate a specific resource on that computer. For example, the Messenger service has a suffix of 0x03. To send a message to COMPUTER42, the client sends a message to the Messenger service on COMPUTER42 by specifying the following NetBIOS name: In the full 16-character name notation, the first 15 characters are padded with spaces, if necessary. A NetBIOS name can be a unique name, which means it maps to a single IP address, or a group name, which means it maps to multiple IP addresses. For example, each computer that runs Windows Server 2003 has a Server service for sharing files and a Workstation service for accessing the files shared by the Server service. These services each have a unique NetBIOS name, so client computers can locate the appropriate server and use the file-sharing service. On the other hand, the domain controllers within a single domain share a group name. The following table describes some of the NetBIOS name suffixes used by Windows Server 2003. The suffixes are listed in hexadecimal format. Other applications, such as Microsoft Exchange and Microsoft Systems Management Server (SMS), register NetBIOS names with different suffixes. Common Windows NetBIOS Name Suffixes The NetBIOS namespace is flat, which means that names can be used only once within a network. By contrast, DNS uses fully qualified domain names (FQDNs), which combine a host name with the hierarchical name of its domain. For example, a NetBIOS name of WINSserver01 might be an FQDN of WINSserver01.reskit.com. Being able to use a NetBIOS name only once within a network can be a restriction with imposing implications for large networks. Using a NetBIOS scope, as described in RFC 1001, is one solution to this situation. A character string, known as the scope identifier, works something like a domain name in DNS and defines the population of computers across which a registered NetBIOS name is known. The scope identifier is appended to NetBIOS names during name services processes. However, the meaning of scope varies based on the NetBIOS node. For example, the scope for B-node includes all the NetBIOS nodes in the local subnet, the scope for P-node includes all the NetBIOS nodes in the routed network that use the same NetBIOS name service, and the scope for M-node and H-node is an intersection of the B-node and P-node scopes. (NetBIOS nodes are defined later in this section.) This situation causes name resolution problems in environments that use more than one type of NetBIOS node. Because only NetBIOS nodes that use the same scope ID can resolve each other’s names, the use of different scope IDs can create communication problems. Therefore, use of the scope identifier is discouraged in Windows Server 2003. NetBIOS Nodes Client computers use NetBIOS name services to register, renew, and release names and to query and resolve IP addresses for network resources. NetBIOS session and datagram services use these name services to locate resources. For example, if a user wants to map a network drive to a file share on a remote computer by using Windows Explorer, the user types the remote computer name and share name in the Map Network Drive window. Windows Explorer uses NetBIOS name services to obtain the remote computer's IP address and then establishes a NetBIOS session over which a file-sharing session is established to access the shared resource. NetBIOS name services are carried out either by using IP broadcasts or by using a NetBIOS name server. Broadcasts are appropriate in single-subnet local area networks (LANs), but rapidly cause administrative problems in multiple-subnet networks. A NetBIOS name server is the desirable alternative for larger networks. To allow for various sizes of networks, RFCs 1001 and 1002 use the concept of node type to determine the specific method a computer uses to perform name services. The following table describes the four NetBIOS node types. NetBIOS Node Types The default node type for Windows-based WINS clients is B-node. When a computer is configured to use a WINS server, whether manually or through DHCP, it becomes H-node. The other NetBIOS node types are configured through DHCP by configuring the WINS/NBT Node Type option for a DHCP client. Because B-node is based on broadcasts, it does not scale beyond a single subnet. Configuring routers to forward NetBIOS broadcasts also does not scale well and is not recommended. To address these limitations of RFC-compliant B-node, Microsoft extended B-node for name service operations. Microsoft’s extension, known as modified B-node, adds the following two name lookup facilities: NetBIOS name cache An in-memory cache of recently resolved NetBIOS names that can be searched before attempting other name resolution methods. LMHosts file A flat file, located in systemroot\System32\Drivers\Etc, that contains a static list of NetBIOS names and their IP addresses. This file does not exist by default. WINS Architecture The WINS service is Microsoft’s implementation of a NetBIOS name server. WINS consists of two primary components: WINS servers and WINS clients. Each WINS server includes a dynamic database of NetBIOS name-to-IP address mappings. WINS clients communicate with a WINS server to register their NetBIOS names in the WINS database and to query the WINS database to resolve the IP addresses associated with other NetBIOS names. A special kind of WINS client is the WINS proxy. WINS proxies support NetBIOS name services in a limited way for client computers that are not WINS-enabled. The following figure illustrates how WINS components fit in a network environment. WINS Component Configuration This example shows two subnets (Subnet 1 and Subnet 2) that include WINS clients. The third subnet (Subnet 3) includes B-node clients and a WINS proxy to act on the behalf of the B-node clients during name service requests. There are two WINS servers, each of which contains a WINS database. The WINS components illustrated in the figure are described in the following table. WINS Components WINS Servers A WINS server handles name registration requests from WINS clients by registering their names and IP addresses, provided the requested unique name is not in active use. It also responds to NetBIOS name queries submitted by clients by returning the IP address of a queried name if it is listed in the WINS database. Either local clients (on the same subnet as the WINS server) or remote clients (across a router from the server) can register with a WINS server. When a WINS-enabled client starts on the network, it sends its name and IP address in a registration request directly to its configured primary WINS server. The WINS server that registers the NetBIOS name of the client in its database is said to be the owner of the WINS name entry. WINS servers can replicate the contents of their databases to other WINS servers. Primary and Secondary WINS Servers WINS servers can act as either a primary WINS server or a secondary WINS server to a client. The difference between primary and secondary WINS servers is simply the priority in which clients contact them. A primary WINS server is the first server a client contacts to perform its NetBIOS name service operations. A client contacts a secondary WINS server only when a primary WINS server is unable to fulfill the request, for example if it is unavailable when the client makes the request or unable to resolve a name for the client. If a primary WINS server fails to fulfill a request, the client makes the same request of its secondary WINS server. If more than two WINS servers are configured for the client, the client tries the additional secondary WINS servers until the list is exhausted or one of the WINS servers successfully responds to the request. After a client uses a secondary WINS server, it periodically tries to switch back to its primary WINS server for future name service requests. WINS Clients WINS clients are computers that are configured to make direct use of a WINS server. WINS clients attempt to register their names with a WINS server when they start or join the network. Thereafter, they query the WINS server to resolve NetBIOS names as needed. WINS clients communicate with WINS servers to: - Register client names in the WINS database. - Refresh client names in the WINS database. - Release client names from the WINS database. - Resolve names by obtaining name-to-IP address mappings from the WINS database. Most WINS clients typically have more than one NetBIOS name that they must register for use with the network. These names are used to publish various types of network services, such as the Messenger or Workstation services, that each computer can use to communicate with other computers on the network. WINS client computers are configured with either static or dynamic IP addresses. Clients that use static IP addresses are manually configured with a set of specific WINS servers. Clients that use dynamic IP addresses use the WINS/NBNS Servers option in DHCP to specify the WINS servers. For Windows 2000, Windows XP, and Windows Server 2003, WINS clients can be configured with up to 12 secondary WINS servers. This feature is useful in an environment in which there are many mobile clients, many NetBIOS-based resources, and services are used often. In such an environment, updates to the WINS database might not be replicated throughout the network of WINS servers at the time of a request, and it can be helpful for clients to be able to query more than two WINS servers. Clients use the additional server addresses only if the primary and secondary servers fail to respond. WINS clients running any of the following versions of Windows can communicate with a WINS server running Windows Server 2003: - 32-bit versions of the Windows Server 2003 family - 64-bit versions of Windows Server 2003, Datacenter Edition and Windows Server 2003, Enterprise Edition - 32-bit versions of Windows XP Professional and Windows XP Home Edition - 64-bit version of Windows XP Professional - Windows Millennium Edition - Windows 2000 Professional; Windows 2000 Server; Windows 2000 Advanced Server; and Windows 2000 Datacenter Server - Windows NT Workstation 4.0 and Windows NT Server 4.0 - Windows 98 - Linux and UNIX clients (with Samba installed) Clients that are not WINS-enabled can participate in name registration and resolution processes in a limited way by using WINS proxies. WINS Proxies A WINS proxy is a WINS client that can perform limited NetBIOS name services, such as registration, release, and resolution, on behalf of other non-WINS clients that are on a routed TCP/IP network. Typically, older NetBIOS clients that are not, or cannot be, configured to use WINS are B-node clients. These computers use broadcasts to register their NetBIOS names on the network and to resolve NetBIOS name queries. Computers configured for B-node cannot use WINS directly because WINS servers do not respond to broadcasts. A WINS proxy can listen on the local subnet for B-node name query broadcasts and respond for the names that are not on the local subnet. WINS proxies communicate with a WINS server by using unicast datagrams. RCF 1001 recommends against using B-node name resolution in a routed network, but in practice, the B-node NetBIOS node type is sometimes useful and sometimes cannot be removed or updated. Microsoft designed WINS proxies to support B-node clients in a routed network. WINS Database The WINS database resides on the WINS server. It stores NetBIOS name-to-IP address mappings for the network. WINS clients use this mapping information to connect with other network resources. NetBIOS names are registered in the WINS database whenever a network resource becomes available for use, for example when a computer starts up. Therefore, the contents of the WINS database change over time as computers join and leave the network. The size of the WINS database depends on the number of WINS clients in the network and the number of NetBIOS names each uses. Unique name entries typically are 42 bytes. Internet group entries can include up to 25 addresses and, therefore, are longer entries. The databases on all WINS servers in a network are about equal in size. All the databases have the same number of NetBIOS name entries, except for those pending replication. The actual size of the database, however, can be much larger than the number of entries, because space is not automatically reclaimed when unused records are deleted. WINS database compaction recovers the unused space. Windows Server 2003 provides both dynamic and manual database compaction. The manual database compaction is most efficient, but requires the database to be offline. The dynamic database compaction runs during idle time after a database update and allows the database to remain online. The use of multiple WINS servers in a NetBIOS environment provides redundancy and load balancing. When multiple WINS servers are used, updates to a WINS database replicate among the WINS servers designated as replication partners until the updates are in all the WINS databases in the network. Although each name entry is eventually replicated to all other WINS databases, a name entry is said to be owned by the WINS server that originated the entry. WINS servers running Windows Server 2003 can replicate with WINS servers running earlier versions of Windows. WINS Database Files The Windows Server 2003 WINS database uses the Extensible Storage Engine (ESE). This database imposes no limit on the number of records that a WINS server can store or replicate. WINS uses the Jet database format for storing its data. Jet produces the Jn.log and other files by default in the systemroot\System32\Wins folder. The files that are created and used by the database on each WINS server are described in the following table. WINS Server Database Files To increase speed and efficiency of data storage, current transactions are written to log files rather than directly to the database. Therefore, the most current view of the data includes both the database and any transactions in the log files. Both the database and the log files are used for recovery if the WINS service abruptly or unexpectedly stops. If the service stops in an unexpected manner, the log files are automatically used to re-create the correct state of the WINS database. Name Data Name entries in the name-to-IP address mapping table include data used during name query requests, as well as data used to age and replicate the entries. Data used for name service requests or for aging and replicating entries is described in the following table. Name Data WINS Time Intervals Name entries in the WINS database have time stamps that determine when specific aging activities are to take place. WINS uses four configurable time intervals to calculate the time stamps. The following table describes the four time intervals. WINS Time Intervals The Windows Server 2003 defaults provided for these values take the following into consideration: - Minimized level of network traffic - Minimized load on WINS servers - Various configurations in which WINS servers might be deployed - Minimized window between replications - Exceptional conditions, such as long weekends and large volumes in worst-case scenarios Server Clocks Replication and scavenging (database cleanup) algorithms rely on a reasonably consistent system clock. Setting the system clock forward or backward affects these algorithms. However, because time stamps are always entered locally, the WINS servers do not need to be time-synchronized. WINS Protocol The WINS protocol is based on, and is compatible with, the protocols defined for NetBIOS name services specified in RFCs 1001 and 1002. Therefore, WINS is compatible with any other implementation of these RFCs. That is, another RFC-compliant implementation of the client can communicate with a WINS server. Similarly, a Microsoft TCP/IP client can communicate with other implementations of an NBNS. To provide scalability for larger networks, however, the WINS implementation of NBNS supports replication of the WINS database between WINS servers. WINS replication is Microsoft proprietary technology, so WINS replication is not compatible with other NBNS implementations. This section briefly describes the format of NetBIOS packets and the ports used by NetBIOS. NetBIOS name services packets NetBIOS name service packets consist of messages sent between a WINS client and a WINS server. These message packets are similar in structure to DNS packets, but with additional types and codes for NetBIOS. The high-level format of name services packets is described in the following table. Name Services Packet Format Each name service packet contains a header and one or more additional entries. The sections included for a packet depend on the message. The format of name service packets used by Windows Server 2003 is compatible with the specification provided in RFC 1002. For a detailed description of packet fields, see RFC 1002. WINS ports The ports listed in the following table are used by specific WINS services. WINS Port Assignments The WINS client and WINS Server services listen on User Datagram Protocol (UDP) port 137. UDP is an unreliable transport protocol in that it does not establish a session or connection between the sender and the receiver. Because of this, it is possible for more requests than responses to be sent. That is, a client might need to send a request multiple times before it receives a response. However, a client never receives more than one response to a request. WINS Processes and Interactions WINS clients communicate with WINS servers for NetBIOS name services. WINS servers communicate with other WINS servers for WINS database replication. WINS servers also periodically run a process to identify and clean up extinct names in the WINS database. NetBIOS name services include four types of processes between a WINS client and a WINS server. The following table briefly describes these processes, which are discussed in more detail in the following sections. NetBIOS Name Service Processes Clients that are not configured to use WINS can also participate in these processes to a limited extent by using a WINS proxy. The remainder of this section describes what happens during typical and WINS proxy name service processes, the scavenge process, and the replication process. Name Registration Before a NetBIOS name can be resolved in a WINS environment, it must be registered with a WINS server. For example, when a WINS client starts up, it sends a name registration request to the WINS server for each NetBIOS name it uses. A name registration request can be for a unique name (maps to a single IP address) or for a group name (maps to multiple IP addresses). As illustrated in the following figure, a WINS client (ClientC) sends a name registration request directly to its configured WINS server, WINSA. Name Registration In this example, ClientC sends a name registration request to its configured primary WINS server, WINSA. WINSA adds an entry for ClientC, with its IP address, in the WINS database and sends a positive reply back to ClientC. Registering a unique NetBIOS name by using a WINS server works as follows: - When a network resource starts up, the WINS client sends a name registration request, which includes the NetBIOS name and IP address, to its configured WINS server. - The WINS server checks to see if the name has already been registered, and if so, whether it is in active use. The WINS server sends a Wait for Acknowledgment (WACK) message to the WINS client while it attempts to determine whether the name can be registered. - If the name is not in use, the server adds the NetBIOS name and IP address to the WINS database and sends the client a positive name registration reply, which includes a TTL value that determines when the name will expire. - If the name is in active use, the WINS server does not add the name and address to the WINS database and sends the WINS client a negative name registration reply. The precise process for registering NetBIOS names depends on the client's node type. B-node clients use broadcasts instead of WINS servers to register names. M-node and H-node clients combine the use of broadcasts and WINS P-node clients use only WINS. Because WINS servers do not respond to broadcasts, the actions described in this section do not apply to broadcast registration. The following table describes the results of WINS server replies. WINS Server Replies Name Conflicts During a NetBIOS name registration request, a WINS server verifies that the requested name is not a duplicate of a NetBIOS name already in use in the network. The WINS server first determines whether the name exists in the WINS database. If the name is already registered, the WINS server determines whether the name is in active use or whether it is available. A variety of factors determine whether the name is available. In some cases, a WINS server can determine from the database entry whether a NetBIOS name is active. If the WINS server cannot determine in this way whether the name is active, it might need to challenge the name. To challenge a name, the WINS server sends a name query request to the WINS client that registered the name. If the name is active, the WINS client that registered the name sends a name query response and is said to defend the name. The following factors influence the action taken by a WINS server when resolving a name conflict: - Whether the name is a unique name or a group name. - The state of the registered name. A registered name can be active, released, or extinct. - Whether the name is owned by the WINS server handling the registration request or another WINS server. - Whether the IP address is the same or different from the IP address specified in the name registration request. - Whether the name is statically or dynamically added to the WINS database. Names with different IP addresses If a WINS client sends a name registration request for a unique name that already exists in the WINS database, but with a different IP address, the WINS server first checks the status of the existing name. If the name is in a released or extinct state, the WINS server treats the request as a new registration and sends a positive name registration reply to the WINS client requesting the name. If the database status of the existing name is active, the WINS server determines whether the unique name is still in use by sending a challenge to the WINS client that registered the name, as illustrated in the following figure. Name Challenge In this example, the following steps take place: - A WINS client (ClientA at IP address 192.168.0.17) sends a name registration request to its configured primary WINS server (WINSA). - WINSA finds the unique name “ClientA” with a different IP address in the WINS database. WINSA sends a Wait for Acknowledgement (WACK) message to the requesting WINS client. The WACK message includes the estimated time of the wait in the TTL field. WINSA then sends a name query request to the WINS client at IP address 192.168.0.20. WINSA waits 500 milliseconds between challenges, and if ClientA is multihomed, WINSA tries each IP address. If WINSA receives no response from the first challenge, it makes two additional attempts. - The name ClientA is still in active use, so the WINS client sends a name query response back to WINSA. - WINSA then sends a negative name registration response back to the requesting WINS client. If the registered name “ClientA” was no longer in active use, no name query response would be sent, and WINSA could send a positive name registration response to the requesting WINS client. Names with the same IP address If a WINS client sends a name registration request for a unique name with the same IP address as one that already exists in the WINS database, the action a WINS server takes depends on the status and ownership of the existing name, as follows: - If the registered name has a status of active and is owned by the WINS server handling the new registration request, the WINS server sends a positive name registration reply to the WINS client making the request. - If the registered name has a released or extinct status, or if it is owned by a different WINS server, the WINS server treats it as a new registration: it sends a positive name registration reply to the WINS client making the request and takes ownership of the name. Group names Group names are handled differently than unique names. A group name can be a normal group name or a special (also known as Internet) group name. Normal group names can have many associated IP addresses, but the member addresses are not stored in the WINS database. WINS responds to a name query for a normal group name with the limited broadcast address 255.255.255.255. Routers do not forward packets addressed to the limited broadcast address, so special groups were developed to support communications between subnets. Special groups are used for special, user-defined administrative groups. For example, a special group can be used to group resources such as file servers or printers. Special groups are associated with multiple IP addresses. A WINS server handles name conflicts for a group name as follows: - If a WINS client sends a unique name registration request that conflicts with a registered normal group name, a WINS server always sends a negative name registration reply. - If a WINS client sends a name registration request for a special group name, a WINS server always sends a positive name registration reply, adding the requested name as an additional member of the group. In this situation, if the existing name has a state of released or extinct, the name registration request is treated as a new registration. - If a WINS client sends a name registration request for a DomainName[1D] name, a WINS server always returns a positive registration response, even though the WINS server does not add this name to the WINS database. When a WINS client queries a WINS server for this type of name, the server responds with a broadcast address, which forces the WINS client to broadcast to resolve the name. Static names In addition to supporting dynamic name registration, WINS supports static name registration for computers that do not directly communicate with WINS. Static names are added manually to the WINS database with the WINS Microsoft Management Console (MMC) snap-in or with the netsh wins server add name command. Static names do not automatically age and drop from the WINS database like dynamically-added names do. Static names remain in the database indefinitely unless there is manual intervention. If a WINS client sends a name registration request for an existing static name, a WINS server by default always sends a negative name registration reply. This behavior can be overridden to always send a positive name registration reply. Positive Name Registration Replies When a WINS server sends a WINS client a positive name registration reply for a name that does not yet exist, it adds the name entry to the WINS database as follows: - Calculates time stamp by adding current time to the renew interval - Takes ownership - Sets state to active - Assigns a new version ID When a WINS server sends a WINS client a positive name registration reply for a name and IP address that already exist in the WINS database, it updates the name entry in the WINS database. The following table describes the database updates for unique, dynamic name registrations. Note - A WINS server does not update existing database records for normal group entries or static entries because the server returns negative name registration replies for these types of name conflicts (unless the default behavior for group entries is overridden). Name Registration Database Updates The time stamp is calculated as the sum of the current time and the renew interval. Changes that increment the version ID are replicated to all other WINS servers. Burst Handling High-volume (burst) server loads occur when a large number of WINS clients simultaneously attempt to register their names with a WINS server, such as when power is restored after an outage. A WINS server can use burst mode to respond positively to client requests before it processes and updates the WINS database. Burst mode uses a configurable burst-queue size as a threshold value. This value specifies how many name registration and name renewal (also known as refresh) requests a WINS server processes normally before it starts burst-mode handling. By default, the value is 500. When the number of name registration and refresh requests exceeds the threshold value, a WINS server initiates burst mode. During burst mode, a WINS server immediately responds to registration and refresh requests with a positive response that includes a very small TTL. The TTL value included in the response varies for different clients to distribute the actual registration load over time. This process slows the refresh and retry rate for new WINS clients and regulates the amount of WINS client network traffic. For example, if the burst queue size is 500 entries and more than 500 requests are active, the WINS server replies immediately to the next 100 WINS registration and refresh requests by sending immediate positive responses, with a starting TTL value of 5 minutes. For each additional round of 100 client requests, the WINS server adds 5 minutes to the TTL, up to a maximum of 50 minutes. If WINS client traffic still arrives at burst levels, the WINS server responds to the next round of 100 client requests starting again with a TTL value of 5 minutes. The WINS server continues to increment the TTL until it reaches its maximum intake of 25,000 requests. At 25,000 requests, the WINS server begins dropping requests. During burst handling, name release requests are queued along with name registration and refresh requests. When the queue becomes full, however, release requests are silently dropped. In this case, the names are released when their TTL expires. Name query requests are queued indefinitely during burst handling. Name Renewal Dynamic NetBIOS names are not owned permanently. When a WINS server successfully registers a name, it sends the WINS client a positive name registration reply with a TTL value that specifies the life span of the name. The default TTL value in Windows Server 2003 is six days. It is the responsibility of the WINS client to renew the name before the TTL expires. If the WINS client does not renew the NetBIOS name before the TTL expires, the state of the name is changed to released, and the WINS server eventually deletes the name from the WINS database, as described later. Static names do not expire, so they do not need to be renewed. To renew a name, a WINS client sends a name refresh request to the WINS server. The WINS server treats name refresh requests similarly to name registration requests, by sending a name refresh reply that includes a new TTL. The following figure illustrates a renewal request. Name Renewal In this example, the WINS client, ClientC, sends a name refresh request to its configured primary server, WINSA. WINSA updates the database entry for ClientC to reflect an active state and sends a positive name refresh reply to ClientC with a new TTL. WINS clients attempt to renew their NetBIOS names when one-half of the TTL value is reached or when the computer or the service restarts. If the WINS server does not respond to the name refresh request, the WINS client continues to try the primary WINS server every 10 minutes for one hour, and then tries the secondary WINS server every 10 minutes for one hour. The process of trying first the primary server for an hour and then the secondary server for an hour continues until the name expires or the WINS server responds and renews the name. Name Release A NetBIOS name is released when it is no longer in active use by the WINS client that registered it. The owning WINS server does not respond to or resolve name queries for these names, unless the WINS client again registers the name. Names can be released actively or passively. Expired names that are not renewed are released passively. WINS clients actively release their NetBIOS names when NetBIOS applications terminate properly, such as when a computer is shut down or a service is stopped, as shown in the following illustration. Name Release In this illustration, the following occurs: - When the computer, ClientC, shuts down properly, it sends a name release request to the WINS server, WINSA. - WINSA changes the state of ClientC's name entry in the WINS database to released, time-stamps the entry with the sum of the current time and the extinction interval, and takes ownership of the of name entry. Note - For active releases in Windows 98, the WINS server makes itself the owner of the name entry, if it is not already. In Windows NT 4.0 and later, if the WINS client sends a name release request to a different WINS server than it registered with, the WINS server changes the name entry to extinct instead of released, as described later in this section. - WINSA sends a positive name release response back to ClientC. When a name entry is changed to the released state, the version ID is not updated and the change is not replicated to other WINS servers. Released name entries are handled differently if the WINS server releasing the name is not the owner of the name entry, as described in the following table. Released Name Handling The different approach for non-owners prevents inconsistencies between primary and secondary WINS servers, because released name entries are not replicated to other servers while extinct name entries are replicated. If a network resource does not shut down properly, or the WINS client is unable to contact the WINS server during shutdown, the name might not be automatically released. The released state simplifies WINS name registration for WINS clients that shut down and then restart. If a name is released, the WINS server does not challenge the name when the network resource restarts. If a proper shut down did not occur and the name is not released, the WINS server challenges the name on the next registration request if the IP address is different, as can happen when a DHCP-enabled laptop changes subnets. In such a case, the challenge fails (because the client cannot defend the old IP address) and the registration succeeds, but the registration requires extra processing. Name Extinction and Deletion When a name entry in the WINS database is marked released and the name is not reregistered, its state progresses to extinct. The name entry is marked with a series of time intervals that determine when the entry changes from released to extinct, and when it can be deleted from the database. The scavenge process checks the time intervals and makes these changes. This process runs automatically, based on the relationship between the configurable renewal and extinction intervals. Name extinction In general, name entries pass through the states described in the following table. Progression of Inactive States Because changing a name entry to the extinct state results in replication, rapid synchronization of WINS databases occurs. The extinct state prevents inconsistencies from lingering. For example, if the primary WINS server of a WINS client is unavailable when the client shuts down, the name release request is directed to the secondary WINS server. If the primary WINS server is available again when the client restarts, the client registers and continues to renew with the primary WINS server, which has not recorded any change in the status of the client, while the secondary WINS server still reflects the released state of the name entry. Name deletion Extinct name entries that have expired extinction time-out intervals are automatically deleted from the WINS database by the scavenge process. Because changing the status to extinct causes name entries to be replicated, replication typically ensures that the name entries are extinct in all copies of the WINS database before any of the entries are deleted, thus ensuring that the name entries are deleted from all copies of the database. Under certain abnormal conditions, however, names no longer in use can remain in the database. For example, if an extinct entry is deleted before it is replicated, the active state of the record in the replica databases never changes. This might happen if a replication copy of the database is not reachable during the extinction time-out period. When an active entry is replicated, it is time-stamped on the pulling server (the WINS server requesting the replication) with the sum of the current time and the verification interval. The default verification interval is 24 days. If the scavenge process determines that there are entries with an expired verification interval, the WINS server sends a name query to the WINS server that owns the name entry to determine whether the version ID is still valid. The following table describes the possible courses of action based on the owning WINS servers response. Verification Interval Evaluation The scavenge process determines which name entries need to be updated or deleted based on ownership, state, and time stamp. This process releases name entries when appropriate, deletes extinct name entries, and verifies whether names are still in use after the verification interval expires. The scavenge process runs periodically based on a scavenging time interval. The scavenging time interval starts at WINS server startup and is half the renew interval (by default, 72 hours). If a WINS server is stopped and restarted before 72 hours have elapsed, the scavenging time interval is reset. If a WINS server is stopped on a daily basis, scavenging does not occur. Scavenging can also be initiated manually. The following table summarizes the changes the scavenge process makes to name entries in the WINS database. Changes to Name Entries During Scavenging During the first scavenging run, all the actions described in the previous table are performed except for deleting name entries. Name entries are not deleted until at least three days after WINS server startup. This delay allows sufficient time for replicating the entries that are ready to be deleted. In addition to the database cleanup that occurs during the scavenge process, database consistency checks verify name entries in the local database and update name entries as necessary to match the owner entry. Version ID consistency checks verify that owner version IDs are higher than replica version IDs at other WINS servers. Name Resolution When a computer needs to communicate with another network resource that uses a NetBIOS name, the computer must first acquire the network resource’s IP address before communications can be established. Name resolution is the process of obtaining the IP address for a NetBIOS name. As the following figure illustrates, the WINS client sends the NetBIOS name to a WINS server, the WINS server sends the IP address back to the client, and then the client uses the IP address to connect to the remote computer. Name Resolution In this figure, ClientA, a WINS client, needs to connect to ClientB. ClientA sends a name query request for the NetBIOS name ClientB to its primary WINS server, WINSA. WINSA finds ClientB in the WINS database and returns the IP address 192.168.1.17 to ClientA, and ClientA then connects to ClientB. The precise steps for resolving a NetBIOS name depend on the client's NetBIOS node type. B-node clients broadcast the name request to the local subnet. P-node clients use a WINS server only. M-node clients first try broadcasting, and if that is unsuccessful, they use a WINS server. H-node clients first try a WINS server, and if that is unsuccessful, they try broadcasting. This section focuses on the WINS server part of the process. WINS clients running Windows 2000, Windows XP, or Windows Server 2003 are configured by default to use DNS first to resolve names that are longer than 15 characters or that have periods (.) within the name. If the client is configured to use a DNS server, DNS is used again as a final option if a WINS query is unsuccessful for names that are less than 15 characters and that do not have periods. For NetBIOS name resolution, a WINS client typically performs the following progression of steps until either the name is resolved or all methods have failed to return an IP address: - Client checks its local NetBIOS name cache of remote names. Recently resolved NetBIOS names (up to 16, by default) are held in this cache for 10 minutes. - Client sends the NetBIOS name query request to its configured primary WINS server. If the primary WINS server fails to respond, either because it is not available or because it does not have an entry for the name, the client tries to contact all other configured WINS servers in the order they are listed in its configuration. - If the client uses H-node, it broadcasts the NetBIOS name query to the local subnet up to three times. (If the client uses M-node, it performs this step before contacting the WINS server (step 2). If the client uses P-node, it does not perform this step.) - Client checks the Lmhosts file, if Lmhosts is enabled in the WINS tab of the advanced TCP/IP properties. - Client converts the NetBIOS name to a host name by removing the last byte and any spaces at the end of the NetBIOS name. - Client checks to see if the host name corresponding to the converted NetBIOS name matches the local host name. - Client checks the DNS client resolver cache. - Client tries a DNS server, if it is configured for one. If the WINS server resolves the name query request, the WINS server sends a positive name query reply that includes the requested IP address to the client. When the client receives the reply, it uses the address to establish a connection to the desired network resource. If the WINS server cannot resolve the name query request or if the request is for a unique name that is in a released or extinct state, it sends a negative name query reply to the client. If none of these steps can resolve the name, Windows returns an error. Name Queries for Normal Groups A normal group name does not have an IP address associated with it, so when a WINS server receives a name query request for a registered normal group name, it cannot return a specific address. Instead, the WINS server returns the limited broadcast address (255.255.255.255). The WINS client then issues a broadcast to its local subnet to resolve the name. If the request is for a normal group name that is in a released or extinct state, a WINS server sends a positive name query reply and also sends the limited broadcast address (255.255.255.255). Name Queries for Special Groups A special group can have multiple IP addresses (up to 25) associated with it. When a WINS server receives a name query request for a special group, it returns all the IP addresses for which the TTL has not expired. Note - The WINS server sends as many addresses as it can fit into a UDP message. Because special groups are limited to 25 addresses, all the addresses fit into the UDP message. WINS Proxy Name Services When a WINS proxy is located on a subnet that includes B-node clients, the WINS proxy can mediate B-node name services requests for registration, release, and resolution by taking the following actions: - Perform a name lookup during name registration and send a negative name registration reply if it finds the name in its local cache of remote names or in the WINS database. - Delete the B-node client name from its cache of remote names, when a client releases its name. - Attempt to resolve a B-node name query request by using information from either its local cache of remote names or from the WINS server. Proxy Support for Name Registration Requests When a B-node client broadcasts a name registration request, the WINS proxy receives the broadcast and then does a name lookup for names that do not exist on the local subnet. First it uses its local cache of remote NetBIOS names, and if the name is not in the cache, the WINS proxy sends a name query request to the WINS server. If the unique name is found in the WINS database, the proxy sends a negative name registration reply to the B-node client. Proxy Support for Name Release When a B-node network resource shuts down, WINS proxies simply delete the name from the local name cache in response to the name release request. Proxy Support for Name Resolution WINS proxies support NetBIOS name resolution for B-node clients. They receive B-node name query broadcasts and respond for names that are not found on the local subnet. The following figure illustrates how a WINS proxy resolves names for non-WINS clients. WINS Proxy Name Resolution In this example, the WINS proxy (ClientB) performs the following steps to resolve names for the B-node client (ClientA): - ClientA broadcasts a NetBIOS name query request to the local subnet (Subnet 1). - ClientB receives the broadcast and checks its cache of remote names for the requested NetBIOS name. The WINS proxy always differentiates name queries for local names from remote names. It compares the address of names it resolves to its own address by using the subnet mask, and if the two match, the WINS proxy does not respond to the name query. - If ClientB locates the NetBIOS name in its cache, ClientB sends a positive name query reply to ClientA with the IP address. - In this example, ClientB cannot locate the NetBIOS name in its cache, so ClientB sends a name query request to the WINS server, WINSA, and enters the requested name in its cache of remote names in a “resolving” state. If ClientB receives another query for the same name before the WINSA responds, ClientB does not query WINSA again. - If WINSA cannot resolve the name, it sends a negative name query reply to ClientB, which in turn sends a negative name query reply to ClientA. - In this example, WINSA can resolve the name, so it sends a positive name query reply with the IP address to ClientB. ClientB updates the cache entry with the IP address and changes the state to resolved. By default, WINS proxies cache remote name mappings resolved by the WINS server for 6 minutes. - ClientB sends a positive name query response to ClientA and uses the name mapping in its cache to respond to subsequent NetBIOS name queries broadcast from any B-node clients on the subnet. A WINS proxy sends reply messages only if the response is already in its cache. Note - When a WINS proxy responds to a query for a multihomed client or for a group record that contains a list of IP addresses, it returns only the first address to the B-node client. Replication Typically, large environments include multiple WINS servers. When multiple WINS servers are used, they can be configured to replicate, or copy, records from one WINS database to other WINS databases. Replication keeps all the WINS databases synchronized and ensures that the names registered on one WINS server are available on all WINS servers. Replication supports the following: - Reduced name services traffic over WANs - Redundancy - Load balancing - Scalability For a WINS server to replicate data, it must be configured with at least one other WINS server as its replication partner. Replication partners are WINS servers that are configured to have a replication relationship with each other. There are three types of replication partners, as described in the following table. Types of Replication Partners A WINS server can be configured to discover its replication partners automatically (known as autodiscovery) or it can be manually configured for specific replication partners. WINS servers periodically announce their presence on the network. The WINS announcements are sent on a multicast address that is reserved for WINS (224.0.1.24). WINS servers that are configured for automatic discovery listen for the announcements and find other WINS servers on the network. Any WINS server discovered this way is automatically added to the replication partners list as a push/pull partner. Regardless of whether servers are configured for one-way replication (push only or pull only) or for two-way replication (push/pull), the primary and secondary WINS servers for a client must have a push and pull relationship to each other to ensure that WINS functions properly if the primary server fails. The following figure illustrates how replication works. Two WINS servers, WINSA and WINSB, are configured to be replication partners. WINS Database Replication In this figure, a WINS client (ClientA) on Subnet 1 registers its name with its primary WINS server, WINSA, and its name is updated in the WINSA database. Another WINS client (ClientB) on Subnet 3 registers its name with its primary WINS server, WINSB, and its name is updated in the WINSB database. If, after replication, ClientA sends a name query request to WINSA to find an IP address for ClientB, ClientB will be in the WINSA database. WINS replication is always incremental, which means that only changed records, rather than all records, are replicated. Persistent Connections By default WINS uses persistent connections between replication partners. When they use persistent connections, WINS servers do not disconnect from their replication partners each time replication is completed and, therefore, avoid the overhead and delays of establishing a new connection each time replication begins. Typically when WINS servers are interconnected through high-speed LAN links, it is preferable to keep connections open. Persistent connections increase the speed of replication because a server can immediately send updates to its partners, making replication more consistent. The bandwidth used by persistent connections is minimal because the connection is usually idle. Persistent connections can be used with push partners and pull partners, either with a specific partner or with all the replication partners of a WINS server. Version ID Every name entry in a WINS database has a version ID field. This field is incremented whenever a change that is to be replicated takes place. That is, the version ID for a name is incremented whenever that name is registered, changed from a released to an active state, or changed to an extinct state. The value in version ID reflects the total number of replicable changes that occurred to owned entries for that particular WINS server. The value is incremented by hexadecimal 1 every time a replicable change occurs. For example, if WINSA is the owner for ClientA, which has a version ID of 4B3, and for ClientB, which has a version ID of 4C2, ClientB was the fifteenth replicated change in the WINSA database after the ClientA change. The number of changes in version ID is one way that WINS determines when to trigger replication between two servers. Push Partners A push partner is a WINS server that is configured to push or notify other WINS servers when it has database updates that are ready to be replicated. Push partners initiate replication. They notify replication partners when it is time for the partners to pull updates, but they do not send any updates. A push partner can be configured to use any of the following events to trigger the push notification: - WINS server startup. - An IP address change in a name-to-address mapping in the database. - A specified number of version ID changes occur. This number is the number of local changes and does not include changes pulled from other partners. WINS can use this number as a threshold for determining how many changes must be made to the database before it starts push replication to its partners. This number can apply globally to all partners to which it pushes or individually to specific partners. When persistent connections are used for push replication and the number of version ID changes for triggering replication is set to 0 (the default), the push partner sends a push trigger notifying its replication partners every time an update occurs. In this situation, push replication is not dependent on the number of times version ID changes but occurs at every update. (An update is defined here as a change that increments the highest version ID in the local WINS database for records the server owns.) If the number of version ID changes is greater than 0, the frequency of push notifications is reduced. If persistent connections are not used for push replication, push replication is dependent on the number of times the version ID changes. If this number is set to zero, push replication never occurs, except if it is set to occur at service startup or when IP addresses change. If the number of version ID changes is greater than 0 when persistent connections are not used, the frequency of push notifications is increased. For example, suppose that the highest version ID for server WINSA is 1C4. WINSA is also set to push to its replication partners when there have been two updates in its database. Suppose also that the following four sets of database changes are then made to the WINS database at WINSA: - ClientA refreshes its previously registered name but keeps the same IP address. - ClientB registers its name, creating a new dynamic name-to-address mapping in the database. - ClientC reregisters a previously released name and changes its IP address. - A pull replication occurs at a specified interval with another WINS server. When these changes are entered into the database, the highest version ID for WINSA is 1C6 because two of the changes — update 2 (registering a new name) and update 3 (changing an IP address) — cause the version ID for that server to be incremented. After these changes occur, WINSA then sends a push notification to its replication partners. Pull Partners A pull partner is a WINS server that is configured to pull, or request replication of, updated WINS database entries from other WINS servers (those configured as its push partners) at a configured interval. Push replication can occur in response to a specified event, in response to a manual request by an administrator, or in response to a push trigger. A pull partner pulls or requests entries that have a higher version ID than the last entry it received from its configured replication partner. A pull partner can be configured to use either of the following events to trigger the request for replication: - WINS server startup - A user-specified amount of elapsed time, which can apply globally to all the partners from which it pulls or individually to specific partners When the specified time has elapsed, the pull partner sends a replication request to its configured partners. The partners respond with incremental updates, if any have occurred since the last replication. Database updates are not physically replicated until a pull partner sends a replication request in response to the notification sent by a push partner. Therefore, pull replication can be viewed as the single process used to replicate data between WINS databases. The IP address-to-owner ID table in the WINS database is used during the replication process. In addition, all WINS servers maintain an internal push partner owner-to-version mapping table. During WINS initialization, a WINS server scans the name-to-IP address mapping table to find the highest version ID for each owner in the IP address-to-owner ID table. The WINS server uses the information to build the push partner owner-to-version table, which maps the owner IDs to their highest version IDs. The WINS server maintains this table in memory and never commits it to the database. WINS uses the push partner owner-to-version table to determine the state of the database at any point before or after replication. During replication, the WINS server updates the push partner owner-to-version table with the highest version IDs sent by its push partners. The WINS server then scans the version ID field in the name-to-IP address table to find the highest version ID for each owner and compares the results with the numbers in the push partner owner-to-version table to determine which push partner has the latest data for each owner. The WINS server also updates its IP address-to-owner ID table with additional owners obtained from its push partners. The following figure illustrates how WINS manages replication. In this example, four WINS servers (WINSA, WINSB, WINSC, and WINSD) are all configured as push/pull partners for a central server, WINSH. Example of Pull Replication Before replication begins in this example, the owner-to-version table at WINSA contains the highest version IDs for all the owners in its database. Assume that these values are the values shown in the following table. WINSA Owner-to-Version Table In reality, pull replication can occur dynamically between WINSH and WINSA, WINSB, WINSC, and WINSD at various times, so the table might not remain static for long. To simplify the details of an individual pull replication cycle, however, the example below focuses on what might happen when WINSA replicates its database with WINSH. In this example, the following changes occur in the replicated WINS network: - Assume that first WINSB, WINSC, and WINSD each replicate with WINSH, based on the highest version ID. - WINSB has added or updated one new record since its last replication cycle, which is replicated at WINSH. - WINSC has the same version ID and does not have any records to be replicated at WINSH. - WINSD has updated 20 records since its last replication cycle, which are replicated at WINSH. - Assume that after WINSB, WINSC, and WINSD replicate with WINSH, WINSH sends a push trigger to WINSA, initiating replication. WINSA then pulls the updated owner-to-version information from WINSH. - WINSA responds by pulling entries from WINSH. WINSA determines which updates it needs to pull based on the difference between its locally-held highest version ID for each owner and the corresponding highest version IDs provided by WINSH. WINSA specifies the range of records to be pulled and replicated by comparing version IDs. In this example, WINSA pulls updates that occurred on WINSH with a version ID greater than 125, updates that occurred on WINSB with a version ID greater than 31, and updates that occurred on WINSD with a version ID greater than 200. If another pull replication to the same partner is already queued, WINS treats the later request as further down in the queue and discards it in favor of keeping the one that is higher in the queue. Accepting and Blocking Replication Partners WINS servers can be configured to accept updates only from specific replication partners (known as persona grata) or to block updates from specific replication partners (known as persona non grata) during replication. A WINS server can be configured for only one of these options. These options apply either during push-pull replication or during pull replication. Accepting replication partners When a WINS server is configured to accept specific replication partners, only updates from WINS servers that are included in the list are replicated. For example, accepting replication from specific partners might be useful when WINS servers are configured in a hub-and-spokes pattern, where a central server is the hub and other distributed servers are the spokes. By including only the IP addresses for the hubs in the list, you can replicate updates only between the hubs, without including the spokes. If a WINS server is configured to accept updates from specific partners and no list of accepted WINS servers is provided, no updates are replicated. Accepting updates only from specific partners is a new WINS feature in Windows Server 2003. Blocking replication partners When a WINS server is configured to block specific replication partners, only updates from WINS servers that are not in the list are replicated. For example, blocking replication partners is useful when a WINS server is removed from service. After a WINS server is removed from service, name entries it owns can continue to be replicated to other servers. Replication of these records can occur for one of the following reasons: - Static entries that were originally added to the now inactive WINS server replicate indefinitely to the other active WINS servers in the network until the entries are deleted manually. - Dynamic entries that were originally added to the now inactive WINS server are not immediately deleted from the WINS database. WINS must check with the owner server before it deletes dynamic entries. If a database entry cannot be verified as expired because the owner server is no longer in use, other WINS server's retain the entry until it can be verified. The blocking replication partners option can prevent replication of name entries from inactive WINS servers. If a WINS server is configured to block updates and no list of blocked WINS servers is provided, updates are replicated for all WINS servers. Owner ID and Time Stamp During Replication WINS replicates only name entries in the active and extinct states. During replication, the fields for these database entries are copied, with the exception of owner ID and time stamp. The owner ID is obtained from the local owner ID-to-version ID mapping table because the value that is used locally to represent a specific WINS server differs from server to server. For example, WINSD might be represented as owner ID 2 on WINSB and as owner ID 3 on WINSA. When a name entry is replicated, it is given a new time stamp. Active name entries are time-stamped with the sum of the local current time and the verification interval. Extinct name entries are time-stamped with the sum of the local current time and the extinction time-out. Name Conflicts During Replication Although name conflicts are usually handled at the time of name registration, it is possible for the same name to be registered at two different WINS servers. This situation might happen if a WINS client registers the same name at a second WINS server before the updates from the first WINS server replicate to the second. In this case, WINS resolves the conflict at replication time. Conflicts at replication can be between two unique name entries, between a unique name entry and a group name entry, or between two group name entries. Conflicts between unique name entries When two unique names conflict, WINS resolves the conflict based on three factors: - State of the entries (active, released, or extinct) - Ownership of the entries - Same or different IP addresses This section describes how WINS resolves conflicts between unique names. Conflicts between two replicas When two replicas conflict, the new replica overwrites the existing replica, regardless of whether the addresses match. The only exception to this rule is if the existing replica is active and the new replica is extinct. If the existing replica is active, the new replica is extinct, and different WINS servers own the replicas, then the new replica does not overwrite the existing replica. If the existing replica is active, the new replica is extinct, and the same WINS server owns both, the new extinct replica overwrites the existing active replica. Conflicts between owned entries and replicas with the same IP address The replica replaces the owned entry unless the owned entry is active and the replica is extinct. In this case, WINS increments the version ID of the owned entry so that it replicates during the next iteration. Conflicts between owned entries and replicas with different IP addresses The replica replaces the owned entry unless the owned entry is active. If the owned entry is active and the replica is extinct, WINS increments the version ID of the owned entry so that it replicates during the next iteration. If both the owned entry and the replica are active, the server receiving the replica challenges the client that registered the owned entry to determine whether the client still uses the name. If it does still use the name, WINS sends the client designated in the replica a name conflict demand. This message puts the client in a conflict state, which forces the client to put the name in a conflict state. A name in a conflict state is marked and the name is no longer used. Conflicts between unique entries and group entries When a unique entry and a group entry conflict, WINS keeps the group entry. If the WINS server owns the unique entry and the entry is not in a released or extinct state, the WINS server requests the client named in the unique entry to release the name. Conflicts between two special group entries When there is a conflict between two special groups, the new replica replaces the existing entry unless the existing entry is active. If the existing entry is active, WINS increments its version ID so that it replicates at the next iteration. If the new replica is also active, the WINS server updates the member list of the existing entry with any new members from the replica. If the list of active members grows to more than 25, the extra members are not added but are dropped silently. Conflicts involving multihomed entries If one of the name entries involved in a name conflict is for a multihomed node, the conflict is resolved in one of the following ways: - If a multihomed replica conflicts with an extinct or released entry in the database, WINS replaces the existing entry in the database with the replica, unless the existing entry is a normal group and is in a released state. This is the same as the other scenarios in which a single-address entry conflicts with a released normal group entry. - If a multihomed replica that is extinct conflicts with an active existing entry and both entries are owned by the same server, WINS replaces the active existing entry. If the active existing entry is a replica owned by a different server, WINS does not replace the existing entry. If the active existing entry is owned by the local WINS server and is a unique entry, WINS increments the version ID of the existing record to force replication. - If an active multihomed replica conflicts with an active, unique, multihomed replica in the local database with the same owner, WINS replaces the existing entry. If the owner is different, WINS does not replace it. If the entry in the database is owned by the local WINS server, and if the members of the record (a single member in the case of a unique record) are a subset of the members of the replica, WINS changes the time stamp of the existing entry and increments its version ID to force replication. If the members of the replica are not a subset, the WINS server challenges the addresses in the existing entry. If there are no responses to the challenges, WINS replaces the existing entry. If there is at least one response to the challenges, WINS notifies the client to release the name from all addresses before it replaces the existing entry with the replica. - If a multihomed replica conflicts with an existing active group entry, WINS increments the version ID of the existing entry to force replication. - If a single-address replica conflicts with an existing inactive multihomed entry, WINS replaces the existing entry with the replica. If the replica conflicts with an existing active multihomed entry and both entries are owned by the same owner, WINS replaces the existing entry with the replica. If the existing multihomed entry is a replica owned by a different server, WINS does not replace it. If, however, the existing multihomed entry is owned by the local WINS server and the new replica is a unique record, then WINS challenges the clients that use the addresses in the multihomed record. If there are no responses to the challenges, WINS replaces the existing entry. If there is at least one response to the challenges, WINS sends requests for the name to the addresses in the existing entry and then updates the existing entry. The address in the unique replica, if present in the member list, is ignored in this situation. WINS Convergence Time There is a latency period between the time a database entry is updated at one WINS server and the time the entry is replicated to all other WINS servers in the network. This latency period is known as the convergence time for the WINS system. Convergence time can be computed as the sum of the configured replication periods from one server to the next over the longest path. The following figure illustrates a replication configuration and indicates the replication periods between nodes. This figure is not intended to be a realistic configuration, but merely to illustrate a longest replication path. WINS Convergence In this figure, the longest replication path is from WINSB to WINSA to WINSC. A name registration request from one of the WINS clients causes the WINSB database to be updated. Changes to the WINSB database are replicated to WINSA every hour, and changes are replicated from WINSA to WINSC every two hours. Therefore, the convergence time for the name registration request in this example is three hours. The convergence time can vary among different types of name services. For example, name registration requests that occur at one server replicate to the server's replication partner at the next replication event. Name release requests, however, are not replicated. NetBIOS names are released when a network resource shuts down. Because it is common for these names to be reused with the same IP address when the network resource is restarted, replicating the name releases unnecessarily increases the network load of replication. Since these name service requests are not replicated, however, a NetBIOS name can be in the release state in one WINS database and still be in the active state in all other WINS databases. In addition, some changes can take place and not be reflected in any of the WINS databases. For example, if a WINS client shuts down improperly, as in the case of an unexpected power outage, it is unable to send a name release request to its primary WINS server, and the registered names are not marked as released in the WINS database. Replication and Name Services Summary The following table describes typical events that might occur in a NetBIOS network, the name service operations they invoke, the resulting WINS database updates, and whether or not the changed name entry is replicated. These scenarios assume that the WINS server handling the name service request is the owner for the name entry and that each name service request results in a positive response. Typical WINS Scenarios Related Information The following resources contain additional information that is relevant to this section. For more information about WINS, see the following RFCs in the IETF RFC Database. - RFC 1001, “Protocol Standard for a NetBIOS Service on a TCP/UDP Transport: Concepts and Methods.” - RFC 1002, “Protocol Standard for a NetBIOS Service on a TCP/UDP Transport: Detailed Specifications.”
http://technet.microsoft.com/en-us/library/cc728457(v=ws.10).aspx
CC-MAIN-2014-35
refinedweb
12,556
58.52
I'm really curious on how threads execute when the JVM is given multiple processors. So, I designed a very simple application that starts a second thread off of the main at the same time and executes. Both threads do the same thing and sleep at the same time. The overhead question for me here was, "does the JVM recognize and work with multiple processors on thread execution? Will it use multiple cores to execute multiple threads simultaneously?" The results were very interesting and not exactly what I expected. Rather than try to explain them to you or post screenshots, I'll give you the source code for you to copy, and run it under TWO scenarios. First, (and this only applies to those running a machine with more than one core) just run the program and observe the results of how the threads execute. Second, run the program, but do not hit a key yet at the scanner line to start it. Open Windows Task Manager (or the equivalent on your platform) and change the processor affinity so that the Java machine process has only ONE processor to work with. Observe those results. If any of you would care to explain to me how Java works with multiple cores, and if it works concurrently, please do so. Thanks! Code : import java.util.Scanner; class ThreadTest { public void startThreads() { Scanner sc = new Scanner(System.in); sc.nextLine(); Thread t = new Thread(new SecondThread()); t.start(); for(int i=50;i>0;i--) { System.out.println("Main thread working"); try { Thread.sleep(1000); } catch(InterruptedException e) {} } System.out.println("Main is done"); } class SecondThread implements Runnable { public void run() { for(int i=50;i>0;i--) { System.out.println("Second thread is working"); try { Thread.sleep(1000); } catch(InterruptedException e) {} } System.out.println("Second thread is done"); } } public static void main(String[] args) { ThreadTest tt = new ThreadTest(); tt.startThreads(); } }
http://www.javaprogrammingforums.com/%20threads/9502-multi-cpu-thread-execution-printingthethread.html
CC-MAIN-2015-40
refinedweb
318
67.04
Uncyclopedia talk:The Article Whisperer/archive2 From Uncyclopedia, the content-free encyclopedia Hey Max, do you want to put a post on the dump? ~ 11:58, January 7, 2010 (UTC) - Yeah I think so. I would like to work out some more of the details before an "official" anouncement though. Also I left you a message after you archived your talk page. Guess you haven't gotten it yet. :) MadMax 12:46, January 7, 2010 (UTC) Sure, that would be great thanks. All I have right now is this sample page I'm working on which, quite obviously, I've stolen from PLS. MadMax 13:30, January 7, 2010 (UTC) I have one in the works for Independent film, User:Nikau/Independent cinema, hopefully I can finish it soon. --Nikau 14:35, January 7, 2010 (UTC) - Wow that looks great. Can't tell you how long I've been waiting for that article to come along! MadMax 14:59, January 7, 2010 (UTC) Points to consider - Once a year? Keeping the PLS the more important one. We also don't want to put too many writing events, with this one we'll come up to 6 of them (2XPLS, 2XCW, 1 TDB). - I think 3 judges per category, like with the other competitions. - Ran for two weeks, judging for 1 week. - For the best article category - the articles has to come from the top 50 requested (so we can differentiate it from the other categories). - I would do the opposite with Best Uncyclopedia-related Article - we don't want noobs to write them, because some of them may translate into policies, and you need some experience with Uncyclopedia to do that. - Best Random or Miscellaneous Article - maybe remove that? I think you have enough categories as it is and this one is a bit vague. - For the alternate space - you can base some of them on - Template:UnNews Other Headlines. - I'd remove the rewrite category, since this is being dealt by CW. - In general, all articles must appear in the requested articles list, otherwise we're missing the objective here. - Now we just need to find a good name! How about - The Article Whisperer? :) ~ 16:17, January 7, 2010 (UTC) - I just updated the page with your suggestions. I've been reorganizing UN:REQ so it'll be easier to categorize. Originally, I thought there could be one category for each topic and then a suggested article from each sub-topic. The thing is there are currently 12 categories, meaning at least 36 articles, which seems kind of high. Aside from not knowing how many participants, that means a lot of judges. I'm trying to narrow it down a bit more and specify the category descriptions. Thanks for pointing out the Uncyclopedia-related category (yikes, it would have been funny had I missed that!). It was actually a copy-paste of PLS's "Best Article by a Noob" and I'd neglected to rewrite the desription. I specified a "veteran editor" as being a registered user for at least a year or more. Does that sound reasonable? MadMax 18:31, January 7, 2010 (UTC) Ok, I've posted the "core" list of categories. Any ideas on which to cut or maybe merge? I've working on this for awhile but all I've come up with is to eliminate the categories by subject and have three basic categories (articles from Special:WantedPages, UN:REQ/UN:Vital and Alternate Mainspace). MadMax 09:53, January 8, 2010 (UTC) A couple of things, in passing, if I may: - There's no way - no way - you're getting 30-odd judges. It was hard enough getting judges for the PLS and the TDB. For a new competition, it may be even harder. Perhaps allow judges to preside over multiple categories? Seriously, if you want any entrants at all, you can't have a number of judges that's higher that the number of users active at any given time! - This page is good - it has a link to one of my articles on it, and a reference to me directly. Keep it up! ;-) - Suggestions for merges: History, Politics, Geography and Science could all sit under one category, such as "educational" (religious could too, at a push, to stop it sitting as a category on its own); as Mordillo suggests, I'd leave out Miscellaneous; Entertainment, Sports and Mass Media could also feasibly fit together under something like "Popular Culture". Good idea though, I hope it takes:10, Jan 8 - I agree with UU. But then again, I always agree with UU. That beating he gave me that one time was quite enough thankyouverymuch. I think we want no more than 9 judges. So you can either join multiple categories or try something new and exciting - a judge per category! But again, I think we need to lower to it to no more than 4-5 categories. So, let say - top 50 wanted ("best article"), two main categories (joined up as UU suggested), an Uncyclopedia category and a misc category. I think we can give up on the alternate space one since there won't be many that fall under that category. ~ 10:56, January 8, 2010 (UTC) I think it's starting to look a lot better now, thanks. About the misc category, did you mean that I should merge the old misc. and alt namespace category or create something new (i.e. anything not covered by the two merged categories)? MadMax 06:32, January 9, 2010 (UTC) - How stringent are we being on the veteran users being 12 months or more? I only ask as I'm < 12 months but > 10 features, and close to 5,000 edits, RotM, WotM, Notm, and nommed UotM, so I wouldn't fall in to the first aspect but feel that I might be able to lend a decent hand. Pup 05:08, 12/02/2010 I certainly don't think a newer author should be disqualified if they've written a great article (especially if its a simple parody of a Wikipedia essay/guideline). The only catch should be that if its an Uncyclopedia guideline that could become official policy it should be written by an "established" user. Someone whose made significant contributions, like winning an award or writing a featured article, certainly qualifies even if they've only been editing for a short time. MadMax 18:56, September 3, 2010 (UTC) Off the top of my head Does it have to be just annual? Why can't it be bi-annual like PLA and CW? • • • Necropaxx (T) {~} Thursday, 14:35, Feb 11 2010 OneTwo more things: Are we allowed to call dibs? And when does it start? • • • Necropaxx (T) {~} Thursday, 14:46, Feb 11 2010 - It'd would be great to have this more than once a year but I'm not sure how successful it would be since this is the first one. Also I wouldn't want to get in the way of other contests that might run during the year. I have considered a format similar to Forum:Hourly writing contest which might be held every few months or so if nothing else is going on. - Yes but there's a limit of one article per category. - I've been really busy over the past few months so I haven't had much time to work on this project for awhile. It was originally intended for this summer but I'd like to try and start it this fall. I'll ask Mordillo and see what he thinks. To sign up as a judge add your name to the list below For next time, you might want to consider working with the grouping a bit. Having one as just General seems to general. It has 5 entries, while others have 2-3. It might want to be made a bit more even. At the very least to prevent 2-entry groups. + = 19:38,6October,2010
http://uncyclopedia.wikia.com/wiki/Uncyclopedia_talk:The_Article_Whisperer/archive2
CC-MAIN-2017-04
refinedweb
1,335
72.05
Version 0.11.0 released 30 April 2015 Dominik Picheta With this release we are one step closer to reaching version 1.0 and by extension the persistence of the Nim specification. As mentioned in the previous release notes, starting with version 1.0, we will not be introducing any more breaking changes to Nim. The language itself is very close to 1.0, the primary area that requires more work is the standard library. Take a look at the download page for binaries (Windows-only) and 0.11.0 snapshots of the source code. The Windows installer now also includes Aporia, Nimble and other useful tools to get you started with Nim. What’s left to be done The 1.0 release is expected by the end of this year. Rumors say it will be in summer 2015. What’s left: - Bug fixes, bug fixes, bug fixes, in particular: - The remaining bugs of the lambda lifting pass that is responsible to enable closures and closure iterators need to be fixed. conceptneeds to be refined, a nice name for the feature is not enough. - Destructors need to be refined. static[T]needs to be fixed. - Finish the implementation of the ‘parallel’ statement. immediatetemplates and macros will be deprecated as these will soon be completely unnecessary, instead the typedor untypedmetatypes can be used. - More of the standard library should be moved to Nimble packages and what’s left should use the features we have for concurrency and parallelism. Changes affecting backwards compatibility Parameter names are finally properly gensym‘ed. This can break templates though that used to rely on the fact that they are not. (Bug #1915.) This means this doesn’t compile anymore: template doIt(body: stmt) {.immediate.} = # this used to inject the 'str' parameter: proc res(str: string) = body doIt: echo str # Error: undeclared identifier: 'str' This used to inject the strparameter into the scope of the body. Declare the doIttemplate as immediate, dirtyto get the old behaviour. - Tuple field names are not ignored anymore, this caused too many problems in practice so now the behaviour is as it was for version 0.9.6: If field names exist for the tuple type, they are checked. logging.leveland logging.handlersare no longer exported. addHandler, getHandlers, setLogFilterand getLogFiltershould be used instead. nim idetoolshas been replaced by a separate tool nimsuggest. - arrow like operators are not right associative anymore and are required to end with either ->, ~>or =>, not just >. Examples of operators still considered arrow like: ->, ==>, +=>. On the other hand, the following operators are now considered regular operators again: |>, -+>, etc. - Typeless parameters are now only allowed in templates and macros. The old way turned out to be too error-prone. - The ‘addr’ and ‘type’ operators are now parsed as unary function application. This means type(x).nameis now parsed as (type(x)).nameand not as type((x).name). Note that this also affects the AST structure; for immediate macro parameters nkCall('addr', 'x')is produced instead of nkAddr('x'). conceptis now a keyword and is used instead of generic. The inc, dec, +=, -=builtins now produce OverflowError exceptions. This means code like the following: var x = low(T) while x <= high(T): echo x inc x Needs to be replaced by something like this: var x = low(T).int while x <= high(T).int: echo x.T inc x - Negative indexing for slicing does not work anymore! Instead of a[0.. -1]you can use a[0.. ^1]. This also works with accessing a single element a[^1]. Note that we cannot detect this reliably as it is determined at runtime whether negative indexing is used! a[0.. -1]now produces the empty string/sequence. - The compiler now warns about code like foo +=1which uses inconsistent spacing around binary operators. Later versions of the language will parse these as unary operators instead so that echo $foofinally can do what people expect it to do. system.untypedand system.typedhave been introduced as aliases for exprand stmt. The new names capture the semantics much better and most likely exprand stmtwill be deprecated in favor of the new names. - The splitmethod in module rehas changed. It now handles the case of matches having a length of 0, and empty strings being yielded from the iterator. A notable change might be that a pattern being matched at the beginning and end of a string, will result in an empty string being produced at the start and the end of the iterator. - The compiler and nimsuggest now count columns starting with 1, not 0 for consistency with the rest of the world. Language Additions - For empty case objectbranches discardcan finally be used instead of nil. - Automatic dereferencing is now done for the first argument of a routine call if overloading resolution produces no match otherwise. This feature has to be enabled with the experimental pragma. Objects that do not use inheritance nor casecan be put into constsections. This means that finally this is possible and produces rather nice code: import tables const foo = {"ah": "finally", "this": "is", "possible.": "nice!"}.toTable() Ordinary parameters can follow after a varargs parameter. This means the following is finally accepted by the compiler: template takesBlock(a, b: int, x: varargs[expr]; blck: stmt) = blck echo a, b takesBlock 1, 2, "some", 0.90, "random stuff": echo "yay" Overloading by ‘var T’ is now finally possible: proc varOrConst(x: var int) = echo "var" proc varOrConst(x: int) = echo "const" var x: int varOrConst(x) # "var" varOrConst(45) # "const" - Array and seq indexing can now use the builtin ^operator to access things from backwards: a[^1]is like Python’s a[-1]. - A first version of the specification and implementation of the overloading of the assignment operator has arrived! system.lenfor strings and sequences now returns 0 for nil. A single underscore can now be used to discard values when unpacking tuples: let (path, _, _) = os.splitFile("path/file.ext") marshal.$$and marshal.tocan be executed at compile-time. - Interoperability with C++ improved tremendously; C++’s templates and operators can be wrapped directly. See this for more information. macros.getTypecan be used to query an AST’s type at compile-time. This enables more powerful macros, for instance currying can now be done with a macro. Library additions reversedproc added to the unicodemodule. - Added multipart param to httpclient’s postContenttogether with a newMultipartDataproc. - Added %*operator for JSON. - The compiler is now available as Nimble package for c2nim. - Added ..^and ..<templates to system so that the rather annoying space between .. <and .. ^is not necessary anymore. - Added system.xlenfor strings and sequences to get back the old lenoperation that doesn’t check for nilfor efficiency. - Added sexp.nim to parse and generate sexp. Bugfixes - Fixed internal compiler error when using char()in an echo call (#1788). - Fixed Windows cross-compilation on Linux. - Overload resolution now works for types distinguished only by a static[int]param (#1056). - Other fixes relating to generic types and static params. - Fixed some compiler crashes with unnamed tuples (#1774). - Fixed channels.tryRecvblocking (#1816). - Fixed generic instantiation errors with typedesc(#419). - Fixed generic regression where the compiler no longer detected constant expressions properly (#544). - Fixed internal error with generic proc using static[T]in a specific way (#1049). - More fixes relating to generics (#1820, #1050, #1859, #1858). - Fixed httpclient to properly encode queries. - Many fixes to the urimodule. - Async sockets are now closed on error. - Fixes to httpclient’s handling of multipart data. - Fixed GC segfaults with asynchronous sockets (#1796). - Added more versions to openssl’s DLL version list (076f993). - Fixed shallow copy in iterators being broken (#1803). nilcan now be inserted into tables with the db_sqlitemodule (#1866). - Fixed “Incorrect assembler generated” (#1907) - Fixed “Expression templates that define macros are unusable in some contexts” (#1903) - Fixed “a second level generic subclass causes the compiler to crash” (#1919) - Fixed “nim 0.10.2 generates invalid AsyncHttpClient C code for MSVC “ (#1901) - Fixed “1 shl n produces wrong C code” (#1928) - Fixed “Internal error on tuple yield” (#1838) - Fixed “ICE with template” (#1915) - Fixed “include the tool directory in the installer as it is required by koch” (#1947) - Fixed “Can’t compile if file location contains spaces on Windows” (#1955) - Fixed “List comprehension macro only supports infix checks as guards” (#1920) - Fixed “wrong field names of compatible tuples in generic types” (#1910) - Fixed “Macros within templates no longer work as expected” (#1944) - Fixed “Compiling for Standalone AVR broken in 0.10.2” (#1964) - Fixed “Compiling for Standalone AVR broken in 0.10.2” (#1964) - Fixed “Code generation for mitems with tuple elements” (#1833) - Fixed “httpclient.HttpMethod should not be an enum” (#1962) - Fixed “terminal / eraseScreen() throws an OverflowError” (#1906) - Fixed “setControlCHook(nil) disables registered quit procs” (#1546) - Fixed “Unexpected idetools behaviour” (#325) - Fixed “Unused lifted lambda does not compile” (#1642) - Fixed “‘low’ and ‘high’ don’t work with cstring asguments” (#2030) - Fixed “Converting to int does not round in JS backend” (#1959) - Fixed “Internal error genRecordField 2 when adding region to pointer.” (#2039) - Fixed “Macros fail to compile when compiled with –os:standalone” (#2041) - Fixed “Reading from {.compileTime.} variables can cause code generation to fail” (#2022) - Fixed “Passing overloaded symbols to templates fails inside generic procedures” (#1988) - Fixed “Compiling iterator with object assignment in release mode causes “var not init”” (#2023) - Fixed “calling a large number of macros doing some computation fails” (#1989) - Fixed “Can’t get Koch to install nim under Windows” (#2061) - Fixed “Template with two stmt parameters segfaults compiler” (#2057) - Fixed “ noSideEffectnot affected by echo” (#2011) - Fixed “Compiling with the cpp backend ignores –passc” (#1601) - Fixed “Put untyped procedure parameters behind the experimental pragma” (#1956) - Fixed “generic regression” (#2073) - Fixed “generic regression” (#2073) - Fixed “Regression in template lookup with generics” (#2004) - Fixed “GC’s growObj is wrong for edge cases” (#2070) - Fixed “Compiler internal error when creating an array out of a typeclass” (#1131) - Fixed “GC’s growObj is wrong for edge cases” (#2070) - Fixed “Invalid Objective-C code generated when calling class method” (#2068) - Fixed “walkDirRec Error” (#2116) - Fixed “Typo in code causes compiler SIGSEGV in evalAtCompileTime” (#2113) - Fixed “Regression on exportc” (#2118) - Fixed “Error message” (#2102) - Fixed “hint[path] = off not working in nim.cfg” (#2103) - Fixed “compiler crashes when getting a tuple from a sequence of generic tuples” (#2121) - Fixed “nim check hangs with when” (#2123) - Fixed “static[T] param in nested type resolve/caching issue” (#2125) - Fixed “repr should display \0” (#2124) - Fixed “‘nim check’ never ends in case of recursive dependency “ (#2051) - Fixed “From macros: Error: unhandled exception: sons is not accessible” (#2167) - Fixed “ fieldPairsdoesn’t work inside templates” (#1902) - Fixed “fields iterator misbehavior on break statement” (#2134) - Fixed “Fix for compiler not building anymore since #c3244ef1ff” (#2193) - Fixed “JSON parser fails in cpp output mode” (#2199) - Fixed “macros.getType mishandles void return” (#2211) - Fixed “Regression involving templates instantiated within generics” (#2215) - Fixed ““Error: invalid type” for ‘not nil’ on generic type.” (#2216) - Fixed “–threads:on breaks async” (#2074) - Fixed “Type mismatch not always caught, can generate bad code for C backend.” (#2169) - Fixed “Failed C compilation when storing proc to own type in object” (#2233) - Fixed “Unknown line/column number in constant declaration type conversion error” (#2252) - Fixed “Adding {.compile.} fails if nimcache already exists.” (#2247) - Fixed “Two different type names generated for a single type (C backend)” (#2250) - Fixed “Ambigous call when it should not be” (#2229) - Fixed “Make sure we can load root urls” (#2227) - Fixed “Failure to slice a string with an int subrange type” (#794) - Fixed “documentation error” (#2205) - Fixed “Code growth when using const” (#1940) - Fixed “Instances of generic types confuse overload resolution” (#2220) - Fixed “Compiler error when initializing sdl2’s EventType” (#2316) - Fixed “Parallel disjoint checking can’t handle <, items, or arrays” (#2287) - Fixed “Strings aren’t copied in parallel loop” (#2286) - Fixed “JavaScript compiler crash with tables” (#2298) - Fixed “Range checker too restrictive” (#1845) - Fixed “Failure to slice a string with an int subrange type” (#794) - Fixed “Remind user when compiling in debug mode” (#1868) - Fixed “Compiler user guide has jumbled options/commands.” (#1819) - Fixed “using method: 1 in a objects constructor fails when compiling” (#1791)
https://nim-lang.org/blog/2015/04/30/version-0110-released.html
CC-MAIN-2018-51
refinedweb
2,018
54.32
Hey C++ Programmers... I am by classes and now i have an question yet.... here comes my question: - How do i import classes from another folder scripts or another script into an main script ?... This is my first stript, called Main.cpp (from an "Dev C++ Project File (not source file))": Script: Module WhileLoops / Main.cpp.. ..Code:// Module Project / Main.cpp #include <iostream> #include <string> using namespace std; int main() { DoLoop Obj; Obj.Input(0, 100, 5); return 0; } So in this script, i want to import my second script, called CPP Project / Folder / Loops.cpp... Now i get my second script, thad i want import them in my first script (CPP Project / Main.cpp), the second script are in the folder... Script: Module WhileLoops / Scripts / Loops.cpp (Scripts is the folder in my .cpp project file, called where i get the script, named Loops.cpp: Code:// Module Project / Folder / Loops.cpp #include <iostream> #include <string> using namespace std; class DoLoop { public: void Input (int number_min, int number_reapet, int number_step) { while (number_min < number_reapet) { cout << number_min << endl; number_min = number_min + number_step; } } void InputName (int number_min, int number_reapet, int number_step, string name) { while (number_min < number_reapet) { cout << name << number_min << endl; number_min = number_min + number_step; } } private: int number_start, number_case, number_step; string name; }; I have no idea, how i can import classes from another script (called CPP Project > Folder / Loops.cpp), into my main script (called CPP Project > Main.cpp) yet.... So can anyone give my correct my code, just to import my "Folder / Loops.cpp" Classes Function(s) into my Main.cpp Script, just i hope learn about this ?.... and i know, i must do some lessions again about my too fast learn process yet... i think if i am already finnished with my cursus on my SoloLearn app, i do search for tutorials and so i want to do some lessions again yet... Can anyone help me to learn import multiple scripts called with classes, just correct my code or give my an example pleace ?..., thanks for help, Jamie.
http://forums.devshed.com/programming/980564-dev-project-file-multiple-scripts-import-post2985347.html
CC-MAIN-2018-22
refinedweb
334
82.75
According to the latest figures, loading on the network of Russian Railways in January-February 2018 amounted 203.3 million tons, which is on 3.7% more than in the same period last year, says press-center of the company. Freight turnover In January-February 2018 freight turnover on Russian Raiways network amounted 411.7 bn. tariff ton-km (+4.8%), freight turnover into account empty wagon runs – 525.7 bn ton-km (+4.1%). Of these in February – 196.3 bn. tariff ton-km (+3.7%), with taking into account empty wagon runs – 251.3 bn. ton-km (+3,4%). Container transportation For January-February 2018 on Russian Rail network transported 643.7 thou. TEU (+13.2%) which is: domestic direction – 274.5 thou. TEU (+5.9%); export – 174.5 thou. TEU (+17.3%); import – 129.5 thou. TEU (+20.1%); transit – 65.2 thou. TEU (+40.8%). The volume of loaded containers in Jan-Feb 2018 amounted 421.5 thou. TEU (+16,9%). Carriage of passengers During the January-February 2018 on the infrastructure of Russian Railways were transported 161.8 mln. Passengers (+5.1% y-o-y), of which: suburban passenger numbers – 147.3 mln. (+4.9%), long-distance passengers – 14.5 mln. (+6 According to the figures, published on the company’s website, the network owned by Russian Railways loaded 516,9 mln t. of freight in January – May 2017 which is 3,8% more
http://navilog.ru/en/overview-of-russian-railways-network-performance-in-january-february-2018/
CC-MAIN-2021-31
refinedweb
239
70.5
ExternalDNS w. EKS and Route53 pt2 Using ExternalDNS with static credentials to access to Route53 In a previous article, I covered how to use ExternalDNS to automate updating DNS records when you deploy an application on Kubernetes. This was done by giving all the nodes on Kubernetes access to the Amazon Route 53 DNS zone. This was not desirable, as it allows anything running on the cluster to read and write records. As an alternative, you can give access to only the ExternalDNS container by uploading a credentials file containing secrets that will provide access to the Route 53 DNS zone. This grant access to only the target service, rather than the whole cluster, but there are some gotchas (see below). This tutorial will show how to setup ExternalDNS using static credentials on Amazon EKS using Amazon Route 53. Dangers of using static credentials At some point, the secrets can get compromised, and then unknown threat actors will have the secrets and unmitigated access to the service. This is not a matter of if, but a matter of when. For this scenario the secret will need to be rotated: where the current secret is replaced with a newly generated secret, and access to the service using the old credentials are removed. When delivering the secret to the ExternalDNS service, it should be done in a secure manner, not stored anywhere after uploading the secret. If the cloud provider has this feature, access to the resource should be closely monitored, so that any unauthorized access generates an alert. ⚠️ This naturally requires automation to help mitigate the risk. Thus given the risk, and complexity in the automation required to mitigate the risk, this method is the least desirable method. It should only be used when no other option is available. Previous Article ExternalDNS with EKS and Route53 Using ExternalDNS with Node IAM Role static credentials method For this process, you will create an IAM user and attach the policy created earlier. Then using that user, create static credentials, called access keys, upload the static credentials as a Kubernetes secret. This part of the process should happen before deploying ExternalDNS. Deploy ExternalDNS Save the following below as externaldns.yaml. This manifest will have the necessary components to deploy ExternalDNS on a single pod with access to the secret through a mounted volume. First replace $DOMAIN_NAME with the domain name, such as example.com, and replace $EXTERNALDNS_NS with the desired namespace, such as externaldns or kube-addons. Replace $EKS_CLUSTER_REGION with the target region of the EKS cluster, such as us-east-2. must be removed before destroying the EKS cluster, otherwise they will be left behind and eat up costs. IAM User The IAM user can be deleted after detaching the policy. aws iam detach-user-policy --user-name "externaldns" \ --policy-arn $POLICY_ARNaws iam delete-user --user-name "externaldns" Secure access to Route53 at the pod level using Kubernetes service account: ExternalDNS w. EKS and Route53 pt3 Using ExternalDNS with IRSA to access Route 53 joachim8675309.medium.com Conclusion Similar to the previous article, the goal is to demonstrate ExternalDNS on EKS with Route 53, and walk through using aws and kubectl tools. Additionally, the goal is to expose you to identities that are configured to access a resource. In the previous article, a role identity was associated to the Kubernetes nodes (EC2 instances managed by ASG) to provide access to Route 53. In this article, a user identity is used by ExternalDNS through generated static credentials called access keys. With these two articles you can see the trade offs between using an IAM role versus using an IAM user. With the IAM role, all containers on the cluster have access, but the secrets used behind the scenes are rotated frequently. With the IAM user, only ExternalDNS has access, but the secrets require complex automation to rotate and secure the secret. As mentioned in the article, using static secrets should only be used a last resort when there is no other option available, such as using a cluster hosted outside of AWS. For services that need access, you can secure access to a resource using the Kubernetes identity, service account, and thus only allow designated pods to access the resource. This is done on AWS with IRSA (IAM Role for service account) using OpenID Connect provider. See the next article for more information: ExternalDNS w. EKS and Route53 pt3: Using ExternalDNS with IRSA to access Route 53. I hope this is useful in your journey.
https://joachim8675309.medium.com/externaldns-w-eks-and-route53-pt2-e94c705f62ae?source=user_profile---------5----------------------------
CC-MAIN-2022-33
refinedweb
751
52.29
#include <disco.h> #include <disco.h> Inherits StanzaExtension. Inheritance diagram for Disco::Info: Definition at line 65 of file disco.h. [inline] Returns the entity's supported features. Definition at line 80 of file disco.h. [virtual] Returns an XPath expression that describes a path to child elements of a stanza that an extension handles. Implements StanzaExtension. Definition at line 182 of file disco.cpp. Returns an optionally included data form. This is used by e.g. MUC (XEP-0045). Definition at line 99 of file disco.h. Use this function to check if the entity the Info came from supports agiven feature. Definition at line 174 of file disco.cpp. Returns the entity's identities. Definition at line 93 105 of file disco.h. Returns the queried node identifier, if any. Definition at line 74 of file disco.h. Returns a Tag representation of the extension. Definition at line 188 of file disco.cpp.
http://camaya.net/api/gloox-trunk/classgloox_1_1Disco_1_1Info.html
crawl-001
refinedweb
155
55.1
Modern and Legacy JavaScript: Differential Loading with Angular 8 Tutorial In this JavaScript tutorial designed for Angular developers, we'll learn how Angular 8 by example makes differential loading to send separate modern and legacy JavaScript bundles to web browsers based on their capabilities thanks to the module and nomodule attributes and browserslist. Next, we'll introduce the various new features of modern JavaScript to Angular devs then finally we'll see how to include custom JavaScript code in our Angular apps. Angular is an open-source, client-side JavaScript platform for building web and mobile apps. Angular is written in TypeScript which is a superset language of JavaScript that gets eventually compiled to JavaScript before it can be executed by web browsers which can only understand JavaScript, CSS and HTML. TypeScript includes all the features of JavaScript plus a plethora of its own features that take your productivity to the next level. Before running your app in a web browser, you need to compile the TypeScript code into JavaScript by configuring the TypeScript compiler but fortunately you don't need to do any manual configurations if your are using the Angular CLI which takes care of all that. Sending Separate Modern and Legacy Angular JavaScript Bundles to Browsers The latest Angular 8 version makes use of a feature called differential loading that allows you to send the modern JS code (ES6+) to modern web browsers that support the latest features of JavaScript or the legacy code (ES5) to old browsers. Note: Differential loading allows you to save about 7/20% in size for Angular apps in modern web browsers. Modern browsers are able to recognize a module type in the HTML <script> tag and to ignore a nomodule attribute. For example, let's take the following code: <script src="dist/bundle1.js" type="module"></script> <script src="dist/bundle2.js" nomodule></script> A modern web browser will be able to load the dist/bundle1.js file but since an old legacy browser doesn't understand the module type, it will load the dist/bundle2.js file instead. Installing Angular CLI 8 Before you can create an Angular 8 project, you must have a recent version of Node.JS and NPM installed on your machine. Open a new command-line interface and run the following command: $ npm install -g @angular/cli Creating an Angular 8 Project Next, create an Angular 8 project using the following command: $ ng new angular-javascript-demo You'll be prompted by the CLI if Would you like to add Angular routing? (y/N) and Which stylesheet format would you like to use?. If you ahev an Angular 7 project, first you need to make sure to update to the latest version: $ cd into__your_angular_project $ ng update @angular/cli @angular/core Navigate to your project's folder, you should find a browserslist file which has the following content: > 0.5% last 2 versions Firefox ESR not dead not IE 9-11 # For IE 9-11 support, remove 'not'. This file is used by the build system to adjust CSS and JavaScript output to support the specified browsers and versions. You can find more information about its format and rule options, refer to the official docs You can customize this file as you see fit per your use cases. You can run the following command in your terminal to display what browsers were selected by these queries: $ angular-javascript-demo $ npx browserslist This is the output for the default browserslist configuration that comes with Angular 8: and_chr 75 and_ff 67 and_qq 1.2 and_uc 12.12 android 67 baidu 7.12 chrome 75 chrome 74 chrome 73 edge 18 edge 17 firefox 68 firefox 67 firefox 60 ie_mob 11 ios_saf 12.2-12.3 ios_saf 12.0-12.1 ios_saf 11.3-11.4 kaios 2.5 op_mini all op_mob 46 opera 62 opera 60 safari 12.1 safari 12 samsung 9.2 samsung 8.2 Now, open the tsconfig.json file: { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, "downlevelIteration": true, "experimentalDecorators": true, "module": "esnext", "moduleResolution": "node", "importHelpers": true, "target": "es2015", "typeRoots": [ "node_modules/@types" ], "lib": [ "es2018", "dom" ] }, "angularCompilerOptions": { "fullTemplateTypeCheck": true, "strictInjectionParameters": true } } Notice that the target property has the es2015 value which means that the TypeScript compiler will target ES2015/ES6. Now, head back to your terminal and let's build the application for production using the following command: $ ng build --prod This it the output of the command: chunk {0} runtime-es2015.24b02acc1f369d9b9f37.js (runtime) 2.83 kB [entry] [rendered] chunk {1} main-es2015.d335718ef48b35971cc1.js (main) 546 kB [initial] [rendered] chunk {2} polyfills-es2015.fd917e7c3ed57f282ee5.js (polyfills) 64.3 kB [initial] [rendered] chunk {3} polyfills-es5-es2015.3aa54d3e5134f5b5b842.js (polyfills-es5) 223 kB [initial] [rendered] chunk {4} styles.6b3fe9320909874e6b1b.css (styles) 61 kB [initial] [rendered] Date: 2019-09-20T11:57:25.514Z - Hash: 0f403b3d18149db6f693 - Time: 299070ms Generating ES5 bundles for differential loading... ES5 bundle generation complete. Now, open the dist/index.html file, you'll notice that Angular CLI 8 added various <script> tags with type="module" and nomodule attributes: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Angulardemo</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <link href="" rel="stylesheet"> <link href="" rel="stylesheet"> <link rel="stylesheet" href="styles.6b3fe9320909874e6b1b.css"> </head> <body> <app-root></app-root> <script src="polyfills-es5.3aa54d3e5134f5b5b842.js" nomodule defer></script> <script src="polyfills-es2015.fd917e7c3ed57f282ee5.js" type="module"></script> <script src="runtime-es2015.24b02acc1f369d9b9f37.js" type="module"></script> <script src="main-es2015.d335718ef48b35971cc1.js" type="module"></script> <script src="runtime-es5.24b02acc1f369d9b9f37.js" nomodule defer></script> <script src="main-es5.d335718ef48b35971cc1.js" nomodule defer></script> </body> </html> Let's see this in a web browser. First install the serve tool to serve our app locally: $ npm install -g serve Next, navigate to your dist folder and serve it: $ cd dist/angular-javascript-demo $ serve Go with your web browser to the address. Go to the Network panel of DevTools, if you use a modern version of Chrome (or any modern web browser), you should see that your web browser loaded the modern ES2015 bundles of your app: Introducing JavaScript for Angular Devs You don't need to master every feature of TypeScript but you must know JavaScript as it's the pillar language of frontend web development. In this tutorial, I'll introduce you to the features of modern JavaScript. ES6 has new syntax sugar and features that make JavaScript powerful and easier to use. The new ES6 lets you write awesome JavaScript code. Among the new features introduced in JavaScript by ES6 are: - New keywords for variable declaration such as constand let, - JavaScript modules - template strings, - arrow functions, - class destructing, - JavaScript Promises etc. Declaring Variables in JavaScript/ES6 ( var vs let vs const) JavaScript developers used the var keyword for declaring variables for a long period of time but is there anything wrong with the var keyword? Yes more than one thing! - Variables declared using varleaks outside their scope (you can access them outside the scope where they are declared), - Variables declared using varare mutable (you can change their values) - Variables declared with varcan be re-declared ES6 provides the const and let keywords which are designed to solve the issues caused by the var keyword. constlets you declare constant variables which can't be re-assigned. letlets you declare variables which can't be re-declared. letallows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the varkeyword, which defines a variable globally, or locally to an entire function regardless of block scope.Source const can be used to declare variables that hold elements returned by DOM query methods such as the document.querySelector() method. const el = document.querySelector(`#my-id`) const variables need to be initialized or otherwise a SyntaxError will be thrown. For example, the following code will throw an error Uncaught SyntaxError: Missing initializer in const declaration: const my_variable This is a screen shot when executing the code in the console of Chrome DevTools: The correct syntax would be: const my_variable = "a const variable declared"; Now, let's try to change the value of my_variable: my_variable = "new value"; The code will fail with the error Uncaught TypeError: Assignment to constant variable. Now let's use let to declare some variables: let my_variable2; let my_variable3= "another variable declaration"; We declare my_variable2 (non initialized) and my_variable2 (initialized with a string value) variables. The value of my_variable2 is undefined. Unlike the var keyword, the let keyword doesn't allow you to re-declare variables within the same function or block scope. The following code will fail with the error Uncaught SyntaxError: Identifier 'my_variable2' has already been declared: let my_variable2; Both const and let keywords are block-scoped meaning the variables are only available inside the block where they are declared. Let's consider this example: let x = 1; if (true) { let x = 2; console.log(x); } console.log(x); We declare the x twice, the first declaration is outside the if{} block and the second declaration is within the if{} block. The second declaration produces a new variable available inside the block but not outside so the first console.log(x) instruction will print 2 while the second console.log(x) will print 1. We now know that varis function scope, and now we know that letand constare block scope, which means any time you’ve got a set of curly brackets you have block scope. Now, we need to know you can only declare a variable inside of its scope once. You can update a letvariable, and we’ll take a look more at letand constbut you cannot redeclare it twice in the same scope. The important thing here is that these two winner variables are actually two separate variables. They have the same name, but they are both scoped differently: let winner = falseoutside of the if loop is scoped to the window. let winner = trueinside the if loop is scoped to the block. JS Modules Almost every language has a concept of modules — a way to include functionality declared in one file within another. Typically, a developer creates an encapsulated library of code responsible for handling related tasks. That library can be referenced by applications or other modules. <!DOCTYPE html> <html> <head> <title>ES6 module example</title> <script src="app/utils.js" type="module"></script> <script src="app/fallback.js" nomodule></script> </head> <body> </body> </html> You can add moduleto the type attribute of a script element <script type="module">. The browser will then treat either inline or external scriptelements as an ES6 module. In utils.js file. function hello() { return "Hello"; } function world() { return "World"; } // Basic export export { hello, world }; In main.js file. import {hello, world} from '/app/utils.js'; hello(); world(); Arrow Functions Arrow functions were introduced with ES6 as a new syntax for writing JavaScript functions. They save developers time and simplify function scope. Surveys show they’re the most popular ES6 feature: Most major modern browsers support arrow functions. are a more concise syntax for writing function expressions. They utilize a new token, =>, that looks like a fat arrow. Arrow functions are anonymous and change the way thisbinds in functions. // ES5 var multiplyES5 = function(x, y) { return x * y; }; // ES6 const multiplyES6 = (x, y) => { return x * y }; Curly brackets aren’t required if only one expression is present. The preceding example could also be written as: const multiplyES6 = (x, y) => x * y; Also, you can use Arrow function with map, filter, and reducebuilt-in functions. Now, that we have seen the important features of modern JavaScript, let's see how we can how to use JavaScript code in your Angular 8 projects which are based on TypeScript. Including Custom JavaScript in Angular 8 Project Now, let's learn about how to include custom JavaScript code in our Angular 8 application. Go ahead and create a new JavaScript file in the src/ folder of your project: $ cd src $ touch custom.js Next write the following code: const helloAngular = () => { console.log("Hello Angular from JavaScript!"); }; Next, open the angular.json file and add the file to the scripts array: "scripts": [ "src/custom.js" ] That's it, you can now use vanilla JavaScript in your project. Conclusion In this tutorial we learned how Angular 8 makes use of differential loading to send separate modern and legacy JavaScript bundles to web browsers based on their capabilities thanks to the module and nomodule attributes and browserslist. Next, we introduced the various new features of modern JavaScript to Angular devs then finally we've seen how to include custom JavaScript code in our Angular apps.
https://www.techiediaries.com/javascript-tutorial-and-example/
CC-MAIN-2021-39
refinedweb
2,136
54.42
Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo You can subscribe to this list here. Showing 3 results of 3. Kind regards, Jan On 04/06/2010 09:17 PM, Jan Moringen wrote: > Hi. > > > >> You may want to consider a "fast" answer, and a "detailed" answer > > >> solution. The immediate feedback variant would use the 'fast' > > >> answer, and an idle mode could then enable a better answer later. > > > > > > For me, the feedback from the idle service seems fast enough, but I > > > only did very limited testing. > > > > > > Please let me know whether the attached patch can be applied > > > (provided I add docstrings and clean up, of course). > > > > Having more modes is always good. I'm not fond of the 'breadcrumb' > > name though. It doesn't tell me what it does. Not that stickyfunc is much > > better, of course. In the case of this mode, it seems like it would > > be the end-all variant of "show me the tag under the cursor" feature.=20 > > Giving it a clean name like 'show-current-tag-name' or something > > similar seems important for discover-ability. > > I think it is the canonical name of the user-interface design pattern > (see). It doesn't > have to be breadcrumbs for me thought. After all, names in Emacs are > expected to be non-standard, aren't they? ;) > > How about show-path-to-current-tag, show-nesting-of-current-tag or > show-current-tag-with-parents? Ok, I guess I'm ok with breadcrumbs. I didn't realize it was all official and stuff. I've been tending for the long descriptive names lately is all. > > Other than that, things look pretty good to me after a quick read. > > So is it OK to commit this version? I tried your patch, and it does not load. You have a function being used in a menu definition before the function is defined. That got me looking at the menu. There is a function in senator that I use everywhere for creating menu items that are compatible between Emacs and XEmacs. If the default is the mode line, then we should use this mode instead of which-func in semantic-load.el. If the default is the header-line, I wonder how to make it easy to choose between this and stickyfunc mode. Thanks Eric On 04/06/2010 08:36 PM, Jan Moringen wrote: >> This solution is similar to what we'd get if we added a new >> > semantic-ctxt function that would, in Java's case, just be the >> > find-tags-by-class code. We would then need to find all the necessary >> > locations to apply it. > Wouldn't the function in question be (the already existing function) > semantic-analyze-scope-nested-tags? This is what I currently do for > Java: > > +(define-mode-local-override semantic-analyze-scope-nested-tags > + java-mode (position scopetypes) > + "Maybe add package declaration to list of parents." I think you have just shown that I can't remember my own API anymore. ;) Perhaps I didn't understand your question, which was: > > in Common Lisp. These do not show up in the parents slots of the scope > > object. In my opinion, it would be useful to have them there. Or should > > the scope be understood to strictly describe the lexical structure of > > the code? So where you instead asking, should code that uses a 'package' statement followed by a function/method definition that is now in 'package' be modified to show that it is indeed a part of package? In that case, the rule so far as been that the tag structure map as directly as possible to what is syntactically in the buffer as opposed to what is logically in the buffer. The premise being that if you come to a tag list for some language there is a deterministic mapping. That, in turn, means you can use srecode to regenerate the essence of a tag list as code from a tag list. That said, I don't feel so strongly as to not allow variation. It's just easier not to when it comes to developing a parser. Your solution in the scope is a fine thing to do where the :parent is added to the tag, especially since you are cloning the tag first, leaving the buffer tag list alone. You also asked: > What do :parent attributes do? I thought, the nesting of tags is > described by having children in the :members attribute of their parents. In C++, this is like: void namespace1::class2::method1() {}; so it is the name of some namespace/class where that method belongs. In EIEIO, it is any method definition. That parent tag is looked up to see if that thing belongs to some other type, and they will be gathered together in the typecache as if they had been parsed that way, making a more easily searched structure. Thanks Eric Eric
http://sourceforge.net/p/cedet/mailman/cedet-devel/?viewmonth=201004&viewday=8
CC-MAIN-2015-14
refinedweb
826
73.27
The VB.NET / C# debacle rages on. . . Well, its Dr. Dotnetsky again. They let me out of my cage for a while, and this time I'm going to take a little detour and make some observations about developers targeting different .NET languages, specifically VB.NET and C#. It's always been good programming practice to use the most specfic type possible; in C++ and C# this is the norm. It would make no sense for a C# programmer to write: object x; when they really want: int x; even though the first one is perfectly acceptable. In Visual Basic 6 and earlier, we had a lot of "lazy" flexibility with variable types. The VARIANT type would allow us to stick just about anything in it and we even had the option of not declaring variables at all. Lazy typing created a lot of - you guessed it -- lazy programmers. It also created inefficiencies and a much higher probability of errors in code. Many VB programmers migrating to the .NET platform want to keep their old bad habits, not the least of which is never setting Option Explicit on. This allows them to write: Dim x and happily go about their programming duties (of course in VBScript, which became ubiquitous because of Classic ASP under IIS, that's your only choice!). Unfortunately, Microsoft has perpetuated this illogical paradigm: because they have an estimated 4 million "VB" programmers on whom they've successfully foisted this weakly typed paradigm, and because they wanted to provide an easy migration path to the .NET platform with VB.NET (which is a full-fledged member of the CLR-compliant programming languages - but ONLY if you use it correctly) they wrote a whole slew of backwards-compliant classes (most of which can be found in the Microsoft.VisualBasic namespace) to enable developers to continue using contructs like Mid(), CType(), and others. None of this stuff is Base Class Framework or ECMA CLI compatible, thank you! And of course, human nature being what it is, millions of VB programmers are continuing on their merry DIM way, happily abusing the CLR type system by almost exclusively using these built-in crutches. Option Strict is not DIM? Option Strict is the newest addition to VB.NET -- Option Explicit forces us to actually declare all our variables (God forbid!), and Option Strict forces us to type them. In VB 6.0, if you declared "Dim x", you got a Variant, which incurred a performance penalty. However in VB.NET, if you choose to do this you will incur a very BIG performance penalty! You are going to get a System.Object instance, which is a reference, not a value type, and that means boxing. If we attempt to add two undeclared variables with Option Strict turned off, the compiler generated IL contains boxing code, moving the value types into the heap by sticking them into a referenced type. Boxing is performed with System.Object, and there is a performance hit because an additional object has to be maintained for each undeclared variable. In addition, there will be a call to the Microsoft.Visualbasic compatibility layer: IL_0015: call object [Microsoft.VisualBasic] Microsoft.VisualBasic.CompilerServices.ObjectType::AddObj(object, object). Understanding the Difference The key to this issue is understanding the difference between value types and reference types, which is a fundamental distinction in the Common Type System, and this means having an understanding of how memory is allocated for instances of each type. In managed code, values can have their memory allocated either on the stack or on the heap, both of which are managed by the CLR. Variables allocated on the stack are normally created when a running method creates them. From a memory perspective,. The memory used by stack variables is automatically freed when the method in which they were created returns. However, variables allocated on the heap don't have their memory freed when the method that created them returns. Instead, the memory used by these variables is freed via the garbage collection process, which can (and often does) occur whenever it "feels like it". It is this second process, involving calling the Microsoft.VisualBasic namespace, creating and boxing the new variables (the ones you didn't declare and type) and finally storing references to these values on the stack and the actual boxed values themselves on the heap is what happens when you don't declare and type variables in VB.NET. The bottom line is there is a definite performance penalty for undeclared or untyped variables in VB.NET. With Option Explicit On and Option Strict On, we must declare our two variables and type them before attempting our addition. The two variables in the compiler - generated IL are declared on the Stack with no boxing, which is obviously less lines of IL code as well as being much more efficient code. Unfortunately, in bringing out the final release of Visual Studio.NET, Microsoft bowed to the cries of millions of VB programmers and left Option Strict Off by default in all our VB.NET projects! Just about every professional author and programmer will tell you that you should ALWAYS set Option Strict to "On"! Forcing good programming habits with the IDE Fortunately, there is a very easy way to do this so that you won't forget. You are hereby strongly encouraged to go to the Visual Studio's Tools | Options menu, click the Projects \ VB Defaults folder and set Option Strict and Option Explicit to On. You might then spend a bit more time writing CType-s or DirectCast-s, but you will avoid spending much more time tracking down some mysterious runtime errors. Many of your programs will also run FASTER. Now all your projects will automatically have "Option Explicit" and "Option Strict" turned on. With C#, you don't have this problem - it has much stricter type safety requirements. If you declare a variable as an object and you really want to use it as an int, you must explicitly cast it to an int (e.g. (int) x ) before you can use it in an arithmetic computation. This process provides the compiler enough information to generate more efficient code (but not as efficient as if you had declared it as int in the first place). There are other issues you should consider if you are a VB.NET programmer (besides the option of learning C#, which I highly recommend - after all, ASP.NET contains over a million lines of code, and they were all written in C#, so who is kidding whom?) Instead of using CType() and similar cast keywords on reference types, use DirectCast(). Instead of using Mid() with strings, consider using the StringBuilder methods. String.Concat() and its overloads are also much faster than using the "&" operator in VB.NET. If you disassemble your VB.NET assemblies with ILDASM and you see a lot of references with the word VIsualBasic in them, then trust me -- you have successfully created inefficient code! To Dr. Dotnetsky, this is the equvalent of drinking Burgundy when you have the money to buy Margaux. Here is an example: IL_0048: call object [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.LateBinding::LateGet(object, class [mscorlib]System.Type, string, object[], string[], bool[]) IL_004d: call object [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::GetObjectValue(object) IL_0052: call void [mscorlib]System.Console::WriteLine(object) IL_0057: ret As a last point of mention, for those who are having difficulty translating C# code to VB.NET and vice-versa, I would recommend Lutz Roeder's fine Reflector product. Compile your stuff in C#, load the assembly into Reflector, choose VB as the language, and hit the Decompiler choice with a method highlighted. Presto - instant "other language" in the code window! You'll also learn a lot about the CLR with its other features. Highly recommended! Price, free. Finally, if you really want to excel in creating efficient, compact managed code, don't use either C# or VB.NET - -use C++. That's my rant for this week! Articles Submit Article Message Board Software Downloads Videos Rant & Rave
http://www.eggheadcafe.com/articles/20030801.asp
crawl-002
refinedweb
1,350
55.44
The mildly controversial geocoding system What3words encodes the geographic coordinates of a location (to a resolution of 3 m) on the Earth's surface into three dictionary words, through some proprietary algorithm. The idea is that human's find it easier to remember and communicate these words than the sequence of digits that makes up the corresponding latitude and longitude. For example, the Victoria Memorial in front of Buckingham Palace in London is located at (51.50187, -0.14063) in decimal latitude, longitude coordinates, but simply using.woods.laws in the language of What3words. The company that established the system in 2013 has been criticised for being closed-source with opaque licensing terms and an extremely active PR team whose press releases have often been picked up unquestioningly by the media. Anyway, let's build our own geocoding system in Python. Latitude is conventionally measured in degrees South and North of the equator (-90° to +90°) and longitude in degrees East and West of the Prime Meridian (-180° to +180°). Let's suppose we aim for a resolution of 0.001° (0.06′); for this we require $N = 180,000 \times 360,000 = 64.8$ billion points. This corresponds to a resolution of roughly 100 m (it varies with latitude because of the Earth's slightly ellipsoid shape, and with longitude because lines of longitude converge from a maximum spacing at the equator to meet at the poles). If we encode these points as a sequence of $m$ objects (e.g. words) drawn from a list of length $M$, then we must have $M > N^{1/m}$. [For example, What3words apparently achieves its 3 m resolution with $N=5.7 \times 10^{13}$ tiles and requires a list of $N^{1/3} \approx 40,000$ words.] Our resolution is lower, so using $m=3$ we can get away with a little over 4,000 distinct words. Let's take them from this Wiktionary list of the most frequent 10,000 words in the English language. First, parse this html file to extract just the words from its tables. We don't care for words with fewer than three letters, or for those with numbers, apostrophes, etc. in them, so exclude these from our wordlist. The following code produces the text file wordlist.txt: from bs4 import BeautifulSoup wiktionary_file = 'Wiktionary_Frequency lists_PG_2006_04_1-10000 - Wiktionary.html' html = open(wiktionary_file).read() soup = BeautifulSoup(html, 'html.parser') tables = soup.find_all('table') with open('wordlist.txt', 'w') as fo: for table in tables: for tr in table.find_all('tr')[1:]: tds = tr.find_all('td') word = tds[1].find_all('a')[0].text if len(word) > 2 and word.isalpha(): print(word.lower(), file=fo) Now we can use this word list to produce our encoded geolocation: import sys import math # Settings: the resolution is 10^(-ires) and we use m words. ires = 1000 ndp = int(math.log10(ires)) m = 3 # Read the word list words = [line.strip() for line in open('wordlist('.') print(decode(code)) For example: $ python get_loc.py 42.360 -71.092 # MIT event.modest.file $ python get_loc.py 25.197139 55.274111 # Burj Khalifa invention.chiefly.shed $ python get_loc.py -33.957314 18.403108 # Table Mountain jewels.east.jane $ python get_loc.py usual.meal.exhibited # New Zealand Parliament Buildings (-41.278, 174.777) Comments are pre-moderated. Please be patient and your comment will appear soon. There are currently no comments New Comment
https://scipython.com/blog/what-n-things/
CC-MAIN-2020-29
refinedweb
569
69.28
score:33 The quick answer is, use .filter() to select the rows you want, e.g.: d3.csv("data.csv", function(csv) { csv = csv.filter(function(row) { return row['Class'] == 'Second Class' || row['Class'] == 'First Class'; }) vis.datum(csv).call(chart); }); This is easy if you, the coder, are choosing the filters. If you need this to be chosen by user interaction, however, you're going to need to build out a more complex function. Assuming that you have saved the user choices in an object called filters, with keys corresponding to your rows, one option might look like: // an example filters object var filters = { 'Class': ['First Class', 'Second Class'], 'Sex': 'Female' }; d3.csv("data.csv", function(csv) { csv = csv.filter(function(row) { // run through all the filters, returning a boolean return ['Class','Age','Sex','Survived'].reduce(function(pass, column) { return pass && ( // pass if no filter is set !filters[column] || // pass if the row's value is equal to the filter // (i.e. the filter is set to a string) row[column] === filters[column] || // pass if the row's value is in an array of filter values filters[column].indexOf(row[column]) >= 0 ); }, true); }) console.log(csv.length, csv); }); (You don't have to do this with .reduce(), but I like how clean it is.) If, as is probably the case, you don't want to do this filtering at load time, but instead filter dynamically depending on user input, you can still use the filter function, but you'll want to store csv in memory somewhere and filter it on the fly, perhaps in an update() function triggered by user interactions. Source: stackoverflow.com Related Query - Select data from a CSV before loading it with javascript (d3 library) - javascript d3.js: initialize brush with brush.extent and stop data from spilling over margin - how to get data with tsv or csv to array in d3.js from a txt file? - Unable to reference d3.js data imported from a csv file with spaces in the header - D3 - Loading data from a second CSV - Loading csv data with d3.csv in nvd3 multiBar Chart example (JSON format) - Javascript d3 pie chart doesn't pull data from JSON file with list of dictionaries - Only display 20 rows of data from a csv file with d3.js - how to convert data selected from a postgres database to json or csv to use it with d3js lib? - data is undefined after importing from a csv file with d3 - Create an array from csv for use with D3.js library - How can I parse csv data from a javascript array of strings for use in d3 graphs - Change format and data of datetime X-axis in a line chart with d3 Javascript library - Extracting data from excel sheet into csv (or) Json using Javascript - - unable to read data from a CSV file using javascript - How to load data from a CSV file in D3 v5 - Importing data from multiple csv files in D3 - Cannot import data from csv file in d3 - D3.js loading local data file from - d3 csv data loading - How do I ensure D3 finishes loading several CSVs before javascript runs? - How to select unique values in d3.js from data - How to pull data from mysql database and visualize with D3.JS? - Dynamically loading external data from database into d3.js - Creating a D3.js Collapsible Tree from CSV data - Read csv data with D3.csv, each column in separate array More Query from same tag - Would this be considered idiomatic ClojureScript? - Troubles with bootstrap modal with angular - Tooltip with Multi-Series Line Chart in Vega-Lite API - Display isolines at fixed z using plotly or d3 contour plot or interpolation - C3.js - Nested JSON objects, How to access and load data? - Can't get antialiasing with SVG & D3.JS - Does the main D3 module namespace not get updated with bleeding edge submodule additions? - Combining two csv's (d3) - Integrating React with D3 - D3 JS bar chart, show y-axis label value at the top of the bar - D3 Chart print issue - Display only values from the data set into X axis ticks - How to convert to nested json from dataframe - How to append javascript file to the body from javascript file which is in the same directory. Java server faces 2 JSF2 - Why does this one block of Javascript (D3) work, but not the other? - Convert d3 chart (svg) to an image and display it - D3 projection not setting cx property - d3 force directed graph downward force simulation - Do zoomable graphs need different data sets for every zoom level? - Points on a map with D3.js - D3: Creating responsive range bar chart - D3.js roll up nested data - d3js call some object's method, not global function - How to update elements of an HTML that the elements are created using data from a CSV file? - Day/Hour Heatmap + mySQL - TypeError: node is null - D3 .on change works on text not on chart - Running D3 in node.js, what am I missing? - create position / and add text in circle using D3 using "g" and svg in JavaScript /or Coffee - Angularjs unknown provider nvd3
https://www.appsloveworld.com/d3js/100/1/select-data-from-a-csv-before-loading-it-with-javascript-d3-library
CC-MAIN-2022-40
refinedweb
863
62.88
#include <db.h> typedef struct { void *app_data; void *data; u_int32_t size; u_int32_t ulen; u_int32_t dlen; u_int32_t doff; u_int32_t flags; } DBT; Storage and retrieval for the refer to strings of zero length up to strings of essentially unlimited length. See Database limits for more information. All fields of the DBT structure that are not explicitly set should be initialized to nul bytes before the first time the structure is used. Do this by declaring the structure external or static, or by calling the C library routine memset(3). By default, the flags structure element is expected to be set to which the pointer refers will be allocated and managed by Berkeley DB. Note that using the default flags for returned DBTs is only compatible with single threaded usage of Berkeley DB. The elements of the DBT structure are defined as follows: void *app_data; Optional field that can be used to pass information through Berkeley DB API calls into user-defined callback functions. For example, this field may be accessed to pass user-defined content when implementing the callback used by DB->set_dup_compare(). void *data; A pointer to a byte string. u_int32_t size; The length of data, in bytes. u_int32_t ulen; The size of the user's buffer (to which data refers), in bytes. This location is not written by the Berkeley DB functions. Set the byte size of the user-specified buffer. Note that applications can determine the length of a record by setting the ulen field to 0 and checking the return value in the size field. See the DB_DBT_USERMEM flag for more information. u_int32_t dlen; The length of the partial record being read or written by the application, in bytes. See the DB_DBT_PARTIAL flag for more information. u_int32_t doff; The offset of the partial record being read or written by the application, in bytes. See the DB_DBT_PARTIAL flag for more information. u_int32_t flags; The flags parameter must be set to 0 or by bitwise inclusively OR'ing together one or more of the following values: Set this flag on a DBT used for the data portion of a record to indicate that the DBT stores BLOB data. If this flag is set, and if the database otherwise supports BLOBs, then the data contained by this DBT will be stored as a BLOB, regardless of whether it exceeds the BLOB threshold in size. When this flag is set, Berkeley DB will allocate memory for the returned key or data item (using malloc(3), or the user-specified malloc function), and return a pointer to it in the data field of the key or data DBT structure. Because any allocated memory becomes the responsibility of the calling application, the caller must determine whether memory was allocated using the returned value of the data field. It is an error to specify more than one of DB_DBT_MALLOC, DB_DBT_REALLOC, and DB_DBT_USERMEM. When this flag is set Berkeley DB will allocate memory for the returned key or data item (using realloc(3), or the user-specified realloc function), and return a pointer to it in the data field of the key or data DBT structure. Because any allocated memory becomes the responsibility of the calling application, the caller must determine whether memory was allocated using the returned value of the data field. The difference between DB_DBT_MALLOC and DB_DBT_REALLOC is that the latter will call realloc(3) instead of malloc(3), so the allocated memory will be grown as necessary instead of the application doing repeated free/malloc calls. It is an error to specify more than one of DB_DBT_MALLOC, DB_DBT_REALLOC, and DB_DBT_USERMEM. The data field of the key or data structure must refer to memory that is at least ulen bytes in length. If the length of the requested item is less than or equal to that number of bytes, the item is copied into the memory to which the data field refers. Otherwise, the size field is set to the length needed for the requested item, and the error DB_BUFFER_SMALL is returned. It is an error to specify more than one of DB_DBT_MALLOC, DB_DBT_REALLOC, and DB_DBT_USERMEM. Do partial retrieval or storage of an item. If the calling application is doing a get, the dlen bytes starting doff bytes from the beginning of the retrieved data record are returned as if they comprised the entire record. If any or all of the specified bytes do not exist in the record, the get is successful, and any existing bytes are returned. For example, if the data portion of a retrieved record was 100 bytes, and a partial retrieval was done using a DBT having a dlen field of 20 and a doff field of 85, the get call would succeed, the data field would refer to; if dlen is larger than size the record will shrink. If the specified bytes do not exist, the record will be extended using nul bytes as necessary, and the put call will succeed. It is an error to attempt a partial put using the DB->put() method in a database that supports duplicate records. Partial puts in databases supporting duplicate records must be done using a DBcursor->put() method.. This flag is ignored when used with the pkey parameter on DB->pget() or DBcursor->pget(). After an application-supplied callback routine passed to either DB->associate() or DB->set_append_recno() is executed, the data field of a DBT may refer to memory allocated with malloc(3) or realloc(3). In that case, the callback sets the DB_DBT_APPMALLOC flag in the DBT so that Berkeley DB will call free(3) to deallocate the memory when it is no longer required. Set in a secondary key creation callback routine passed to DB->associate() to indicate that multiple secondary keys should be associated with the given primary key/data pair. If set, the size field indicates the number of secondary keys and the data field refers to an array of that number of DBT structures. The DB_DBT_APPMALLOC flag may be set on any of the DBT structures to indicate that their data field needs to be freed. When this flag is set Berkeley DB will not write into the DBT. This may be set on key values in cases where the key is a static string that cannot be written and Berkeley DB might try to update it because the application has set a user defined comparison function.
http://docs.oracle.com/cd/E17076_03/html/api_reference/C/dbt.html
CC-MAIN-2014-15
refinedweb
1,064
57.5
Created on 2008-04-18 21:02 by jmillikin, last changed 2008-05-04 09:09 by georg.brandl. This issue is now closed. Using the following class layout: class A (object): def a (self): "A.a" pass class B (A): def b (self): "B.b" pass If sphinx.ext.autodoc is used to extract documentation, the entry for class B will have subentries for both the a() and b() methods. This is unnecessary clutter. It would be nice if the inherited method was skipped when documenting B, or even better if it was inserted as a "stub" linking to the documentation for A.a(). Thanks. In SVN (r62695), autodoc now skips inherited members unless the :inherited-members: flag option is given.
https://bugs.python.org/issue2656
CC-MAIN-2018-13
refinedweb
122
67.65
Find the number of CPUs using python : Using python, we can easily check the number of CPUs available in a system. In this example program, we will learn two different methods to get this count. What is CPU numbers : CPU or central processing unit is the main processing unit in a computer that handles all computational works. A CPU can contain only one single core or multiple cores. Single core CPUs are rare these days and they are slower than multi-core units. A single core CPU can work on only one process but a multi-core CPU can work on multiple tasks simultaneously. In simple words, multi-core CPUs can provide a better result on multitasking. For example, a dual-core CPU appears to the operating system as two separate CPUs. Actually, the computer has only one CPU, but it appears like two. Similarly, a quad-core CPU has four central processing units and an octa-core CPU has eight processing units. You can do multitasking on a single core processor but the speed will be significantly low than any other multi-core processor. It will give you an illusion that more than one process is running at the same time, but actually, the CPU will work one process at a time. It will keep switching between processes to create the illusion. Multiple core CPUs can work on multiple processes at the same time. For example, a dual-core process can work on two processes parallel at the same time. It will make the system faster than a single core CPU. So, systems have actually one physical CPU unit with multiple cores in it. Previously multiple physical CPUs were used before multiple cores were introduced, but that required multiple ports for each CPU on the motherboard, space for each CPU and a lot of other issues. Using multiple cores helps us to keep the CPU unit small and it requires less space and fewer ports. In this tutorial, we are going to learn how to get the total CPU count in the system using python. Both are one-liner programs as we are only printing out the count of total CPUs. Note the output of the program will be different on different systems. This program will come in handy if you are writing code that behaves differently with platforms of different CPU count. Python program to find the CPU number : We will show you two different methods to find out the CPU count. Both methods will print the same output in the same machine. Method 1 : Using os.cpu_count() . It returns the number of CPUs in the system and ‘None’ if undetermined. Method 2 : Using multiprocessing.cpucount(). The output is equal to the previous example i.e. both methods will return the same value. Both of these numbers are not equivalent to the number of CPUs the current process can use. To get the number of usable CPUs, we can use len(os.schedgetaffinity(0)). But this value is available on some Unix platforms. Python program : import multiprocessing import os print (multiprocessing.cpu_count()) print (os.cpu_count()) #print (len(os.sched_getaffinity(0))) You can also download this program from here. Sample Output : As you can see that the values are the same for all these three methods. Similar tutorials : - - Python program to print numbers with comma as thousand separators
https://www.codevscolor.com/write-python-program-find-number-cpu-count/
CC-MAIN-2020-29
refinedweb
559
65.93
Domain Ownership Checker Project description This Python library implements different strategies to validate the ownership of a domain name. Available strategies All strategies takes 3 arguments: the domain to check, a static DNS safe prefix like “yourservice-domain-verification” and a randomly generated code. - DNS TXT record: checks for the {prefix}-{code} string present in one of the TXT records on the domain name. - DNS CNAME record: checks for the existence of CNAME` record composed on the static ``{prefix}-{code} on the domain pointing to domain (usually yours) which the host is {prefix} (i.e.: {prefix}.yourdomain.com). NOTE: you may want to make sure that {prefix}.yourdomain.com resolves to something as some zone editors may check that. - Meta Tag: checks for the presence of a <meta name="{prefix}" content="{code}"> tag in the <head> part of the domain’s home page using either HTTP or HTTPs protocols. - HTML File: checks for the presence of a file named {code}.html at the root of the domain’s website containing the string {prefix}={code} using either HTTP or HTTPs protocols. Usage Example Simple usage will check the domain with all available strategies and return True if the validation passed: import domcheck domain = "example.com" prefix = "myservice-domain-verification" code = "myserviceK2d8a0xdhh" if domcheck.check(domain, prefix, code): print "This domain is verified" You may filter strategies by passing a coma separated list of strategies: domcheck.check(domain, prefix, code, strategies="dns_txt,meta_tag") Installation To install domcheck, simply: $ pip install domcheck Licenses All source code is licensed under the MIT License. Project details Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/domcheck/
CC-MAIN-2021-21
refinedweb
282
54.12
How to access MainWindow statusBar from a OpenGL glWidget mouse event? Inside my "class glwidget : public QGLWidget, protected QGLFunctions" I want to call the MainWindow method "statusBar()->showMessage( cursor location)" as the cursor moves over an image in my mouseMoveEvent() method. I've tried passing the MainWindow instance down into the glwidget, but there are circular include problems - MainWindow.h includes glwidget.h, so I can't include mainwindow.h inside glwidget.h. I've tried playing with the Ui namespace, and after 3 hours I'm giving up. Is there an easy way to do this? I'll even try the difficult way ... Thanks - Chris Kawa Moderators In your glwidget create a signal eg. signalMessage(QString msg) and emit it in the mouseMoveEvent(). In your main window create a slot eg. showMessage(QString msg) that will output something in the status bar. Connect those two in your main window. That way you don't need to include anything in the glwidget.
https://forum.qt.io/topic/24137/how-to-access-mainwindow-statusbar-from-a-opengl-glwidget-mouse-event
CC-MAIN-2017-43
refinedweb
162
69.89
[This is now documented here:] This should help dealing with scenarios in Outlook that cause forms to become one-offed. Topic How to remove one-off form attributes from a message which has unexpectedly been “one-offed”. One-Off Forms A message which has been “one-offed” is one where a custom form definition has been saved with the message. While there are legitimate scenarios for one-offing a form, typically this happens unexpectedly. The negative side effects and descriptions of how messages can become one-offed are discussed in the following Knowledge Base article: Removing One-Off Properties A message which has been marked as a one-off can be restored to a regular message by deleting a set of named properties and removing some flags from another named property. This process can be done with Extended MAPI or CDO. The properties which must be deleted are all in the PSETID_Common namespace and are dispidFormStorage, dispidPageDirStream, dispidFormPropStream, and dispidScriptStream. The property which must be modified is also in the PSETID_Common namespace. The flags INSP_ONEOFFFLAGS must be removed from dispidCustomFlag. In addition, the property dispidPropDefStream in the PSETID_Common namespace may also be removed. If this property is removed, then the flag INSP_PROPDEFINITION should be removed from dispidCustomFlag. A side effect of removing this property is that the Outlook Object Model and the Outlook User Interface will no longer be able to access user properties which have been set on the item. These properties and their values will still be accessible through MAPI. Note that if this property is not removed and the items is one-offed again, it is possible that the property can be overwritten with new data. Definitions #define dispidFormStorage 0x850F #define dispidPageDirStream 0x8513 #define dispidFormPropStream 0x851B #define dispidPropDefStream 0x8540 #define dispidScriptStream 0x8541 #define dispidCustomFlag 0x8542 #define INSP_ONEOFFFLAGS 0xD000000 #define INSP_PROPDEFINITION 0x2000000 DEFINE_OLEGUID(PSETID_Common, MAKELONG(0x2000+(8),0x0006),0,0); Usage The following sample code illustrates how to remove one-off attributes from a message using Extended MAPI: // we'll be updating, don't count it lpTags->cValues = ulNumOneOffIDs-1; // If we're not removing the prop def stream OL // doesn't look for the props we; } The following sample code illustrates how to remove one-off attributes from a message using CDO 1.21: Sub DeleteFormDefinitionWithCDO(MessageEID As String, bDeletePropDef As Boolean) Const strPSetCommonGUID = "0820060000000000C000000000000046" ' PSETID_Common Dim objSession As MAPI.Session Dim oFolderCDO As MAPI.Folder Dim oMessages As MAPI.Messages Dim oMessage As MAPI.Message Dim myFields As MAPI.Fields Set objSession = New MAPI.Session objSession.Logon , , True, False Set oMessage = objSession.GetMessage(MessageEID) Set myFields = oMessage.Fields On Error Resume Next myFields.Item("{" & strPSetCommonGUID & "}0x850F").Delete ' dispidFormStorage myFields.Item("{" & strPSetCommonGUID & "}0x8513").Delete ' dispidPageDirStream myFields.Item("{" & strPSetCommonGUID & "}0x851B").Delete ' dispidFormPropStream myFields.Item("{" & strPSetCommonGUID & "}0x8541").Delete ' dispidScriptStream ' Update dispidCustomFlag myFields.Item("{" & strPSetCommonGUID & "}0x8542") = _ myFields.Item("{" & strPSetCommonGUID & "}0x8542") And Not &HD000000 ' INSP_ONEOFFFLAGS If bDeletePropDef Then myFields.Item("{" & strPSetCommonGUID & "}0x8540").Delete ' dispidPropDefStream myFields.Item("{" & strPSetCommonGUID & "}0x8542") = _ myFields.Item("{" & strPSetCommonGUID & "}0x8542") And Not &H2000000 ' INSP_PROPDEFINITION End If oMessage.Update objSession.Logoff Set objSession = Nothing End Sub Form One-offs are a major headache and in practice appears to rarely be the desired behavior – is there some major technical roadblock from allowing developers to completely short-curcuit the creation of one-offs? It would be interesting to be enlightened as to the details of the original decision to add the current form one-off behavior and why it persists to this day. Hello. I’m new to the Outlook programming and I have headaches on the one-off forms. If I were to reopen the previously saved item, the item becomes one-off, am I right? Can you teach me what I have to do if I need to run the code on the previously saved item? I have done everything done almost everything that prevents the item to go one-off but still can’t work. My email is natur3_dr3am3rz@hotmail.com Thanks in advance. Gosaca – I can’t speak for the original designers of the Outlook form features, but my understanding is that the initial design was based on the assumption that when a developer made a change to the form definition they wanted that change to stick -for example adding a new user-defined field to the item and being able to reference that field later. Back in the Outlook 97/98/2000 days one-offs weren’t as big of a headache because users would still be prompted to run the VBScript code in a one-off item (via the Enable/Disable Macro dialog). Although one-offs still weren’t very desirable by most form developers, some intentionally designed one-off forms with the assumption that users would be able to click Enable on the Enable/Disable macro button. This was fairly common with form solutions distributed in the .oft (Outlook Template) file format. Since the Outlook Object Model Security features released around the Outlook 2000 SR1 timeframe security has been improved, but one-off forms have been less and less useful due to the default blocking VBScript and non-default ActiveX controls. Now, one-offs are pretty much a headache for most form developers. There is always risk in trying to make a significant change to the architecture of a developer feature especially when developers have depended on it working a specific way for several years. It is not easy to predict all of the consequences of making a change. The good news is that most of the time one-off behavior can be avoided, and going forward the new Outlook 2007 Form Regions feature provides a more robust solution, especially if multiple developers from other companies need to customize the same item. I hope this helps add some perspective. Here are some suggestions to help identify and eliminate the cause of one-off behavior when working with I have a problem where all my recuring tasks no longer function. I dabled with a custom form and used it for a while instead of tasks. I then decided I didn’t like it so reset msgclass back to default task form. however all my tasks still look like the original form. (i.e. I must have saved the definition). Now I can’t undo anything. My standard tasks still work but the recurring ones no longer allow me to make changes or complete etc. I am not a programmer so have no idea how to apply what you have raised in this blog. Someone please develop a generic tool to help us non programmers recover our system.
https://blogs.msdn.microsoft.com/stephen_griffin/2005/12/29/new-outlook-documentation-part-5-one-off-forms/
CC-MAIN-2018-30
refinedweb
1,093
55.95
We’ll build our UI following a Component-Driven Development (CDD) methodology. It’s a process that builds UIs from the “bottom up” starting with components and ending with screens. CDD helps you scale the amount of complexity you’re faced with as you build out the UI. Task is the core component in our app. Each task displays slightly differently depending on exactly what state it’s in. We display a checked (or unchecked) checkbox, some information about the task, and a “pin” button, allowing us to move tasks up and down the list. Putting this together, we’ll need these props: title– a string describing the task state- which list is the task currently in and is it checked off? As we start to build Task, we first write our test states that correspond to the different types of tasks sketched above. Then we use Storybook to build the component in isolation using mocked data. We’ll manually test the component’s appearance given each state as we go. First, let’s create the task component and its accompanying story file: src/components/Task.js and src/components/Task.stories.js. We’ll begin with a basic implementation of the Task, simply taking in the attributes we know we’ll need and the two actions you can take on a task (to move it between lists): // src/components/Task.js import React from 'react'; export default function Task({ task: { id, title, state }, onArchiveTask, onPinTask }) { return ( <div className="list-item"> <input type="text" value={title} readOnly={true} /> </div> ); } Above, we render straightforward markup for Task based on the existing HTML structure of the Todos app. Below we build out Task’s three test states in the story file: // src/components/Task.stories.js import React from 'react'; import Task from './Task'; export default { component: Task, title: 'Task', }; const Template = args => <Task {...args} />; export const Default = Template.bind({}); Default.args = { task: { id: '1', title: 'Test Task', state: 'TASK_INBOX', updatedAt: new Date(2018, 0, 1, 9, 0), }, }; export const Pinned = Template.bind({}); Pinned.args = { task: { ...Default.args.task, state: 'TASK_PINNED', }, }; export const Archived = Template.bind({}); Archived.args = { task: { ...Default.args.task, state: 'TASK_ARCHIVED', }, }; There are two basic levels of organization in Storybook: the component and its child stories. Think of each story as a permutation of a component. You can have as many stories per component as you need. Component To tell Storybook about the component we are documenting, we create a default export that contains: component-- the component itself, title-- how to refer to the component in the sidebar of the Storybook app, excludeStories-- exports in the story file that should not be rendered as stories by Storybook. argTypes-- specify the args behavior in each story. To define our stories, we export a function for each of our test states to generate a story. The story is a function that returns a rendered element (i.e. a component with a set of props) in a given state---exactly like a Stateless Functional Component. As we have multiple permutations of our component, it's convenient to assign it to a Template variable. Introducing this pattern in your stories will reduce the amount of code you need to write and maintain. Template.bind({})is a standard JavaScript technique for making a copy of a function. We use this technique to allow each exported story to set its own properties, but use the same implementation. Arguments or args for short, allow us to live edit our components with the controls addon without restarting Storybook. Once an args value changes so does the component. When creating a story we use a base task arg to build out the shape of the task the component expects. This is typically modelled from what the true data looks like. Again, export-ing this shape will enable us to reuse it in later stories, as we'll see. action()to stub them in. We'll need to make a couple of changes to the Storybook configuration so it notices not only our recently created stories, but also allows us to use the CSS file that was introduced in the previous chapter. Start by changing your Storybook configuration file ( .storybook/main.js) to the following: // .storybook/main.js module.exports = { //👇 Location of our stories stories: ['../src/components/**/*.stories.js'], addons: [ '@storybook/addon-links', '@storybook/addon-essentials', '@storybook/preset-create-react-app', ], }; After completing the change above, inside the .storybook folder, change your preview.js to the following: // .storybook/preview.js import '../src/index.css'; //👈 The app's CSS file goes here //👇 Configures Storybook to log the actions( onArchiveTask and onPinTask ) in the UI. export const parameters = { actions: { argTypesRegex: '^on[A-Z].*' }, }; parameters are typically used to control the behavior of Storybook's features and addons. In our case we're going to use them to configure how the actions (mocked callbacks) are handled. actions allows us to create callbacks that appear in the actions panel of the Storybook UI when clicked. So when we build a pin button, we’ll be able to determine in the test UI if a button click is successful. Once we’ve done this, restarting the Storybook server should yield test cases for the three Task states: Now we have Storybook setup, styles imported, and test cases built out, we can quickly start the work of implementing the HTML of the component to match the design. The component is still basic at the moment. First write the code that achieves the design without going into too much detail: // src/components/Task.js import React from 'react'; export default function Task({ task: { id, title, state }, onArchiveTask, onPinTask }) { return ( <div className={`list-item ${state}`}> <label className="checkbox"> <input type="checkbox" defaultChecked={state === 'TASK_ARCHIVED'} disabled={true} <span className="checkbox-custom" onClick={() => onArchiveTask(id)} /> </label> <div className="title"> <input type="text" value={title} readOnly={true} </div> <div className="actions" onClick={event => event.stopPropagation()}> {state !== 'TASK_ARCHIVED' && ( // eslint-disable-next-line jsx-a11y/anchor-is-valid <a onClick={() => onPinTask(id)}> <span className={`icon-star`} /> </a> )} </div> </div> ); } The additional markup from above combined with the CSS we imported earlier yields the following UI: It’s best practice to use propTypes in React to specify the shape of data that a component expects. Not only is it self documenting, it also helps catch problems early. // src/components/Task.js import React from 'react'; import PropTypes from 'prop-types'; export default function Task({ task: { id, title, state }, onArchiveTask, onPinTask }) { // ... } Task.propTypes = { /** Composition of the task */ task: PropTypes.shape({ /** Id of the task */ id: PropTypes.string.isRequired, /** Title of the task */ title: PropTypes.string.isRequired, /** Current state of the task */ state: PropTypes.string.isRequired, }), /** Event to change the task to archived */ onArchiveTask: PropTypes.func, /** Event to change the task to pinned */ onPinTask: PropTypes.func, }; Now a warning in development will appear if the Task component is misused. We’ve now successfully built out a component without needing a server or running the entire frontend application. The next step is to build out the remaining Taskbox components one by one in a similar fashion. As you can see, getting started building components in isolation is easy and fast. We can expect to produce a higher-quality UI with fewer bugs and more polish because it’s possible to dig in and test every possible state. Storybook gave us a great way to manually test our application UI during construction. The ‘stories’ will help ensure we don’t break our Task's appearance as we continue to develop the app. However, it is a completely manual process at this stage, and someone has to go to the effort of clicking through each test state and ensuring it renders well and without errors or warnings. Can’t we do that automatically? Snapshot testing refers to the practice of recording the “known good” output of a component for a given input and then flagging the component whenever the output changes in future. This complements Storybook, because it’s a quick way to view the new version of a component and check out the changes. With the Storyshots addon a snapshot test is created for each of the stories. Use it by adding the following development dependencies: yarn add -D @storybook/addon-storyshots react-test-renderer Then create an src/storybook.test.js file with the following in it: // src/storybook.test.js import initStoryshots from '@storybook/addon-storyshots'; initStoryshots(); That's it, we can run yarn test and see the following output: We now have a snapshot test for each of our Task stories. If we change the implementation of Task, we’ll be prompted to verify the changes.
https://storybook.js.org/tutorials/intro-to-storybook/react/en/simple-component/
CC-MAIN-2021-10
refinedweb
1,442
55.03
Minor tweaks to documentation. 1: \ A less simple implementation of the blocks wordset. 23: \ provide it and many buffers on OSs that do not provide mmap. 24: 25: \ Now, the replacement algorithm is "direct mapped"; change to LRU 26: \ if too slow. Using more buffers helps, too. 27: 28: \ I think I avoid the assumption 1 char = 1 here, but I have not tested this 29: 30: \ 1024 constant chars/block \ mandated by the standard 31: 32: require struct.fs 33: 34: struct 35: cell% field buffer-block \ the block number 36: cell% field buffer-fid \ the block's fid 37: cell% field buffer-dirty \ the block dirty flag 38: char% chars/block * field block-buffer \ the data 39: cell% 0 * field next-buffer 40: end-struct buffer-struct 41: 42: Variable block-buffers 43: Variable last-block 44: 45: $20 Value buffers 46: 47: User block-fid 48: User offset 0 offset ! \ store 1 here fore 0.4.0 compatibility 49: 50: : block-cold ( -- ) 51: block-fid off last-block off 52: buffer-struct buffers * %alloc dup block-buffers ! ( addr ) 53: buffer-struct %size buffers * erase ; 54: 55: ' block-cold INIT8 chained 56: 57: block-cold 58: 59: Defer flush-blocks ( -- ) \ gforth 60: 61: : open-blocks ( c-addr u -- ) \ gforth 62: \g Use the file, whose name is given by @i{c-addr u}, as the blocks file. 63: 2dup open-fpath-file 0<> 64: if 65: r/w bin create-file throw 66: else 67: rot close-file throw 2dup file-status throw bin open-file throw 68: >r 2drop r> 69: then 70: block-fid @ IF flush-blocks block-fid @ close-file throw THEN 71: block-fid ! ; 72: 73: : use ( "file" -- ) \ gforth 74: \g Use @i{file} as the blocks file. 75: name open-blocks ; 76: 77: \ the file is opened as binary file, since it either will contain text 78: \ without newlines or binary data 79: : get-block-fid ( -- wfileid ) \ gforth 80: \G Return the file-id of the current blocks file. If no blocks 81: \G file has been opened, use @file{blocks.fb} as the default 82: \G blocks file. 83: block-fid @ 0= 84: if 85: s" blocks.fb" open-blocks 86: then 87: block-fid @ ; 88: 89: : block-position ( u -- ) \ block 90: \G Position the block file to the start of block @i{u}. 91: offset @ - chars/block chars um* get-block-fid reposition-file throw ; 92: 93: : update ( -- ) \ block 94: \G Mark the state of the current block buffer as assigned-dirty. 95: last-block @ ?dup IF buffer-dirty on THEN ; 96: 97: : save-buffer ( buffer -- ) \ gforth 98: >r 99: r@ buffer-dirty @ r@ buffer-block @ 0<> and 100: if 101: r@ buffer-block @ block-position 102: r@ block-buffer chars/block r@ buffer-fid @ write-file throw 103: r@ buffer-dirty off 104: endif 105: rdrop ; 106: 107: : empty-buffer ( buffer -- ) \ gforth 108: buffer-block off ; 109: 110: : save-buffers ( -- ) \ block 111: \G Transfer the contents of each @code{update}d block buffer to 112: \G mass storage, then mark all block buffers as unassigned. 113: block-buffers @ 114: buffers 0 ?DO dup save-buffer next-buffer LOOP drop ; 115: 116: : empty-buffers ( -- ) \ block-ext 117: \G Mark all block buffers as unassigned; if any had been marked as 118: \G assigned-dirty (by @code{update}), the changes to those blocks 119: \G will be lost. 120: block-buffers @ 121: buffers 0 ?DO dup empty-buffer next-buffer LOOP drop ; 122: 123: : flush ( -- ) \ block 124: \G Perform the functions of @code{save-buffers} then 125: \G @code{empty-buffers}. 126: save-buffers 127: empty-buffers ; 128: 129: ' flush IS flush-blocks 130: 131: : get-buffer ( u -- a-addr ) \ gforth 132: 0 buffers um/mod drop buffer-struct %size * block-buffers @ + ; 133: 134: : block ( u -- a-addr ) \ gforthman- block 135: \G If a block buffer is assigned for block @i{u}, return its 136: \G start address, @i{a-addr}. Otherwise, assign a block buffer 137: \G for block @i{u} (if the assigned block buffer has been 138: \G @code{update}d, transfer the contents to mass storage), read 139: \G the block into the block buffer and return its start address, 140: \G @i{a-addr}. 141: dup offset @ u< -35 and throw 142: dup get-buffer >r 143: dup r@ buffer-block @ <> 144: r@ buffer-fid @ block-fid @ <> or 145: if 146: r@ save-buffer 147: dup block-position 148: r@ block-buffer chars/block get-block-fid read-file throw 149: \ clear the rest of the buffer if the file is too short 150: r@ block-buffer over chars + chars/block rot chars - blank 151: r@ buffer-block ! 152: get-block-fid r@ buffer-fid ! 153: else 154: drop 155: then 156: r> dup last-block ! block-buffer ; 157: 158: : buffer ( u -- a-addr ) \ block 159: \G If a block buffer is assigned for block @i{u}, return its 160: \G start address, @i{a-addr}. Otherwise, assign a block buffer 161: \G for block @i{u} (if the assigned block buffer has been 162: \G @code{update}d, transfer the contents to mass storage) and 163: \G return its start address, @i{a-addr}. The subtle difference 164: \G between @code{buffer} and @code{block} mean that you should 165: \G only use @code{buffer} if you don't care about the previous 166: \G contents of block @i{u}. In Gforth, this simply calls 167: \G @code{block}. 168: \ reading in the block is unnecessary, but simpler 169: block ; 170: 171: User scr ( -- a-addr ) \ block-ext s-c-r 172: \G @code{User} variable -- @i{a-addr} is the address of a cell containing 173: \G the block number of the block most recently processed by 174: \G @code{list}. 175: 0 scr ! 176: 177: \ nac31Mar1999 moved "scr @" to list to make the stack comment correct 178: : updated? ( n -- f ) \ gforth 179: \G Return true if @code{updated} has been used to mark block @i{n} 180: \G as assigned-dirty. 181: buffer 182: [ 0 buffer-dirty 0 block-buffer - ] Literal + @ ; 183: 184: : list ( u -- ) \ block-ext 185: \G Display block @i{u}. In Gforth, the block is displayed as 16 186: \G numbered lines, each of 64 characters. 187: \ calling block again and again looks inefficient but is necessary 188: \ in a multitasking environment 189: dup scr ! 190: ." Screen " u. 191: scr @ updated? 0= IF ." not " THEN ." modified " cr 192: 16 0 193: ?do 194: i 2 .r space scr @ block i 64 * chars + 64 type cr 195: loop ; 196: 197: : (source) ( -- c-addr u ) 198: blk @ ?dup 199: IF block chars/block 200: ELSE tib #tib @ 201: THEN ; 202: 203: ' (source) IS source ( -- c-addr u ) \ core 204: \G @i{c-addr} is the address of the input buffer and @i{u} is the 205: \G number of characters in it. 206: 207: : load ( i*x n -- j*x ) \ block 208: \G Save the current input source specification. Store @i{n} in 209: \G @code{BLK}, set @code{>IN} to 0 and interpret. When the parse 210: \G area is exhausted, restore the input source specification. 211: push-file 212: dup loadline ! blk ! >in off ['] interpret catch 213: pop-file throw ; 214: 215: : thru ( i*x n1 n2 -- j*x ) \ block-ext 216: \G @code{load} the blocks @i{n1} through @i{n2} in sequence. 217: 1+ swap ?DO I load LOOP ; 218: 219: : +load ( i*x n -- j*x ) \ gforth 220: \G Used within a block to load the block specified as the 221: \G current block + @i{n}. 222: blk @ + load ; 223: 224: : +thru ( i*x n1 n2 -- j*x ) \ gforth 225: \G Used within a block to load the range of blocks specified as the 226: \G current block + @i{n1} thru the current block + @i{n2}. 227: 1+ swap ?DO I +load LOOP ; 228: 229: : --> ( -- ) \ gforthman- gforth chain 230: \G If this symbol is encountered whilst loading block @i{n}, 231: \G discard the remainder of the block and load block @i{n+1}. Used 232: \G for chaining multiple blocks together as a single loadable 233: \G unit. Not recommended, because it destroys the independence of 234: \G loading. Use @code{thru} (which is standard) or @code{+thru} 235: \G instead. 236: refill drop ; immediate 237: 238: : block-included ( a-addr u -- ) \ gforth 239: \G Use within a block that is to be processed by @code{load}. Save 240: \G the current blocks file specification, open the blocks file 241: \G specified by @i{a-addr u} and @code{load} block 1 from that 242: \G file (which may in turn chain or load other blocks). Finally, 243: \G close the blocks file and restore the original blocks file. 244: block-fid @ >r block-fid off open-blocks 245: 1 load block-fid @ close-file throw flush 246: r> block-fid ! ; 247: 248: \ thrown out because it may provide unpleasant surprises - anton 249: \ : include ( "name" -- ) 250: \ name 2dup dup 3 - /string s" .fb" compare 251: \ 0= IF block-included ELSE included THEN ; 252: 253: get-current environment-wordlist set-current 254: true constant block 255: true constant block-ext 256: set-current 257: 258: : bye ( -- ) \ tools-ext 259: \G Return control to the host operating system (if any). 260: ['] flush catch drop bye ;
http://www.complang.tuwien.ac.at/cvsweb/cgi-bin/cvsweb/gforth/blocks.fs?f=h;only_with_tag=MAIN;content-type=text%2Fx-cvsweb-markup;ln=1;rev=1.29
CC-MAIN-2020-45
refinedweb
1,556
75.44
With new Parsing API GroovyVirtualSourceProvider is not called anymore - as a consequence Groovy files are not available in Java code completion. Actually more important thing is that java parser does not know about groovy classes so it is displaying errors in source files. This sounds rather serious... Not sure how serious it is. As far as I know there are two clients of this API and just one uses it in reality (groovy). This API is used during index building to allow mixed compilation unit among java and languages compiled into class files. The only use case for it is this: java: class A { private B b; } groovy: class B { private A a; } VirtualSourceProvider seems to be required even for groovy only code (in situation when there is not 1-to-1 mapping between file and class and such class is used in other groovy file). *** Issue 164341 has been marked as a duplicate of this issue. *** Changing the description to reflect the problem user sees. When groovy class is used in Java source this gives the user false error - this happens even for demo project bundled with ide. When user defines multiple classes in one groovy source file and use these in other file he will get compilation error in the editor. *** Issue 160900 has been marked as a duplicate of this issue. *** *** Issue 165348 has been marked as a duplicate of this issue. *** *** Issue 164288 has been marked as a duplicate of this issue. *** This issue was also reported by NetCAT 6.7 participant. I will integrate VSP this week. integrated into jet-main: 6ad317084d5d Integrated into 'main-golden', will be available in build *200906081401* on (upload may still be in progress) Changeset: User: Tomas Zezula <tzezula@netbeans.org> Log: #161176:False compilation errors in editor (was: VirtualSourceProvider does not work anymore) - this is fixing some problems introduced by 6ad317084d5d. Mainly there are indexers registered for 'all languages' (aka MimePath.EMPTY) and they should not be considered by the algorithm determining mime types that each particular indexer is registered for. Without this fix these indexers received *all* files for every mimetype in the resources map. However even with this fix indexers registered for multiple mimetypes will receive the same set of files multiple times, which is not very efficient. I'll change this when I rewrite this whole algorithm for issue #166340. *** Issue 166851 has been marked as a duplicate of this issue. *** Just downloaded & tried 200906110201. While the parser error seems to have been fixed (the is no error in the Java file that incorporates a Groovy object), the there are still Red exclamation marks on the project & package icons, indicating a parsing/compilation error that is non-existent. See attached screenshot... Created attachment 83442 [details] Invalid error icons - there are no compilation or parsing errors Integrated into 'main-golden', will be available in build *200906111401* on (upload may still be in progress) Changeset: User: Vita Stejskal <vstejskal@netbeans.org> Log: #161176: following up on 6ad317084d5d; ignoring 'all languages' indexers, they are always registered to recieve all the files *** Issue 167647 has been marked as a duplicate of this issue. *** The error badges in the editor are not related to this issue which original name was "Missing VSP support" and was renamed to the "False compilation errors in editor". Also the error badges on packages are unrelated to the editor. There are two possible reasons of these error badges. 1) The groovy VSP generates wrong (non valid) java stub - can be handled by java support, I've fill separate issue on it #167756. 2) When the groovy file on which depends a java file is deleted (created) the java support doesn't know about it. There an enhancement filled by madamek on groovy for this. I have this same issue with my own VirtualSourceProvider implementation plug-in. I could have sworn this worked at some earlier point in 6.7 development, but it clearly does *not* work in the final 6.7 release. This is a *very* serious issue for our NetBeans usage -- and I'll have to recommend that everyone here go back to 6.5 until this is fixed. Are there plans to supply this fix in a near term module / plug-in update from the update center? [Please.] This issue has "67patch-candidate" keyword in the "Status whiteboard" which means, it will be considered for NetBeans 6.7 Update 1 [1]. [1] In the early state of the NB 6.7, only part of the java module was migrated to the parsing api but there was not the indexing api. The java module used the old RepositoryUpdater which had a support for the VirtualSources. Later we have merged the indexing api and migrated java to use it. The new API had no support for VirtualSources. I've reintroduced the VirtualSources after the feature freeze of the NB 6.7 release, it's not a part of the NB 6.7. But it will be covered by the first NB 6.7 patch. This patch will also contains the fix of #167756 which handles situations when the generated stub has errors. *** Issue 168013 has been marked as a duplicate of this issue. *** v *** Issue 168031 has been marked as a duplicate of this issue. *** The fix has been ported into the release67_fixes repository. *** Issue 168151 has been marked as a duplicate of this issue. *** *** Issue 168054 has been marked as a duplicate of this issue. *** Added a note about this issue into the Groovy tutorial: does not seem to contain all the changes from 6ad317084d5d and 4a23160602c7. I'm fixing it now. Hopefully this transplants all the changes correctly - v in 6.7.1 *** Issue 168770 has been marked as a duplicate of this issue. *** I am still seeing this error in 6.7.1 (installed fresh as 6.7.1 rather than obtained by updating 6.7) for my plug-in which implements VirtualSourceProvider. The same plug-in works flawlessly in 6.5. Is there something that I need to change -- if not, this bug is most certainly *not* resolved by 6.7.1. I have a good amount of logging in my module -- but the log management module no longer appears to be available for 6.7. How does one go about managing NetBeans logging otherwise? "I am still seeing this error in 6.7.1 (installed fresh as 6.7.1 rather than obtained by updating 6.7) for my plug-in which implements VirtualSourceProvider." - So, does you VirtualSourceProvider get instantiated and called? The groovy plugin uses VirtualSourceProvider as well and it seems to work ok. It seems that my plug-in is not getting called. Could this have something to do with lazier plug-in loading in 6.7? My plug-in is activated and the IDE log does not show any errors associated with it. "It seems that my plug-in is not getting called." - Do you mean that your implementation of VirtualSourceProvider is not getting called? Is it correctly registered (eg. is it instantiated, but not called)? It should be registered in the default Lookup (eg. via o.o.util.lookup.ServiceProvider annotation). Also I'm not sure if this was required prior 6.7, but you should have JavaCustomIndexer registered for your mime type in MimeLookup. Look at how groovy.editor does it. It adds something like <file name="JavaIndexer.shadow"> <attr name="originalFile" stringvalue="Editors/text/x-java/JavaIndexer.instance"/> </file> to the Editors/text/x-groovy folder. I added more logging to my plug-in and hard-wired the verbosity to Level.ALL (though I did find the log management plug-in, which really should be part of NetBeans' own module development module set). In my VirtualSourceProvider implementation, I log "Instantiated" in the constructor and "Translate called" first thing in translate() [followed by a lot of other logging later in translate()]. The result (with only a couple of projects open and clearing the var directory prior to startup) is: FINE [com.ptc.rbinfohandler.RbInfoHandler]: Instantiated INFO [org.netbeans.modules.parsing.impl.indexing.RepositoryUpdater]: Complete indexing of 6 source roots took: 8384 ms That's it -- note the lack of "Translate called". My VirtualSourceProvider implementation is called out in META-INF/services just as it was in 6.5.1. Is there something else that needs to be done to actually get my VirtualSourceProvider to be called?!? My getSupportedExtensions() returns Collections.singleton( "rbInfo" ) -- my comments state that extensions do not include the "." for this API and that certainly worked in 6.5.1. My index() returns "true". I've tried normal, autoload, and eager settings -- which made no difference. Something is screwy here as this worked great in 6.5.1. There is one important change. The NB 6.7.x is using a common infrastructure for parsing and indexing (the parsing API). In the 6.5 the creation of set of files to be scanned was done by java module. In the 6.7.x the set is created by parsing API and passed to the java. As your file is not known for the java indexer the parsing API is not passing it to java module. You have to tell the parsing API that your files should be handled by the java indexer. This is done by registering the java indexer for your files: <folder name="Editors"> <folder name="text"> <folder name="your-mime-type"> <file name="JavaIndexer.shadow"> <attr name="originalFile" stringvalue="Editors/text/x-java/JavaIndexer.instance"/> </file> </folder> </folder> </folder> Also you have to have mime type recognizer for your file type associating your mime-type. If you have any problems feel free to reopen. Thanks for the help. How do I add a "mime type recognizer" for my file type? Also are these changes compatible with 6.5? Or do I need separate versions of my plug-in for 6.5 and 6.7 now? You have to provide mime type recognizer. The simplest way is to use extension based mime type recognizer. Here is an example: 1st) You have to register the recognizer in the layer.xml <folder name="Services"> <folder name="MIMEResolver"> <file name="MyMimeResolver.xml" url="MyMimeResolver.xml"> <attr name="position" intvalue="300"/> </file> </folder> </folder> 2nd) You have to create MyMimeResolver.xml file in the same package as you have a layer.xml <!DOCTYPE MIME-resolver PUBLIC "-//NetBeans//DTD MIME Resolver 1.0//EN" "http://"> <MIME-resolver> <file> <ext name="my_file_extension"/> <resolver mime="text/x-myfiletype"/> </file> </MIME-resolver> Unfortunately the changes are not compatible with 6.5. This was a reason why I didn't want to put the VirtualSourceProvider into the API, as I was not able to keep the compatibility. The module with the registered java indexer (6.7) should work even in 6.5. The IDE may complain in log about broken link as the java indexer doesn't exist in 6.5. But it should work. Thanks. This all now works great with one notable exception. I can't "Go To Declaration" or "Go To Source" from usages of the classes produced by my VirtualSourceProvider. In 6.5, when I did this it would take me to the file from which the given class was generated in my VirtualSourceProvider. Any ideas here? Does your VirtualSourceProvider.index() method return true? If so, it seems that the java module is not able to resolve the file. Can you attach one lucene index containing such a virtual source? I will look on the resource path. Yes, my index() returns true (always). How do I find such a Lucene index to attach? Created attachment 85625 [details] cache index segment apparently of interest I attached the cache/index segment that is apparently of interest (as s1.zip). The entries of interest are clientResource and launcherResource. I'll attach my VirtualSourceProvider implementation shortly. It is very short and should simply create a virtual class "A" for every A.rbInfo (with the appropriate Java package given the placement of rbInfo in the source tree). Created attachment 85626 [details] my VirtualSourceProvider implementation Your VSP seems good. I've looked into the caches and it seems that the java indexer didn't store the resource name into it. I've filled an issue #169658 to resolve it. Thanks! *** Issue 167969 has been marked as a duplicate of this issue. *** This appears to have regressed in 7.0. I was testing the Introduction to Groovy tutorial,. This has the simple Groovy class GreetingProvider, contents class GreetingProvider { def greeting = "Hello from Groovy" } I'm supposed to be able to call this from a JFrame inside the same package, with the code String greeting = provider.getGreeting().toString(); jTextField1.setText(greeting); Compilation fails utterly to know what to do with provider. I cannot reproduce the provider methods with code completion. So sorry, guys. Exact same app built by Geertjan works on my machine, same groovy jar, everything. Gremlins on my machine, it seems.
https://netbeans.org/bugzilla/show_bug.cgi?id=161176
CC-MAIN-2019-09
refinedweb
2,158
67.55
How to create File and directory in Java is probably the first things come to mind when we exposed to the file system from Java. Java provides rich IO API to access contents of File and Directory in Java and also provides lots of utility method to create a file, delete a file, read from a file, and write to file or directory. Anybody who wants to develop an especially after the introduction of java.nio package and concepts like In Memory Files, we will discuss those in probably another blog post but what it confirms is the importance of knowledge of File IO for java programmer. How to Create File and Directory in Java Example What is File in Java An important point to remember is that java.io.File object can represent both File and Directory in Java. You can check whether a File object is a file in filesystem by using utility method isFile() and whether its directory in file system by using isDirectory(). Since File permissions is honored while accessing File from Java, you can not write into a read-only files, there are utility methods like canRead() and CanWrite(). name):it will create file object inside a directory which is passed as the first argument and the file as read only in Java and listing files from to. Further Learning Complete Java Masterclass Java Fundamentals: The Java Language Java In-Depth: Become a Complete Java Engineer! Other Related Java Tutorial 11 comments : A nice post.. Never thought this can also be done.. here is my link on how to read and write into files in java Reading and Writing to Files a Java Tutorial Thanks for you comment keval . Good to know that you like my file creation tutorial. What is worth to remember is that closing any file which has been opened by java Program and handling of File related exception to make your Java program more robust. You may also like my new tutorial on files as Anonymous, thanks for your comment. Indeed using PATH separator is great idea that makes your code to run on both windows and unix, but samples are just to do it quick rather than do it perfectly but yes in production code path should not be hardcoded.? Hi , i need program for below statement , Please help me please send it my email Design & code a very simple in-memory file system and expose the file system operations e.g. create, read, write, list over HTTP. code should: * Be modular and re-usable * Be Easy to test * Demonstrate Object oriented features of the language (for Java) * Demonstrate the use of the right data structures * Demonstrate the use of the right design pattern Really nice and different Technic. Easy to understand each function. thanks. How to write program in java create folder and store multiple files then count how many files are stored in folder import java. io.DataInputStream; import java. io. File; import java. io. Exception ; Class file { public static void main(String args[]) { DataInputStream in=new DataInputStream(System. in); String r="" ; Try { r=in. readLine() ; String s1 =r +".txt"; File f1=new File(s1) ; f1. createNewFile() ; } catch(Exception e) {} } }
https://javarevisited.blogspot.com/2011/12/create-file-directory-java-example.html?showComment=1323177502988
CC-MAIN-2018-26
refinedweb
532
61.87
PERL5240DELTA(1pm) Perl Programmers Reference Guide PERL5240DELTA(1pm) NAME perl5240d); [perl #125587] <> [perl #121058] <> o The overhead of scope entry and exit has been considerably reduced, so for example subroutine calls, loops and basic blocks are all faster now. This empty function call now takes about a third less time to execute: sub f{} f();. o ". o. o Preincrement, predecrement, postincrement, and postdecrement have been made faster by internally splitting the functions which handled multiple cases into different functions. o Creating Perl debugger data structures (see "Debugger Internals" in perldebguts) for XSUBs and const subs has been removed. This removed one glob/scalar combo for each unique ".c" file o On Win32, "stat"ing or "-X"ing a path, if the file or directory does not exist, is now 3.5x faster than before. o Single arguments in list assign are now slightly faster: ($x) = (...); (...) = ($x); o Less peak memory is now used when compiling regular expression patterns. Modules and Pragmata Updated Modules and Pragmata o arybase has been upgraded from version 0.10 to 0.11. o Attribute::Handlers has been upgraded from version 0.97 to 0.99. o autodie has been upgraded from version 2.26 to 2.29. o autouse has been upgraded from version 1.08 to 1.11. o B has been upgraded from version 1.58 to 1.62. o B::Deparse has been upgraded from version 1.35 to 1.37. o base has been upgraded from version 2.22 to 2.23. o Benchmark has been upgraded from version 1.2 to 1.22. o bignum has been upgraded from version 0.39 to 0.42. o bytes has been upgraded from version 1.04 to 1.05. o Carp has been upgraded from version 1.36 to 1.40. o Compress::Raw::Bzip2 has been upgraded from version 2.068 to 2.069. o Compress::Raw::Zlib has been upgraded from version 2.068 to 2.069. o Config::Perl::V has been upgraded from version 0.24 to 0.25. o CPAN::Meta has been upgraded from version 2.150001 to 2.150005. o CPAN::Meta::Requirements has been upgraded from version 2.132 to 2.140. o CPAN::Meta::YAML has been upgraded from version 0.012 to 0.018. o Data::Dumper has been upgraded from version 2.158 to 2.160. o Devel::Peek has been upgraded from version 1.22 to 1.23. o Devel::PPPort has been upgraded from version 3.31 to 3.32. o Dumpvalue has been upgraded from version 1.17 to 1.18. o DynaLoader has been upgraded from version 1.32 to 1.38. o Encode has been upgraded from version 2.72 to 2.80. o encoding has been upgraded from version 2.14 to 2.17. o encoding::warnings has been upgraded from version 0.11 to 0.12. o English has been upgraded from version 1.09 to 1.10. o Errno has been upgraded from version 1.23 to 1.25. o experimental has been upgraded from version 0.013 to 0.016. o ExtUtils::CBuilder has been upgraded from version 0.280221 to 0.280225. o ExtUtils::Embed has been upgraded from version 1.32 to 1.33. o ExtUtils::MakeMaker has been upgraded from version 7.04_01 to 7.10_01. o ExtUtils::ParseXS has been upgraded from version 3.28 to 3.31. o ExtUtils::Typemaps has been upgraded from version 3.28 to 3.31. o feature has been upgraded from version 1.40 to 1.42. o fields has been upgraded from version 2.17 to 2.23. o File::Find has been upgraded from version 1.29 to 1.34. o File::Glob has been upgraded from version 1.24 to 1.26. o File::Path has been upgraded from version 2.09 to 2.12_01. o File::Spec has been upgraded from version 3.56 to 3.63. o Filter::Util::Call has been upgraded from version 1.54 to 1.55. o Getopt::Long has been upgraded from version 2.45 to 2.48. o Hash::Util has been upgraded from version 0.18 to 0.19. o Hash::Util::FieldHash has been upgraded from version 1.15 to 1.19. o HTTP::Tiny has been upgraded from version 0.054 to 0.056. o I18N::Langinfo has been upgraded from version 0.12 to 0.13. o if has been upgraded from version 0.0604 to 0.0606. o IO has been upgraded from version 1.35 to 1.36. o IO-Compress has been upgraded from version 2.068 to 2.069. o IPC::Open3 has been upgraded from version 1.18 to 1.20. o IPC::SysV has been upgraded from version 2.04 to 2.06_01. o List::Util has been upgraded from version 1.41 to 1.42_02. o locale has been upgraded from version 1.06 to 1.08. o Locale::Codes has been upgraded from version 3.34 to 3.37. o Math::BigInt has been upgraded from version 1.9997 to 1.999715. o Math::BigInt::FastCalc has been upgraded from version 0.31 to 0.40. o Math::BigRat has been upgraded from version 0.2608 to 0.260802. o Module::CoreList has been upgraded from version 5.20150520 to 5.20160320. o Module::Metadata has been upgraded from version 1.000026 to 1.000031. o mro has been upgraded from version 1.17 to 1.18. o ODBM_File has been upgraded from version 1.12 to 1.14. o Opcode has been upgraded from version 1.32 to 1.34. o parent has been upgraded from version 0.232 to 0.234. o Parse::CPAN::Meta has been upgraded from version 1.4414 to 1.4417. o Perl::OSType has been upgraded from version 1.008 to 1.009. o perlfaq has been upgraded from version 5.021009 to 5.021010. o PerlIO::encoding has been upgraded from version 0.21 to 0.24. o PerlIO::mmap has been upgraded from version 0.014 to 0.016. o PerlIO::scalar has been upgraded from version 0.22 to 0.24. o PerlIO::via has been upgraded from version 0.15 to 0.16. o Pod::Functions has been upgraded from version 1.09 to 1.10. o Pod::Perldoc has been upgraded from version 3.25 to 3.25_02. o Pod::Simple has been upgraded from version 3.29 to 3.32. o Pod::Usage has been upgraded from version 1.64 to 1.68. o POSIX has been upgraded from version 1.53 to 1.65. o Scalar::Util has been upgraded from version 1.41 to 1.42_02. o SDBM_File has been upgraded from version 1.13 to 1.14. o SelfLoader has been upgraded from version 1.22 to 1.23. o Socket has been upgraded from version 2.018 to 2.020_03. o Storable has been upgraded from version 2.53 to 2.56. o strict has been upgraded from version 1.09 to 1.11. o Term::ANSIColor has been upgraded from version 4.03 to 4.04. o Term::Cap has been upgraded from version 1.15 to 1.17. o Test has been upgraded from version 1.26 to 1.28. o Test::Harness has been upgraded from version 3.35 to 3.36. o Thread::Queue has been upgraded from version 3.05 to 3.08. o threads has been upgraded from version 2.01 to 2.06. o threads::shared has been upgraded from version 1.48 to 1.50. o Tie::File has been upgraded from version 1.01 to 1.02. o Tie::Scalar has been upgraded from version 1.03 to 1.04. o Time::HiRes has been upgraded from version 1.9726 to 1.9732. o Time::Piece has been upgraded from version 1.29 to 1.31. o Unicode::Collate has been upgraded from version 1.12 to 1.14. o Unicode::Normalize has been upgraded from version 1.18 to 1.25. o Unicode::UCD has been upgraded from version 0.61 to 0.64. o UNIVERSAL has been upgraded from version 1.12 to 1.13. o utf8 has been upgraded from version 1.17 to 1.19. o version has been upgraded from version 0.9909 to 0.9916. o warnings has been upgraded from version 1.32 to 1.36. o Win32 has been upgraded from version 0.51 to 0.52. o Win32API::File has been upgraded from version 0.1202 to 0.1203. o XS::Typemap has been upgraded from version 0.13 to 0.14. o XSLoader has been upgraded from version 0.20 to 0.21. Documentation Changes to Existing Documentation perlapi o The process of using undocumented globals has been documented, namely, that one should send email to perl5-porters@perl.org <mailto:perl5-porters@perl.org> first to get the go-ahead for documenting and using an undocumented function or global variable. perlcall o A number of cleanups have been made to perlcall, including: o use "EXTEND(SP, n)" and "PUSHs()" instead of "XPUSHs()" where applicable and update prose to match o add POPu, POPul and POPpbytex to the "complete list of POP macros" and clarify the documentation for some of the existing entries, and a note about side-effects o add API documentation for POPu and POPul o use ERRSV more efficiently o approaches to thread-safety storage of SVs. perlfunc o The documentation of "hex" has been revised to clarify valid inputs. o Better explain meaning of negative PIDs in "waitpid". [perl #127080] <> o General cleanup: there's more consistency now (in POD usage, grammar, code examples), better practices in code examples (use of "my", removal of bareword filehandles, dropped usage of "&" when calling subroutines, ...), etc. perlguts o A new section has been added, "Dynamic Scope and the Context Stack" in perlguts, which explains how the perl context stack works. perllocale o A stronger caution about using locales in threaded applications is given. Locales are not thread-safe, and you can get wrong results or even segfaults if you use them there. perlmodlib o We now recommend contacting the module-authors list or PAUSE in seeking guidance on the naming of modules. perlop o The documentation of "qx//" now describes how $? is affected. perlpolicy o This note has been added to perlpolicy: While civility is required, kindness is encouraged; if you have any doubt about whether you are being civil, simply ask yourself, "Am I being kind?" and aspire to that. perlreftut o Fix some examples to be strict clean. perlrebackslash o Clarify that in languages like Japanese and Thai, dictionary lookup is required to determine word boundaries. perlsub o Updated to note that anonymous subroutines can have signatures. perlsyn o Fixed a broken example where "=" was used instead of "==" in conditional in do/while example. perltie o The usage of "FIRSTKEY" and "NEXTKEY" has been clarified. perlunicode o Discourage use of 'In' as a prefix signifying the Unicode Block property. perlvar o The documentation of $@ was reworded to clarify that it is not just for syntax errors in "eval". [perl #124034] <> o The specific true value of $!{E...} is now documented, noting that it is subject to change and not guaranteed. o Use of $OLD_PERL_VERSION is now discouraged. perlxs o The documentation of "PROTOTYPES" has been corrected; they are disabled by default, not enabled. Diagnostics The following additions or changes have been made to diagnostic output, including warnings and fatal error messages. For the complete list of diagnostic messages, see perldiag. New Diagnostics New Errors o %s must not be a named sequence in transliteration operator o Can't find Unicode property definition "%s" in regex; o Can't redeclare "%s" in "%s" o Character following \p must be '{' or a single-character Unicode property name in regex; o Empty \%c in regex; marked by <-- HERE in m/%s/ o Illegal user-defined property name o Invalid number '%s' for -C option. o Sequence (?... not terminated in regex; marked by <-- HERE in m/%s/ o Sequence (?P<... not terminated in regex; marked by <-- HERE in m/%s/ o Sequence (?P>... not terminated in regex; marked by <-- HERE in m/%s/ New Warnings o Assuming NOT a POSIX class since %s in regex; marked by <-- HERE in m/%s/ o %s() is deprecated on :utf8 handles Changes to Existing Diagnostics o Accessing the "IO" part of a glob as "FILEHANDLE" instead of "IO" is no longer deprecated. It is discouraged to encourage uniformity (so that, for example, one can grep more easily) but it will not be removed. [perl #127060] <> o The diagnostic "Hexadecimal float: internal error" has been changed to "Hexadecimal float: internal error (%s)" to include more information. o Can't modify non-lvalue subroutine call of &%s This error now reports the name of the non-lvalue subroutine you attempted to use as an lvalue. o o "Configure" now acts as if the "-O" option is always passed, allowing command line options to override saved configuration. This should eliminate confusion when command line options are ignored for no obvious reason. "-O" is now permitted, but ignored. o Bison 3.0 is now supported. o Configure no longer probes for libnm by default. Originally this was the "New Math" library, but the name has been re-used by the GNOME NetworkManager. [perl #127131] <> o Added Configure probes for "newlocale", "freelocale", and "uselocale". o "PPPort.so/PPPort.dll" no longer get installed, as they are not used by "PPPort.pm", only by its test files. o It is now possible to specify which compilation date to show on "perl -V" output, by setting the macro "PERL_BUILD_DATE". o Using the "NO_HASH_SEED" define in combination with the default hash algorithm "PERL_HASH_FUNC_ONE_AT_A_TIME_HARD" resulted in a fatal error while compiling the interpreter, since Perl 5.17.10. This has been fixed. o Configure should handle spaces in paths a little better. o No longer generate EBCDIC POSIX-BC tables. We don't believe anyone is using Perl and POSIX-BC at this time, and by not generating these tables it saves time during development, and makes the resulting tar ball smaller. o The GNU Make makefile for Win32 now supports parallel builds. [perl #126632] o You can now build perl with MSVC++ on Win32 using GNU Make. [perl #126632] o The Win32 miniperl now has a real "getcwd" which increases build performance resulting in "getcwd()" being 605x faster in Win32 miniperl. o Configure now takes "-Dusequadmath" into account when calculating the "alignbytes" configuration variable. Previously the mis- calculated "alignbytes" could cause alignment errors on debugging builds. [perl #127894] Testing o A new test (t/op/aassign.t) has been added to test the list assignment operator "OP_AASSIGN". o Parallel building has been added to the dmake "makefile.mk" makefile. All Win32 compilers are supported. Platform Support Platform-Specific Notes AmigaOS o The AmigaOS port has been reintegrated into the main tree, based off of Perl 5.22.1. Cygwin o <mailto" ranges o Use the "fdclose()" function from FreeBSD if it is available. [perl #126847] <> IRIX o Under some circumstances IRIX stdio "fgetc()" and "fread()" set the errno to "ENOENT", which made no sense according to either IRIX or POSIX docs. Errno is now cleared in such cases. [perl #123977] <> o Problems when multiplying long doubles by infinity have been fixed. [perl #126396] <> MacOS X o" before. o o Workaround where Tru64 balks when prototypes are listed as "PERL_STATIC_INLINE", but where the test is build with "-DPERL_NO_INLINE_FUNCTIONS". VMS o On VMS, the math function prototypes in "math.h" are now visible under C++. Now building the POSIX extension with C++ will no longer crash. o VMS has had "setenv"/"unsetenv" since v7.0 (released in 1996), "Perl_vmssetenv" now always uses "setenv"/"unsetenv". o Perl now implements its own "killpg" by. o For those %ENV elements based on the CRTL environ array, we've always preserved case when setting them but did look-ups only after upcasing the key first, which made lower- or mixed-case entries go missing. This problem has been corrected by making %ENV elements derived from the environ array case-sensitive on look-up as well as case-preserving on store. o Environment look-ups for "PERL5LIB" and "PERLLIB" previously only considered logical names, but now consider all sources of %ENV as determined by "PERL_ENV_TABLES" and as documented in "%ENV" in perlvms. o The minimum supported version of VMS is now v7.3-2, released in 2003. As a side effect of this change, VAX is no longer supported as the terminal release of OpenVMS VAX was v7.3 in 2001. Win32 o A new build option "USE_NO_REGISTRY" has". o The behavior of Perl using "HKEY_CURRENT_USER\Software\Perl" and "HKEY_LOCAL_MACHINE\Software\Perl" to lookup certain values, including %ENV vars starting with "PERL" has changed. Previously, the 2 keys were checked for entries at all times through the perl process's life time even if they did not exist. For performance reasons, now, if the root key (i.e. "HKEY_CURRENT_USER\Software\Perl" or "HKEY_LOCAL_MACHINE\Software\Perl") does not exist at process start time, it will not be checked again for %ENV override. o One glob fetch was removed for each "-X" or "stat" call whether done from Perl code or internally from Perl's C code. The glob being looked up was "${^WIN32_SLOPPY_STAT}" which is a special variable. This makes "-X" and "stat" slightly faster. o During miniperl's process startup, during the build process, 4 to 8 IO calls related to the process starting .pl and the buildcustomize.pl file were removed from the code opening and executing the first 1 or 2 .pl files. o Builds using Microsoft Visual C++ 2003 and earlier no longer produce an "INTERNAL COMPILER ERROR" message. [perl #126045] o Visual C++ 2013 builds will now execute on XP and higher. Previously they would only execute on Vista and higher. o You can now build perl with GNU Make and GCC. [perl #123440] o "truncate($filename, $size)" now works for files over 4GB in size. [perl #125347] o Parallel building has been added to the dmake "makefile.mk" makefile. All Win32 compilers are supported. o Building a 64-bit perl with a 64-bit GCC but a 32-bit gmake would result in an invalid $Config{archname} for the resulting perl. [perl #127584] o against o The implementation of perl's context stack system, and its internal API, have been heavily reworked. Note that no significant changes have been made to any external APIs, but XS code which relies on such internal details may need to be fixed. The main changes are: o The "PUSHBLOCK()", "POPSUB()" etc. macros have been replaced with static inline functions such as "cx_pushblock()", "cx_popsub()" etc. These use function args rather than implicitly relying on local vars such as "gimme" and "newsp" being. o Various macros, which now consistently have a CX_ prefix, have been added: CX_CUR(), CX_LEAVE_SCOPE(), CX_POP() or renamed: CX_POP_SAVEARRAY(), CX_DEBUG(), CX_PUSHSUBST(), CX_POPSUBST() o "cx_pushblock()" now saves "PL_savestack_ix" and "PL_tmps_floor", so "pp_enter*" and "pp_leave*" no longer do ENTER; SAVETMPS; ....; LEAVE o "cx_popblock()" now also restores "PL_curpm". o). o The temps stack is now freed on scope exit; previously, temps created during the last statement of a block wouldn't be freed until the next "nextstate" following the block (apart from an existing hack that did this for recursive subs in scalar context); and in something like "f(g())", the temps created by the last statement in "g()" would formerly not be freed until the statement following the return from "f()". o Most values that were saved on the savestack on scope entry are now saved in suitable new fields in the context struct, and saved and restored directly by "cx_pushfoo()" and "cx_popfoo()", which is much faster. o Various context struct fields have been added, removed or modified. o The handling of @_ in "cx_pushsub()" and "cx_popsub()" has been considerably tidied up, including removing the "argarray" field from the context struct, and extracting out some common (but rarely used) code into a separate function, "clear_defarray()". Also, useful subsets of "cx_popsub()" which had been unrolled in places like "pp_goto" have been gathered into the new functions "cx_popsub_args()" and "cx_popsub_common()". o "pp_leavesub" and "pp_leavesublv" now use the same function as the rest of the "pp_leave*"'s to process return args. o "CXp_FOR_PAD" and "CXp_FOR_GV" flags have been added, and "CXt_LOOP_FOR" has been split into "CXt_LOOP_LIST", "CXt_LOOP_ARY". o Some variables formerly declared by "dMULTICALL" (but not documented) have been removed. o The obscure "PL_timesbuf" variable, effectively a vestige of Perl 1, has been removed. It was documented as deprecated in Perl 5.20, with a statement that it would be removed early in the 5.21.x series; that has now finally happened. [perl #121351] <>] <> o "::" has been replaced by "__" in "ExtUtils::ParseXS", like it's done for parameters/return values. This is more consistent, and simplifies writing XS code wrapping C++ classes into a nested Perl namespace (it requires only a typedef for "Foo__Bar" rather than two, one for "Foo_Bar" and the other for "Foo::Bar"). o The "to_utf8_case()" function is now deprecated. Instead use "toUPPER_utf8", "toTITLE_utf8", "toLOWER_utf8", and "toFOLD_utf8". (See <>.) o Perl core code and the threads extension have been annotated so that, if Perl is configured to use threads, then during compile- time clang (3.6 or later) will warn about suspicious uses of mutexes. See <> for more information. o The "signbit()" emulation has been enhanced. This will help older and/or more exotic platforms or configurations. o Most EBCDIC-specific code in the core has been unified with non- EBCDIC code, to avoid repetition and make maintenance easier. o MSWin32 code for $^X has been moved out of the win32 directory to caretx.c, where other operating systems set that variable. o "sv_ref()" is now part of the API. o "sv_backoff" in perlapi had its return type changed from "int" to "void". It previously has always returned 0 since Perl 5.000 stable but that was undocumented. Although "sv_backoff" is marked as public API, XS code is not expected to be impacted since the proper API call would be through public API "sv_setsv(sv, &PL_sv_undef)", or quasi-public "SvOOK_off", or non-public "SvOK_off" calls, and the return value of "sv_backoff" was previously a meaningless constant that can be rewritten as "(sv_backoff(sv),0)". o The "EXTEND" and "MEXTEND" macros have been improved to avoid various issues with integer truncation and wrapping. In particular, some casts formerly used within the macros have been removed. This means for example that passing an unsigned "nitems" argument is likely to raise a compiler warning now (it's always been documented to require a signed value; formerly int, lately SSize_t). o "PL_sawalias" and "GPf_ALIASED_SV" have been removed. o "GvASSIGN_GENERATION" and "GvASSIGN_GENERATION_set" have been removed. Selected Bug Fixes o It now works properly to specify a user-defined property, such as qr/\p{mypkg1::IsMyProperty}/i with "/i" caseless matching, an explicit package name, and IsMyProperty not defined at the time of the pattern compilation. o Perl's "memcpy()", "memmove()", "memset()" and "memcmp()" fallbacks are now more compatible with the originals. [perl #127619] o Fixed the issue where a "s///r") with -DPERL_NO_COW attempts to modify the source SV, resulting in the program dying. [perl #127635] o Fixed an EBCDIC-platform-only case where a pattern could fail to match. This occurred when matching characters from the set of C1 controls when the target matched string was in UTF-8. o Narrow the filename check in strict.pm and warnings.pm. Previously, it assumed that if the filename (without the .pmc? extension) differed from the package name, if was a misspelled use statement (i.e. "use Strict" instead of "use strict"). We now check whether there's really a miscapitalization happening, and not some other issue. o Turn an assertion into a more user friendly failure when parsing regexes. [perl #127599] o Correctly raise an error when trying to compile patterns with unterminated character classes while there are trailing backslashes. [perl #126141]. o Line numbers larger than 2**31-1 but less than 2**32 are no longer returned by "caller()" as negative numbers. [perl #126991] o "unless ( assignment )" now properly warns when syntax warnings are enabled. [perl #127122] o Setting an "ISA" glob to an array reference now properly adds "isaelem" magic to any existing elements. Previously modifying such an element would not update the ISA cache, so method calls would call the wrong function. Perl would also crash if the "ISA" glob was destroyed, since new code added in 5.23.7 would try to release the "isaelem" magic from the elements. [perl #127351] "untie()" would sometimes return the last value returned by the "UNTIE()" handler as well as it's normal value, messing up the stack. [perl #126621] o Fixed an operator precedence problem when " castflags & 2" is true. [perl #127474] o Caching of DESTROY methods could result in a non-pointer or a non- STASH stored in the "SvSTASH()" slot of a stash, breaking the B "STASH()" method. The DESTROY method is now cached in the MRO metadata for the stash. [perl #126410] o The AUTOLOAD method is now called when searching for a DESTROY method, and correctly sets $AUTOLOAD too. [perl #124387] [perl #127494] o Avoid parsing beyond the end of the buffer when processing a "#line" directive with no filename. [perl #127334] o Perl 5.22 added support to the C99 hexadecimal floating point notation, but sometimes misparses hex floats. This has been fixed. [perl #127183] o A regression that allowed undeclared barewords in hash keys to work despite strictures has been fixed. [perl #126981] <> o Calls to the placeholder &PL_sv_yes used internally when an "import()" or "unimport()" method isn't found now correctly handle scalar context. [perl #126042] <> o Report more context when we see an array where we expect to see an operator and avoid an assertion failure. [perl #123737] <> o Modifying an array that was previously a package @ISA no longer causes assertion failures or crashes. [perl #123788] <> o Retain binary compatibility across plain and DEBUGGING perl builds. [perl #127212] <> o Avoid leaking memory when setting $ENV{foo} on darwin. [perl #126240] <> o "/...\G/" no longer crashes on utf8 strings. When "\G" is a fixed number of characters from the start of the regex, perl needs to count back that many characters from the current "pos()" position and start matching from there. However, it was counting back bytes rather than characters, which could lead to panics on utf8 strings. o In some cases operators that return integers would return negative integers as large positive integers. [perl #126635] <> "@x = sort { *a = 0; $a <=> $b } 0 .. 1" no longer frees the GP for *a before restoring its SV slot. [perl #124097] <> o Multiple problems with the new hexadecimal floating point printf format %a were fixed: [perl #126582] <>, [perl #126586] <>, [perl #126822] <> o Calling "mg_set()" in "leave_scope()" no longer leaks. o A regression from Perl v5.20 was fixed in which debugging output of regular expression compilation was wrong. (The pattern was correctly compiled, but what got displayed for it was wrong.) o ". o Certain syntax errors in "Extended Bracketed Character Classes" in perlrecharclass caused panics instead of the proper error message. This has now been fixed. [perl #126481] o Perl 5.20 added a message when a quantifier in a regular expression was useless, but then caused the parser to skip it; this caused the surplus quantifier to be silently ignored, instead of throwing an error. This is now fixed. [perl #126253] o The switch to building non-XS modules last in win32/makefile.mk (introduced by design as part of the changes to enable parallel building) caused the build of POSIX to break due to problems with the version module. This is now fixed. o Improved parsing of hex float constants. o Fixed an issue with "pack" where "pack "H"" (and "pack "h"") could read past the source when given a non-utf8 source, and a utf8 target. [perl #126325] o Fixed several cases where perl would abort due to a segmentation fault, or a C-level assert. [perl #126615], [perl #126602], [perl #126193]. o There were places in regular expression patterns where comments ("(?#...)") weren't allowed, but should have been. This is now fixed. [perl #116639] <> o Some regressions from Perl 5.20 have been fixed, in which some syntax errors in "(?[...])" constructs within regular expression patterns could cause a segfault instead of a proper error message. [perl #126180] <> [perl #126404] <> o Another problem with "(?[...])" constructs has been fixed wherein things like "\c]" could cause panics. [perl #126181] <> o] <> o In a regex conditional expression "(?(condition)yes-pattern|no-pattern)", if the condition is "(?!)" then perl failed the match outright instead of matching the no- pattern. This has been fixed. [perl #126222] <> o The special backtracking control verbs "(*VERB:ARG)" now all allow an optional argument and set "REGERROR"/"REGMARK" appropriately as well. [perl #126186] <> o] <> o Duplicating a closed file handle for write no longer creates a filename of the form GLOB(0xXXXXXXXX). [perl #125115] o Warning fatality is now ignored when rewinding the stack. This prevents infinite recursion when the now fatal error also causes rewinding of the stack. [perl #123398] o In perl v5.22.0, the logic changed when parsing a numeric parameter to the -C option, such that the successfully parsed number was not saved as the option value if it parsed to the end of the argument. [perl #125381] o The PadlistNAMES macro is an lvalue again. o. o] o "alarm()" and "sleep()" will now warn if the argument is a negative number and return undef. Previously they would pass the negative value to the underlying C function which may have set up a timer with a surprising value. o Perl can again be compiled with any Unicode version. This used to (mostly) work, but was lost in v5.18 through v5.20. The property "Name_Alias" did not exist prior to Unicode 5.0. Unicode::UCD incorrectly said it did. This has been fixed. o Very large code-points (beyond Unicode) in regular expressions no longer cause a buffer overflow in some cases when converted to UTF-8. [perl #125826] <> o The integer overflow check for the range operator (...) in list context now correctly handles the case where the size of the range is larger than the address space. This could happen on 32-bits with -Duse64bitint. [perl #125781] <> o A crash with "%::=(); J->${\"::"}" has been fixed. [perl #125541] <> o "qr/(?[ () ])/" no longer segfaults, giving a syntax error message instead. [perl #125805] o Regular expression possessive quantifier v5.20 regression now fixed. "qr/"PAT"{"min,max"}+""/" is supposed to behave identically to "qr/(?>"PAT"{"min,max"})/". Since v5.20, this didn't work if min and max were equal. [perl #125825] o "BEGIN <>" no longer segfaults and properly produces an error message. [perl #125341] o In "tr///" an illegal backwards range like "tr/\x{101}-\x{100}//" was not always detected, giving incorrect results. This is now fixed. Acknowledgements Perl 5.24.0 represents approximately 11 months of development since Perl 5.24.0 and contains approximately 360,000 lines of changes across 1,800 files from 75oenig, Andy Broad, Andy Dougherty, Aristotle Pagaltzis, Chase Whitener, Chas. Owens, Chris 'BinGOs' Williams, Craig A. Berry, Dagfinn Ilmari Mannsaaker, Dan Collins, Daniel Dragan, David Golden, David Mitchell,, Ricardo Signes, Sawyer X, Shlomi Fish, Sisyphus, Stanislaw Pusep, Steffen Mueller,. perl v5.26.1 2017-07-18 PERL5240DELTA(1pm) perl 5.26.1 - Generated Fri Nov 10 19:30:10 CST 2017
http://www.manpagez.com/man/1/perl5240delta/
CC-MAIN-2018-51
refinedweb
5,287
69.18
vmod-accept sanitizes content negotiations headers, most notably the Accept-Language header. As backends can deliver different objects for the same URL based on this headers, it can be needed to normalize them to avoid object duplication. The vmod follows RFC 7231 and evaluates a list of possible candidates and returns a match to the user’s header, if any, according to the quality (the q parameter) specified by the client for each choice. Note: Varnish already handles the Accept-Encoding header, so you should NOT do it in VCL. import accept; sub vcl_init { # our server can only return html, json, and its default, plain text new format = accept.rule("text/plain"); format.add("text/html"); format.add("application/json"); # also, the content is available in english (the default) # as well as french new lang = accept.rule("en"); lang.add("fr"); } sub vcl_recv { # only leave one choice for each header set req.http.accept = format.filter(req.http.accept); set req.http.accept-language = lang.filter(req.http.accept-language); } rule(STRING string) -> RULE Create a new rule object, using string as fallback in case no match is found. .add(STRING string) This is a method of the rule object, and adds string to the list of acceptable candidates. .remove(STRING string) This method removes string from the list of candidates. .filter(STRING string) -> STRING Process string and compares it with the list of candidates. The one with the highest quality is returned, or, failing that, the fallback string specified at the rule object creation is used.
https://docs.varnish-software.com/varnish-cache-plus/vmods/accept/
CC-MAIN-2019-51
refinedweb
257
54.12
Applications should not refer to the clear text versions of passwords - not in the database, not when logging, nor in any other area. The clear text version of the password should be the end user's secret. It should never be directly repeated or stored by an application. Clear Text Versus Hash A user inputs a password in its original, unaltered form - that is, in "clear text". However, a database should never store passwords in clear text. Instead, the value stored by the database should be calculated as stored-value = hash(clear-text-password + salt-value)The intent here is to store text which cannot be easily reverse-engineered back into the original password. The salt-value is a random string added to the password. It's added to prevent simple dictionary-style reverse engineering of the hashed value of the plain text password. (Regarding Tomcat5: its implementation of form-based login doesn't allow for the salt value.) Hash Functions SHA-1, SHA-256, SHA-384, and SHA-512 are all examples of hash functions. A hash function is also called a MessageDigest. (The MD5 hash has been shown to be defective, and should usually be avoided.) A hash function is not an encryption. Encrypted items are always meant for eventual decryption. A hash function, on the other hand, is meant only as a one-way operation. The whole idea of a hash function is that it should be very difficult to calculate the original input value, given the hash value. If y = hash(x) is a hash function, and y and x both represent text strings, then - given the output y, it's very hard to deduce the original input x - similar inputs will give markedly different outputs - input x can have arbitrary length - output y will have fixed length - there is only a trivial chance of "collisions", where different inputs give the same output The above properties allow for passwords (or pass phrases) of arbitrary length, while still letting the underlying database column which stores the hash value to be of fixed width. Example This example uses MessageDigest and the SHA-1 hash function: import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** Example hash function values.*/ public final class HashExamples { public static void main(String... aArgs) { try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); byte[] hashOne = sha.digest("color".getBytes()); log("Hash of 'color': " + hexEncode(hashOne)); sha.reset(); byte[] hashTwo = sha.digest("colour".getBytes()); log("Hash of 'colour': " + hexEncode(hashTwo)); } catch (NoSuchAlgorithmException ex){ log("No such algorithm found in JRE."); } } private static void log(Object aObject) { System.out.println(String.valueOf(aObject)); } /** * The byte[] returned by MessageDigest does not have a nice * textual representation, so some form of encoding is usually performed. * * This implementation follows the example of David Flanagan's book * "Java In A Nutshell", and converts a byte array into a String * of hex characters. */ static private String hexEncode( byte[] aInput){ StringBuffer result = new StringBuffer(); char[] digits = {'0', '1', '2', '3', '4','5','6','7','8','9','a','b','c','d','e','f'}; for (int idx = 0; idx < aInput.length; ++idx) { byte b = aInput[idx]; result.append( digits[ (b&0xf0) >> 4 ] ); result.append( digits[ b&0x0f] ); } return result.toString(); } } Example run: Hash of 'color': 6dd0fe8001145bec4a12d0e22da711c4970d000b Hash of 'colour': 79d41a47e8fec55856a6a6c5ba53c2462be4852e
http://javapractices.com/topic/TopicAction.do;jsessionid=F454284B8AD1422C2376A7AA55940683?Id=216
CC-MAIN-2017-30
refinedweb
543
57.27
After doing some searching and editing, I can't seem to find a solution to fixing this error. I'm trying to link my location search results with a table to display the search results in a list-form. I have my map with the details button linked with a UIViewController called 'FirstViewController.' My results table is linked with a UITableViewController called 'ResultsTableViewController.' My prototype cells are linked with a UITableViewCell called 'ResultsTableCell' which is also where my outlets are located. Here are the 2 separate errors: Illegal Configuration: The nameLabel outlet from the ResultsTableViewController to the UILabel is invalid. Outlets cannot be connected to repeating content. Illegal Configuration: The phoneLabel outlet from the ResultsTableViewController to the UILabel is invalid. Outlets cannot be connected to repeating content. let cell = tableView.dequeueReusableCellWithIdentifier("resultCell", forIndexPath: indexPath) as! ResultsTableCell // Configure the cell... let row = indexPath.row let item = mapItems[row] cell.nameLabel.text = item.name cell.phoneLabel.text = item.phoneNumber return cell } import UIKit class ResultsTableCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var phoneLabel: UILabel! } This message only occurs if you connect it to the view controller. As I have already commented, you probably did not delete the first connection outlet you've made to your view controller. Even if you delete the IBOutlet code from your view controller you still need to right click it and delete the old connection that probably still there. After deleting it the error message will go away.
https://codedump.io/share/D3idhUZr5IBG/1/xcode-error-outlets-cannot-be-connected-to-repeating-content
CC-MAIN-2017-51
refinedweb
243
51.34
Hi, currently I'm trying to get a button to display a raw image. I have the game objects set-up in the canvas I just don't know how to get the image to be invisible when the scene loads and then when the button is clicked to have the image appear. For context this is for a character selection screen and I'm wanting the image of the player character to display when the character head shot is clicked on. Answer by Dinosaurs · Nov 19, 2015 at 11:31 PM Disable the gameObject with the image, and have the button activate it when clicked. gameObject.SetActive(true); I'm completely new to coding do you care to elaborate a bit more, please. Answer by SeasiaInfotechind · Nov 20, 2015 at 05:39 AM Hi, If I have understood your problem correctly, solution is below: using UnityEngine; using System.Collections; using UnityEngine.UI; public class abc : MonoBehaviour { public Button xyz; // button to be clicked public Sprite change_texture; // texture you want to assign on button click // Use this for initialization void Start () { } // Update is called once per frame public void ButtonClicked () { xyz.GetComponent<Image>().sprite = change_texture; // on clicking button sprite would change } } Also don't forget to assign button function to be called on buttonclick from inspector.ScreenShot is attached. Script is attached to main camera. I hope your problem gets solved.Have a good Day!! Hi, first of all thanks for your help. I have a couple of queries, I'm unsure where to put in the specific names of the objects and images in my project. For context these are the names of the items I'm using. Button to be clicked : Es UI Raw Image (place where I want to image to be displayed) : EsFull Image I want displayed : EsmeraldaFull From the code you gave me this is what I have so far : using UnityEngine; using System.Collections; using UnityEngine.UI; public class ShowPlayerCharacter : $$anonymous$$onoBehaviour { public Button Es; // button to be clicked public Sprite EsmeraldaFull; // texture you want to assign on button click // Use this for initialization void Start () { } // Update is called once per frame public void ButtonClicked () { Es.GetComponent<Image>().sprite = EsmeraldaFull; // on clicking button sprite would change } } Also I can see that you placed the script on the camera, is there any specific options that I need to select on the camera to get the script to work. Thanks again. Hi, Were you able to make it work? Its not necessary to place your script on camera.You can place it on any object and drag drop that object on button Onclick property. In order to fetch the method you need to give reference of the script and its done by passing the object holding the script. So here my script was attached to camera thats why i dragged camera on Onclick property of button. If you will select camera and check inspector you will find the script attached .You only need to drag drop all the reference. eg: In option showing EsmeraldaFull , drag image from assets . Feel free to ask if any doubts. Answer by superhero02 · Jun 25, 2017 at 09:04 AM When I Put characters in rawimage button how can you do levelmanager and character select at the. Button not working after adding Canvas 0 Answers AddListener fuction throwing a NullReferenceException error 1 Answer World space canvas buttons are not working? 0 Answers Button custom collider 0 Answers UI in World Space doesn't respond 1 Answer EnterpriseSocial Q&A
https://answers.unity.com/questions/1100902/how-to-have-get-button-display-a-raw-image.html
CC-MAIN-2022-21
refinedweb
588
62.17
[dev-20011005] IDE hanged up (consumed 100% of time) after popup invocation from editor. Not reproducible now. What I did: 1. Invoke Internationalization|Internationalize action on examples/advanced/MemoryView.form (results in opening of this form). 2. Open examples/texteditor/About.form and go to its editor pane. 3. There I tried to invoke popup menu. The fragment of stacktrace is attached. Created attachment 2859 [details] thread dump It happened next two times for me - when working with debugger. Complete thread dump (however long) is available. Created attachment 2870 [details] complete thread dump Looks like debugger problem. It happens on Solaris also when I've done these action: Create Java file: public class Main () { public static void main (String[] str) { System.out.println ("AA"); } }Press F4 on line with System.out.... Press F7 for step into println method Created attachment 2873 [details] Thread dump from Solaris It happens every time if you have a running debugger and stop over a variable. Tooltip evaluation is then invoked which asks registered tooltip annotations (currently only debugger) to return tooltip text. Looks like the debugger tooltip annotation evaluates the result and it fires property change, but it does not remember the returned value once the getShortDescription() is called again and initiates the computation again which causes infinite loop. The tooltip support was previously calling Annotation.getShortDescription() in the propertyChange() body to get the current value of the description text (to cover the case when somebody would only fire(prop, null, null)) but to avoid things like this I will assume that valid value will be always fired and only get the text by using evt.getNewValue(). Fixed in NbToolTip. Verified in Netbeans build 20011009. *** Issue 15915 has been marked as a duplicate of this issue. *** Resolved for 3.3.x or earlier, no new info since then -> closing.
https://netbeans.org/bugzilla/show_bug.cgi?id=16270
CC-MAIN-2016-18
refinedweb
305
58.79
Specifies that one or more declared member variables refer to an instance of a class that can raise events. When a variable is defined using WithEvents, you can declaratively specify that a method handles the variable's events using the Handles keyword. You can use WithEvents only at class or module level. This means the declaration context for a WithEvents variable must be a class or module and cannot be a source file, namespace, structure, or procedure. You cannot use WithEvents on a structure member. You can declare only individual variables—not arrays—with WithEvents. Element Types. You must declare WithEvents variables to be object variables so that they can accept class instances. However, you cannot declare them as Object. You must declare them as the specific class that can raise the events. The WithEvents modifier can be used in this context: Dim Statement (Visual Basic)
http://msdn.microsoft.com/en-us/library/aty3352y.aspx
crawl-002
refinedweb
146
65.42
While. I will briefly discuss each method using Windows 7 in the examples below. These instructions will also work in Windows Vista. Each method uses a different component of Windows to initiate the transfer: - Internet Explorer 8 - Windows Explorer - DOS command line Method One - Internet Explorer 8 Everyone who browses the Internet should be familiar with the addresses that are typed in the browser address bar to access a Web site, for example: The address for FTP access is similar: This blog post is also available in PDF format in a TechRepublic download. Figure A Here is FTP from Internet Explorer 8.Note: Tools | Internet Options | Advanced tab | Enable FTP folder view (outside of Internet Explorer) and the Use Passive FTP (for firewall and DSL modem compatibility) options under Browsing should be checked by default. If not, enable these options. Non-public sites require a user name and password (Figure B). This is convenient for listing the files on the remote FTP server, but if you are using IE 7 or IE 8 you will need to launch Windows Explorer to transfer files. (See Figures C, D, E, and F.) Figure B Non-public sites require a user name and password. Figure C Select Page | Open FTP Site in Windows Explorer to open Windows Explorer. Alternatively, you can select View | Open FTP Site in Windows Explorer from the menu. Figure D Click Allow when the Internet Explorer Security window opens. Figure E Enter your user name and password and select Log On to connect using Windows Explorer. Figure F If you connect successfully, you should be able to transfer files to and from the FTP server just as you would with any local drive. Method Two - Windows ExplorerMethod one is rather awkward. You can connect to the remote server directly in Windows Explorer (Figures G and H). Figure G Open Windows Explorer and type the FTP address in the address bar. Figure H Hit Return after typing the address, and you will be prompted for a user name and password. But what if you routinely connect to a FTP server? You don't want to have to type the FTP address each time you want to connect. There are three ways to create a shortcut or link for quick access. First, connect to the FTP server in Windows Explorer. Option one - Create a desktop shortcut There are two ways to create a desktop shortcut for a file or folder for quick access: - Select the remote file or folder and press and hold down the [Ctrl][Shift] keys. Drag and drop the file or folder to the desktop. - Right-click on the remote file or folder and hold down the right mouse button. Drag and drop the file or folder to the desktop. Select Create Shortcuts Here. Option two - Create a link under Favorites There are two ways to create a link to a folder for quick access: - Drag and drop a remote folder to Favorites in the navigation pane. - Right-click on the remote folder and then hold down the right mouse button. Drag and drop the folder to Favorites in the navigation pane. Select Create Shortcuts Here. Option three - Create a link under Computer The Add Network Location Wizard will create a link under Computer in the navigation pane. Right-click on Computer in the navigation pane then select Add a Network Location to open the Add Network Location Wizard. For a complete step-by-step guide, please visit the associated TechRepublic Photo Gallery. FTP folders in Windows Explorer A Microsoft spokesperson sent me the following information about the features and limitations of FTP folders in Windows Explorer: "FTP Folders work natively in the Windows Explorer and allow users to: - Browse them, in a limited way (no metadata or thumbnails) - Copy, move and delete files and folders - Create new folders - Search/filter the current view - Add to favorite links - Open Files using the Common File Dialog Unsupported behavior: - You cannot copy or move files between folders on the server, only to and from your PC - There are no thumbnails, metadata or previews - You can only save to FTP folders using the Common File Dialog if the application supports opening from a virtual namespace (which is rare) - You cannot see Unicode file names - There are no secondary streams" Method Three - DOS command line The executable is a Windows utility that can be started from a command prompt window command line. You can manually transfer files using the FTP utility, but the power of this method is automation. It is a very convenient way to schedule and automate the regular transfer of files. To view help for the FTP utility, open a command prompt window and type ftp -? [Return] at the command line. To view the commands available in FTP, type ftp [Return] to start the FTP utility and then type ? [Return] at the FTP prompt. Type bye [Return] at the FTP prompt to exit the FTP utility. You can create batch files and FTP scripts in order to automate the file transfer process. In the following examples, replace the italicized text with your unique host name, user name, password, local path, and remote server directory.Editor's note: The following commands are examples. You will have to adjust drive letters and folders to match your system. Transfer a single file Type the following into Notepad and save as H:\TransferTest\transfer.bat: ftp -v -n -s:H:\TransferTest\transfer.ftp This is what the ftp command does: - ftp — Invoke FTP utility - -v — Suppress display of remote FTP server responses - -n — Suppress auto-login - -s: — Specifies the path including the name of the file containing FTP commands. Note: The path cannot contain spaces. Type the following into Notepad and save as H:\TransferTest\transfer.ftp: open example.yourhostingsite.com user yourusername cd /public_ftp/test put "W:\pecos-softwareworks\shtml\changes_to_the_windows7_taskbar_you_should_know_about.shtml" - put — Upload the specified local file. The quotation marks are optional if there are no spaces in the path. - bye — Quit FTP session and exit FTP - Navigate to the file in Windows Explorer, right-click on any part of the breadcrumb style address in the address bar, and select Copy Address as Text. Paste the address into your FTP script file and add the file name. - The full path including the file name can be copied to the clipboard. Right-click on a file in Windows Explorer, select Properties, and click the Security tab. Select and copy the full path next to Object name: and paste it into your FTP script file. Figure I Select the Public Networks option and click Allow Access. Figure J The put command uploads one file from the client to the server. If the file already exists on the remote server, it will be overwritten. Use the get command to download one file from the server to the client. Transferring multiple files Type the following into Notepad and save as H:\TransferTest\multiple_transfer.bat: cd /D W:\pecos-softwareworks\shtml ftp -v -n -s:H:\TransferTest\multiple_transfer.ftp Type the following into Notepad and save as H:\TransferTest\multiple_transfer.ftp: open example.yourhostingsite.com user yourusername cd /public_ftp/test prompt mput "changes_to_the_windows7_taskbar_you_should_know_about.shtml" "a_case_of_maxtaken_identity.shtml" lcd \Projects\PSWW\VIC\Package binary mput "vista_image_capture_1_1_2.zip" "vista_image_capture_1_2_0.zip" - prompt — Disable interactive prompting when uploading multiple files using the mput command - mput - Upload the specified local ASCII files. The quotation marks are optional if there are no spaces in the path. - lcd - Change to the specified local directory containing the files that will be transferred, \Projects\PSWW\VIC\Package in this example - binary — Switch to the binary transfer mode - mput — Upload the specified local binary files. The quotation marks are optional if there are no spaces in the path. - bye — Quit FTP session and exit FTP Figure K You can do multiple transfers. Note that I used the cd change drive and directory command in the batch file and the lcd change local directory FTP command in the FTP script to simplify the mput commands so that the relative path could be used instead of the full path.Tip: Spaces can be problematic. Use underscore characters instead of spaces when possible. The mput command uploads multiple files from the client to the server. If the files already exist on the remote server, they will be overwritten. Use the mget command to download multiple files from the server to the client. There are other variations of this method, including creating one batch file. I'll leave it to you to explore them if you wish. Transferring ASCII and binary files FTP handles transfers of ASCII (text) files differently from binary files. By default, the Windows FTP utility transfers files using the ASCII mode. The single file example above transfers one ASCII file. The multiple file example transfers both ASCII and binary files. To avoid possible data corruption, use the right transfer mode. Security issues There is one obvious security issue. If you have your user ID and password in an unencrypted text file, it can be read by anyone with access to the computer, so you will want to encrypt the FTP script file. Search for encrypt in Windows Help and click the Encrypt or Decrypt a Folder or File item or view these Microsoft Web pages for how to encrypt your data with Windows 2000, Windows Server 2003, Windows XP, Windows Vista, or Windows 7. Wikipedia lists the Windows operating systems that support the Encrypting File System (EFS). You can also use a third-party application like TrueCrypt. Potential firewall issues If you receive a 425 Unable to build data connection: Connection timed out error the problem is likely with your firewall. The FTP utility does not support the passive transfer mode, and this can lead to firewall issues. I received this error using Comodo Firewall 4.0, and there are several workarounds that I can detail in the forum. If you are having this issue with your firewall, you will need to configure the firewall to allow access for the FTP utility. The final word Before you go looking for a third-party app, take a closer look at the tools provided in Windows. One of the above methods may be the perfect solution for your FTP needs. Susan Harkins makes a good point in "Recommend Clients Using FTP Switch to SSL or SSH" that sensitive or confidential data should not be sent using the FTP protocol. Additional resources Microsoft Windows Command-Line FTP Command List - nsftools.com Active FTP vs. Passive FTP, a Definitive Explanation - Slacksite.com ASCII or Binary? Which Files Are Which - Webweaver Stay on top of the latest XP tips and tricks with TechRepublic's Windows XP newsletter, delivered every Thursday. Automatically sign up today! Author's Note I would like to thank Microsoft.
http://www.techrepublic.com/blog/windows-and-office/two-plus-ways-to-transfer-files-via-ftp-in-windows/?count=50&view=collapsed
CC-MAIN-2017-13
refinedweb
1,801
63.8
Public C++ API [TOC] Overview The Blink public API (formerly known as the WebKit API) is the C++ embedding layer by which Blink and its embedder (Chromium) communicate with each other. The API is divided into two parts - the web API, located in public/web/, and the platform API located in public/platform/. The embedder uses the web API to talk to Blink and Blink uses the platform API to ask the embedder to perform lower-level tasks. The platform API also provides common types and functionality used in both the web and platform APIs. This shows the overall dependency layers. Things higher up in the diagram depend only on things below them. +-------------------------------------------+ | Embedder (Chromium) | +-------------------------------------------+ | Blink public web API | +---------------------+ | | Blink internals | | +-------------------------------------------+ | Blink public platform API | +-------------------------------------------+ | Embedder-provided platform implementation | +-------------------------------------------+ The web API covers concepts like the DOM, frames, widgets and input handling. The embedder typically owns a WebView which represents a page and navigates WebFrames within the page. Many objects in the web API are actually thin wrappers around internal Blink objects. The platform API covers concepts like graphics, networking, database access and other low-level primitives. The platform API is accessible to nearly all of Blink's internals. The platform API is provided through an implementation of the pure virtual blink::Platform interface provided when Blink is initialized. Most of the platform API is expressed by pure virtual interfaces implemented by the embedder. Conventions and common idioms Naming The Blink API follows the Blink coding conventions. All public Blink API types and classes are in the namespace blink and have the prefix Web, both mostly for historical reasons. Types that are thin wrappers around Blink internal classes have the same name as the internal class except for the prefix. For instance, blink::WebFrame is a wrapper around blink::Frame. Enums in the public Blink API prefix their values with the name of the enum. For example: enum WebMyEnum { kWebMyEnumValueOne, kWebMyEnumValueTwo, ... }; No prefixes are needed for " enum class". enum class WebMyEnum { kValueOne, kValueTwo, ... }; WebFoo / WebFooClient Many classes in the Blink API are associated with a client. This is typically done when the API type is a wrapper around a Blink internals class and the client is provided by the embedder. In this pattern, the WebFooClient and the WebFoo are created by the embedder and the embedder is responsible for ensuring that the lifetime of the WebFooClient is longer than that of the WebFoo. For example, the embedder creates a WebView with a WebViewClient* that it owns (see WebView::create). Wrapping a RefCounted Blink class Many public API types are value types that contain references to Blink objects that are reference counted. For example, WebNode contains a reference to a Node. To do this, web_node.h has a forward declaration of Node and WebNode has a single member of type WebPrivatePtr <Node>. WebNode also exports a WebNode::reset() that can dereference this member (and thus potentially invoke the Node destructor). There's also a WebPrivateOwnPtr <T> for wrapping types that are single ownership.
https://www.chromium.org/blink/public-c-api/
CC-MAIN-2022-27
refinedweb
502
55.44
import "gopkg.in/hockeypuck/conflux.v2" Package conflux provides set reconciliation core functionality and the supporting math: polynomial arithmetic over finite fields, factoring and rational function interpolation. The Conflux API is versioned with gopkg. Use in your projects with: import "gopkg.in/hockeypuck/conflux.v2" bitstring.go decode.go matrix.go poly.go zp.go var P_128 = big.NewInt(0).SetBytes([]byte{ 0x1, 0x11, 0xd, 0xb2, 0x97, 0xcd, 0x30, 0x8d, 0x90, 0xe5, 0x3f, 0xb8, 0xa1, 0x30, 0x90, 0x97, 0xe9}) P_128 defines a finite field Z(P) that includes all 128-bit integers. var P_160 = big.NewInt(0).SetBytes([]byte{ 0x1, 0xfe, 0x90, 0xe7, 0xb4, 0x19, 0x88, 0xa6, 0x41, 0xb1, 0xa6, 0xfe, 0xc8, 0x7d, 0x89, 0xa3, 0x1e, 0x2a, 0x61, 0x31, 0xf5}) P_160 defines a finite field Z(P) that includes all 160-bit integers. var P_256 = big.NewInt(0).SetBytes([]byte{ 0x1, 0xdd, 0xf4, 0x8a, 0xc3, 0x45, 0x19, 0x18, 0x13, 0xab, 0x7d, 0x92, 0x27, 0x99, 0xe8, 0x93, 0x96, 0x19, 0x43, 0x8, 0xa4, 0xa5, 0x9, 0xb, 0x36, 0xc9, 0x62, 0xd5, 0xd5, 0xd6, 0xdd, 0x80, 0x27}) P_256 defines a finite field Z(P) that includes all 256-bit integers. var P_512 = big.NewInt(0).SetBytes([]byte{ 0x1, 0xc7, 0x19, 0x72, 0x25, 0xf4, 0xa5, 0xd5, 0x8a, 0xc0, 0x2, 0xa4, 0xdc, 0x8d, 0xb1, 0xd9, 0xb0, 0xa1, 0x5b, 0x7a, 0x43, 0x22, 0x5d, 0x5b, 0x51, 0xa8, 0x1c, 0x76, 0x17, 0x44, 0x2a, 0x4a, 0x9c, 0x62, 0xdc, 0x9e, 0x25, 0xd6, 0xe3, 0x12, 0x1a, 0xea, 0xef, 0xac, 0xd9, 0xfd, 0x8d, 0x6c, 0xb7, 0x26, 0x6d, 0x19, 0x15, 0x53, 0xd7, 0xd, 0xb6, 0x68, 0x3b, 0x65, 0x40, 0x89, 0x18, 0x3e, 0xbd}) P_512 defines a finite field Z(P) that includes all 512-bit integers. P_SKS is the finite field used by SKS, the Synchronizing Key Server. Zarray returns a new array of integers, all initialized to v. Generate points for rational function interpolation. Bitstring describes a sequence of bits. NewBitstream creates a new zeroed Bitstring of the specified number of bits. NewZpBitstring creates a new Bitstring from a Zp integer over a finite field. BitLen returns the number of bits in the Bitstring. ByteLen returns the number of bytes the Bitstring occupies in memory. Bytes returns a new buffer initialized to the contents of the Bitstring. Clear clears the bit at the given position to a 0. Flip inverts the bit at the given position. Get returns the bit value at the given position. If the bit position is greater than the Bitstring size, or less than zero, Get panics. Lsh shifts all bits to the left by one position. Rsh shifts all bits to the right by one position. Set sets the bit at the given position to a 1. SetBytes sets the Bitstring bits to the contents of the given buffer. If the buffer is smaller than the Bitstring, the remaining bits are cleared. String renders the Bitstring to a string as a binary number. Matrix represents a rectangular array of numbers over a finite field Z(p). NewMatrix returns a new Matrix of the given dimensions and finite field p. Get returns the value at the given (row, column) location. Reduce performs Gaussian elimination on a matrix of coefficients, in-place. Set sets the value at the given (row, column) location. String returns a string representation of the matrix. Poly represents a polynomial in a finite field. NewPoly creates a polynomial with the given coefficients, in ascending degree order. For example, NewPoly(1,-2,3) represents the polynomial 3x^2 - 2x + 1. PolyDiv returns the quotient between two Polys. PolyDivmod returns the quotient and remainder between two Polys. PolyGcd returns the greatest common divisor between two Polys. PolyDiv returns the mod function between two Polys. PolyRand generates a random polynomial of degree n. This is useful for probabilistic polynomial factoring. PolyTerm creates a new Poly with a single non-zero coefficient. Add sets the Poly instance to the sum of two Polys, returning the result. Coeff returns the coefficients for each term of the polynomial. Coefficients are represented as integers in a finite field Zp. Copy returns a deep copy of the polynomial and its term coefficients. Degree returns the highest exponent that appears in the polynomial. For example, the degree of (x^2 + 1) is 2, the degree of (x^1) is 1. Equal compares with another polynomial for equality. Eval returns the output value of the Poly at the given sample point z. Factor reduces a polynomial to irreducible linear components. If the polynomial is not reducible to a product of linears, the polynomial is useless for reconciliation, resulting in an error. Returns a ZSet of all the constants in each linear factor. IsConstant returns whether the Poly is just a constant value. Mul sets the Poly to the product of two Polys, returning the result. Neg negates the Poly, returning the result. P returns the integer P defining the finite field of the polynomial's coefficients. String represents a polynomial in a more readable form, such as "z^2 + 2z^1 + 1". Sub sets the Poly to the difference of two Polys, returning the result. RationalFn describes a function that is the ratio between two polynomials. Interpolate returns the ratio of two polynomials RationalFn, given a set of sample points and output values. The coefficients of the resulting numerator and denominator represent the disjoint members in two sets being reconciled. ZSet is a set of integers in a finite field. NewZSet returns a new ZSet containing the given elements. Reconcile performs rational function interpolation on the given output values at sample points, to return the disjoint values between two sets. ZSetDiff returns the set difference between two ZSets: the set of all Z(p) in a that are not in b. Add adds an element to the set. AddAll adds all elements in another set. AddSlice adds all the given elements to the set. Equal returns whether this set is equal to another set. Has returns whether the set has the given element as a member. Items returns a slice of all elements in the set. Len returns the length of the set. Remove removes an element from the set. RemoveAll removes all elements in another set from this one. RemoveSlice removes all the given elements from the set. String returns a string representation of the set. type Zp struct { // Int is the integer's value. *big.Int // P is the prime bound of the finite field Z(p). P *big.Int } Zp represents a value in the finite field Z(p), an integer in which all arithmetic is (mod p). Z returns a new integer in the finite field P initialized to 0. Zb returns a new integer in the finite field p from a byte representation. Zi returns a new integer n in the finite field p. Zrand returns a new random integer in the finite field p. Zs returns a new integer from base10 string s in the finite field p. Zzp returns a new integer in the finite field P initialized to zp. Add sets the integer value to the sum of two integers, returning the result. Bytes returns the byte representation of Zp. Cmp compares zp with another integer. See big.Int.Cmp for return value semantics. Copy returns a new Zp instance with the same value. Div sets the integer value to x/y in the finite field p, returning the result. Exp sets the integer value to x**y ("x to the yth power"), returning the result. Inv sets the integer value to its multiplicative inverse, returning the result. IsZero returns whether the integer is zero. Mul sets the integer value to the product of two integers, returning the result. Neg sets the integer to its additive inverse, returning the result. Norm normalizes the integer to its finite field, (mod P). SetBytes sets the integer from its byte representation. Sub sets the integer value to the difference of two integers, returning the result. ZpSlice is a collection of integers in a finite field. String returns a string representation of the ZpSlice. Package conflux imports 6 packages (graph) and is imported by 11 packages. Updated 2016-07-16. Refresh now. Tools for package owners.
https://godoc.org/gopkg.in/hockeypuck/conflux.v2
CC-MAIN-2017-39
refinedweb
1,353
59.3
Prepositions and Particles in English This page intentionally left blank PREPOSITIONS AND PARTICLES IN ENGLISH A Discourse-functional Account Elizabeth M. O'Dowd O'Dowd, Elizabeth M. Prepositions and particles in English : a discoursefunctional account / Elizabeth O'Dowd p. cm. Based on the author's thesis (Ph. D., University of Colorado, Boulder, 1994) Includes bibliographical refrerences and index. ISBN 0-19-511102-8 h language—Prepositions. 2. English language—Discourse analysis. 3. English language—Particles. I. Title. PE1335.036 1998 425—dc21 98-18309 9 8 7 6 5 4 3 2 1 Printed in the United States of America on acid-free paper Acknowledgments First, I thank Barbara Fox, my dissertation advisor at the University of Colorado, for her example as a teacher and scholar, her laser-like precision in critiquing my work, and her unfailingly cheerful encouragement. She has contributed immeasurably to the production of this book. I also thank other faculty members of the University of Colorado for their generous contributions: Bill Bright, Susanna Gumming, Zygmunt Frajzyngier, Lise Menn, Jim Martin, and especially Laura Michaelis, whose careful and articulate insights added new dimensions to this book. I am grateful to several scholars outside Colorado for their assistance: to Sandra Thompson in particular, who gave generously of her time in responding to my work, and to Paul Hopper, Knud Lambrecht, Ron Langacker, and Bernd Heine for helpful conversations about prepositions and particles. For the recordings and transcripts that make up the database, I thank Emanuel Schegloff for his "Upholstery Shop" data, Charles Goodwin for his "Auto" transcript, Randy Sparks for his "Round the Dinner Table" Conversation, and Bob Jasperson for "Eldora." In addition, Bob helped me greatly with astute comments on conversational transcription. I also thank Tracy and the Red Cross Clinic in Longmont, Colorado, for allowing me to record the "CPR" training conversation. My friends and colleagues in Colorado, in New Mexico, and at Saint Michael's College have been an invaluable source of help and moral support: Immanuel Barshi, Phyllis Bellver, Linh-Chan Brown, Carolyn Duffy, Alex Eggena, Bob Fox, John Hughes, Kathy Mahnke, Chart Norloff, Mia Thomas-Ruzic, Brian Trouth (who persistenty rescued me from my own computer semiliteracy), and especially Debra Daise. My friend Dean Birkenkamp offered crucial assistance in preparing this manuscript for publication. Lori Heintzelman's excellent indexing was a godsend. vi ACKNOWLEDGMENTS I will always be indebted to GB and Yvonne Oliver of La Luz, New Mexico, who so warmly and graciously provided a home away from home, and nurtured the development of this volume as it if were their own. Most of all, I thank my parents, to whom this work is dedicated, for their unconditional love and support. Contents Abbreviations and Transcription Conventions 1 The "P" Phenomenon 1 1.1. Elusive Elements 3 1.2. Preposition or Particle? 6 1.3. Developing a New Approach 1.4. Conclusion 13 xi 10 2 Syntactic Solutions to the Problem of P 14 2.1. Preposition vs. Particle Tests 14 2.2. The "Adprep" Category 23 2.3. The Inadequacy of Syntactic Tests 25 3 Semantic Solutions to the Problem of P 26 3.1. Particle Constructions 26 3.2. Preposition Constructions 33 3.3. Inadequacy of Syntactic-Semantic Explanations 4 The Problem Revisited: A Data-driven Approach 4.1. The Need for Naturalistic Texts 41 4.2. The Discourse-Functional Approach 43 4.3. P as a Discourse-Functional Element 44 4.4. A Discourse-Based Methodology 46 4.5. Conclusion 53 41 5 P in Discourse: Orienting, Situating, and Linking 5.1. Orientation and Cognition 55 55 39 viii CONTENTS 5.2. 5.3. 5.4. 5.5. 5.6. 5.7. 6 7 Orientation and Discourse 56 Situating and Linking Adpreps 59 Situating Particles 62 Linking Prepositions 64 Possible Counterarguments 66 Conclusion 71 Landmarks as Contextual Props 72 6.1. Information Properties of P-Landmarks 73 6.2. Semantic Class of Landmarks 74 6.3. Landmarks as Discourse Props 76 6.4. Semantic Class as an Exception to the Pattern 79 6.5. Pronoun Landmarks as an Exception to the Pattern 6.6. Prepositional Phrases and Intonation Units 82 6.7. Conclusion 67 80 Prepositions, Particles, and Pragmatic Focus 84 7.1. Preposition or Particle? Cognitive-Semantic Motivations 7.2. Cognitive-Semantic Motivations for Transitivity 86 7.3. Proposed Discourse Motivations 87 7.4. Contexts for Particle-Preposition Alternation 90 7.5. Pragmatic Focus 94 7.6. Particle Movement: A Focus-Marking Strategy 102 7.7. Conclusion 103 8 P in Construction 105 8.1. Constructional Meaning 106 8.2. The Layered Structure of the Clause 106 8.3. Core Scope Constructions 107 8.4. Nuclear Scope Constructions 112 8.5. Peripheral Scope Constructions 121 8.6. NP Scope 128 8.7. P Scope: The P-Compound Construction 129 8.8. Conclusion 131 9 The Historical Picture: P and Specialization 135 9.1. Particle and Preposition Specialization 136 9.2. Grammaticization Principles 144 9.3. P-Meanings in Unrelated Languages 147 9.4. The History of Indo-European P-Forms 148 9.5. P-Specialization as a "Panchronic" Phenomenon 9.6. The Basic Function of P 161 9.7. Synchronic Reconstruction 162 9.8. Conclusion: What Do Speakers "Know" about P? 10 The Big Picture 172 10.1. Summary of the Study 10.2. Questions Answered 172 174 160 170 84 CONTENTS 10.3. 10.4. 10.5. Questions Unanswered Implications 186 Conclusion 189 Appendix Notes 191 201 Bibliography Index ix 211 203 183 This page intentionally left blank Abbreviations and Transcription Symbols Abbreviations Symbol Gloss A S O LM NP RRG PIE IE Agent (subject of transitive clause) Subject (of intransitive clause) Object (of transitive clause) Landmark (of preposition) Noun phrase Role and Reference Grammar Proto-Indo-European Indo-European Transcription Symbols 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. Symbol Gloss . . . (O.n) long (timed) pause medium pause short pause; tempo lag lengthened segment primary stress secondary stress final pitch contour continuing pitch contour rising (question) contour exclamatory intonation = "[double quote] ' [single quote] . [period] , [comma] ? ! xi ABBREVIATIONS AND TRANSCRIPTION SYMBOLS xii Transcription Symbols (continued) 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. <COMMENT> hh CARRIAGE RETURN SPACE CAPITAL U:23 truncated intonation unit researcher's comment (on voice quality, etc.) glottalization truncated word intervening (untranscribed or uninterpretable passages) inhalation intonation boundary word boundary sentence beginning transcript reference: e.g., "Upholstery: page 23" (Adapted, for the purposes of this study, from Du Bois, Cumming, and SchuetzeCoburn, 1988.) Prepositions and Particles in English This page intentionally left blank 1 The "P" Phenomenon 1.1. Elusive Elements There is in English a small group of words which, depending on their sentential context, is usually classified as either "preposition" (the (a) examples) or "particle" (the (b) examples): (1) a. Jack ran up the hill. b. Jack ran ug the bill. (2) (Liles, 1987:19) a. Do you often come along this road? b. Do you want to come along? (3) a. They could send a bullet right through the window. (R:32)' b. If you roll an animal onto your hood, I' m sure that it would come roaring through.(R:33) This group of words, which I will call "P," has defied linguistic description for several hundred years. The descriptive problems have centered traditionally on the issues of how to categorize P syntactically and how to account for its many meanings. If we go by traditional grammatical definitions, examples (l)-(3) are relatively straightforward categorially: we can reason that each underlined (a) example is a preposition: that is, "a closed-class, uninflectable morpheme which shows the relationship between its [noun phrase] object and another word in the sentence" (Liles, 1987:229). In these examples, the noun phrase (NP) objects are clearly identifiable as the hill, this road, and the window, respectively. Similarly, we can reason from traditional grammatical definitions that each underlined (b) example is a particle. Although this term is less clearly defined in the 3 4 PREPOSITIONS AND PARTICLES IN ENGLISH literature, the following characterization, paraphrased from Liles (1987:16) captures its commonly understood meaning: word which may also function as a preposition, but which commonly attaches to verbs in verb-particle combinations. In these (b) examples, there is no prepositional object, and P is attached to the verb to produce a unitary meaning: ran up here roughly means "accumulated"; come along means "accompany (me)"; and roaring through means "penetrating." In explaining word classes, Liles (1987:16-18) goes on to point out that particles may transform the meaning of the verb (as we see in Ib) or simply add a spatial meaning (as in 3b), and that the particle, unlike the preposition, may be moved after the direct object (e.g., Jack ran the bill up). All these features seem to distinguish prepositions from particles uncontroversially. But even the straightforward examples given here raise some logical questions about the categorial status and function of P. For example, why should the same lexical form—up. along, or through — have membership in two different lexical categories? And why should through in (3b) have a different categorial status here than in (3a), an utterance which differs only in that the understood object (the window) is left unspecified? Example (4) raises even more questions. It unveils some of the complexities of a single P-form, up.—one °f me most useful words in the English language. We will see that pinning down the meaning of up. is trickier than it was for the P-forms in examples (l)-(3), and that even categorizing up> as a preposition or particle can give us problems. Example (4) presents naturally occurring utterances from my original database.2 (4) a. b. c. d. e. f. She'llcli-'tryto'climbugyour "leg'man. An ' 'I'm gonna clean up)the 'me=ss ? When we 'cleanug the "tableit'H" . . .and I uh-an I . .an I' messed you ' 'up. There 'used to be a 'place up in ' 'Toledo laid 'off a . . .bunch of . .'really high UE "people, (U:83) (U:2) (R:34) (U:30) (A:31) (R:19) The first utterance contains a clear token of up. as a preposition, according to the traditional definition: up shows a directional relationship between its object, your leg. and the subject of the sentence, she, which moves upward. For (4b), we have to rely on semantics, rather than word order, to identify up. as a particle rather than a preposition. Up is followed by a noun phrase (the mess), but has a very different relationship to it than to your leg in (4a). In (4a), your leg serves as a sort of landmark—a stable entity in terms of which the movement of another entity is defined: "your leg" does not move. However, in (4b), the mess is not a landmark but, rather, the entity that moves; we can think of "the mess" as being "up" (in a dustpan, perhaps), as a result of the cleaning. And that movement is not defined in relation to any other landmark element in the sentence. Therefore, we conclude that clean up constitutes a verb-particle construction, with the mess as the object of the construction. Example (4c) looks very similar to (4b): the table functions as the object of clean up. so we might expect that clean up here means the same as clean up in THE "P" PHENOMENON 5 (4b). However, in (4b), "the mess" moves "up" as the result of cleaning; but in (4c), "the table" does not move at all. The meaning contributed to the verb by up_ in (4c) seems to be more abstract than in (4b); a sense of completion — of doing the cleaning thoroughly — rather than one of direction. Therefore, even in these apparently identical verb-particle constructions, up. has two different meanings. Again, in (4d), we can identify a verb-particle construction, for the same reasons as in (4b) and (4c); but here the meaning of up_ becomes even more obscure, since neither messed nor up. makes sense independently of the construction (here, messed up means "inconvenienced"). Rather than adding some independent meaning, the particle seems to be idiomatically collocated with the verb; and the collocation carries no spatiodirectional sense at all. So far, we have been able to categorize up as either a particle or a preposition. But what about up in (4e)? It does not meet our definition of preposition, nor does it seem to form any construction with the verb phrase used to be. However, it does form a semantic and syntactic unit with the prepositional phrase, in Toledo: if we repositioned the prepositional phrase (as in 5a), or removed it altogether (as in 5b), up. would have to go along with it: (5) a. Up in Toledo, there used to be a place, b. *There used to be a place up. Traditionally, this use of up. would be classified as neither a preposition nor a particle, but simply as an "adverb" (traditionally defined as a word modifying some sentence element other than a noun). As for the meaning of up. it does share some of the spatiodirectional reference of up. in (4a-4c)— after all, it tells you where "a place" is — but not in the literal sense of vertical movement. The meaning of P here is more like "somewhere north of where I am now." Finally, in (4f) we have a case of up. that does not meet the traditional definitions of preposition, particle, or adverb, but could only be classified as an adjective: a word that modifies a noun. Here, ug modifies people and means something like "senior" or "important." Again, we detect a directional meaning, but not in any literal sense. It is as if we are placing "people" on some metaphorical ladder of success, where more successful people are positioned "higher" than less successful people. In summary, the simple questions "How can we classify the word up?" and "What does up, mean?" have no simple answers in traditional grammatical or dictionary terms. What we have with up) is a word that seems to belong to several lexical categories (or word classes), with a wide variety of meanings sometimes but not always clearly related to the notions of space and direction. Furthermore, there is no direct correspondence between lexical category and meaning: similar meanings may be expressed across different categories (for example, the preposition in 4a and the particle in 4b both express directional movement); or different meanings may be expressed within the same category (the particle in 4b expresses vertical movement, in 4c it expresses some abstract sense of completion, and in 4d it seems to have no meaning independent of the idiomatic construction messed up). 6 PREPOSITIONS AND PARTICLES IN ENGLISH 1.2. Preposition or Particle? 1.2.1. Teaching and Learning Difficulties The study reported here was undertaken to solve the "problem of P," which may be formulated as a central theoretical question: How can linguists define and describe these multipurpose P-forms in a way that accounts for their categorial flexibility and semantic versatility, as well as their syntactic constraints? In answering this question, I will directly address many smaller ones. Several of them are often raised by students of English grammar, and in particular by nonnative speakers of English who, in my experience, find prepositions and particles (and Pforms in particular) among the most difficult, but also the most intriguing, forms that they have to master in learning the English language. In fact, it was in the context of teaching English as a Second/Foreign Language (TES/FL) that my interest in P-forms was aroused. Nonnative speakers, grappling with long lists of "phrasal verbs" (common verb-particle collocations) in their grammar textbooks, wonder why some, such as think over, are "separable" and others, such as think about, are "inseparable": you can think over a problem, and think about a problem; and you can think a problem over—but you can't think a problem about. Nonnative speakers also despair of memorizing which preposition goes with which verb: care about, or care for? think about, or think on — or in — or of? None of these prepositions seems to have any distinct spatial meaning, so what do they mean? Particles can seem even more arbitrary in their assignment to specific verbs. Why does something that is burning up seem to be getting hotter, while something that is burning out seems to be getting colder? And would a building on fire be burning up or down? Learners of English concerned about writing style may ask why so many verbparticle or verb-preposition combinations—put out, look into, and climb up — have one-word synonyms, such as "extinguish," "investigate," and "ascend," respectively; and which alternative is "better." They have heard somewhere that verb-particle combinations are "informal," but why should this be? Another very good question to be addressed in this study is: Why isn't every preposition and particle a P-form? Certain prepositions (of, at, from) never function as particles, while certain adverbial particles (for example, away), never function as prepositions. Only a certain subset of forms, including those illustrated in examples (l)-(4), seems to have dual membership in both categories. Why is it that out can sometimes function alone as a simple preposition but other times has to be followed by of—I threw it out the window but not / threw it out the room! In my experience, the most common reaction by language learners to P-forms is that of fascination at the richness of P's idiomatic possibilities. They marvel that the simple combination of a verb such as make with a particle such as up can yield so many different meanings e.g., "invent," "apply cosmetics," "put together," "compensate for an inadequacy," "make friends after fighting," and "act obsequiously." (Consider the combinations make out, take up. and put out for a similarly wide range of meanings.) In their eagerness to become real communicators of conversational, idiomatic English, THE "P" PHENOMENON 7 second language learners generally share Bolinger's delight in P as the source of "an outpouring of lexical creativeness that surpasses anything else in our language" (1971 :xi). Still, learners wonder what the source of all this creativeness may be, and what its limits are. I propose that grammar textbooks have never satisfactorily addressed such questions because they have always treated prepositions and particles as "fixed" elements within a static model of grammar. They take little account of how P's meanings can vary, depending on its interaction with other elements in the same utterance, or on its use in different communicative contexts. The goal of this study is to propose a theoretical model of P within which both the larger and the smaller questions can be answered. P is approached here as a dynamic discourse-pragmatic element, highly productive but highly principled in the range of meanings that it generates. Although the study focuses centrally on data from the "P" subgroup, the scope of its conclusions includes the larger group of nonalternating prepositions and particles, other grammatical elements that overlap functionally with prepositions and particles, and, finally, the counterparts of English prepositions and particles in the world's languages. The model proposed here synthesizes many insights from leading cognitive and discourse-functional linguistic theories. These theories, although well known to scholars, have not generally been brought to bear on the specific issues that interest learners and teachers of English grammar. I hope to offer insights that will be useful pedagogically, not only for understanding prepositions and particles but also for a new way of looking at grammar and language. When we begin to understand how language is rooted in human cognition, experience, and interaction, we can more readily describe its elements in terms that invoke universal, commonsense communicative purposes. This study is not intended as a grammar textbook, but as a theoretical contribution to the field of linguistics. Nevertheless, its conclusions should be interesting and useful for applied linguists, too, helping to bridge the well-known gap between linguistic theory and language teaching practice. Its conclusions about categoriality may also be of use to lexicographers seeking more practical ways of documenting P's meanings. 1.2.2. Evolving Descriptions English language scholars have not always shared Bolinger's delight in prepositions and particles as a fountainhead of creative language use. In fact, some of them warned their readers not to be seduced into linguistic sloth by the easy fluency of these vernacular forms and not to abandon the purer structures of Latin-based grammar. In 1655, William Walker wrote a treatise on English particles, explaining how their meanings could be rendered in correct Latin. He was spurred on to do so by "the great variety of use that is made. . . of English Particles (the ignorance whereof is the cause of those many gross and ridiculous barbarisms committed daily by young learners, for whose use chiefly this work is designed)" (Walker, 1970: Preface). Although "particles" for Walker included many forms that would be differently categorized today, such as possessive and demonstrative pronouns, they also included most of the P-forms addressed in this study. 8 PREPOSITIONS AND PARTICLES IN ENGLISH In the eighteenth century, Dryden was preoccupied with the phenomenon of sentence-final, "stranded" prepositions (as in, This is the field we walked through). He labeled this phenomenon an "idiom" and frowned on it as a rather immodest and potentially cancerous growth within the English language. After careful examination of his linguistic conscience, Dryden found "no other way to clear my doubts but by translating my English into Latin" (in Visser, 1984:402). By the higher authority of that translation, he was forced to condemn the end-preposition as "inadmissible" and to purge it from his own usage. The flavor of this dogma persisted at least through the first part of this century, and is reflected in Arthur Kennedy's 1920 admonition on verb-particle combinations. While Kennedy values the creativity of many combinations, he warns: beyond all these, there lie a great number of colloquial or slang combinations which should not be encouraged, not merely because they are bizarre and render impossible that modest reticence which characterizes good breeding in speech as well as in dress, but largely because they detract from the simple expression of the unqualified idea. (1920:45) It would seem that such value judgments as Dryden's and Kennedy's directly reflected a contemporaneous linguistic puritanism, which considered that the most "correct" English was that which most closely resembled the grammar of Latin. Elizabeth Close Traugott explains that the genre of prescriptive grammar, which extended from the last half of the eighteenth century to the first part of this one, developed in response to cultural pressures, where "three major issues were at stake: social, literary, and philosophical": Perhaps the main social factor in the development of prescriptive grammars was the rise of the middle class. In urban communities the gentry felt threatened and sought ways to keep themselves apart from the middle class. They looked for overt behavioral tokens by which to single themselves out . . . which would create barriers between themselves and the middle class. Language was an obvious vehicle for such an aim. (1972:163) Today, the evolution of descriptive linguistics has produced a more tolerant attitude, along with an acceptance of workaday language as an object worthy of study. It is in the workaday domain of conversation that P-constructions are most productive, especially in the formation of new meanings through verb-particle combinations. But instead of helping define and describe P-forms efficiently, descriptivism has simply uncovered the complexities of the task. For every major theoretical approach to linguistics, there have been several attempts to account for the "P" phenomenon. The questions asked in these studies reflect the assumptions of the approaches. Traditional, structural, and generative grammarians focus on the lexical categoriality and syntactic function of P. More semantically oriented linguists tend to focus on P's wide range of meanings and try to explain its semantic productivity. Depending on their conceptual frameworks, these scholars have used a bewildering variety of names to classify P-forms, prepositions, and particles, including the following: preposition, particle, adverb, locative auxiliary, stative predicate, predicator, modifier, preverb, adprep, verbal adjunct, aspect marker, satellite, intransitive preposition, transitive adverb. THE "P" PHENOMENON 9 Verb-particle and prepositional-phrase constructions have been assigned an even more dazzling variety of names, including: phrasal verb, polyverb, compound verb, two-word verb, group verb, discontinuous verb, prepositional phrase, prepositional verb, conjunct, adjunct, disjunct, adverbial phrase. When faced with all the versatility and polysemy of P-forms, scholars respond in a variety of ways. Some scholars have simply concentrated on classifying all their meanings without attempting to explain their differences—for example, Hill (1968) lists thousands of sequences but makes "no rigid and fundamental distinction ... between prepositions, on the one hand, and adverbial particles, on the other" (1968:vii). In contrast, most syntactically oriented studies have claimed that we can successfully categorize P as either a preposition or a particle in any given sentence, on the basis of "tests," involving invented sentences, which reveal different predictable patterns for prepositions as opposed to particles. Unfortunately, these tests do not produce very satisfying results, and their authors have had to acknowledge a certain amount of overlap and indeterminacy between the two categories. Furthermore, syntactically oriented studies have done little to explain why, although both preposition and particle categories are labeled "closed class," they seem to offer an almost inexhaustible supply of new meanings, especially in combination with other sentence elements. And these studies do not begin to explain why, although different P-forms all seem to share a common property of spatiodirectional meaning, the most frequently used Ps have several meanings that do not refer to the spatiodirectional or physical domain at all. The semantically oriented literature has been more promising and has explained some of P's variation as an effect of its interaction with other constituents at different syntactic levels. The main concern of this literature has been with P's multiple meanings, or polysemy, rather than with its categoriality. In particular, recent cognitivesemantic frameworks have produced very useful models to account for much of this polysemy in terms of radial categories, semantic webs, and extensions from prototypical "core" meanings. When they have addressed the categoriality question, their answer has been either, as with grammarians, to assign prepositions and particles to discrete lexical categories, or to unify them by positing that particles are some sort of "intransitive preposition." While the latter interpretation is promising in that it acknowledges the obvious overlap between P-prepositions and P-particles (that they share the same lexical forms, and often refer to the same spatiodirectional notions), it leaves unanswered some intriguing questions about the grammar and distribution of certain Ps, including the one I asked previously: Why are all prepositions and particles not like P in their property of alternation? In other words, why are some prepositions, such as of, for, and at always transitive (or prepositional), while the particle away is never transitive? Furthermore, the data from the present study reveal that, even within the Pgroup, alternation is very predictably constrained. For example, up and out function as particles 98% of the time and as prepositions only 2% of the time in the present database. To my knowledge, cognitive-semantic approaches to P have not addressed this problem of categorial specialization at all. What previous syntactic and semantic approaches have in common is that, as 10 PREPOSITIONS AND PARTICLES IN ENGLISH with traditional grammar textbooks, they assume a static model of grammar, where lexical categories and grammatical relations have an autonomous status in the structure of the language itself or in our mental models of the language, rather than being shaped by the purposes of particular communicative contexts. Thus, their descriptions and accounts are generally based on made-up sentences rather than on evidence from real conversations. Since such sentences come from the inventor's memory rather than from actual observation and are presented in isolation without any anchoring or explanatory context, they can only provide rather speculative distillations of what we speakers actually do with language. As a result, "mental model" approaches are unlikely to uncover intriguing facts about P's usage (such as the categorial specialization mentioned previously) that could provide significant clues to its pragmatic, semantic, and syntactic functions. This study was grounded in the following premises: that language can best be understood when observed in its natural setting — conversation; that language forms and meanings are not static, but fluid and constantly susceptible to change over time and space; and that these changes are driven primarily in conversational contexts, where speakers are constantly using language in creative and strategic ways to achieve their interactive purposes. Therefore, my theoretical perspective aligns itself with that of recent grammaticization research, which views language variation in present-day contexts as possible evidence for language change or shift. And, consistent with current discourse-functional linguistic theory, I look for clues to P's functions in the conversational contexts where it is used: clues which show what kind of information is being focused by P, how P interacts with other linguistic elements, how information is constructed between speaker and hearer, and so on. 1.3. Developing a New Approach The central thesis to be developed by the following chapters is that P-forms are best understood, not as syntactic or semantic elements, but as pragmatic, discourseorienting elements. It is this orientational function that determines their grammatical function as prepositions, particles, or other lexical categories, and that drives their semantic extensions into a variety of meanings. In elaborating this hypothesis, I will place English P-forms — prepositions and particles — in the wider context of the world's languages by showing how they exemplify universal principles of language variation and change. The approach takes the form of a cumulative argument, based on the analysis of five American English conversations from a database containing 1,245 P tokens. The argument is driven by findings from the database and supported by cognitive and functional linguistic theories that provide independent evidence for my claims. Chapters 2 and 3 set the stage for the argument by explaining the shortcomings of purely syntactic or semantic solutions to the problem of P. Chapter 4 argues for a corpus-based approach to the problem that will reveal semantic-pragmatic motivations for the observed variation of P's meanings, and then briefly outlines the methodological features of this approach. THE "P" PHENOMENON 11 The remaining chapters present the details of this study and elaborate a discoursefunctional account that solves the "problem" of P. Chapter 5 defines the semanticpragmatic function of Orientation as that of situating elements of information in relation to other, contextual elements. This function is as basic in the construction of discourse as it is in human cognition and experience of the physical world. The prototypical orienting element is the adprep, an element originally introduced by Dwight Bolinger (1971). Orientation involves both situating (predicating states or changes of state) and linking (introducing contextual information). I argue that particles situate and prepositions link. The basic difference between a particle and a preposition is the omission of the prepositional object, or contextual information; the choice of one form over the other is determined by issues of pragmatic focus in specific conversational environments. Evidence for these arguments is presented in the prosodic, semantic, and information properties of elements in utterances containing P (chapters 6 and 7). Indirect support comes from current theories of information structure and assertion (Givon, 1984b; Lambrecht, 1994). Moving from the basic functional distinction between prepositions and particles, chapter 8 examines in detail their constructional capabilities. It sketches a template for preposition and particle constructions which shows how their respective linking and situating functions generate a wide variety of meanings at many levels of constituency. The template makes it possible to account coherently for the previously confusing results of syntactic categoriality tests and to answer several of the specific questions already raised in the present chapter. Chapter 9 answers the remaining questions from a diachronic perspective, which provides the last major piece of the "P-puzzle." It explains why P-forms seem to specialize as either particles or prepositions but not as both, and why all particles and prepositions are not P-forms. In the process, P is revealed as an element constantly evolving in response to situating and linking requirements and takes its place in the larger picture of universal tendencies for linguistic change and grammaticization. By chapter 10, there is a comprehensive account of P as a discourse-orienting element and a new theoretical model for prepositions and particles in English. The conclusion for this study revisits the "problem of P," recasting the questions raised in the present chapter as fundamental theoretical ones about linguistic categoriality and variation. It suggests several lines of inquiry for further research and, finally, it addresses the implications of this study for language scholars in general, and for teachers of English to nonnative speakers in particular. 1.3.1. Defining "P" The argument outlined in the preceding section is based on evidence from a corpus of 1,245 utterances containing P-forms recorded and transcribed from a series of five unrelated, naturally occurring conversations in American English, representing about three and a half hours of discourse in total. In these data, a preliminary working definition was used to identify P. P is a form that alternates between the traditional functions of preposition and particle, and 12 PREPOSITIONS AND PARTICLES IN ENGLISH which displays the same kinds of variation seen in examples (l)-(4) for in, along, off. and up. From this corpus, at least twenty alternating P-forms have been identified: about above across after along around before behind between by down in off on out over through to under up This list requires a few words of explanation. First, it is not exhaustive; a larger database would undoubtedly reveal a larger number of words alternating as prepositions and particles. For example, since is listed in W. Nelson Francis and Henry Kucera's (1982) frequency analysis of English words as a conjunction, a preposition, and a particle; however, it is excluded from the working list because it occurred only as a conjunction in my own database. Since my purpose here is to analyze the properties of these words in their different syntactic distributions, I have limited my focus to those words that yield some basis for comparison. Conversely, about is included even though it never actually appeared in the role of a particle in the database. It revealed variation of a different kind, which turns out to be of particular theoretical interest to this study. The potential occurrence of about as a particle is documented, however, by dictionaries and will be discussed more fully in subsequent chapters. Second, my working definition of P effectively disqualifies certain nonalternating words from P-membership — such exclusively "prepositional" words as from, of, and with, and such exclusively "particle" words as away. However, even these words may yield surprises; for example, in my own idiolect I have experienced the use of with as a particle co-occurring with the verb take (e.g.. You might need your raincoat, so let's take it with). It will be argued later that these words are not categorially distinct from P-prepositions, and that their more limited syntactic potential simply reflects their greater specialization as linking elements. Therefore, certain "pure" prepositions and particles are coded in the corpus when their occurrence is of particular interest. Finally, within this group of twenty words, I take the rather nontraditional step of coding certain instances as "particles" even when they do not attach to a verb in verb-particle constructions. For instance, in examples (6e) and (6f) up. is coded as a particle: (6) e. There 'used to be a 'place up in "Toledo. f. laid'offa . . .bunch of . .'really high up_ "people, (A:31) (R:19) I apply the term "particle" to these instances for want of a better working definition to distinguish them from clearly prepositional forms. It will become clear that this distinction is a crucial one; that nonprepositional uses have certain functional commonalities that justify their consideration as a set. Traditionally, such nonprepositional uses would be labeled "adverbial." In fact, several scholars classify P-forms in verb-particle combinations as "adverbial particles" even though Bruce Liles avoids this classification in the definition paraphrased above (1987:15-18). However, such a label is problematic. The category "adverb" includes many other forms not directly related to P, including adjectivally derived adverbs of manner, so the term is too THE "P" PHENOMENON 13 broad. As well, this category is itself in need of clearer definition; many adverbs have meanings that do not involve modification of or attachment to a verb, so there is little explanatory value in this term. Since a major goal of the present study is to redefine the traditional categories of preposition and particle (chapter 10), the reader is asked to suspend judgment and accept these terms as convenient coding devices only: "prepositions" will be defined ad hoc as P-forms that appear with following landmarks and "particles" as P-forms that appear without them. 1.4. Conclusion This brief overview outlines the task and approach taken in this study. In more general terms, the following chapters are intended to follow the lead suggested by Bolinger's (1971) work, The Phrasal Verb in English. While drawing extensively on Bolinger's insights, the study presented here goes beyond them by unifying prepositions and particles, by uncovering new phenomena about both categories, and by refocusing his analysis in light of current theoretical research. In the process, it is hoped that this present account of P's versatility may help untangle the processes by which a language may "coin out of its own substance" (Bolinger, 1971:xi) in the continuous creation of new meanings. 2 Syntactic Solutions to the Problem of P 2.1. Preposition vs. Particle Tests This chapter presents the "problem of P" from a syntactic standpoint. It will show why attempts to define P as a lexical category by means of syntactic tests can only produce indeterminate results. The most useful of these tests draw on semantic and pragmatic criteria, which indicates that we cannot analyze syntactic patterns without looking at the meaning and use of the elements involved. Much of the syntactic literature seems to agree on a polarization of P between the two categories of preposition and particle. The definition of these terms varies according to theoretical perspective, but it is generally agreed that prepositional Ps are somehow bound in constituency to a following NP, whereas adverbial particles are more bound to the verb. Traditionally, the justification for the categorial split comes from a variety of sentence-level tests designed to disambiguate prepositions from adverbial particles in terms of their syntactic, semantic, and prosodic properties. 2.1.1. Some Categoriality Tests Some of the more widely accepted tests for prepositions and adverbial particles are summarized in table 2.1, which have been synthesized and paraphrased for purposes of simplicity, from a variety of studies.1 2.1.2. Analysis of Tests The general principle underlying these tests is that in certain verb-P sequences, P constructs closely with the verb, performing an adverbial function while in others 14 SYNTACTIC SOLUTIONS Table 2.1: 15 Preposition/Particle Categoriality Tests Test Example Only Prepositional (not Particle) constructions: Al. Conjunction-reduction A2. Verb-gapping A3. Adverb-insertion A4. P-fronting A5. NP-ellipsis We turned off the road and onto the highway. *We turned off the light and on the stereo. He sped up. the street, and she, up. the alleyway. *He sped uo. the process and she, up. the distribution. We turned quickly off the road, *We turned quickly off the light. Up the hill John ran. *Up a bill John ran. We turned off (the road). *We turned off (the light). Only Particle (not Prepositional) constructions: Bl. Passivization 82. Verb-substitution B3. NP-insertion B4. P-stress B5. V-nominalization The light was turned off. *The road was turned off. The light was extinguished. (= The light was turned off) We turned the light off. *We turned the road off. The button was sewed ON (particle). The dress was SEWED on (preposition). His looking up. of the information. *His looking into of the information. it constructs with the following NP, performing a prepositional function. This principle explains why what appear to be lexically similar sequences may actually be syntactically different. For example, test Al (conjunction-reduction)predicts that the following example is ungrammatical (as indicated by an asterisk). (1) * We turned off the light and on the stereo. According to test 1 A, the underlined P is seen as an element inseparable from the verb turned, a fact which prohibits verb-ellipsis in the conjoined clause. This inseparability indicates that P is a particle. However, the following contrasting sentence does allow verb ellipsis, because the underlined P is interpreted as a preposition: it forms a phrasal unit, not with the verb, but with the following NP: (2) We turned off the road and onto the highway, Thus, off the road and onto the highway are interpreted as two prepositional phrases conjoined in a parallel syntactic relation to the same verb. The same principle of verb-particle unity explains the constraints in tests A2-A4. It also accounts for the semantic possibilities of the verb-substitution test in B2: if combinations such as turned off and put in are considered verbal units, then it makes sense that they can be paraphrased with simplex verbs such as "extinguished" and "install." Conversely, the passivization, NP-insertion, and nominalization tests (Bl, B3, 16 PREPOSITIONS AND PARTICLES IN ENGLISH B5) work on the principle of preposition-NP unity: that a preposition must precede its object and may not be separated from or inverted with it. (3) *The road was turned off, (passivization test) *We turned the road off. (NP-insertion test) *His looking into of the information, (nominalization test) Tests such as those in table 2.1 demonstrate that all Ps do not pattern the same way. However, the results, on examination, are not consistent enough to justify any absolute categorial distinction between adverbial particles and prepositions. The following discussion will show that several of the tests listed in table 2.1 allow plenty of overlap and indeterminacy between the two P-categories (see also Lindner 1981:18-25 for a critical review of the gapping, adverb-insertion and nominalization tests). Two of the most popular tests for adverbial particles versus prepositions are the NP-insertion or particle movement test (B3), and the passivization test (Bl). Unfortunately, these two tests do not produce the same results. The NP-insertion test has been used as the main criterion (for example, by Martin, 1990:5-7) to distinguish phrasal verbs (another name for verb-particle constructions) such as take out from verb-plus-preposition sequences such as talk about. The test predicts that prepositions will fail the NP-insertion test since they do not allow the intervention of a NP between verb and P: the following (invented) examples are not acceptable: (4) *We're talking you about. (5) *We turned the road off. Unfortunately, however, when the passivization test is applied to these examples, P easily passes the test in (4) (You were being talked about) but has much more difficulty with (5). Verb-preposition sequences are supposed to be intransitive and therefore not passivizable, but in (4), P behaves just like a transitive particle. Similarly, given the sequence in example (6), we find that P behaves like a preposition in failing the NP-insertion test (7), but more like a particle in passing the passivization test (8): (6) George Washington slept in this bed, (7) *George Washington slept this bed in, (8) This bed was slept in by George Washington. This result, furthermore, contradicts the expectations of Anna Live (1965:435) and R.M.W. Dixon (1982:12), who suggest that literal meanings for P (in the sense of spatiodirectional reference) imply nonpassivizability. The meaning of in is clearly spatial in (3) and yet this P-form participates in passivization. How can we account for such ambivalence? The best answer may well come from the perspective of Cognitive Grammar, which makes the point that we cannot meaningfully analyze the patterning of a sentence unless we consider its semanticpragmatic context. Only transitive verb phrases can be passivized, but Sally Rice (1987) claims that the "transitive" potential of a verb-preposition construction is determined by contextual considerations, or, as she puts it, by the overall "scene construal properties" of the proposition. SYNTACTIC SOLUTIONS 17 In example (8), this bed is seen as somehow affected by association with a significant event (the encounter with George Washington). For the purposes of this particular utterance, we might interpret slept in as a two-word verb, representing the "affecting" event, with this bed as its notional object. Therefore, in this context at least, we cannot explain P's categoriality without considering the semantic and pragmatic import of the whole sentence. In this way, transitivity is determined according to the semantic property of affectedness, and this property itself is assigned strategically by the speaker for pragmatic effect—that is, to mark his/her attitude to the overall situation. The NP-insertion test is problematic in other ways, too. First, even when applied in isolation (rather than matched with the passivization test), it fails to disambiguate prepositions from particles consistently. For example, Live's (1965) study, dealing with discontinuous verbs (by which she means verb-particle constructions), divides P-forms into three different groups mainly on the basis of the NP-insertion test. Group 1 particles (e.g., up. down, out, and off) are distinguished from Group 3 particles (e.g., in, on, and after) on the grounds that the object of the discontinuous verb, if it is a pronoun, is usually placed before a group 1 particle (e.g., look it up), whereas the pronoun objects of group 3 particles always follow the particle (e.g., look after it). However, Live concedes that these two word order patterns do overlap for a "special category" of particles (group 2), consisting of over, through, across, along, about, around, and by. The group 2 category "occasions both constructions": for example, we can say talked it over as well as went over it (1965:432-443). Furthermore, Live notes that in and on — group 3 particles — may sometimes pattern like those of group 1, since we do find sequences like swear him in or lay it on. Both the distinctions and the overlaps between these P-groups are instructive. Live acknowledges that "most of the common prepositions double as adverbs, the bases of distinction between the two being closeness of association with the verb or with a following noun or pronoun, and relative stress" (1965:432). However, her grouping system implies that particular Ps seem intrinsically more likely to pattern as either adverbs or prepositions, but not as both. This tendency for a given P to specialize in one syntactic role or another has not been explored in the literature, and will be discussed more fully in chapter 9. Live's group 2 seems to be the most flexible group categorially. But the exceptions noted for in and on suggest that, even within group 3, P's categoriality is not entirely predictable: we need to look at the particular verbal collocation in which it participates. In other words, we need to look at semantics again. Live does not address these implications, which will be explored in later chapters under the claim that prepositions and particles are not inherently separate categories — that although most Ps tend to specialize as either particle or preposition, they do have the potential to perform as both. Another interesting problem with the NP-insertion test is that it only works for certain kinds of object NPs, as illustrated in the following invented examples (the NP object is underlined). Some NPs must be inserted (9a), others may (9b-c), and still others may not (9d). (9) a. We turned it off. 18 PREPOSITIONS AND PARTICLES IN ENGLISH b. We turned off the light. c. We turned the light off. d. *We turned those lights that had been blinking on and off like crazy for the last two days off. It is well known that pronouns can and must be inserted between verb and particle (9a); but it is more difficult to predict exactly which lexical NPs are possible in that position. For instance, (9c) seems quite acceptable, but (9d) does not. Therefore, once again, we must qualify the generalization in table 2.1 that particles allow NP-insertion. Bruce Fraser (1976) claims that such qualifications can be accounted for in terms of underlying syntax, without resorting to semantic criteria. However, his explanations seem to involve a fair amount of subjectivity. For example, he invokes a sort of "heavy NP shift" rule which states that "whenever the direct object noun phrase is long and complicated, the particle must remain next to the verb" (1976:19). But, as Anthony Kroch's (1979) review points out, "long" and "complicated" are semantic value judgments rather than syntactically definitive criteria. A more detailed syntactic account of NP-insertion comes from the field of generative syntax — from government-binding theory (GB). Bas Aarts (1989) suggests that the basic underlying structure of a sentence such as (9) is that of (9a) and (9c): verb-NP-particle. The word order in (9b) comes about by rightward movement of the object. As an explanation for the rule that pronoun objects must be inserted, Aarts posits the "lightness" of the pronoun, which consists only of a nominal head with no modifying elements. For "heavier" NPs, as in (9b) and (9d), there exists the option of rightward movement (1989:286-287). However, this rule of optional movement begs the question as to why the speaker's option seems to become more constrained as objects get progressively more heavy. In other words, why is movement in (9d) not only possible but almost obligatory? To answer this question, we must once again consider semantic-pragmatic motivations, as we did for the passivization test. A more satisfying account of NP-insertion and heavy NP-shift has been offered from a semantic-pragmatic perspective by both Dwight Bolinger (1971) and Ping Chen (1986). As Bolinger puts it, "the longer an element is, the more likely it is to contain critical information and hence to take the normal position for semantic focus, at the end" (1971:66). Similarly, in a detailed study of particle movement (or NP-insertion), Chen argues from a discourse perspective that word order is largely determined by the information status of the direct object (1986:93). He presents evidence to show that the medial position (between verb and object) tends to be the place conventionally reserved for familiar and predictable elements of information (e.g., pronouns, whose referent is already known to the hearer). New and unpredictable information tends to be staged later in the utterance — i.e., in clause-final position. Example (9d) would be unacceptable by Chen's analysis, not because the object NP is so long, but because it contains so much new and unpredictable information. Further discussions on this point, as well as the pragmatics of P's word order, can be found in chapter 7. In summary, the passivization and NP-insertion tests are most instructive precisely where they fail to produce consistent results. Although they show strong constraints on P's patterning, they also show that adverbial particles cannot be clearly SYNTACTIC SOLUTIONS 19 disambiguated from prepositions in all cases. In several instances, the overlap between these categories is best accounted for, not by syntactic rules, but in terms of semantic and pragmatic motivations. The NP-ellipsis test (A5) is instructive in the same way. By this test, a preposition may sometimes occur with or without its object NP (lOa). However, a lexically identical verb-P collocation does not allow the same alternation (lOb): (10) a. We turned off (the road), b. *We turned off (the light). From such examples, the test is intended to distinguish prepositions (as in lOa) from particles (as in lOb). However, the results are less than satisfactory since it is possible to find alternations such as the following, recorded in the present database: (11) a. And I'm goan clean up the mess? b. I'm cleanin uj>, right? (U:2) c. And I'm goan clean it up. The NP-insertion test shows that up in (1 la) must be a particle and not a preposition, since this sentence would presumably allow NP-insertion (ll c). Nevertheless, this particle evidently passes the NP-ellipsis test in (llb). It would seem then, that NP-ellipsis is not the prerogative of prepositions, but also applies to verb-particle constructions. In other words, we could interpret both (lOa) and (llb) as cases of null complementation (Fillmore, 1986). In (lOa), it is the complement of the preposition which is not expressed and in (11b) it is the complement of the verb-particle Collocation, cleaning up. which is omitted. But now we are left with the question: why is null complementation not permissible for the verb-particle collocation in (lOb)? Why can't we say We turned off and mean We turned off the light! In order to answer this question, the semantic difference between the two verb-particle sequences must be considered: (12) a. We turned off the light. b. I'm goan clean up the mess. In interpreting this difference, Sue Lindner's (1981) Trajector-Landmark schema becomes useful. In her lexico-semantic analysis of up_ and out particle constructions, she examines their semantic relations from a Cognitive Grammar perspective, where P-forms express a relationship between their trajector (generally speaking, the entity that moves) and their landmark (the stable entity in relation to which movement is defined). This two-term relationship loosely corresponds to Leonard Talmy's (1985) Figure-Ground schema. Within this schema, the effect of P is predicated on the trajector: for example, in (13), John represents the trajector of up., which predicates the effect of the running — that is, a change of state for John — in relation to the landmark (the hill). (13) John ran Up the hill. By the same logic, the light in (12a) represents the trajector of off, even though 20 PREPOSITIONS AND PARTICLES IN ENGLISH the relationship with its landmark does not refer to the physical spatiodirectional domain. Lindner has an analogous example (repeated here as 14): (14) The lights went out; did you turn them out? According to Lindner's explanation, the trajector is the lights, which change their state, or become imperceptible. The landmark is unexpressed, but implicitly understood as that state where the trajector would be perceptible: once the trajector "leaves the landmark, it becomes inaccessible to the viewer" (1981:88). Using Lindner's schema, we can see why NP-ellipsis is not possible in (12a). As the trajector affected by the predication of off, the light may not undergo ellipsis. If it could, the hearer might mistakenly construe a different NP — we — as the trajector of off, a construal which in fact holds for (15): (15) We turned off (the road). In contrast, no such misinterpretation could apply to (16a) and (16b), because they have a different semantic composition from that of (12a): (16) a. I'm goan clean up the mess, b. I'm cleanin up, right? In these two sentences, there is no risk that the hearer will attribute the up predication to the wrong NP (which is what happens with the unacceptable sequence We turned off in lOb). I is clearly not the trajector of up in either sentence, since the I referent does not change its state as a result of the cleaning. Furthermore, Lindner suggests that ellipsis is facilitated in sentences such as these, by the interpretation of clean up as a verbal unit, with a meaning which is not the sum of its parts: Clean and clean up code different sets of activities. Clean refers to removing dirt, making sanitary. . . Cleaning up the room need not involve cleaning it, but rather implies putting clothes away, shoving things into the closet, stacking things neatly — changing the overall appearance of the room. (Lindner, 1981:157) Under this interpretation of clean up. the mess is construed, not as the trajector of up. but as the (ellided) complement of the whole verb-particle combination. In conclusion, the NP-ellipsis test reveals more about the semantic construal of verb-P collocations and about how speakers choose to package information for their hearers than about the preposition/particle distinction. Turning from considerations of transitivity and word order, we may briefly consider another test: verb-substitution (B2 in table 2.1). This test shows that verb-particle constructions such as turn off (the light) may be replaced by simplex verbs (usually derived from Latin) such as exit. Bolinger objects that this test is too vague to be very informative: for example, he points out that take off is not really a synonym for "depart," because it is more specific semantically (1971:6). Furthermore, Mario Pelli notes that this test yields "only fragmentary results" (1976:28): Latinate paraphrases are simply not available for many verb-particle sequences. Even if they were, it is unlikely that we would be any closer to an unequivocal test for particles, because we can also find Latinate paraphrases for verb-plus-preposition sequences — for SYNTACTIC SOLUTIONS 21 example, turn off (the road) = "leave", look into (the problem) = "investigate," and so on. Once again, the results of this test suggest overlap, rather than clear distinction, between prepositions and particles in that both may form unitary concepts or lexicalizations with the verb. Finally, in this discussion of categoriality we must consider the stress test (B4 in table 2.1). Stress (or accent placement) is one of the properties most often claimed to disambiguate prepositions from particles. In the majority of cases, it works predictably: particles receive stress, and prepositions do not. However, there are enough exceptions to the rule to raise questions about categorial distinctness; and once again, semantic-pragmatic considerations are required to answer these questions. It is well established in the literature that there are different levels of stress placement in any given utterance (Halliday, 1967; Chafe, 1987,1993; Du Bois et al., 1988). The stress test should perhaps then be reformulated, to predict that particles rather than prepositions receive primary stress, which represents the prosodic peak of an intonation contour. But even this prediction may fail. In the present database, for example, we can find a particular pattern where prepositions receive primary stress (marked here by double quote marks, following Du Bois et al., 1988): (17) Just kinda "tiptoe because you have to go right "by. them. (C:14) (18) They can't call out, from Germany ,) "on AT&T lines (R: 7) (19) (You know where they introduce competition ,)' 'to AT&T (R:8) (20) (Where they actually bring ' 'in, an ' 'MCI line or a US ' 'SPRINT line ) ' 'into your office, (R:10) Examples (17)-(20) have prepositions (underlined) that introduce a NP object which is already familiar and topical in the conversational context. In (17), for example, them refers to a class which is going on upstairs from the speaker's group, and this antecedent has just been mentioned in the previous utterance. This pattern of stress placement is very common among native speakers of English and seems to have nothing to do with emphasis or contrastive marking. Yet it clearly violates the prediction of the stress test—namely, that only particles, and not prepositions, should be stressed. An explanatory account of this pattern is offered by Knud Lambrecht whose theory of pragmatic focus predicts that primary stress falls on "the last accentable constituent" in a sentence (1994:251). This would normally be the object of the preposition; but in cases where this object is familiar or presupposed, the stress is placed elsewhere by a strategy of default accentuation, or destressing, which marks a normally focal constituent as nonfocal (1994:248-251). Further discussion of Lambrecht's account of pragmatic relations can be found in chapter 8; for the moment, it is enough to say that his account explains an apparently arbitrary set of exceptions to the Stress rule, by appealing to semantic-pragmatic considerations. Finally, one particular P-pattern that remains unresolved by categorial tests is the one in which P functions sometimes like a preposition (the (a) sentences) and sometimes like a postposition (the (b) sentences): (21) a. John walked over the field (to get to the other side). 22 PREPOSITIONS AND PARTICLES IN ENGLISH b. John walked the field over (looking for a wallet). (22) a. The director ran over the idea (with the scriptwriters). b. The director ran the idea over (in his head—to examine it very closely). (Dixon, 1982:27) In Live's (1965) analysis, over is contained within the group 2 set of Ps, which may pattern as both prepositions (in the (a) sentences) and particles (in the (b) sentences). Admittedly, the P-form in the (b) sentences may, at first glance, look like a particle. However, Bolinger, Dixon, and Talmy (1975, 1985) all claim that such Ps are more like postpositions than particles, arguing from the premise that the (a) and (b) versions in examples (21) and (22) seem to have identical meanings. For Bolinger, this pattern is evidence that word order differentiation between prepositions and particles "is not absolute" (1971:37). In other words, if we interpret a postposition as a rightwardmoved preposition (as Bolinger does), then we can say that prepositions and particles sometimes follow exactly the same syntactic pattern. Looked at this way, examples (21b) and (22b) seem to display a flagrant violation of the NP-insertion rule, with prepositional objects being inserted between the verb and the preposition. Talmy's (1985) semantically based theory of motion accounts for this pattern by invoking a variable "valence precedence," where certain Ps may place either Figure or Ground (i.e., the trajector or the landmark, respectively) in direct object position. For example, in (23a), the Figure NP (it — the entity that moves) occurs in the direct object slot, while in (23b) the Ground NP (him—the stable entity) occurs in this slot. In this example, it refers to "my sword": (23) a. I ran it through him. b. I ran him through with it. (Talmy, 1985:119) What remains puzzling, however, is why postpositional examples are so marginal in the English language. Bolinger, Dixon and Talmy all acknowledge that postpositional constructions are limited to a small set of Ps (such as over, through, and by) and to an even smaller set of verb-P collocations. In fact, Dixon reports that he cannot find any examples of bv. as a postposition, except in collocation with the verb pass. (24) a. Mary passed by John.2 b. Mary passed John by. (Dixon, 1982:28) To understand the marginality of such P-constructions, we must once again look beyond purely syntactic descriptions. What postpositional Ps illustrate is apparently a diachronic layer of usage from an earlier stage of English word order. Bolinger interprets these Ps as "fossils" which "retain in Modern English their old freedom with transitive verbs to go either before the object or after it in what appear to be identical functions" (1971:37-38). But why should this old freedom be retained? Apparently, for pragmatic purposes: for the expression of speaker attitude. Dixon mentions that these postposed Ps "imply a more thorough treatment of the referent of the prepositional object" (1982:27; italics mine). Thus, example (25) might, according to Dixon, "be paraphrased John walked all over the field," and example (26) "could be The director ran over every facet of the idea" (1982:27). SYNTACTIC SOLUTIONS (25) John walked the field over (26) The director ran the idea over 23 It would seem that the postposition survives in a restricted group of idiomatic collocations because of the effectiveness of these idioms in producing a particular subjective connotation. In conclusion, we can see once again thatP's patterning is not predictable from syntactic rules alone: we must also take into account its semantic and pragmatic functions in construction with other elements and within particular contexts, and we must acknowledge that syntactic irregularities, or violations of the rules, may be occasioned by the dynamics of language change. 2.2. The "Adprep" Category Having considered the difficulty of distinguishing prepositions from particles, I will now introduce Bolinger's notion of the "adprep" as a further indication that binary categoriality tests may be heading in the wrong direction. The adprep has been identified as a third, intermediate category for P. Constructionally, adpreps seem to "belong" to the verb as much as to the following NP (Bolinger, 1971; Sroka, 1972). Example (27), paraphrased from Bolinger (1971:2627), illustrates the three-way distinction for particle, preposition, and adprep Ps, respectively. (27) a. She swept off the stage (cleaned it). b. She swept off the stage (did her sweeping elsewhere). c. She swept off the stage (departed majestically). In (27a), swept off may be taken as a verb-particle construction, where off adds a completive adverbial meaning to the verb: she completed the job of sweeping the stage. In (27b), off the stage is interpreted as a prepositional phrase, modifying the preceding clause by expressing the location where the event took place (offstage, as opposed to onstage). In (27c), Bolinger sees an adprep, or "a case of dual constituency" (1971:27), where off contributes meaning both to the verb and to the following NP object: we can construe swept off as a directional verbal unit but we can also construe off the stage as a directional prepositional phrase. Accordingly, as we might expect, categorial tests such as those outlined in table 2.1 reveal the adprep in (27c) as patterning in some ways like a preposition and in some ways like an adverbial particle. For example, like a preposition, off fails the NP-insertion test in (28) but passes the Adverb-insertion test in (29). (28) a. She swept off it majestically, b. *She swept it off majestically. (29) She swept majestically off the stage. However, the adprep also passes the stress test, which we should expect only for particles; Bolinger points out that "the in-between status of the adprep shows up in 24 PREPOSITIONS AND PARTICLES IN ENGLISH the possibility of accenting either way" (1971:42). Thus, we could presumably place stress either on off (30a), or on swept (30b). (30) a. Show me the stage she swept "off, b. Show me the stage she "swept off. So what does the adprep tell us about the categoriality of P? Bolinger's explanation for the adprep phenomenon is that "Adpreps are portmanteau words, fusions of elements that are syntactically distinct but semantically identical" (1971:31; italics mine). In other words, according to Bolinger, we should interpret (27c) as meaning "She (swept off), (off the stage)." The same kind of intuition seems to be expressed by Talmy's decompositional semantic analysis of motion events, where he notes that past in a sentence such as (31) "has properties of both a satellite (i.e., particle) and a preposition" (1985:105-106). (31) I went past him. Talmy argues that this P constitutes a coalescence, where the satellite "is coupled with a zero preposition." In other words, (31) can be interpreted to mean "I (went past), (past him)," where the second prepositional past is omitted, and its meaning is carried by the first satellite past. Both Bolinger's and Talmy's interpretations seem to hold to the principle that, at some underlying level of syntax, the preposition and the particle are categorially distinct, even though they may be semantically identical. This principle is supported by Talmy's evidence that prepositions are formally distinct from particles in other Indo-European languages (in Latin, for example), where "the satellite is bound prefixally to the verb while the preposition accompanies the noun ... and governs its case" (1985:105). Furthermore, Talmy points out that particles and prepositions do not have identical lexical memberships: There are forms with only one function or the other. For example, together, apart and forth are satellites that never act as prepositions, while from, at and toward are prepositions that never act as satellites. Furthermore, forms serving in both functions often have different senses in each. Thus, to as a preposition (I went to the store) is different from to as a satellite (/ came to). (1985:105) Bolinger makes a similar point about underlying distinctness when he claims that the fused elements of the adprep separate "when an object noun is inserted, though the second element undergoes a stylistic change" (1971:31): (32) a. He drove the chickens off the lawn. b. *He drove off the chickens off the lawn. c. He drove off the chickens from the lawn. (1971:31) However, I am not sure that Talmy's and Bolinger's arguments must lead to the conclusion that there is any inherent categorial distinction between prepositions and particles. It is clear that syntactic, semantic, and lexical differences show up in particular constructions and collocations. But this is also true of other elements, particularly those which have undergone grammatical shift. For example, the historical SYNTACTIC SOLUTIONS 25 development of the verb do into a main verb and an auxiliary has resulted in different patterning constraints in modern English. In the negative-interrogative construction, we can invert an auxiliary do in (33), but not a main-verb do (in 34): (33) a. I don't like linguistics. b. Don't you like linguistics? (34) a. I do linguistics. b. *Do you linguistics? We would say, therefore, that do performs differentiated semantic and syntactic functions. We can also say that it has differentiated morphosyntactic properties, since only the auxiliary form allows the negative contraction don't. However, we know that historically both uses of do derive from the same verb. Subsequent chapters of the present study will argue an analogous pattern of divergence for prepositions and particles from a common adprep source. Evidence for this argument comes from 1. the literature reviewed in this chapter, which shows so much categorial overlap between prepositions and particles that even some formalists posit a unitary category — for example, Joseph Emonds (1972), who defines adverbs as "intransitive prepositions" 2. the present database, which also contains many examples of prepositionparticle overlap 3. the diachronic and typological literature discussed in chapter 9, which shows that prepositions and particles have always displayed overlap in an intermediate adprep-like function — even, contrary to Talmy's claim, in Latin and other Indo-European languages 4. the conclusions of several discourse-pragmatic studies, which suggest that categoriality for other parts of speech (such as nouns and verbs) is similarly ambivalent. 2.3. The Inadequacy of Syntactic Tests In conclusion to this chapter on categoriality, I suggest that syntactic tests do not clearly establish a dichotomy between prepositions and particles, although they do reveal a tendency for P-forms to participate in constructions and collocations which constrain their syntactic role. The most satisfactory explanations for the test results all seem to suggest that categoriality is flexible, influenced by semantic and pragmatic considerations. Furthermore, the existence of an intermediate adprep category suggests a possible diachronic source for the divergence of prepositions and particles. Another limitation of syntactic approaches to P is that they do not explain why P-forms have so many meanings. Having established that many of P's meanings are generated only in certain types of constructions and collocations, several scholars have examined the semantics of these constructions for clues to the problem of P. The next chapter summarizes the most significant insights of the semantics literature for the purposes of this study and indicates some issues still unresolved. 3 Semantic Solutions to the Problem of P Following the analysis in chapter 2 of P's categoriality and the inadequacy of purely syntactic explanations, this chapter examines what semantically oriented explanations can tell us. Specifically, we want to know what it is about P's function that can produce such different interpretations for one word, so that, for example, run up the hill has a different meaning for up_than run up the flag; and believe in has a different meaning for in than in the library. We also want to know, following chapter 2 (section 2.1.2), why different syntactic constraints seem to apply not only to prepositions and particles but also to different kinds of prepositional sequences, so that, for example, these sequences may be passivized in some sequences but not in others. In this chapter we will see that early semantic accounts of prepositions and particles do little to explain such phenomena satisfactorily; however, three more recent theoretical models hold more promise. Although these models are not centrally concerned with explaining the preposition-particle distinction, they do suggest that at least part of the answer lies in the level of constituency at which P attaches to other elements. The first model (Lindner, 1981) deals with the functions of verbparticle combinations, while the remaining two (Vestergaard, 1977; Foley and Van Valin, 1984) examine the functions of prepositional phrases. Although these models provide important insights for discussions in later chapters, I argue here that their semantic-syntactic accounts still fall short of solving the problem of P — particularly, of explaining what motivates P's many meanings, and what constrains certain Ps to specialize as either prepositions or particles. 3.1. Particle Constructions As explained in chapter 1, "particle," for the immediate purposes of this study, refers to all constructions where P takes no prepositional object. Particles usually follow 26 SEMANTIC SOLUTIONS 27 the verb in an utterance and their meaning is construed with the verb. We know from section 1.1 that not all particles function postverbally—or even adverbially, if we define adverbial functions as modifying something other than nouns, and we will consider these non-postverbal cases in due course (particularly, in chapter 8). Most P-studies, however, have overlooked these more unusual cases and have focused on the much larger group of adverbial particles in verb-particle constructions. The meanings of these constructions range from clearly literal combinations, where P adds spatiodirectional force to the situation expressed by the verb (e.g., look up. meaning "glance upward," and take off, meaning "remove from a surface") to combinations where P's sense is more abstract (e.g., adding a completive sense in look up the information), and finally, to completely idiomatic fusions of verb and particle, as in take off, meaning "impersonate." Early accounts of verb-particle constructions—also commonly called separable phrasal verbs, verb-adverb constructions, poly verbs, or compound verbs — display some vagueness in the way they either ignore important syntactic distinctions or assume them inappropriately. In one of the most important early accounts, Arthur G. Kennedy (1920) is primarily interested in P-forms that have non-literal meanings and have entered into some sort of welded association with the verb. Acknowledging the difficulty of clearly distinguishing prepositions from particles, Kennedy finally identifies sixteen prepositional adverbs as his focus which, in combination with different verbs, produce a corpus of over 900 constructions with several thousand meanings. Kennedy's is one of the first attempts to explain the polysemy of P in a principled way. He takes literal, spatially referring verb-plus-P combinations as a sort of semantic prototype from which more abstract or figurative meanings can be inferred metaphorically. His account in many ways is a precursor to later semantic models which also look for cognitive principles to explain how P-meanings can extend into so many domains of reference (Lindner, 1981, 1982; Brugman, 1981; Hawkins, 1984; Lakoff, 1987). For example, Kennedy offers some very helpful speculations as to why a P such as on could come to be interpreted as a continuative aspect marker, as in He just talked on and on. According to Kennedy, when something is on a surface it can be seen, and as long as a process is continuing, it can be perceived. Therefore, the relationship expressed by on may also refer to a nonspatial domain of reference, such as the activity of talking, where a similar relationship of continuous perceptibility holds. However, since he does not take on the problem of categoriality, Kennedy's verb + adverb set includes combinations that are clearly not parallel in their syntactic status. For example, he includes come by (= "find") and set about (= "begin") in his corpus, together with let out (= "release") and spruce up (= "decorate") (1920:1617). He does not attempt to explain why the first two combinations, but not the last two, would fail the NP-insertion test (*/ came it by) or the stress test (*How was that money come by?). This syntactic difference, however, would be crucial to any analysis that attempted a comprehensive account of P's functions since it would prohibit the inclusion of both pairs in a single set. A different kind of definitional vagueness occurs when semantic and syntactic criteria are inadvertently mixed up. In a later survey of the research on phrasal 28 PREPOSITIONS AND PARTICLES IN ENGLISH verbs, K.A. Sroka (1972) searches for some semantic unity that may characterize this group. Discussing L.P. Smith's (1948) account, he finds it most satisfying to the extent that it captures several correspondences between English phrasal verbs and other Indo-European prefixed compounds: Thus "fall out" has the meaning of the Latin excidere. the German ausfallen. . . . As a matter of fact, we have in English both compound and phrasal verbs, often composed of the same elements — "upgather" and "gather up," "uproot" and "root up," "underlie" and "lie under." In these instances the meaning is the same in each, but in other cases the meaning is changed by the grouping of the different elements: "undergo" and "go under," "overtake" and "take over," have not the same signification; and "upset" and "set up" are almost opposite in meaning. (Sroka, 1972:181) This account is vague because the parallelism attested here between phrasal verbs and Indo-European compounds cannot be substantiated; it is only the forms, not the meanings, which are parallel. Smith's study defines the phrasal verb a priori as an idiomatic construction; however, fall out as a phrasal verb (meaning, perhaps, "happen" or "have an argument") is not semantically parallel to ausfallen and excidere. which have literal spatiodirectional meanings. By the same logic, Smith is inaccurate in labeling gather up and root up as phrasal verbs, since their meaning is also literal rather than idiomatic; in this paragraph he seems to be inconsistent with his own definitions in classifying these combinations on the basis of their phrasal form rather than their meaning. W.P. Jowett, also cited in Sroka, assumes a similarly semantic definition of "phrasal verb" when he posits a "lexical indivisibility" between verb and particle to differentiate phrasal verbs as in (2) from literal, composite constructions as in (1). As with Kennedy's "verb-adverb" set, Jowett's "phrasal verb" set does not seem to exclude combinations which, according to any categoriality test, would be classified as prepositions. (1) Flowers grow on plants. (2) This coffee will grow on you. (in Sroka, 1972:182-184) However, this semantic definition once again breaks down when Jowett includes the following combinations as phrasal verbs: (3) He came into [entered] the room, picked up [seized] a book, looked at [regarded] it casually, put it down [discarded it] and went out [exited]. (in Sroka, 1972:183; paraphrases added) Jowett identifies these verbal combinations as phrasal verbs because they each allow simplex verb paraphrases — in other words, they all pass the verb-substitution test of table 2.1. However, this raises the question of what lexical indivisibility means. The "indivisibility" that Jowett points to in the paraphrases is formal: morphosyntactic rather than semantic. It is difficult to see the semantic justification for classifying grow on in (1) as more "divisible" than came into and looked at. since all of these combinations have literal, composite meanings. In contrast, grow on in (2) has a figurative meaning — for which Jowett offers no simplex verb paraphrase. Therefore, his SEMANTIC SOLUTIONS 29 rationale for classifying (2) and (3) together as phrasal verbs but excluding (1) is far from clear. Recently, more promising and systematic approaches to particles have been developed within cognitively oriented models of grammar (Langacker, 1986, 1991; Lakoff, 1987) which explain syntactic constructions in terms of underlying semantic relationships. In the previous chapter's discussion on categoriality, we saw that these models can offer some useful explanations for certain syntactic irregularities of prepositions and particles. These models are especially valuable for their mental "maps," which explain how certain grammatical phenomena are conceptually organized. The maps invoke psychological principles from prototype theory and cognitive operations such as metaphorical inference or image-schematic organization, to explain how the semantic features of a core reference can be extended via "radial categories," "fuzzy boundaries," or other conceptual paths to produce an ever-widening network of meanings from a single word. Several studies, using this cognitive perspective, have approached the problem of P-forms and mapped out many of their meanings (Lindner, 1981,1982; Brugman, 1981; Hawkins, 1984; Lakoff, 1987). Perhaps the most thorough analysis, which also faces the issue of P's categoriality and accounts for several syntactic constraints, comes from Sue Lindner's research into verb-particle constructions containing urj and out. Lindner defines prepositions and particles in general as "extended locative relations," which predicate relations between the trajector and landmark of the P-form. The only difference between a preposition and a particle for Lindner is that a preposition specifies a landmark, whereas a particle "sublexicalizes," or leaves it unspecified. Lindner proposes that this difference is not best explained in terms of distinct word classes like preposition and adverb, which entails that we posit a preposition out and an adverb out as distinct, homophonous lexical items. Instead, we may attribute to OUT [in both particle and preposition constructions] the same intrinsic semantic structure and show that the real differences lie at the level of construction, that is, in the way the substructures present in the predicates involved are "hooked up" to each other. (1981:195) In Lindner's account, the core semantic structure of up and out is decomposed into various semantic features so that the extensions from this core can be explained in detail. For example, she explains how a difference in one feature—the relation with the landmark—can produce two different meaning schemata for up: thus, The cat climbed up_ the tree posits the tree-landmark itself as the upward path of motion, whereas He rushed ug_ and said hello posits the nonspecified landmark (me, perhaps) as the goal of the motion (1981:112-139). This decompositional approach has perhaps been more enlightening than any other in accounting for the impressive polysemy of P-forms. A similar approach is applied to the semantic extensions of over by Claudia Brugman (1981), and to the meanings of English prepositions by Bruce Hawkins (1984). This study will draw extensively on Lindner's and Hawkins's insights to describe some of P's extensions. Lindner's research is especially helpful in accounting for certain alternative interpretations of verb-particle constructions which have not been approached elsewhere 30 PREPOSITIONS AND PARTICLES IN ENGLISH in the semantic literature. She points out that the same word may be construed at different levels of constituency, as in the following set of examples. (4) He ran up. (5) He ran UTJ the hill. (6) He ran Up the flag. (7) He ran the flag up. In both (4) and the prepositional example (5), the subject of the sentence (he) is the trajector of up. and the only difference is that the landmark NP (the hill) is sublexicalized in (4) but expressed in (5). However, in (6) and (7), the trajector of up is now the object of the sentence (the flag), with the landmark (the pole) sublexicalized. The word order difference between (6) and (7) is explained in terms of alternative constituencies: runup is construed as a "composite scene" (or verbal unit) in (6), with flag as its direct object. But in (7), ran the flag is construed as a composite scene (or verb-object predication), modified (or "elaborated") by up. (Lindner, 1981:188-189). These interpretations provide some valuable principles to explain some of the syntactic constraints discussed previously, in section 2.1.2. As explained there, the Trajector- Landmark schema can be used to clarify the results of the NP-ellipsis test: we can say 'We turned off, meaning We turned off the road, but we cannot say We turned off, meaning We turned off the lights, because the road, as a landmark, may be sublexicalized, whereas the lights, as a trajector, may not. The trajector-landmark schema also ties in with Ping Chen's (1986) and Dwight Bolinger's (1971) pragmatic interpretation of NP-insertion. For them, pronouns are inserted between verb and particle because they express familiar information whereas lexical NPs are more likely to be placed after the particle, according to how much new information they express (see 2.1.2). Lindner's schema suggests a useful iconic frame for this pragmatic interpretation, in the following way. Example (8) groups verb and particle together syntactically as a composite event, isolating the lights as the new information; however, example (9) groups verb and object together, isolating the P-form off as new information, which represents a change of state. (8) We turned off the lights. (9) We (turned the lights) off. Thus Lindner's account allows us to interpret syntactic patterns in a way that mirrors the pragmatic purposes of the speaker. Furthermore, this schema helps clarify Bolinger's (1971) and R.M.W. Dixon's (1982) postpositional constructions, as in "He walked the field over." If we construe walked the field as a verb-object unit analogous to ran the flag, with over as the "new" information, then we can translate Dixon's intuition of a "more thorough treatment" as meaning focal treatment: after all, that which is new is likely to be focused. More will be said about the relationship between particles and focused infonnation in chapter 7. Following Lindner's lead, we can also now schematize the semantic and syntactic differences in Bolinger's riddle (1971:26-27): SEMANTIC SOLUTIONS 31 (10) a. She (swept off) the stage, (particle) b. (She swept) (off the stage), (preposition) c. She (swept[ off) the stage]. (adprep) In (lOa), the stage is construed as the complement of the verbal unit swept off (meaning "cleaned"). In (lOb), she swept is a whole event, construed as the trajector of off, with the stage as the landmark: the relationship could be paraphrased as "Her sweeping was off the stage." In (lOc), she is construed as the trajector of off, meaning that "she" changed her position as a result of the sweeping, with the stage as the landmark. Example (lOc) is an adprep sentence; that is, the adverbial particle off adds a resultative meaning to the verb swept and also serves as a preposition. It represents a prototypical motion event in Leonard Talmy's (1985) terms, where the figure (she) follows a path (off) in relation to a ground NP (the stage). And finally, with Lindner's insights we can return to my introductory examples of the problem of P (section 1.1.1) to explain the difference between "I'm goan clean up the mess" and "I'm cleaning up the table." In that discussion I posed the question as to why two apparently identical verb-particle phrases predicated two different states: if "the mess" moves in the former example, why doesn't "the table" move in the latter? Now we can answer that question by positing two possible construals for "clean up the mess." In one construal, the mess is the trajector of up: it moves upward as a result of cleaning (analogous to "pick up the pieces"). In the other construal, the mess is the complement of a verbal unit, clean up. For "clean up the table," however, only the latter construal is possible: up does not add directional force, but, rather, completive force to the verb, and the whole situation is interpreted not as a motion event but as an event being performed to completion. Thus, Lindner's semantic analysis of up and out is very helpful in our approach to the problem of P. We have now uncovered and explained several syntactic idiosyncracies, and caught a glimpse of several paths along which P's meanings can extend, depending on how speakers choose to construe P-forms with verbs, landmarks, and other elements. However, several issues remain unresolved. For example, Lindner's analysis, like Brugman's and Hawkins's, interprets all prepositions as being extended locative relations. Presumably, then, they should all have the same property of optional landmark sublexicalization as up. out, and over. In other words, they should be optionally usable as particles. But we know that this is not true. Certain prepositions (e.g., from, of, at) never sublexicalize their landmarks no matter what the context. They always appear as prepositions and never as particles. Conversely, other words that express extended locative relations (away, toward, forth) never lexicalize their landmarks. They always appear as particles and never as prepositions. The semantic accounts of P have not addressed this issue. Lindner does propose a principle of "salience" to motivate sublexicalization—that landmarks which are nonsalient do not get lexicalized; but she never clearly defines this notion of salience. Nor does she explain why preposition-particle alternation is possible only for P-forms and not for all prepositions and particles. This problem will be defined in more detail in chapter 7. 32 PREPOSITIONS AND PARTICLES IN ENGLISH Table 3.1: Frequencies and Particle/Preposition Distribution of P-Lexemes in the Corpus P-Lexeme in on up out over about down by around off through number of P-uses: % Particles % Prepositions 18% 81% 83% 2% 1% 15% 98% 98% 73% 0% 94% 4% 66% 79% 31% 24% 97% 4% 89% 34% 21% 65% Other Total 1% 204 2% 0% 1% 3% 3% 2% 7% 0% 0% 4% 175 132 114 71 66 52 35 35 34 23 941 Furthermore, even within the P-group, sublexicalization does not seem to be as optional for some Ps as it is for others. The conversational database used in the current study uncovers an intriguing pattern of skewed distribution for its P-tokens and shows that certain Ps, such as up and out, almost always occur as particles, while others, such as on and by. rarely do. Table 3.1 summarizes the distribution of the eleven most frequently occurring P-forms in this database. Percentages refer to the number of times a certain P-form is used as either a preposition or a particle, relative to the total number of uses of that P-form. The "Other" column refers to repeats, repaired utterances and uninterpretable uses. These P-forms are listed in order of decreasing frequency. The skewed distributions in the sample are clearly mirrored by those of W. Nelson Francis and Henry Kucera's (1982) word frequency analysis for American English (see chapter 9 for a more detailed comparison between their study and this one). In fact, the Francis and Kucera study shows strongly skewed distributions for all twenty P-forms included in the study presented here, whereas table 3.1 only shows the eleven most frequently occurring Ps in my own database. That is, it would appear that the patterns illustrated by the tests in table 2.1 are strongly representative of P-use in American English generally. As we can see, none of the forms listed in table 3.1 occurs with equal frequency as both preposition and adverbial particle. Over, around, and through are relatively flexible while others display very little flexibility. In particular, up and out come close to resembling such pure adverbial particles as away and together, while about and by_ are almost as purely prepositional as to, with, and from. These results suggest that the usage of P-forms in actual conversation is constrained by certain principles that have not been uncovered by semantic models such as Lindner's. Chapter 9 will address the phenomenon of P-skewing in more detail, as a logical result of discourse-pragmatic requirements in conversation. Lindner's alternative constituency approach to particles is mirrored to some extent by two semantic-syntactic approaches to prepositional sequences. The next SEMANTIC SOLUTIONS 33 section shows that these approaches are similarly helpful in explaining some interpretations and constraints, while leaving some key issues unresolved. 3.2. Preposition Constructions 3.2.1. The Functions of Prepositional Phrases Prepositional phrases occur in a wide variety of syntactic contexts: for example, after the verb (/ live in Boulder), clause-initially ( On the other hand . . . ), or clausefinally (I've lived there for three years; you should be tired by now; and so on). Such prepositional phrases are traditionally classified as adverbial since they modify verbs or whole clauses. However, prepositional phrases may also modify nouns, thus functioning like adjectives: angelsfrom heaven could be paraphrased as "heavenly angels"; and medicine in a bottle is generally synonymous with "bottled medicine". We cannot, therefore, assume adverbial status for all prepositional phrases any more than we can assume a priori categoriality for prepositions and particles. Like particles, prepositions construct with other elements to produce a wide variety of meanings, ranging from transparently spatiodirectional to abstract, as in the examples of the previous paragraph. For example, in English, prepositions have almost totally replaced inflections as case-marking morphemes at the clause level: to marks dative case by specifying that its landmark is the recipient in events of giving, showing, and telling (I gave the letter to my mother). The P-form in is often interpreted as a locative case marker specifying its landmark as a location (/ live in Boulder), and it may also refer nonspatially, in prepositional phrases beyond the clause level (e.g., /'// be with you in a minute; in fact . . .; in particular, . . .; and so on). With clause-external constructions such as these, we have no trouble identifying the P-form as a preposition rather than a particle. Categorial indeterminacy between preposition and particle is an issue only in syntactic contexts where the two functions overlap: that is, postverbally in clause-level constructions such as we saw in the categoriality tests of chapter 2 (table 2.1). However, here I will examine prepositional constructions at all levels of constituency (see chapter 8) in an attempt to unify them functionally. By examining the syntax and semantics of prepositions both in postverbal contexts and beyond, we hope to find some clues as to how prepositions are similar to particles, and how they are different. We also hope to discover why it is that even prepositional phrases do not all pattern alike; for this we turn to Torben Vestergaard's model. 3.2.2. Vestergaard's Semantic—Syntactic Continuum Vestergaard's (1977) monograph examines the semantic—syntactic role of the prepositional object in relation to the clause. He plots five different roles along a five-point semantic continuum, ranging from non-role-playing prepositional objects, with relative syntactic freedom from the clause, to central participants in a tightly bound case-marking function: 34 PREPOSITIONS AND PARTICLES IN ENGLISH (11) a. Non-Role-Playing: On the other hand, it is true that . . . b. Abstract Circumstantial: George appeared on the appointed day. c. Concrete Circumstantial: The lizards ran on these steps. d. Marginal Participant: He was sitting on a beer crate, e. Central Participant: I shouldn't be imposing on you. (compiled from Vestergaard, 1977) Of these functions, (lla) would traditionally be classified as a sentential adverb, or conjunct, (lib) and (lie) as free adjuncts, and (lid) and (lie) as prepositional complements (Quirk et al., 1972). Vestergaard's analysis successfully captures the semantic continuity among these constructions, which have traditionally been seen as discrete. It also helps clarify their syntactic constraints in a way that mirrors their progressive centrality to the clause predication. The least central sentence, (lla), is the most free syntactically: we know from experience that sentential adverbs can be moved to the end of the sentence or inserted into a sentence-medial position (e.g., It is, on the other hand, true that . . .). Furthermore, this sentential adverb is not entailed in any sense by the other elements in the sentence. In contrast, the most central prepositional phrase, in (lie), is so tightly construed with the verb that it cannot be placed elsewhere in the sentence, while the verb imposing entails, or sets up, the expectation that it will be followed by the preposition on. In fact, this kind of verb-preposition combination has been described as having a transitivizing effect on the verb, and bringing the prepositional object into the construction as the direct object of a two-word verb, imposed on. English contains many verb-preposition constructions like (lie). Some of them use P-forms that alternate as particles in other constructions (e.g., depend on, talk about, believe in), but many others use "pure prepositions" (e.g., care for, see to, believe in). The tight construction between verb and preposition has also earned such combinations the label of "inseparable phrasal verb" in some grammar-teaching textbooks (e.g., Azar, 1989). However, this term is misleading since it suggests some syntactic or semantic parallel with separable phrasal verbs (or
https://el.b-ok.org/book/690552/a0de64
CC-MAIN-2019-43
refinedweb
16,336
50.67
This article describes how to create a very simple project using GOA WinForms for Flash. Even if we will focus on the Flash target, the process for creating a project targeting Microsoft Silverlight is very close to the one that is described in the article. GOA WinForms allows developers to build web applications using their WinForms experiences and skills. It is an implementation of the standard System.Windows.Form .NET library for both Adobe Flash and Microsoft Silverlight. It allows .NET developers to write standard WinForms applications that will run on these two RIA platforms. System.Windows.Form GOA WinForms contains the full-featured System.Windows.Forms core library, enabling to freely develop and deploy Flash & Silverlight RIA applications using Microsoft Visual Studio. System.Windows.Forms The basic package of GOA WinForms is completely free to use and deploy. It includes 40+ standard controls and components. HelloWorld A new Visual Studio project is created. Open the Form1.ccs file that has been automatically generated. In this file, you can watch the code of an "almost standard" .NET Windows Form holding a button. Here is what has happened when you have started debugging the application: If you go to the bin\Debug subdirectory of your project using Windows Explorer, you will see two files: Note that the project has been compiled using the GOA compiler and not the .NET C# compiler. The GOA compiler allows to generate a swf ("executable" Flash file) from C# code. Also note the ccs extension of the Form1.ccs file. This is the default C# file extension for GOA. The swf file that you have just compiled can be run under Flash Player version 7 or above. Nevertheless, it is recommended to target Flash Player version 9 or above. Now that your platform target is Flash 9, the swf will run a lot faster but it will not be compatible with the earlier versions of the Flash Player. Now that we understand the basics of GOA WinForms for Flash, we can write some code in the HelloWorldForm class to create our Hello World application. HelloWorldForm Note that we are coding our project in a standard way as if we were creating a .NET Windows Forms desktop application. We are adding a label at the top of the form and moving the button at the bottom. When the user will click on the button, the label will display the "Hello World" text. public class Form1 : System.Windows.Forms.Form { private Button button1; private Label label1; private System.ComponentModel.Container components = null; public Form1() { InitializeComponent(); } protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } private void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); this.label1 = new System.Drawing.Point(84, 140); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(104, 36); this.button1.Text = "Click Me"; this.label1.Location = new System.Drawing.Point(40, 44); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(200, 44); this.Controls.Add(this.label1); this.Controls.Add(this.button1); this.ResumeLayout(false); } static void Main() { Application.Run(new Form1()); } } InitializeComponent this.button1.Click += new EventHandler(button1_Click); And, of course, we also have to add the method that will set the text of the label: void button1_Click(object sender, EventArgs e) { this.label1.Text = "Hello World"; } Before starting the application, let's change the settings in order to start it in an external browser. Now, you can start your application. This article is only a quick introduction but it shows that it is now possible to create web application using only your WinForms programming.
http://www.codeproject.com/Articles/19437/Create-your-first-Web-Application-with-GOA-WinForm?msg=2169734
CC-MAIN-2015-40
refinedweb
605
52.15
index Fortran Tutorials Java Tutorials Java Applet Tutorials Java Swing and AWT Tutorials JavaBeans Tutorials applications, mobile applications, batch processing applications. Java is used... | Hibernate Tutorial | Spring Framework Tutorial | Struts Tutorial | OGNL Index Introduction of OGNL in struts. Object Graph Navigation Language is a expression language. It is used for getting and setting the properties of java object... properties of java object. It has own syntax, which is very simple. It make Java arraylist index() Function Java arrayList has index for each added element. This index starts from 0. arrayList values can be retrieved by the get(index) method. Example of Java Arraylist Index() Function import Str Java Bean tags in struts 2 i need the reference of bean tags in struts 2. Thanks! Hello,Here is example of bean tags in struts 2: Struts 2 UI What is Struts Framework? of Struts Struts tutorial index page Struts 2 Tutorials Struts 1 Tutorial...What is Struts Framework? Learn about Struts Framework This article is discussing the Struts Framework. It is discussing the main points of Struts framework Apache Struts is used to create Java web applications using Java Servlet API... and their associated Java classes. Struts is open-source and uses Java... do not work when it comes to large projects and hence we require Struts. Java Struts Frameworks : Latest Version of Struts Struts tutorial index page Struts 2...Struts Frameworks Struts framework is very useful in the development of web... highly maintainable web based enterprise applications. Struts is also being How Struts Works How Struts Works The basic purpose of the Java Servlets in struts is to handle requests... Struts configuration file. Java bean is nothing but a class having get clustered and a non-clustered index? clustered and a non-clustered index? What is the difference between clustered and a non-clustered index Query - Struts Writing quires in Struts How to write quires in Java you want in your project. Do you want to work in java swing? Thanks Mysql Btree Index Mysql Btree Index Mysql BTree Index Which tree is implemented to btree index? (Binary tree or Bplus tree or Bminus tree java - Struts
http://www.roseindia.net/tutorialhelp/comment/94500
CC-MAIN-2015-06
refinedweb
357
59.7
CS194-16 Introduction to Data Science Name: Please put your name Student ID: Please put your student ID In this assignment, we will use machine learning techniques to perform data analysis and learn models about our data. We will use a real world music dataset from Last.fm for this assignment. There are two parts to this assignment: In the first part we will look at Unsupervised Learning with clustering and in the second part, we will study Supervised Learning. The play data (and user/artist matrix) comes from the Last.fm 1K Users dataset, while the tags come from the Last.fm Music Tags dataset. You won't have to interact with these datasets directly, because we've already preprocessed them for you. Note: Before you begin, you should install pydot by running sudo apt-get install python-pydot. Additionally, you should be running on a VM with at least 1GB of RAM allotted to it - less than that and you may run into issues with scikit-learn. Machine learning is a branch of artifical intelligence where we try to find hidden structure within data. For example, lets say you are hired as a data scientist at a cool new music playing startup. You are given access to logs from the product and are asked find out what kinds of music are played on your website and how you can promote songs that will be popular. In this case we wish to extract some structure from the raw data we have using machine learning. There are two main kinds of machine learning algorithms: Many of the techniques you'll be using (like testing on a validation set) are of critical importance to the modeling process, regardless of the technique you're using, so keep these in mind in your future modeling efforts. Your assignment is to use machine learning algorithms for two tasks on a real world music dataset from Last.fm. The goal in the first part is to cluster artists and try to discover all artists that belong a certain genre. In the second part, we'll use the same dataset and attempt to predict how popular a song will be based on a number of features of that song. One component will involve incorporating cluster information into the models. Data files for this assignment can be found at: The zip file includes the following files: We will explain the datasets and how they need to used in the assignment sections. Complete the all the exercises below and turn in a write up in the form of an IPython notebook, that is, an .ipynb file. The write up should include your code, answers to exercise questions, and plots of results. Complete submission instructions will be posted on Piazza. We recommend that you do your work in a copy of this notebook, in case there are changes that need to be made that are pushed out via github. In this notebook, we provide code templates for many of the exercises. They are intended to help with code re-use, since the exercises build on each other, and are highly recommended. Don't forget to include answers to questions that ask for natural language responses, i.e., in English, not code! This assignment can be done with basic python, matplotlib and scikit-learn. Feel free to use Pandas, too, which you may find well suited to several exercises. As for other libraries, please check with course staff whether they're allowed. You're not required to do your coding in IPython, so feel free to use your favorite editor or IDE. But when you're done, remember to put your code into a notebook for your write up. This assignment is to be done individually. Everyone should be getting a hands on experience in this course. You are free to discuss course material with fellow students, and we encourage you to use Internet resources to aid your understanding, but the work you turn in, including all code and answers, must be your own work. Download the data and unzip it. Read in the file artists-tags.txt and store the contents in a DataFrame. The file format for this file is artist-id|artist-name|tag|count. The fields mean the following: Similarly, read in the file userart-mat-training.csv . The file format for this file is artist-id, user1, user2, .... user1000. i.e. There are 846 such columns in this file and each column has a value 1 if the particular user played a song from this artist. import pandas as pd DATA_PATH = "/home/saasbook/datascience-sp14/hw2" # Make this the /path/to/the/data def parse_artists_tags(filename): df = pd.read_csv(filename, sep="|", names=["ArtistID", "ArtistName", "Tag", "Count"]) return df def parse_user_artists_matrix(filename): df = pd.read_csv(filename) return df artists_tags = parse_artists_tags(DATA_PATH + "/artists-tags.txt") user_art_mat = parse_user_artists_matrix(DATA_PATH + "/userart-mat-training.csv") print "Number of tags %d" % 0 # Change this line. Should be 952803 print "Number of artists %d" % 0 # Change this line. Should be 17119 The first task we will look at is how to discover artist genres by only looking at data from plays on Last.fm. One of the ways to do this is to use clustering. To evaluate how well our clustering algorithm performs we will use the user-generated tags and compare those to our clustering results. Last.fm allows users to associate tags with every artist (See the top tags for a live example). However as there are a number of tags associated with every artists, in the first step we will pre-process the data and get the most popular tag for an artist. # TODO Implement this. You can change the function arguments if necessary # Return a data structure that contains (artist id, artist name, top tag) for every artist def calculate_top_tag(all_tags): pass top_tags = calculate_top_tag(artists_tags) # Print the top tag for Nirvana # Artist ID for Nirvana is 5b11f4ce-a62d-471e-81fc-a69a8278c7da # Should be 'Grunge' print "Top tag for Nirvana is %s" % "TODO: Tag goes here" # Complete this line b. To do clustering we will be using numpy matrices. Create a matrix from user_art_mat with every row in the matrix representing a single artist. The matrix will have 846 columns, one for whether each user listened to the artist. def create_user_matrix(input_data): pass user_np_matrix = create_user_matrix(user_art_mat) print user_np_matrix.shape # Should be (17119, 846) Having pre-processed the data we can now perform clustering on the dataset. In this assignment we will be using the python library scikit-learn for our machine learning algorithms. scikit-learn provides an extensive library of machine learning algorithms that can be used for analysis. Here is a nice flow chart that shows various algorithms implemented and when to use any of them. In this part of the assignment we will look at K-Means clustering Note on terminology: "samples" and "features" are two words you will come across frequently when you look at machine learning papers or documentation. "samples" refer to data points that are used as inputs to the machine learning algorithm. For example in our dataset each artist is a "sample". "features" refers to some representation we have for every sample. For example the list of 1s and 0s we have for each artist are "features". Similarly the bag-of-words approach from the previous homework produced "features" for each document. Clustering is the process of automatically grouping data points that are similar to each other. In the K-Means algorithm we start with K initially chosen cluster centers (or centroids). We then compute the distance of every point from the centroids and assign each point to the centroid. Next we update the centroids by averaging all the points in the cluster. Finally, we repeat the algorithm until the cluster centers are stable. Take a minute to look at the scikit-learn interface for calling KMeans. The constructor of the KMeans class returns a estimator on which you can call fit to perform clustering. From the above description we can see that there are a few parameters which control the K-Means algorithm. We will look at one parameter specifically, the number of clusters used in the algorithm. The number of clusters needs to be chosen based on domain knowledge of the data. As we do not know how many genres exist we will try different values and compare the results. We will also measure the performance of clustering algorithms in this section. You can time the code in a cell using the %%time IPython magic as the first line in the cell. Note: By default, the scikit-learn KMeans implementation runs the algorithm 10 times with different center initializations. For this assignment you can run it just once by passing the n_initargument as 1. %%time from sklearn.cluster import KMeans # Run K-means using 5 cluster centers on user_np_matrix kmeans_5 = None b. Run K-means using 25 and 50 cluster centers on the user_np_matrix. Also measure the time taken for both cases. %%time kmeans_25 = None %%time kmeans_50 = None d. Of the three algorithms, which setting took the longest to run ? Why do you think this is the case ? TODO - Answer question here. In addition to the performance comparisons we also wish to compare how good our clusters are. To do this we are first going to look at internal evaluation metrics. For internal evaluation we only use the input data and the clusters created and try to measure the quality of clusters created. We are going to use two metrics for this: Inertia is a metric that is used to estimate how close the data points in a cluster are. This is calculated as the sum of squared distance for each point to it's closest centroid, i.e., its assigned cluster center. The intution behind inertia is that clusters with lower inertia are better as it means closely related points form a cluster.Inertia is calculated by scikit-learn by default. Exercise 3 a. Print inertia for all the kmeans model computed above. print "Inertia for KMeans with 5 clusters = %lf " % 0.0 print "Inertia for KMeans with 25 clusters = %lf " % 0.0 print "Inertia for KMeans with 50 clusters = %lf " % 0.0 b. Does KMeans run with 25 clusters have lower or greater inertia than the ones with 5 clusters ? Which algorithm is better and why ? TODO: Answer question The silhouette score measures how close various clusters created are. A higher silhouette score is better as it means that we dont have too many overlapping clusters. The silhouette score can be computed using sklearn.metrics.silhouette_score from scikit learn. c. Calculate the Silhouette Score using 500 sample points for all the kmeans models. from sklearn.metrics import silhouette_score # NOTE: Use 500 sample points to calculate the silhouette score def get_silhouette_score(data, model): pass print "Silhouette Score for KMeans with 5 clusters = %lf" % 0.0 print "Silhouette Score for KMeans with 25 clusters = %lf " % 0.0 print "Silhouette Score for KMeans with 50 clusters = %lf " % 0.0 d. How does increasing the number of clusters affect the silhouette score ? TODO: Answer question While internal evaluation is useful, a better method for measuring clustering quality is to do external evaluation. This might not be possible always as we may not have ground truth data available. In our application we will use top_tags from before as our ground truth data for external evaluation. We will first compute purity and accuracy and finally we will predict tags for our test dataset. a. As a first step we will need to join the artist_tags data with the set of labels generated by K-Means model. That is, for every artist we will now have the top tag, cluster id and artist name in a data structure. # Return a data structure that contains artist_id, artist_name, top tag, cluster_label for every artist def join_tags_labels(artists_data, user_data, kmeans_model): pass # Run the function for all the models kmeans_5_joined = None kmeans_25_joined = None kmeans_50_joined = None b. Next we need to generate a genre for every cluster id we have (the cluster ids are from 0 to N-1). You can do this by grouping the data from the previous exercise on cluster id. One thing you might notice is that we typically get a bunch of different tags associated with every cluster. How do we pick one genre or tag from this ? To cover various tags that are part of the cluster, we will pick the top 5 tags in each cluster and save the list of top-5 tags as the genre for the cluster. # Return a data structure that contains cluster_id, list of top 5 tags for every cluster def assign_cluster_tags(joined_data): pass kmeans_5_genres = None kmeans_25_genres = None kmeans_50_genres = None Two commonly used metrics used for evaluating clustering using external labels are purity and accuracy. Purity measures the frequency of data belonging to the same cluster sharing the same class label i.e. if we have a number of items in a cluster how many of those items have the same label ? Meanwhile, accuracy measures the frequency of data from the same class appearing in a single cluster i.e. of all the items which have a particular label what fraction appear in the same cluster ? NOTE: This is similar to precision and recall that we looked at in the previous assignment. Purity here makes sure that our clusters have mostly homogeneous labels while accuracy make sure that our labels are not spread out over too many clusters. d. Compute the purity for each of our K-Means models. To do this find the top tags of all artists that belong to a cluster. Check what fraction of these tags are covered by the top 5 tags of the cluster. Average this value across all clusters. HINT: We used similar ideas to get the top 5 tags in a cluster. def get_cluster_purity(joined_data): pass print "Purity for KMeans with 5 centers %lf " % 0.0 print "Purity for KMeans with 25 centers %lf " % 0.0 print "Purity for KMeans with 50 centers %lf " % 0.0 e. To compute the accuracy first get all the unique tags from top_tags. Then for each tag, compute how many artists are found in the largest cluster. We denote these as correct cluster assignments. For example, lets take a tag 'rock'. If there are 100 artists with tag 'rock' and say 90 of them are in one cluster while 10 of them are in another. Then we have 90 correct cluster assignments Add the number of correct cluster assignments for all tags and divide this by the total size of the training data to get the accuracy for a model. def get_accuracy(joined_data): pass print "Accuracy of KMeans with 5 centers %lf " % 0.0 print "Accuracy of KMeans with 25 centers %lf " % 0.0 print "Accuracy of KMeans with 50 centers %lf " % 0.0 f. What do the numbers tell you about the models? Do you have a favorite? TODO: Your answer here. Finally we can treat the clustering model as a multi-class classifier and make predictions on external test data. To do this we load the test data file userart-mat-test.csv and for every artist in the file we use the K-Means model to predict a cluster. We mark our prediction as successful if the artist's top tag belongs to one of the five tags for the cluster. a Load the testdata file and create a NumPy matrix named user_np_matrix_test. user_art_mat_test = parse_user_artists_matrix(DATA_PATH + "/userart-mat-test.csv") # NOTE: the astype(float) converts integer to floats here user_np_matrix_test = create_user_matrix(user_art_mat_test).astype(float) user_np_matrix_test.shape # Should be (1902, 846) # For every artist return a list of labels def predict_cluster(test_data, test_np_matrix, kmeans_model): pass # Call the function for every model from before kmeans_5_predicted = None kmeans_25_predicted = None kmeans_50_predicted = None c. Get the tags for the predicted genre and the tag for the artist from top_tags. Output the percentage of artists for whom the top tag is one of the five that describe its cluster. This is the recall of our model. NOTE: Since the tag data is not from the same source as user plays, there are artists in the test set for whom we do not have top tags. You should exclude these artists while making predictions and while computing the recall. # Calculate recall for our predictions def verify_predictions(predicted_artist_labels, cluster_genres, top_tag_data): pass d. Print the recall for each KMeans model. We define recall as num_correct_predictions / num_artists_in_test_data # Use verify_predictions for every model print "Recall of KMeans with 5 centers %lf " % 0.0 print "Recall of KMeans with 25 centers %lf " % 0.0 print "Recall of KMeans with 50 centers %lf " % 0.0 Another way to evaluate clustering is to visualize the output of clustering. However the data we are working with is in 846 dimensions !, so it is hard to visualize or plot this. Thus the first step for visualization is to reduce the dimensionality of the data. To do this we can use Prinicipal Component Analysis (PCA). PCA reduces the dimension of data and keeps only the most significant components of it. This is a commonly used technique to visualize data from high dimensional spaces. NOTE: We use RandomizedPCA, an approximate version of the algorithm as this has lower memory requirements. The approximate version is good enough when we are reducing to a few dimensions (2 in this case). We also sample the input data before PCA to further reduce memory requirements. a. Calcluate the RandomizedPCA of the sampled training data set sampled_data and reduce it to 2 components. Use the fit_transform method to do this. from sklearn.decomposition import RandomizedPCA import numpy as np sample_percent = 0.20 rows_to_sample = int(np.ceil(sample_percent * user_np_matrix.shape[0])) sampled_data = input_data[np.random.choice(input_data.shape[0], rows_to_sample, replace=False),:] # Return the data reduced to 2 principal components def get_reduced_data(input_data): pass user_np_2d = get_reduced_data(sampled_data) # TODO: Write code to fit and plot reduced_data. import pylab as pl %pylab inline In this section of the assignment you'll be building a model to predict the number of plays a song will get. Again, we're going to be using scikit-learn to train and evaluate regression models, and pandas to pre-process the data. In the process, you'll encounter some modeling challenges and we'll look at how to deal with them. We've started with the same data as above, but this time we've pre-computed a number of song statistics for you. These are: a. Let's start by loading up the data - we've provided a "training set" and a "validation set" for you to test your models on. The training set are the examples that we use to create our models, while the validation set is a dataset we "hold out" from the model fitting process, we use these examples to test whether our models accurately predict new data. %pylab inline import pandas as pd train = pd.read_csv(DATA_PATH + "/train_model_data.csv") validation = pd.read_csv(DATA_PATH + "/validation_model_data.csv") Now that you've got the data loaded, play around with it, generate some descriptive statistics, and get a feel for what's in the data set. For the categorical variables try pandas ".count_values()" on them to get a sense of the most likely distributions (countries, etc.). b. In the next cell put some commands you ran to get a feel for the data. # TODO: Your commands for data exploration here. c. Next, create a pairwise scatter plot of the columns: plays, pctmale, age, pctgt1, pctgt2, pctgt5. (Hint: we did this in lab!) Do you notice anything about the data in this view? What about the relationship between plays and other columns? # TODO: Your commands to generate a scatter plot here. TODO: What do you notice about the data in this view? Write your answer here. scikit-learn does a number of things very well, but one of the things it doesn't handle easily is categorical or missing data. Categorical data is data that can take on a finite set of values, e.g. a categorical variable might be the color of a stop light (Red, Yellow, Green), this is in contrast with continuous variables like real numbers in the range -Infinity to +Infinity. There is another common type of data called "ordinal" that can be thought of as categorical data that has a natural ordering, like: Cold, Warm, Hot. We won't be dealing with this kind of data here, but having that kind of ranking opens up the use of certain other statistical methods. a. For the first part of the exercise, let's eliminate categorical variables, and impute missing values with pandas. Write a function to drop all categorical variables from the data set, and return two pandas data frames: def basic_prep(data, col): #TODO - make a copy of the original dataset but with the categorical variables removed! *Cluster* should be thought of as a #categorical variable and should be removed! Make use of pandas ".drop" function. #TODO - impute missing values with the mean of those columns, use pandas ".fillna" function to accomplish this. pass #This will create two new data frames, one that contains training data - in this case all the numeric columns, #and one that contains response data - in this case, the "plays" column. train_basic_features, train_basic_response = basic_prep(train, 'plays') validation_basic_features, validation_basic_response = basic_prep(validation, 'plays') Now, we're going to train a linear regression model. This is likely the most widely used model for fitting data out there today - you've probably seen it before, maybe even used it in Excel. The goal of linear modeling, is to fit a linear equation that maps a set of input features to a numerical response. This equation is called a model, and can be used to make predictions about the response of similar input features. For example, imagine we have a dataset of electricity prices ($p$) and outdoor temperature ($t$), and we want to predict, given temperature, what electricity price will be. A simple way to model this is with an equation that looks something like $p = basePrice + factor*t$. When we fit a model, we are estimating the parameters ($basePrice$ and $factor$) that best fit our data. This is a very simple linear model, but you can easily imagine extending this to situations where you need to estimate several parameters. Note: It is possible to fill a semester with linear models (and classes in other departments do!), and there are innumerable issues to be aware of when you fit linear models, so this is just the tip of the iceberg - don't dismiss linear models outright based on your experiences here! A linear model models the data as a linear combination of the model and its weights. Typically, the model is written with something like the following form: $y = X\theta + \epsilon$, and when we fit the model, we are trying to find the value of $\theta$ that minimizes the loss of the model. In the case of regression models, the loss is often represented as $\sum (y - X\theta)^2$ - or the squared distance between the prediction and the actual value. In the code below, X refers to the the training features, y refers to the training response, Xv refers to the validation features and yv refers to the validation response. Note that X is a matrix (or a DataFrame) with the shape $n \times d$ where $n$ is the number of examples and $d$ is the number of features in each example, while y is a vector of length $n$ (one response per example). Our goal with this assignment is to accurately estimate the number of plays a song will get based on the features we know about it. The score we'll be judging the models on is called $R^2$, which is a measure of how well the model fits the data. It can be thought of roughly as the percentage of the variance that the model explains. a. Fit a LinearRegression model with scikit-learn and return the model score on both the training data and the validation data. from sklearn import linear_model def fit_model(X, y): #TODO - Write a function that fits a linear model to a dataset given a column of values to predict. pass def score_model(model, X, y, Xv, yv): #TODO - Write a function that returns scores of a model given its training #features and response and validation features and response. #The output should be a tuple of two model scores. pass def fit_model_and_score(data, response, validation, val_response): #TODO - Given a training dataset, a validation dataset, and the name of a column to predict, #Using the model's ".score()" method, return the model score on the training data *and* the validation data #as a tuple of two doubles. pass #END TODO print fit_model_and_score(train_basic_features, train_basic_response, validation_basic_features, validation_basic_response) model = fit_model(train_basic_features, train_basic_response) We realize that this may be your first experience with linear models - but that's a pretty low $R^2$ - we're looking for scores significantly higher than 0, and the maximum is a 1. So what happened? Well, we've modeled a linear response to our input features, but the variable we're modeling (plays) clearly has a non-linear relationship with respect to the input features. It roughly follows a power-law distribution, and so modeling it in linear space yields a model with estimates that are way off. We can verify this by looking at a plot of the model's residuals - that is, the difference between the training responses and the predictions. A good model would have residuals with two properties: b. Write a function to calculate the residuals of the model, and plot those with a histogram. def residuals(features, y, model): #TODO - Write a function that calculates model residuals given input features, ground truth, and the model. pass #TODO - Plot the histogram of the residuals of your current model. See the structure in the plot? This means we've got more modeling to do before we can call it a day! It satisfies neither of our properties - we're often way wrong with our predictions, and seem to systematically under predict the number of plays a song will get. What happens if we try and predict the $log$ of number of plays? This controls the exponential behaviour of plays, and gives less weight to the case where our prediction was off by 100 when the true answer was 1000. a. Adapt your model fitting from above to fit the log of the nubmer of plays as your response variable. Print the scores. from sklearn import linear_model #TODO - Using what you built above, build a model using the log of the number of plays as the response variable. b. You should see a significantly better $R^2$ and validation $R^2$, though still pretty low. Take a look at the model residuals again, do they look any better? #TODO Plot residuals of your log model. Note - we want to see these on a "plays" scale, not a "log(plays)" scale! There must be something we can do here to build a better model. Let's try incorporating country and cluster information. Linear models expect numbers for input features. But we have some features that we think could be useful that are discrete or categorical. How do we represent these as numbers? One solution is something called one-hot encoding. Basically, we map a discrete space to a vector of binary indicators, then use these indicators as numbers. For example, if I had an input column that could take on the values {$RED$, $GREEN$, $BLUE$}, and I wanted to model this with one-hot-encoding, I could use a map: We use this representation instead of traditional binary numbers to keep these features independent of one another. Once we've established this representation, we replace the columns in our dataset with their one-hot-encoded values. Then, we can fit a linear model on the data once it's encoded this way! Statisticians and econometricians call these types of binary variables dummy variables, but we're going to call it one-hot encoding, because that sounds cooler. Scikit-learn has functionality to transform values to this encoding built in, so we'll leverage that. The functionality is called DictVectorizer in scikit-learn. The idea is that you feed a DictVectorizer a bunch of examples of your data (that's the vec.fit line), and it builds a map from a categorical variable to a one-hot encoded vector like we have in the color example above. Then, you can use this object to translate from categorical values to sequences of numeric ones as we do with vec.transform. In the example below, we fit a vectorizer on the training data and use the same vectorizer on the validation data so that the mapping is consistent and we don't run into issues if the categories don't match perfectly between the two data sets. a. Use the code below to generate new training and validation datasets for the datasets with the categorical features in them. from sklearn import feature_extraction def one_hot_dataframe(data, cols, vec=None): """ Takes a dataframe and a list of columns that need to be encoded. Returns a tuple comprising the data, and the fitted vectorizor. Based on """ if vec is None: vec = feature_extraction.DictVectorizer() vec.fit(data[cols].to_dict(outtype='records')) vecData = pd.DataFrame(vec.transform(data[cols].to_dict(outtype='records')).toarray()) vecData.columns = vec.get_feature_names() vecData.index = data.index data = data.drop(cols, axis=1) data = data.join(vecData) return (data, vec) def prep_dset(data, col, vec=None): #Convert the clusters to strings. new_data = data new_data['cluster'] = new_data['cluster'].apply(str) #Encode the data with OneHot Encoding. new_data, vec = one_hot_dataframe(new_data, ['country1','cluster'], vec) #Eliminate features we don't want to use in the model. badcols = ['country2','country3','artid','key','age'] new_data = new_data.drop(badcols, axis=1) new_data = new_data.fillna(new_data.mean()) return (new_data.drop([col], axis=1), pd.DataFrame(new_data[col]), vec) train_cats_features, train_cats_response, vec = prep_dset(train, 'plays') validation_cats_features, validation_cats_response, _ = prep_dset(validation, 'plays', vec) b. Now that you've added the categorical data, let's see how it works with a linear model! print fit_model_and_score(train_cats_features, train_cats_response, validation_cats_features, validation_cats_response) You should see a much better $R^2$ for the training data, but a much worse one for the validation data. What happened? This is a phenomenon called overfitting - our model has too many degrees of freedom (one parameter for each of the 100+ features of this dataset. This means that while our model fits the training data reasonably well, but at the expense of being too specific to that data. John Von Neumann famously said "With four parameters I can fit an elephant, and with five I can make him wiggle his trunk!". So, we're at an impasse. We didn't have enough features and our model performed poorly, we added too many features and our model looked good on training data, but not so good on test data. What's a modeler to do? There are a couple of ways of dealing with this situation - one of them is called regularization, which you might try on your own (see RidgeRegression or LassoRegression in scikit-learn), another is to use a model which captures non-linear relationships between the features and the response variable. One such type of model was pioneered here at Berkeley, by the late, great Leo Breiman. These models are called regression trees. The basic idea behind regression treees is to recursively partition the dataset into subsets that are similar with respect to the response variable. If we take our temperature example, we might observe a non-linear relationship - electricity gets expensive when it's cold outside because we use the heater, but it also gets expensive when it's too hot outside because we run the air conditioning. A decision tree model might dynamically elect to split the data on the temperature feature, and estimate high prices both for hot and cold, with lower prices for more Berkeley-like temperatures. Go read the scikit-learn decision trees documentation for more background. a. Using the scikit learn DecsionTreeRegressor API, write a function that fits trees with the parameter 'max_depth' exposed to the user, and set to 10 by default. from sklearn import tree def fit_tree(X, y, depth=10): ##TODO: Using the DecisionTreeRegressor, train a model to depth 10. pass b. You should be able to use your same scoring function as above to compute your model scores. Write a function that fits a tree model to your training set and returns the model's score for both the training set and the validation set. def fit_model_and_score_tree(train_features, train_response, val_features, val_response): ##TODO: Fit a tree model and report the score on both the training set and test set. pass c. Report the scores on the training and test data for both the basic features and the categorical features. print fit_model_and_score_tree(train_basic_features, train_basic_response, validation_basic_features, validation_basic_response) print fit_model_and_score_tree(train_cats_features, train_cats_response, validation_cats_features, validation_cats_response) Hooray - we've got a model that performs well on the training data set and the validation dataset. Which one is better? Why do you think that is. Try varying the depth of the decision tree (from, say, 2 to 20) and see how either data set does with respect to training and validation error. d. Now, let's build a tree to depth 3 and take a look at it. import StringIO import pydot from IPython.display import Image tmodel = fit_tree(train_basic_features, train_basic_response, 3) def display_tree(tmodel): dot_data = StringIO.StringIO() tree.export_graphviz(tmodel, out_file=dot_data) graph = pydot.graph_from_dot_data(dot_data.getvalue()) return Image(graph.create_png()) display_tree(tmodel) e. What is the tree doing? It looks like it's making a decision on variables X[4] and X[2] - can you briefly describe, in words, what the tree is doing? TODO: Your answer goes here. f. Finally, let's take a look at variable importance for a tree trained to 10 levels - this is a more formal way of deciding which features are important to the tree. The metric that scikit-learn calculates for feature importance is called GINI importance, and measures how much total 'impurity' is removed by splits from a given node. Variables that are highly discriminitive (e.g. ones that occur frequently throughout the tree) have higher GINI scores. You can read more about these scores here. tmodel = fit_tree(train_basic_features, train_basic_response, 10) pd.DataFrame(tmodel.feature_importances_, train_basic_features.columns) g. What do you notice? Is the output interpretable? How would you explain this to someone? TODO: Your answer goes here.
http://nbviewer.jupyter.org/github/amplab/datascience-sp14/blob/master/hw2/HW2.ipynb
CC-MAIN-2018-51
refinedweb
5,767
55.44
SEM_WAIT(3) BSD Programmer's Manual SEM_WAIT(3) sem_wait, sem_trywait - decrement (lock) a semaphore #include <semaphore.h> int sem_wait(sem_t *sem); int sem_trywait(sem_t *sem);- mented and an error is returned. The sem_wait() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error. sem_wait() and sem_trywait() will fail if: [EINVAL] sem points to an invalid semaphore. Additionally, sem_trywait() will fail if: [EAGAIN] The semaphore value was zero, and thus could not be decre- mented. sem_destroy(3), sem_getvalue(3), sem_init(3), sem_open(3), sem_post(3) sem_wait() and sem_trywait() conform to ISO/IEC 9945-1:1996 ("POSIX"). MirOS BSD #10-current February 15,.
https://www.mirbsd.org/htman/sparc/man3/sem_wait.htm
CC-MAIN-2019-18
refinedweb
115
56.96
> ... aaaand, that means disabling setup.py or hacking it significantly > to support a win32 build, e.g. to build pyexpat, detect which modules > are left, etc. by examining the remaining vcproj files in PCbuild. ok - i started the hacking. the first bit of hacking is this, in distutils/sysconfig.py, added to _init_nt() try: filename = get_makefile_filename() parse_makefile(filename, g) except IOError, msg: my_msg = "invalid Python installation: unable to open %s" % filename if hasattr(msg, "strerror"): my_msg = my_msg + " (%s)" % msg.strerror raise DistutilsPlatformError(my_msg) # load the installed pyconfig.h: try: prefix = EXEC_PREFIX prefix = os.path.join(prefix, "PC") filename = os.path.join(prefix, "pyconfig.h") parse_config_h(file(filename), g) except IOError, msg: my_msg = "invalid Python installation: unable to open %s" % filename if hasattr(msg, "strerror"): my_msg = my_msg + " (%s)" % msg.strerror raise DistutilsPlatformError(my_msg) global _config_vars _config_vars = g that gets me part-way - at least i get... oh dear : self.build_extensions() File "../setup.py", line 183, in build_extensions self.compiler.set_executables(**args) File "Z:\mnt\src\python2.5-2.5.2\lib\distutils\ccompiler.py", line 165, in set_executables (key, self.__class__.__name__) ValueError: unknown executable 'compiler_so' for class MSVCCompiler whoops :) so, next, we hack in a compiler, in to ... ooo, let's saaay... distutils/cygwinccompiler.py, just for fun. now we get this! wha-hey! but... oh dear. oh dear number 1) firstly, err.... this is cross-compiling - those path names are bullshit because actually we're compiling on.... LINUX damnit, not windows. hmm.... there's something to work around that one, perhaps, by installing the mingw32 compiler under wine (o god i've done that before, it's dreadfully slow) oh dear number 2) File "Z:\mnt\src\python2.5-2.5.2\lib\os.py", line 562, in spawnv return _spawnvef(mode, file, args, None, execv) File "Z:\mnt\src\python2.5-2.5.2\lib\os.py", line 545, in _spawnvef wpid, sts = waitpid(pid, 0) NameError: global name 'waitpid' is not defined err.... oh - ok, found another missing function: spawnv. so, added that, in PC/pcbuild.h: #ifdef __WINE__ #define HAVE_SPAWNV #endif and after some futzing around with yet more #ifdefs in posixmodule.c we have another build - this time using wine's spawnv so it doesn't try to find a non-existent waitpid aaannnd SPLAT yesss, we get the crash-output from winegcc: Failed to configure _ctypes module building '_ctypes_test' extension wine: Unhandled page fault on read access to 0x7265704f at address 0x601ec25b (thread 001c), starting debugger... Unhandled exception: page fault on read access to 0x7265704f in 32-bit code (0x601ec25b). Register dump: CS:0023 SS:002b DS:002b ES:002b FS:0063 GS:006b EIP:601ec25b ESP:0032c70c EBP:0032c718 EFLAGS:00010206( - 00 - RIP1) EAX:7265704f EBX:7bc8a7a4 ECX:00000003 EDX:604ab3d7 ESI:0032c848 EDI:7265704f Stack dump: 0x0032c70c: 7bc6859d 7265704f 6056a0b8 0032c788 0x0032c71c: 603fd0eb 7265704f 006e9544 001bc84c 0x0032c72c: 006c574c 6056b82c 605721a0 00000002 0x0032c73c: 0032c7d8 718e21fe 0016329c 7265704f 0x0032c74c: 00730065 002e0074 0000006f 00159320 0x0032c75c: 603aa590 001b3f0c 005086e0 00000004 Backtrace: =>1 0x601ec25b strlen+0xb() in libc.so.6 (0x0032c718) fixme:dbghelp_dwarf:dwarf2_parse_variable Unsupported form for const value degToRad (a) 2 0x603fd0eb do_mkvalue+0x3db(p_format=<register ESI not in topmost frame>, p_va=<is not available>, flags=0x0) [/mnt/src/python2.5-2.5.2/ build/../Python/modsupport.c:419] in python (0x0032c788) 3 0x603fcc6d do_mktuple+0x7d(p_format=0x32c848, p_va=0x32c844, endchar=0x29, n=0x2, flags=0x0) [/mnt/src/python2.5-2.5.2/build/../ Python/modsupport.c:268] in python (0x0032c7b8) ..... ..... hey, this is fun! let's try a crazed compile of python and see what falls over, wheeeee :) ... much as this seems to be consuming much of my time, for some bizarre reason i just can't seem to stop. anyway - yes, this is effectively cross-compiling, and so the python25.exe and environment created is unfortunately expecting to see a windows-like environment. bugger. i'll ask on the wine lists if there's a "back-translator". winegcc and wineg++ are wrapper-scripts that wrap gcc and g++ to "make it look like" you're compiling for win32 when in fact you're compiling under linux. if there was a back-translation of that concept, that recognised z: \blahblah and back-translated it into /unix/blah then it would be possible to get away with specifying _that_ script as the compiler, which would then pass winegcc as _its_ script.... yuukkk!
https://mail.python.org/pipermail/python-list/2009-January/519018.html
CC-MAIN-2014-15
refinedweb
726
57.77
. Update: As of SAS/IML 12.1, the MAHALANOBIS function is distributed as part of SAS/IML software. It is no longer necessary to implement the function yourself. You can skip the next two sections of this article unless you are interested in the mathematical ideas.: proc iml; /* simplest approach: x and center are row vectors */ start mahal1(x, center, cov); y = (x - center)`; /* col vector */ d2 = y` * inv(cov) * y; /* explicit inverse. Not optimal */ return (sqrt(d2)); finish; x = {1 0}; /* test it */ center = {1 1}; cov = {9 1, 1 1}; md1 = mahal1(x, center, cov); print md1;: /* (1) Use ROOT and TRISOLV instead of INV to solve linear system (2) Let x be a matrix. Compute distances from row x[i,] to center. */ start mahal2(x, center, cov); /* x[i,] and center are row vectors */ n = nrow(x); d2 = j(n,1); /* allocate vector for distances */ U = root(cov); /* Want d2 = v * inv(cov) * v` = v * w where cov*w = v` ==> (U`U)*w = v` Cholesky decomp of cov ==> First solve U` z = v` for z, then solve U w = z for w */ y = x - center; do i = 1 to n; /* using the DO loop is not optimal */ v = y[i,]; /* get i_th centered row */ z = trisolv(2, U, v`); /* solve linear system */ w = trisolv(1, U, z); d2[i,] = v * w; /* dot product of vectors */ end; return (sqrt(d2)); finish; x = {1 0, /* test it: x has more than one row */ 0 1, -1 0, 0 -1}; md2 = mahal2(x, center, cov); print md2;. /* 3) Enable pairwise Mahalanobis distances by allowing 2nd arg to be a matrix. 4) Solve linear system for many right-hand sides at once */ start mahalanobis(x, center, cov); /* x[i,] and center[i,] are row vectors */ n = nrow(x); m = nrow(center); d2 = j(n,m); /* return matrix of pairwise Mahalanobis distances */ U = root(cov); /* solve for Cholesky root once */ do k = 1 to m; /* for each row of the center matrix */ v = x - center[k,]; /* v is matrix of right-hand sides */ z = trisolv(2, U, v`); /* solve n linear systems in one call */ w = trisolv(1, U, z); /* Trick: vecdiag(A*B) = (A#B`)[,+] without computing product */ d2[,k] = (v # w`)[,+]; /* shortcut: diagonal of matrix product */ end; return (sqrt(d2)); finish; y = {1 1, 0 0, 1 2}; /* x and y are BOTH matrices */ md = mahalanobis(x, y, cov); /* compute pairwise distances between x and y */ print md;)) 13 Comments For the mahalnobis example, would it be possible to provide an example of what the dataset should look like, please? Thank you To use this code with a SAS data set, the p variables should be in p columns of the data set. For example: In PROC IML you can then say:. 4 Trackbacks [...] Uses the Mahalanobis module to compute the Mahalanobis distance between each point and the origin. The Mahalanobis distance is a standardized distance that takes into account correlations between the variables. [...] [...] distance between the multidimensional point x and the mean vector μ. I have previous written a SAS/IML function that computes the Mahalanobis distance in SAS, so it is simple to construct a SAS/IML function that computes the multivariate normal PDF for any [...] [...] concepts, including bivariate normal cumulative distribution, inverse hyperbolic functions and Mahalanobis distance ... to name a [...] [...] [...]
http://blogs.sas.com/content/iml/2012/02/22/how-to-compute-mahalanobis-distance-in-sas/
CC-MAIN-2014-42
refinedweb
553
59.77
ASF Bugzilla – Bug 52210 Add TLS Next Protocol Negotiation (NPN) support to mod_ssl Last modified: 2014-04-30 13:31:15 UTC Created attachment 27969 [details] Patch for mod_ssl to add NPN hooks OpenSSL 1.0.1 added support for TLS Next Protocol Negotiation (NPN) [1], a feature which allows client and server to negotiate what protocol should be used over the secure connection. I propose adding hooks into mod_ssl to allow other modules to access this feature. In particular, this would open the door for a module that would support SPDY [2], a performance-improving protocol that is now supported by (at least) Google Chrome, Amazon Silk, Firefox (targeting FF11), and Strangeloop, but not yet by Apache httpd. (Not coincidentally, I am working on implementing such a module.) The changes needed to mod_ssl are pretty simple; I have a small patch here that adds these hooks. The patch attached below was made against the httpd-2.2.x branch, but of course I would be happy to modify the patch as necessary for other version(s). [1] NPN is described here: [2] SPDY is described here: Issues: * Patch includes a few inline data declarations that won't compile with a strict c89 compiler. * I'd suggest adding a log level debug with the negotiated protocol. Also, yes, would prefer a patch rebased against the current trunk -- all new features land there first. Created attachment 28486 [details] Updated patch for mod_ssl to add NPN hooks Thanks for the comments; here's an updated patch. I've rebased the patch against trunk, and I believe I've fixed the C89 issues (tested with gcc -std=c89 -pedantic). I've also added a debug-level logging message for the negotiated protocol, as suggested. Created attachment 28513 [details] Updated patch for mod_ssl to add NPN hooks Some minor tweaks to the patch to better conform to surrounding code style. Patch looks fine to me, though this: + const char *next_proto = NULL; + unsigned next_proto_len = 0; + SSL_get0_next_proto_negotiated( + inctx->ssl, (const unsigned char**)&next_proto, &next_proto_len); is going to trip up gcc strict-aliasing tests, it should pass next_proto without a cast. Thanks for taking a look. I confess that I am not terribly familiar with the strict-aliasing rules, so I am not sure how best to avoid the problem here. The issue is that SSL_get0_next_proto_negotiated requires an unsigned char**, but apr_pstrmemdup and ssl_run_npn_proto_negotiated_hook each require a (plain, not unsigned) char*. If I have no casts at all, the compiler complains. Is the aliasing issue avoided if I cast to char* when I call apr_pstrmemdup and ssl_run_npn_proto_negotiated_hook, rather than casting to unsigned char** when I call SSL_get0_next_proto_negotiated, as I do now? If so, I'll fix that right away; if not, what should I do instead? It’s not safe to const char ** to const unsigned char **, but it is safe to cast const unsigned char * to const char * (because a specific exemption in the strict aliasing rules allows any type of object to be accessed through a pointer to a character type). So do this instead: const unsigned char *next_proto = NULL; SSL_get0_next_proto_negotiated(inctx->ssl, &next_proto, &next_proto_len); ssl_run_npn_proto_negotiated_hook(f->c, (const char *)next_proto, next_proto_len); Created attachment 28588 [details] Updated patch for mod_ssl to add NPN hooks Aha, that is good to know, thanks. I've updated the patch as you suggested. Added in r1332643 - I made a few tweaks: 1) added HAVE_TLS_NPN in ssl_private.h with the OpenSSL version logic 2) tweaked the hook name to use "modssl_" rather than "ssl_" to avoid further polluting the "ssl_" namespace Please shout if I broke something, I only tested compilation. Thanks a lot for the contribution! Re-opening; this is only in trunk. This is currently behing discussed in
https://issues.apache.org/bugzilla/show_bug.cgi?id=52210
CC-MAIN-2014-23
refinedweb
620
60.04
..plugins import status c['status'].append(status(status(statusforthe tag=query arguments to the URL will limit the display to Builders that were defined with one of the given tags.file in public_htmlmustoption may help sorting revisions, although it depends on the date being set correctly in each commit: w = status. URL. .plugins import status c['status'].append(status = util(status..plugins import status mn = status = status = status = status.plugins import def html_message_formatter(mode, name, build, results, master_status): """Provide a customized message to Buildbot's MailNotifier. The last 80 lines of the log are provided as well as the changes relevant to the build. Message content is formatted as html. """ result = util all the steps in build in reversed order rev_steps = reversed(build.getSteps()) # find the last step that finished for step in rev_steps: if step.isFinished(): break # get logs for the last finished step if step.isFinished(): logs = step.getLogs() # No step finished, loop just exhausted itself; so as a special case we fetch all logs else: logs = build.getLogs() # logs within a step are in reverse order. Search back until we find stdio for log in reversed(logs): if log.getName() == 'stdio': break name = "%s.%s" % (log.getStep().getName(), log.getName()) status, _ =>') text.extend(unilist) text.append(u'</pre>') text.append(u'<br><br>') text.append(u'<b>-The Buildbot</b>') return { 'body': u"\n".join(text), 'type': 'html' } mn = status. tags(list of strings) - A list of tag names to serve status information for. Defaults to None(all tags). Use either builders or tags,ifiersends emails using TLS and authenticates with the relayhost. When using TLS the arguments smtpUserand smtpPasswordmustfor more details. Regardless of the setting of lookup, MailNotifierwill also send mail to addresses in the extraRecipientslist. messageFormatter - This is a optional function that can be used to generate a custom mail message. A(dictionary) - A dictionary containing key/value pairs of extra headers to add to sent e-mails. Both the keys and the values may be a Interpolate instance. -instance) -, _ =.plugins import status irc = status from buildbot.plugins import status pbl = status from buildbot.plugins import status def Process(self): print str(self.queue.popChunk()) self.queueNextServerPush() sp = status from buildbot.plugins import status sp = status,.
http://docs.buildbot.net/0.8.14/manual/cfg-statustargets.html
CC-MAIN-2017-17
refinedweb
373
53.07
Very bizarre behavior has cropped up in a few spots. the action for viewing a blog post def posts @post = BlogPost.find_by_slug(params[:id], :include => :commentary) a breakpoint here shows @post and @post.commentary with appropriate data redirect_to :action => ‘archive’ unless @post end posts.rhtml <%= @post.inspect %> => nil <%= render :partial => ‘post’, :object => @post %> => renders with correct data <%= @post.comments %> => NoMethodError <%= render_tree_of( @post.comments, … ) %> => generates no errors, but within the partial reports @post.comments as nil WinXP Ruby 1.8.2 Edge Rails (behavior has existed over several iterations now) I’ve not run into anybody else with this problem, and have not had much luck with IRC and my own debugging efforts. Any clues? – Seth Thomas R.
https://www.ruby-forum.com/t/controller-instance-variables-falling-in-and-out-of-scope/55585
CC-MAIN-2020-50
refinedweb
117
60.82
It seems that changing the rounding modes make some functions (like exp, or sin, or ...) buggy on many archs. The testing code is: =============================================================================== #include <stdio.h> #include <stdlib.h> #include <math.h> #include <fenv.h> static int rnd[4] = { FE_TONEAREST, FE_TOWARDZERO, FE_DOWNWARD, FE_UPWARD }; static char rc[4] = "NZDU"; int main (int argc, char *argv[]) { int i; for (i = 1; i < argc; i++) { int r; double x; char *end; x = strtod (argv[i], &end); if (*end != '\0') exit (EXIT_FAILURE); for (r = 0; r < 4; r++) { double y; fesetround (rnd[r]); y = exp (x); printf ("%c: exp(%.17g) = %.17g\n", rc[r], x, y); } } return 0; } =============================================================================== I've checked on my amd64 that it indeed works in 32bits mode (and it also work on an i386 machine) but it does not in 64bits mode: [madcoder mad] gcc -m32 -lm -o a a.c ; ./a 1 2 N: exp(1) = 2.7182818284590451 Z: exp(1) = 2.7182818284590451 D: exp(1) = 2.7182818284590451 U: exp(1) = 2.7182818284590455 N: exp(2) = 7.3890560989306504 Z: exp(2) = 7.3890560989306495 D: exp(2) = 7.3890560989306495 U: exp(2) = 7.3890560989306504 [madcoder mad]) = 0.04788398250919005 N: exp(2) = 7.3890560989306504 Z: exp(2) = 4.0037745305985499 D: exp(2) = 4.0037745305985499 U: exp(2) = 7.3890560989306504 I tested it on other archs, here is the summary: - i386, m68k, ia64 have been tested OK. - arm: only FE_ROUNDTONEAREST exists (which is ok as per C standard) - amd64, mips, ppc, hppa, s390, sparc produce wrong results, in their own unique way. I've not been able to test alpha yet though. (In reply to comment #0) > I've not been able to test alpha yet though. alpha gives curious results as all values are exactly the same, which is quite reasonnable, but may hide a bug too. It gave (for 1 2 3 4 5): N: exp(1) = 2.7182818284590451 Z: exp(1) = 2.7182818284590451 D: exp(1) = 2.7182818284590451 U: exp(1) = 2.7182818284590451 N: exp(2) = 7.3890560989306504 Z: exp(2) = 7.3890560989306504 D: exp(2) = 7.3890560989306504 U: exp(2) = 7.3890560989306504 N: exp(3) = 20.085536923187668 Z: exp(3) = 20.085536923187668 D: exp(3) = 20.085536923187668 U: exp(3) = 20.085536923187668 N: exp(4) = 54.598150033144236 Z: exp(4) = 54.598150033144236 D: exp(4) = 54.598150033144236 U: exp(4) = 54.598150033144236 N: exp(5) = 148.4131591025766 Z: exp(5) = 148.4131591025766 D: exp(5) = 148.4131591025766 U: exp(5) = 148.4131591025766 You can see other results in the bug I originally reported on the Debian BTS: In short, sin can even give out-of-range results, and pow can segfault. At least on my Core2 Duo it's also not working with still other values (32bit version is ok):) = 7.1387612927397726 N: exp(2) = 7.3890560989306504 Z: exp(2) = 4.0037745305985499 D: exp(2) = 4.0037745305985499 U: exp(2) = 7.3890560989306504 As far as I dug into it, the 32bit and 64bit versions use other code. 64bit comes from the IBM Accurate Mathematical Library. For exp sysdeps/ieee754/dbl-64/e_exp.c produces the wrong results. The functions have defined behavior only in the default rounding mode (round-to-even), anything else is undefined behavior and completely programmer's fault for calling the functions in those rounding modes. (In reply to comment #4) > The functions have defined behavior only in the default rounding mode > (round-to-even), anything else is undefined behavior and completely programmer's > fault for calling the functions in those rounding modes. No, it isn't. There's no undefined behavior there. The C standard says (F.9): "Whether the functions honor the rounding direction mode is implementation-defined." So, this just means that an implementation doesn't need to return a result rounded to the correct direction (this is implementation-defined). Still it should return an approximate value whatever the rounding direction mode is, and not behave erratically. Subject: Re: libm rounding modes do not work correctly for many archs On Mon, 27 Oct 2008, vincent+libc at vinc17 dot org wrote: > So, this just means that an implementation doesn't need to return a result > rounded to the correct direction (this is implementation-defined). Still it > should return an approximate value whatever the rounding direction mode is, and > not behave erratically. Furthermore, some functions whose implementations only work in round-to-nearest mode do save the mode then set round-to-nearest using feholdexcept and fesetround (e.g. sysdeps/ieee754/dbl-64/e_exp2.c). I think this is the best thing to do in such cases. (Regarding the issue of rounding modes in signal handlers, I think the best thing is for ABI documents to make explicit that library functions may temporarily save and restore rounding modes; that's what is being done in the Power Architecture ABI document being worked on, to document what the de facto ABI is right now.) *** Bug 6869 has been marked as a duplicate of this bug. *** Problem with exp confirmed on x86_64 with current sources. Patch for exp proposed: Given that patch applied: * I cannot confirm the problem with sin or cos on x86_64 (though tests should be added to the testsuite). * pow (1.6, 1.6) does not segfault, but the result in round-upward mode is substantially inaccurate; pow will need a similar fix (and test in the testsuite). If other functions have problems in current sources, it would be best to have a separate bug for each function with problems (identifying clearly the platform on which the problem occurs). Created attachment 6256 [details] Test a math function in the 4 rounding modes. (In reply to comment #8) > * I cannot confirm the problem with sin or cos on x86_64 (though tests should > be added to the testsuite). I still get the bug on the argument 100 under Debian (glibc 2.13). > * pow (1.6, 1.6) does not segfault, but the result in round-upward mode is > substantially inaccurate; I confirm, but pow(1.01,1.1) crashes: N: pow(1.01,1.1000000000000001) = 1.0110054835779234 Z: pow(1.01,1.1000000000000001) = 1.0110054835779232 D: pow(1.01,1.1000000000000001) = 1.0110054835779232 zsh: segmentation fault (core dumped) ./tfct-4rm 1.01 1.1 > pow will need a similar fix (and test in the testsuite). Yes, like the other functions. > If other functions have problems in current sources, [...] I would say that each function probably has the same problem. I did the tests with gcc -std=c99 tfct-4rm.c -o tfct-4rm -lm -DFCT=exp gcc -std=c99 tfct-4rm.c -o tfct-4rm -lm -DFCT=sin gcc -std=c99 tfct-4rm.c -o tfct-4rm -lm -DFCT=cos gcc -std=c99 tfct-4rm.c -o tfct-4rm -lm -DFCT=pow -DTWOARGS using the attached code. (In reply to comment #9) > I would say that each function probably has the same problem. Actually log and atan seem to behave correctly (and even honor the rounding mode). But tan, sinh and cosh are buggy: $ ./tfct-4rm 1.6 N: tan(1.6000000000000001) = -34.232532735557314 Z: tan(1.6000000000000001) = -34.232532735557307 D: tan(1.6000000000000001) = -34.232532735557307 U: tan(1.6000000000000001) = -1.9000553624671392 $ ./tfct-4rm 100 N: sinh(100) = 1.3440585709080678e+43 Z: sinh(100) = 1.3440585709080676e+43 D: sinh(100) = 1.3440585709080676e+43 U: sinh(100) = -5.7576991416613074e+42 $ ./tfct-4rm 100 N: cosh(100) = 1.3440585709080678e+43 Z: cosh(100) = 1.3440585709080676e+43 D: cosh(100) = 1.3440585709080676e+43 U: cosh(100) = -5.7576991416613074e+42 tanh seems accurate, but it doesn't honor the rounding mode: $ ./tfct-4rm 0.8 N: tanh(0.80000000000000004) = 0.66403677026784913 Z: tanh(0.80000000000000004) = 0.6640367702678488 D: tanh(0.80000000000000004) = 0.66403677026784902 U: tanh(0.80000000000000004) = 0.66403677026784891 exp fixed by: commit 28afd92dbdb4fef4358051aad5cb944a9527a4b5 Author: Joseph Myers <joseph@codesourcery.com> Date: Fri Mar 2 15:12:53 2012 +0000 Fix exp in non-default rounding modes (bug 3976). This may fix some cases of sinh and cosh (where they use exp internally) though tests still need adding for those functions and other functions still need to be fixed. sinh and cosh appear to have been fixed by the exp fix. I confirm what you report for tan and pow. For sin and cos, I don't see the problem for 100 with current sources, but do for 7: N: cos(7) = 0.7539022543433046 Z: cos(7) = 0.7539022543433046 D: cos(7) = 0.7539022543433046 U: cos(7) = -3.5593280928702544e+244 N: sin(7) = 0.65698659871878906 Z: sin(7) = 0.65698659871878906 D: sin(7) = 0.65698659871878906 U: sin(7) = 6.5993918533387462e+246 Examples for pow involving arguments that are exactly representable in all floating-point types (always nice for the testsuite): N: pow(1.0625,1.125) = 1.0705822930287614 Z: pow(1.0625,1.125) = 1.0705822930287612 D: pow(1.0625,1.125) = 1.0705822930287612 U: pow(1.0625,1.125) = 0.032633984947502387 N: pow(1.5,1.03125) = 1.5191270987147432 Z: pow(1.5,1.03125) = 1.0003045181943615 D: pow(1.5,1.03125) = 1.0003045181943615 U: pow(1.5,1.03125) = 1.5191270987147434 sin, cos, tan fixed by: commit 804360ed837e3347c9cd9738f25345d2587a1242 Author: Joseph Myers <joseph@codesourcery.com> Date: Fri Mar 2 20:51:39 2012 +0000 Fix sin, cos, tan in non-default rounding modes (bug 3976). cosh, sinh tests (some errors in round-upward mode up to 27ulp) added by: commit ca811b2256d2e48c7288219e9e11dcbab3000f19 Author: Joseph Myers <joseph@codesourcery.com> Date: Mon Mar 5 12:20:24 2012 +0000 Test cosh, sinh in non-default rounding modes (bug 3976). pow fixed by: commit b7cd39e8f8c5cf2844f20eb03f545d19c4c25987 Author: Joseph Myers <joseph@codesourcery.com> Date: Mon Mar 5 12:22:46 2012 +0000 Fix pow in non-default rounding modes (bug 3976). So all the reported issues are fixed here. If cases are found of functions that still (in any rounding mode, for any of float, double, long double) produce wild results or crash with glibc after my patches - or of functions that should always produce correctly rounded results such as rint, nextafter, fma, sqrt, that fail to do so (in any rounding mode, for any of float, double, long double), please file them as separate bugs for each function found to have a problem. (In reply to comment #10) > (In reply to comment #9) > > I would say that each function probably has the same problem. > > Actually log and atan seem to behave correctly (and even honor the rounding > mode). I forgot that since Ziv's strategy is used to provide correct rounding, my tests where incomplete (I tested only on a few random values). To understand the problem, here's what Ziv's strategy does: 1. Compute an approximation with slightly more precision than the target precision, typically by representing it as an exact sum of two floating-point values a+b, where |b| is much smaller than |a|. An error bound e1 is determined and a rounding test is performed. Most of the time, the correct rounding can be guaranteed by this test, so that the computed result can be returned. But there's a low probability of failure (problem known as the "Table Maker's Dilemma"), in which case a second step is necessary. 2. Ditto with even more precision and a lower error bound e2. In case of failure, a third step is necessary. 3. Computation with even more precision. IIRC, a 768-bit precision is used here in IBM's library (that's the mp*.c files), which assumes that this is sufficient. So, for functions that are believed to behave correctly in the directed rounding modes, and for which the active rounding mode is not changed temporarily in the function, one should consider the following remarks: One would need to test cases that fall in (2) and in (3). The probabilities of failure depend on the algorithm and implied error bounds e1 and e2, and possibly on the magnitude of the input (or some other criteria). To get cases in (2) from random tests, one may need to test several dozens of thousands of inputs (analyzing the code can give a better idea of what is needed -- it doesn't seem to be much documented). Ideally, tools like gcov to get code coverage would be useful. From my work on the Table Maker's Dilemma, I also have a list of the hardest-to-round cases ("worst cases") for some functions in some domains, which should probably fall in (3). AFAIK, in IBM's library, (3) uses integer arithmetic, so that it shouldn't depend on the active rounding mode (though I'm not completely sure because FP may also be used, e.g. at the end). Note that testing cases for (3) only is not sufficient, because with such cases, the results from (2) are discarded. It is also possible that in directed rounding modes, (1) and/or (2) always fail, meaning that a slower step would be performed. This wouldn't be incorrect, but rather inefficient. This should be checked too... *** Bug 15010 has been marked as a duplicate of this bug. *** *** Bug 260998 has been marked as a duplicate of this bug. *** Seen from the domain Page where seen: Marked for reference. Resolved as fixed @bugzilla.
https://sourceware.org/bugzilla/show_bug.cgi?id=3976
CC-MAIN-2020-16
refinedweb
2,191
77.23
I'm trying to pass an image taken from ImageGrab from a class method. But it returns None. The im.show() inside takeSS() works. import pyscreenshot as ImageGrab class Manager(): def takeSS(self): if __name__ == "__main__": im = ImageGrab.grab(bbox=(0,0,1980,200)) im.show() return im m = Manager() img = m.takeSS() img.show() AttributeError: 'NoneType' object has no attribute 'show' You have a if __name__ == "__main__": guard in the middle of your method. That's a very unusual place for that test. Unless this script is run as the main script, your Manager.takeSS() method will always return None, leading to your error. Remove the if test from there altogether. It may have place outside of the class though: import pyscreenshot as ImageGrab class Manager(): def takeSS(self): im = ImageGrab.grab(bbox=(0,0,1980,200)) # X1,Y1,X2,Y2 im.show() return im if __name__ == "__main__": m = Manager() img = m.takeSS() img.show() The code in the if test is now only run if you use this module as a script. That same block will not run when you use import yourmodule.
https://codedump.io/share/CdAfB8JcBDqg/1/39nonetype39-object-has-no-attribute-39show39
CC-MAIN-2016-44
refinedweb
185
77.74
IZUT/Common-CLI-0.04 - 28 Feb 2008 17:30:43 GMT - Search in distribution App::LDAP is intent on providing client-side solution of RFC 2307 <>, RFC 2798 <>....SHELLING/App-LDAP-0.1.2 - 02 Oct 2013 07:18:38.20 - 26 Aug 2015 11:38:14.54 - 21 Apr 2016 02:23:38 GMT - Search in distribution CLI::Gwrap builds a GUI wrapper around a Command Line Interface (CLI) script or program. The GUI presents the CLI options to the user and then runs the CLI program. The specific GUI is chosen with a plugin system. To write a new Gwrapper, follow the ...REID/CLI-Gwrap-0.030 - 05 Aug 2013 20:19:45 GMT - Search in distribution PERLANCAR/DefHash-1.0.11 - 02 Sep 2015 18:58:29.22.1 4.5 (6 reviews) - 13 Dec 2015 19:48:31 GMT - Search in distribution - perldiag - various Perl diagnostics - perl56delta - what's new for perl v5.6.0 - perl561delta - what's new for perl v5.6.1 This command-line program is an interface to File::Trash::Undoable, which in turn uses File::Trash::FreeDesktop. Features: undo/redo, dry run mode, per-filesystem trash dir. This program is relatively new and have not yet been tested extensively. Use...PERLANCAR/File-Trash-Undoable-0.18 - 03 Sep 2015 09:30:52 GMT - Search in distribution The namespace "Complete::" is used for the family of modules that deal with completion (including, but not limited to, shell tab completion, tab completion feature in other CLI-based application, web autocomplete, completion in GUI, etc). This (famil...PERLANCAR/Complete-0.19 - 17 Dec 2015 13:45:04 GMT - Search in distribution DBD::Pg is a Perl module that works with the DBI module to provide access to PostgreSQL databases....TURNSTEP/DBD-Pg-3.5.3 4 (12 reviews) - 01 Oct 2015 14:06:04 GMT - Search in distribution The "CPANPLUS" library is an API to the "CPAN" mirrors and a collection of interactive shells, commandline programs, etc, that use this API....BINGOS/CPANPLUS-0.9156 4 (4 reviews) - 15 Oct 2015 12:40:05 GMT - Search in distribution WordPress NOTE: EARLY RELEASE. ONLY BASH SUPPORT HAS BEEN ADDED. SUPPORT FOR THE OTHER SHELLS WILL FOLLOW. Some shells, like bash/fish/zsh, supports tab completion for programs. They are usually activated by issuing one or more "complete" (zsh uses "compctl") ...PERLANCAR/App-shcompgen-0.15 - 29 Feb 2016 05:17:44 GMT - Search in distribution TAPPER/Tapper-Cmd-5.0.6 - 06 Apr 2016 08:08:43.50 - 30 Nov 2015 04:44:38 GMT - Search in distribution
https://metacpan.org/search?q=Common-CLI
CC-MAIN-2016-18
refinedweb
434
57.87
I'm trying to code this thing in python, and I have bumped into a road block. I have this list, and I want to modify it, and keep the changes after the program is exited. I have no clue where to start. Essentially, I want a list that can be accessed and modified, and will be saved and not reset after the thing using it is closed. EDIT: Here is my idea; There is a list that I have, let's call it basket. I want to code a program to add to and remove from the 'basket', and to keep the changes after I close the program. Hope that clarifies... And I tried using global, but that got all funny, so I essentially deleted that version. You can use json, pickle, or any similar library to write data to a file and read it back and store in a list. This will create the file save.json in your current working directory that contains json-information about your list. You will notice that your list will always contain the numbers you added before, it doesn't "forget" what you added to the list since it's saved in a file. import os import json foo = [1,2,5,9] #default #if safe file exists, load its contents into foo list if os.path.isfile("save.json"): with open("save.json", "r") as file: foo = json.loads(file.read()) foo.append(int(input("Enter a number to add to foo"))) print(foo) #write foo list to file with open("save.json", "w") as file: file.write(json.dumps(foo))
https://codedump.io/share/tHrQCpP49kqo/1/how-to-i-modify-an-external-list
CC-MAIN-2017-04
refinedweb
270
73.98
Categories: Python | S60 | Code Examples | How To This page was last modified 05:34, 29 April 2008. How to edit an image From Forum Nokia Wiki This article describes how to manipulate images in PyS60. import appuifw, e32 from graphics import * #Define the exit function: app_lock=e32.Ao_lock() def quit():app_lock.signal() appuifw.app.exit_key_handler=quit #We open the image img=Image.open("C:\\i.jpg") #We can see its current size print img.size #Now we resize it: img=img.resize((240,240), keepaspect=0) #The target size is a tuple containing the new dimensions in pixles #keepaspect is optional. If 1, the image's current aspect ratio is maintained #The image can also be transposed (here we rotate it by 90 degrees) img=img.transpose(ROTATE_90) #Other ways of transposing are: #FLIP_LEFT_RIGHT, FLIP_TOP_BOTTOM, ROTATE_180, ROTATE_270 #Note that rotations are counterclockwise #Finally, we save the new image img.save("C:\\i2.jpg", quality=100) #Tell the application not to close until the user tells it to: app_lock.wait() Here is the result for the example above: The initial image The resulting image See also: How to add text to an image
http://wiki.forum.nokia.com/index.php/How_to_edit_an_image
crawl-001
refinedweb
192
57.67
My TitleWindow is set up, now I need to pass some dataKristin95762 Apr 21, 2011 11:00 PM This is Flash Builder I'm talkin' about. Having a really hard time finding examples on this subject. My main app contains a list box with authors. When I double click on an author, the TitleWindow popup appears. That part is great thanks to some wonderful help here on the forum. Now, how do I transfer the author name to the popup, and then transfer any changes I make back to the list? There was one method I saw (very limited info on it) which indicated that I could access the children of the popup from the main application, which I think would be ideal in my case because I'm a noob trying to set up a local database application (sqlite), and all these components and classes are giving me a headache. My popup merely contains a label, a text input, and a button. In the future I might like to add a datagrid but I'm having trouble figuring out the theory of the popup and data transfer. Thank you much Kristin 1. Re: My TitleWindow is set up, now I need to pass some datajfb00 Apr 22, 2011 5:12 AM (in response to Kristin95762)1 person found this helpful Hi, Are you calling the popup window like this? customWin=myScreen(PopUpManager.createPopUp(this.parentDocument as DisplayObject,myScreen,true)); customWin.mainApp = this; customWin.title = "My title"; PopUpManager.centerPopUp(customWin); Where mainApp variable contain the parent info, so in the custom window you need to declare a variable like: [Bindable] public var mainApp:Object = null; Then you have access to the label from the parent window like: var temp:String = ""; temp = mainApp.myLabel.text; You also can call a function from the parent windows but make sure the function is declare as private. I hope this help. Rgds Johnny 2. Re: My TitleWindow is set up, now I need to pass some databrendalc1636 Apr 22, 2011 6:30 AM (in response to Kristin95762) I usually end up displaying my titlewindow from some actionscript code. Usually I read in some data, then display the title window. Since I am doing it from the actionscript code, and not from the display, I create an instance of my TitleWindow and send that to the popup manager. I can then set variables on the instance to whatever values I wish. var myTitleWindow:TitleWindow = new MyTitleWindow(); myTitleWindow.myLabel.text = "Label Text"; myTitleWindow.myButton.text = "Button Text"; PopUpManager.addPopUp(myTitleWindow, DisplayObject(Application.application), false); PopUpManager.centerPopUp(myTitleWindow); Brenda 3. Re: My TitleWindow is set up, now I need to pass some dataKristin95762 Apr 22, 2011 3:10 PM (in response to jfb00) Hi, All my code is in an actionscript file and this is the function I use: private function authorsList_doubleClickHandler(event:MouseEvent):void { PopUpManager.createPopUp(this, authorEdit, true); } This is the code in the TitleWindow component mxml file: <fx:Script> <![CDATA[ import mx.events.*; import mx.managers.PopUpManager; private function titlewindow1_closeHandler(event:CloseEvent):void { PopUpManager.removePopUp(this); } private function submitHandler(event:MouseEvent):void { if((authorName.text = "Hello")) { PopUpManager.removePopUp(this); } } ]]> </fx:Script> I think there is some way to access the textarea and the submit button from the main application file. Just haven't figured out how to do it. 4. Re: My TitleWindow is set up, now I need to pass some dataKristin95762 Apr 22, 2011 3:17 PM (in response to brendalc1636) Hi So, all the code you listed in your reply is in the main application file, correct? 5. Re: My TitleWindow is set up, now I need to pass some dataKristin95762 Apr 22, 2011 4:47 PM (in response to brendalc1636) In your code copied below: PopUpManager.addPopUp(myTitleWindow, DisplayObject(Application.application), false); What does (Application.application) stand for? Thank you Kristin 6. Re: My TitleWindow is set up, now I need to pass some dataFlex harUI Apr 22, 2011 6:06 PM (in response to Kristin95762) Application.application in Flex 3 is FlexGlobals.topLevelApplication in Flex 4. FWIW, my recommendation is that the TitleWindow components should pull their data from a central data model. Model-View or MVC architectures are a bit more to set up, but pay off in the end. -Alex 7. Re: My TitleWindow is set up, now I need to pass some dataKristin95762 Apr 22, 2011 8:25 PM (in response to Flex harUI) Okay, thanks for your advice. I see where I have to start looking. As a neophite in Flex 4, and not all that well versed in AS3 I've been trying to keep things as simple as possible while learning how to code. I figured once I got everything working well enough I'd turn to figuring out how to do it right. Hey, if you know a lot about AIR, how about writing a new book. Information is so hard to find on that subject. Thanks again Alex. Kristin
https://forums.adobe.com/thread/841874
CC-MAIN-2018-30
refinedweb
828
65.12
At the Forge - Ruby on Rails Now that we know how to see the default message, let's move toward a “Hello, world” program. In Rails, there are two basic ways to do this. We can create a controller that returns HTML to the user's browser, or we can create a view that does the same. Let's try it both ways, so that we can better understand the relationship between controllers and views. If all we want to do is include a simple, static HTML document, we can do so in the public directory. In other words, the file blog/public/foo.html is available under WEBrick—started by executing blog/script/server—at the URL /foo.html. Of course, we're interested in doing something a bit more interesting than serving static HTML documents. We can do that by creating a controller class and then defining a method within that class to produce a basic “Hello, world” message. Admittedly, this is a violation of the MVC separation that Rails tries to enforce, but as a simple indication of how things work, it seems like a good next step. To generate a new controller class named MyBlog, we enter the blog directory and type: ruby script/generate controller MyBlog Each time we want to create a new component in our Rails application, we call upon script/generate to create a skeleton. We then can modify that skeleton to suit our specific needs. As always, Rails tells us what it is doing as it creates the files and directories: exists app/controllers/ exists app/helpers/ create app/views/my_blog exists test/functional/ create app/controllers/my_blog_controller.rb create test/functional/my_blog_controller_test.rb create app/helpers/my_blog_helper.rb Also notice how our controller class name, MyBlog, has been turned into various Ruby filenames, such as app/views/my_blog and app/helpers/my_blog_helper.rb. Create several more controller classes, and you should see that all of the names, like FooBar, are implemented in files with names like foo_bar. This is part of the Rails convention of keeping names consistent. This consistency makes it possible for Rails to take care of many items almost magically, especially—as we will see next month—when it comes to databases. The controller that interests us is my_blog_controller.rb. If you open it up in an editor, you should see that it consists of two lines: class MyBlogController < ApplicationController end In other words, this file defines MyBlogController, a class that inherits from the ApplicationController class. As it stands, the definition is empty, which means that we have neither overridden any methods from the parent class nor written any new methods of our own. Let's change that, using the built-in render_text method to produce some output: class MyBlogController < ApplicationController def hello_world render_text "Hello, world" end end After adding this method definition, we can see its results by going to. Notice how the URL has changed: static items in the public directory, such as our file foo.html, sit just beneath the root URL, /. By contrast, our method hello_world is accessed by name, under the controller class that we generated. Also notice that we did not need to restart Rails in order to create and test this definition. As soon as a method is created or changed, it immediately is noticed and integrated into the current Rails system. If we define an index method for our controller class, we can indicate what should be displayed by default: class MyBlogController < ApplicationController def hello_world render_text "Hello, world" end def index render_text "I am the index!" end end Of course, it's not that exciting to be able to product static text. Therefore, let's modify our index method such that it uses Ruby's built-in Time object to show the current date and time: def index render_text "The time is now " + Time.now.to_s + "\n" end And voil� As soon as we save this modification to disk, the default URL (, on my computer) displays the time and date at which the request was made, as opposed to a never-changing “Hello, world” message. Let's conclude this introduction to Rails by separating the controller from its view once again. In other words, we want to have the controller handle the logic and the view handle the HTML output. Once again, Rails allows us to do this easily by taking advantage of its naming conventions. For example, let us modify our index method again, this time removing its entire body: def index end This might seem strange at first glance. It tells Rails that the MyBlog controller class has an index method. But it doesn't generate any output. If you attempt to retrieve the same URL as before, Rails produces an error message indicating that it could not find an appropriate template. Because the template is a view, we can define it inside of the blog/app/views directory of our application. And because we are defining the index view for the MyBlog class, we modify the index.rhtml file in the my_blog subdirectory of views. Notice how Rails turns ThisName into this_name when it comes to directories. Doing so saves users from having to think about capitalization in URLs, while staying consistent with traditional Ruby class naming conventions. .rhtml files are a Ruby version of the same kind of template that you might have seen before. It acts similarly to ASP and JSP syntax, with <% %> blocks containing code and <%= %> blocks containing expressions that should be interpolated into the template. However, nothing stops us from creating an .rhtml template that actually is static: <html> <head> <title> Hello, again! </title> </head> <body> <p>Hello, again!</p> </body> </html> Consider what happens now if you attempt to load MyBlog in your browser. The controller class MyBlog is handed the request. Because no method was named explicitly, the index method is invoked. And because index doesn't produce any output, the my_blog/index.rhtml template is returned to the user. Finally, let's take advantage of our template's dynamic properties to set a value in the controller and pass that along to the template. We modify our index method to read: def index @now = Time.now.to_s end Notice how we have used an @ character at the beginning of the variable @now. I found this to be a little confusing at first, as @ normally is used as a prefix for instance variables in Ruby. But it soon becomes fairly natural and logical after some time. Finally, we modify our template such that it incorporates the string value contained in @now: <html> <head> <title> Hello, world! </title> </head> <body> <p>Hello, world!</p> <p>It is now <%= @now %>.</p> </body> </html> Once again, you can retrieve the page even without restarting Ruby. You should see the date and time as kept on the server, updated each time you refresh the!
http://www.linuxjournal.com/article/8433?page=0,1&quicktabs_1=2
CC-MAIN-2015-06
refinedweb
1,151
62.68
windows 10 - python 3.5.2 Hi, I have the two following python files, and I want to edit the second file's variables using the code in the first python file. firstfile.py from X.secondfile import * def edit(): #editing second file's variables by user input if Language == 'en-US': print('language is English-us') elif Language == 'en-UK': print('language is English-uk') Language = 'en-US' with open("secondfile.py","a") as f: f.write("Language = 'en-US'") You can embed the Language in a class in the second file that has a method to change it. class Language: def __init__(self): self.language = 'en-US' def __str__(self): return self.language def change(self, lang): assert isinstance(lang, str) self.language = lang language = Language() Then import the "language," and change it with the change method. from module2 import language print(language) language.change("test") print(language)
https://codedump.io/share/HHmbFG9oKDjA/1/how-to-modify-variables-in-another-python-file
CC-MAIN-2017-43
refinedweb
150
68.97
Do You Know Why 99% of ALL Affiliate Marketers Fail? Ranked #15,867 in How-To, #159,178 overall Newly Revised: The "Real" Secret To Massive Online Profits In Your Own Internet Home-Based Business and Why 99% of All Internet Affiliate Marketers Fail. Learn The Necessary Skills and Proven Techniques To Drive Profits Soaring Month after Month. I'm going to be very blunt here - for two reasons; - One - I want to convey a critical message to you as quickly and as concisely as possible so you can take IMMEDIATE action without delay. - Two - it's Saturday afternoon, a beautiful day and I'm sitting behind the computer - enough said :-) Do you know why 99% of ALL affiliate and Internet marketers fail? They fail for two reasons: - One - The affiliate marketer FAILS TO TAKE ACTION, explained further below. - Two - They think this is just a game of numbers and fail to consider their customers and build a "real" business. More on point number one above. It should be quite self explanatory, but for those who aren't quite following me or perhaps are very new to affiliate marketing, I'll delve a little deeper. Affiliate marketers fail in their Internet Home Business or Affiliate Marketing Business because they spend 99% of their time on unproductive and quite honestly, relatively useless tasks. What do I mean by that? Well, instead of doing the ONLY two things that matter when building an Internet Home-Based Affiliate Marketing Business; GENERATING TRAFFIC, and CONVERTING THAT TRAFFIC, they spend their time on useless tasks. That's it - nothing more. Generate online traffic and convert that traffic to sales. How do we do that? - By offering "real" value to our customers. So instead of focusing on those two items above, most affiliate marketers get sidetracked and distracted by the next "big thing" everyone else is promoting. Focus on building your business and you WILL succeed. On Point number Two above... It's not a numbers game. It's a business about servicing customer needs. More on this below. The next big reason 99% of all affiliate marketers fail to generate the maximum income possible is because they think it's a numbers game. They think... "If I can only put up a few more products in my 'huge, humongous, colossal, widget online mall', THEN I'll really make the money." It doesn't work that way - although I must admit - several years ago I thought it did. I thought it was about building the biggest and most "widget-packed" site you could build. Build it and they will come... That's what I thought... And I thought wrong. You have to offer your customers real value. You have to build a relationship. Internet shoppers are browsing your site for one of two reasons (see a pattern here). They are researching looking to solve a problem they have, or they're just casually browsing along - window shopping. Lets say I just dropped my favorite Japanese WOK and I'm having a small dinner party next month with some of my best friends (and I'm cooking)... Now let's say I'm browsing the Net and I come across your site - "Huge, Humongous, Colossal WOK Store". Am I going to order a WOK from you...maybe...but probably not... I'll probably just head down to my local Williams & Sonoma and pick one up. So I leave your site and you're none the wiser. You never knew I was there and you'll probably never see me again. CUSTOMER LOST - or more accurately, you never really had me to begin with... Now lets change this up a bit... Now I'm on your site (still not going to buy that WOK) but you have a link to a free e-Book on Japanese WOK cooking recipes. EXCELLENT - I could use that for some ideas for next month. So I register on your site and I happily download my free e-Book. And in return (you guessed it... you now have my email address and can easily follow up with me and start to build that customer relationship). So next month you're running a 40% off promotion on all stir fry skillets. You should out a quick broad cast message to your registers users and voila... I get the email and click on the link... I could use a new skillet. I loved your free e-Book so what the heck - where's my VISA - I'll grab that skillet - after all it's on sale for 40% off. Are you starting to see the real message here? Build real relationships with a real business and you're destined to succeed even if the Internet Home Business arena is littered with people who never really take it to its full potential. The above scenario is why I have written a step by step guide of "never before published" proven techniques to make your Internet Home Business and website explode. My "Secret Formula To Massive Online Profits" e-Course has over 33 hours of instructional video built in and you can download this e-Course right now for - YOU GUESSED IT - FOR FREE. It is by far "The Most Comprehensive, One Of A Kind, In-Depth, Step-By-Step Money-Making System Available On The Internet Today!" Learn how a 'hideous' little two page website can bring in $4272.33 in less than 18 hours without spending one dime on advertising. Not One Dime! These are the types of techniques anyone with just a computer and a desire to succeed can duplicate as quickly as tomorrow -- and see immediate results. Would You Rather Learn The Hard Way... Or Discover An Easy Way To The Freedom And Success You Deserve? This is a MASSIVE on-line training course and I won't be giving it away for free forever! If you've ever thought about starting your own Internet Home-Based Business, then download my FREE e-Course and begin building your financial independence today! Be sure to sign up for my FREE 12-Part Internet Marketing eCourse. Lesson 1 could be on its way to your inbox in a matter of moments. Here's To Your Online Success; Thomas A. Hall Table of Contents Web 2.0 Wealth Secrets Do you Know The 3 Key Ingredients Necessary To Snatch Up Instant, Highly Responsive Traffic To Any Website On A ZERO Budget? We're here to help you succeed! Newly Revised: "The Secret Formula To Massive Online Profits" F-R-E-E Online Training e-Course. Over 33 Hours of online video showing you everything you need to know to start your own online business TODAY! "The Quick & Easy Way To Make Massive Profits Online. No Website, No Products, No Experience - No Problem" Recommended Reading: - Internet Home Business Resources - FREE Internet Home Business Resources and Ideas - FREE Internet Marketing e-Course - Download Your Internet Marketing e-Course Today! - Free Online Business Model - Totally Free, Ridiculously Simple Business Model? - Do You Have Your Own Website? - Get Paid To Place a Small Ad on Your Website Internet Home Business Resources Follow Me On Twitter - YourInternetBiz - aka YourInternetBiz - 76 followers - 35 following - - Bookmarking pages with - this takes a while..... - - Going to be another hot day in So. Calif. - lots of work to do this weekend.. - - Using socialmarker.com to bookmark my pages - Lots O Work - - Who's got the best source of Twitter backgrounds - need a couple - hit me back.. - - OK - it's official - TweetMic for iPhone rocks.... New Guestbook Like this lens? Want to share your feedback, or just give a thumbs up? Be the first to submit a blurb!
http://www.squidoo.com/best-home-business-ideas
crawl-002
refinedweb
1,281
73.88
Add jQuery to Angular (4) project This week-end I struggled to add jQuery to my angular project. After a long battle, I finally won (victory was to change the color of a title, wow.) So, what to do to include jquery to an Angular (testing on version 4) project ? First, add jQuery dependency : npm install jquery --save Install typings : npm instal @types/jquery --save-dev Add typings : typings install dt~jquery --save --global In you .angular-cli.json, include jquery to scripts : "scripts":["../node_modules/jquery/dist/jquery.min.js"] And finally, include it in you component : import * as jquery from 'jquery'; You can then use it : jquery(#tilte).css('color', 'black'); (of for something more interesting…). Hope it will help someone !
https://medium.com/@bnpinel/add-jquery-to-angular-4-project-87e68553a630
CC-MAIN-2017-34
refinedweb
122
57.87
!-Converted with LaTeX2HTML 95.1 (Fri Jan 20 1995) by Nikos Drakos (nikos@cbl.leeds.ac.uk), CBLU, University of Leeds -> Next: Multiple World Coordinate Systems for DEIMOS Mosaic Images Previous: Error and Bias in the STSDAS fitting Package Up: FITS-Flexible Image Transport System Table of Contents - Index - PS reprint De Clarke and S. L. Allen UCO/Lick Observatory, Kerr Hall, UCSC, 1156 High Street, Santa Cruz, CA 95064 Using a centralized database or information service to document FITS keywords is not a new idea. However, in previous incarnations of this concept, the object has either been purely documentary or single-purpose (e.g., the SaveTheBits database schema). Our goal was to capture enough information, and to generalize the information sufficiently, that multiple related applications could all use one authoritative, online reference database for information about FITS keywords. For example, live observing and engineering interfaces to an instrument could rely on the same database that was used to generate printed documents, drawings, and even sections of source code. A more complete documentation of our work, with examples, and live demos, can be found online at Memes (Keywords) Database Homepage. The first challenge was to determine the list of attributes necessary to document a FITS keyword. Some, such as name, FORTRAN datatype, semantics, and min/max values, were obvious. Others were more subtle, and the list of attributes was revised several times as we explored the syntax and semantics of existing FITS headers and our proposed DEIMOS instrument keywords. FITS keywords have provenance or context (i.e., an institution, instrument, author, or standards document which defines their valid use). Knowing the context is essential, given the lack of constraint on duplication in FITS namespace. FITS keywords have relationships to other keywords in the same dataset (for example, the value of NAXIS controls the occurrence of NAXISn). We developed attributes for a generalized description of these relationships. FITS keywords occur in groups or ``bundles''; a standard set of required keywords must appear in a valid table extension header, for example. A FITS header itself is a special case of such a bundle, as is a FITS table. We established ancillary tables to describe the grouping or bundling of keywords. We found it necessary to establish special types of keywords called ``tuple keywords,'' whose values are actually a list or other parsable structure of subvalues. We established a general-purpose way of documenting such tuple values, which handles any such keyword by defining subsemantics and subformats, separators, delimiters, etc. We accommodated the case where identical semantics are repeated N times, and the case where N sub-elements have distinct semantics. Given that our instrument and telescope control systems use a keyword/value architecture, we needed to establish access control for keywords: some are writable, some readable, some are both. Access control attributes are needed for the configuration of dynamically-generated graphical user interfaces. We found it necessary to establish a special relationship between certain keywords and an ``archetypal'' keyword of the same semantics. For example, one instrument system may format a value as F8.4 where another will format it as F6.4 or as a string. It is evident that these are really ``the same'' keyword. As we struggled with subsemantics and archetypes, it became clear that we were documenting something more abstract than ``a FITS keyword.'' We borrowed the term ``meme'' to describe ``a unit of meaning''-a more general-purpose name for the entities we were manipulating. This generalization led swiftly to the use of the ``Memes'' database to document itself, since the fields (columns) of a database table are memes with a large subset of the attributes of a FITS keyword (such as name, datatype, semantics, etc.). Exploration of the relationship between database tables and Meme bundles led equally swiftly to automated translation between these formats. In other words, we are able to extract (outload) a Sybase table as a FITS table extension, and to import (inload) a defined FITS table extension to a Sybase table. We are able to generate Sybase table definitions for any meme bundle, including standard FITS headers and FITS table extensions. There are many practical applications for these abilities (see Table 1). Although we cannot adequately discuss the Memes schema within the present page limit, we invite the FITS community to investigate the Memes table definition and related tables, using the demo reports available at the Memes (Keywords) Database Demos page. If you choose ``Documentation of Memes by Name'' and enter the name Memes, the resulting report will be the current Memes table definition. We propose these attributes as the first draft of a standard set of attributes of FITS keywords, and invite comments from the FITS community. The schema was expanded to include a set of ancillary tables describing protocols, formats, event timings, and agents (software, hardware, and human) so that we could document the flow of information through any large system. The Agents schema permits us to document the source language, revision, authorship, and other attributes special to software agents. (This model corresponds well with the ``gaming table'' model of Noordam & Deich 1996.) As with Memes, a URI field permits the attachment of detailed documentation to any Agent. A table of Paths documents the passage of Memes between Agents. The attributes of a Path are the sending and receiving agent, a controlling agent, the Meme ID, and a cluster of attributes describing the transaction: format, protocol, event timing, and elapsed time. Since human beings can be agents and Key Entry is an acceptable protocol, it is possible to document the Memes/Agents toolset itself using this schema. We use a digraph generation package (see Acknowledgments) to generate graphical representations of information flow. A hierarchy of agents and paths was required in order to generate both simplified and detailed drawings. Accordingly, the schema was adjusted to permit the definition of ``superAgents'' which consist of multiple Paths. The Agents/Paths database can be used not only to generate functional diagrams, but to assist in diagnostic procedures. It can be used to trace any FITS keyword value back to the originating or authoritative source; conversely, it can reveal which agents handle a keyword and thus may be affected by changes to the syntax or semantics of that keyword; it can reveal which keywords are handled by an agent, and which ``downstream'' agents may be affected if an agent is disabled or altered. Currently we are addressing the distinction between syntactic and functional relationships among Memes. We have addressed, for example, the fact that the value of NAXIS controls the appearance of keywords NAXISn (a syntactic relationship). We have now to model those relationships in which a set of FITS keywords acts (in use, rather than in syntactic specification) as a state engine. This is particularly relevant for instrument control systems, in which (for example) a HATCHCLO keyword and a HATCHOPN keyword cannot both be true, but may both be false. The solution to this problem will almost certainly require one additional ancillary table in the schema. We would like to acknowledge the invaluable contributions of the free software community, with particular gratitude to Tom Poindexter (Talus Technologies) for the SybTcl package, Stephen North and Eleftherios Koutsoufios (Lucent) for their digraph toolkit, Per Cederqvist and friends for CVS, John Ousterhout (Sun) for Tcl/Tk, and Mark Diekhans (Information Refinery) and Karl Lehenbauer (Neosoft) for TclX. Noordam, J. E., & Deich, W. T. 1996, in Astronomical Data Analysis Software and Systems V, ASP Conf. Ser., Vol. 101, eds. G. H. Jacoby and J. Barnes (San Francisco, ASP), 229 Next: Multiple World Coordinate Systems for DEIMOS Mosaic Images Previous: Error and Bias in the STSDAS fitting Package Up: FITS-Flexible Image Transport System Table of Contents - Index - PS reprint
http://www.cv.nrao.edu/adass/adassVI/clarked.html
crawl-002
refinedweb
1,291
50.36
Earn Income by Being a Bumper Liquidity Provider You might already know Bumper as the leading DeFi price protection platform, but did you know you can also earn money through Bumper too? You can do this by being a liquidity provider (LP), which essentially means lending your coins to the platform and getting paid for it, making Bumper a kind of crypto savings account that earns you interest. There’s much more to it than that, so sit back, relax and let us tell you how Bumper can make your crypto work for you. It will be painless, we promise! What Are Liquidity Pools? Being a Bumper LP means that you can earn a yield from the platform, making money from the premiums paid by those taking out protection. For some people this is enough, given that the interest rate is far higher than the banks are offering, but the beauty of Bumper is that you can do more than just spend or save your earnings — of course you could cash it out and hit the shops, but you could also reinvest it into the liquidity pool or even send it to a secondary protocol for an extra dividend. If you’re new to the concept of liquidity pooling then this article will give you a brief rundown on the principles of the process, but if you’ve already spent some time swimming in liquidity pools or out there working the yield farms then you might be more interested in the nuts and bolts of being a Bumper LP, which we explain a little later. First though, the basics. Liquidity pools have become the go-to method of providing liquidity for decentralized crypto protocols. Anywhere one token is swapped for another in a decentralized manner, an LP has to be there to provide the funds being traded. In centralized exchanges this is down to the exchange itself and market makers employed by the exchange, but in a decentralized model (like Bumper) it comes down to individuals to fulfil this role (and potentially market makers employed by specific projects). Liquidity pools came about because the traditional order book system didn’t work for the DeFi model — the fees were too high and the processing time too slow to operate the standard exchange mechanism. Liquidity pools have become the premiere solution for exchange projects in the DeFi space, offering continuous, automated liquidity, and earning LPs a nice sideline into the bargain. Why Should I Be a Liquidity Provider? You might have guessed this already, but the primary benefit of being an LP is that you get paid for it. Of course some will get a kick out of knowing that they are helping further the cause of decentralized finance…but most are in it for the payday. And why not. With Bumper, LPs are required to fill the liquidity pool to counterbalance those wishing to protect their assets, providing an essential service. The beauty of the pooling system is that LPs can pool as much or as little of their assets as they like, and with Bumper you can remove your tokens after just a couple of weeks if you want to. Once you’ve left the pool you’re free to sell your tokens (and your interest), or you might want to grab a piña colada and hop back in the pool again. The whole thing is performed through smart contracts so the process is instant and has no middle man complicating things. If you decide to leave the pool you just redeem the bumpered tokens from the protocol and Bumper returns your original stake plus accrued interest back into your wallet. What could be simpler? Why Should I Choose Bumper? Those that have been in the crypto and particularly the DeFi space for a while will know that there are many places where you can put your stablecoins to work, but Bumper is different. The protocol benefits everyone who interacts with the platform, with both LPs and Bumper policyholders being rewarded and opportunities to compound those earnings. As a Bumper LP you will fill the liquidity pool with one or more of the tokens supported on the platform (initially USDC), getting an equal amount of Bumpered tokens in return (e.g. bUSDC). This is a fungible yield-bearing token, pegged to the relevant fiat currency (in the case of USDC, the U.S. dollar), that you can trade just like any other cryptocurrency, and the number of tokens you receive (your ‘yield’) will grow in accordance with how much collateral you put in and how much the platform is being used — the more liquidity you provide, the more interest you get. If that wasn’t enough, you can even send the tokens you have earned to other protocols (for example YEARN) and claim a secondary yield, in addition to the money earned from the floating premiums paid by those taking protection (‘Takers’). This is known as ‘yield farming’. The cherry on the cake is that Bumper will also reward all users with native BUMP tokens which can be held or sold as desired, making three ways in which you can earn interest off your stablecoins through being a Bumper LP. That beats the 0.6% per year from your bank, right? How Do I Provide Liquidity to Bumper? Providing liquidity to the Bumper protocol couldn’t be easier. Simply access the Bumper protocol and connect the wallet containing your stablecoins (e.g. MetaMask). Then head to the ‘Earn’ page, which will automatically showcase the tokens in your wallet that are supported on the Bumper platform for deposit, as well as the APR associated with each one. When you’re ready to deposit, simply choose the asset you wish to supply, hit ‘deposit’ and set the amount and other parameters. Once you have set these parameters you will be provided with an estimated weekly yield, but don’t forget you can still deploy your bUSDc tokens elsewhere for an increased gain on top of that figure. When you’re happy with how everything looks, hit ‘Next’ and you’re away. Congratulations, you are now a Bumper liquidity provider! Hungry For More? We designed Bumper so that it would be an attractive proposition for anyone interacting with the platform, and with the opportunity to earn money in three different ways we reckon we’ve done that. For more information on the Bumper liquidity pool mechanism, or to ask any questions regarding it or any aspect of the Bumper protocol, head over to our Telegram channel where our team will be happy to help and advise. Join the conversation in… Telegram: Discord: Photo by Dids from Pexels
https://medium.com/bumper-finance/earn-income-by-being-a-bumper-liquidity-provider-4005e1282fdf?source=post_internal_links---------2----------------------------
CC-MAIN-2022-33
refinedweb
1,114
64.75
Code. Collaborate. Organize. No Limits. Try it Today. A lot has been already said about extending Windows and Internet Explorer with Band Objects, Browser Bands, Toolbar Bands and Communication Bands. So if you are familiar with COM and ATL you even might have implemented one yourself. Well, in case your were waiting for an easy way to impress your friends with something like Google Toolbar here it is - the .NET way (or should I say Windows Forms and COM Interop way?). In this tutorial I am going to show how to create any of the mentioned above Band Object types with the help of the BandObject control. Later I will also talk about some implementation details of the BandObject. BandObject Build a Release version of BandObjectLib and register it in the Global Assembly Cache. The easiest way to do this is to open BandObjectLib.sln in Visual Studio, set the active configuration to Release and select 'Rebuild Solution' from the 'Build' menu. The second project in the solution - RegisterLib - is a C++ utility project that performs the 'gacutil /if BandObjectLib.dll' command that puts assembly into GAC. As you probably already know, Band Objects are COM components. And for the .NET framework to find an assembly that implements a COM component it must be either be registered in the GAC or located in the directory of the client application. There are two possible client applications for Band Objects - explorer.exe and iexplorer.exe. Explorer is located in the windows directory and IE somewhere inside 'Program Files'. So GAC is actually the only one option in this case. Thus .NET assemblies that implement Band Objects should be registered in GAC and all libraries they depend on - like BandObjectLib.dll - should also be there. Assemblies in the GAC must have strong names and thus key pairs are required. I have provided the BandObjects.snk file with a key pair but I encourage you to replace it with your own. See the sn.exe tool for more details. Create a new Windows Control Library project and call it SampleBars. We are going to rely on the base functionality of BandObjectLib so we have to add a reference to BandObjectLib\Relase\bin\BandObjectLib.dll. As we are developing a 'Hello World Bar', rename UserControl1.cs and the UserControl1 class inside it appropriately - into HelloWolrdBar.cs and HelloWorldBar. Also put the following lines at the beginning of HelloWorldBar.cs: UserControl1 HelloWorldBar using BandObjectLib; using System.Runtime.InteropServices; Make HelloWorldBar class inherit BandObject instead of System.Windows.Forms.UserControl. As I mentioned earlier, Band Objects are COM components so we should use the Guid attribute. Use guidgen.exe to generate your unique GUID or you can use the one I have generated for you: System.Windows.Forms.UserControl Guid [Guid("AE07101B-46D4-4a98-AF68-0333EA26E113")] We also have to sign our assembly with a strong name. You can do this by putting the following line into AssemblyInfo.cs file: [assembly: AssemblyKeyFile(@"..\..\..\BandObjects.snk")] Now its time to decide what kind of Band Object we want to develop. Lets make it an Explorer Toolbar as well as a Horizontal Explorer Bar (also known as a Browser Communication Band). All we need to do to implement this decision is to add custom BandObject attribute to our HelloWorldBar class: { ... That's enough to make our control available through 'View->Explorer Bars' and 'View->Toolbars' explorer menus. It also takes care of menu item text - "Hello World Bar", and hen the menu item is highlighted status bar displays "Shows bar that says hello.". Don't you like declarative programming and custom attributes? Now it is time to open HelloWorldBar.cs in the Visual Studio Designer and put some controls on it. Although in my version of HelloWorldBar I decided to put a single button with 'Say Hello' caption on it you are free to do something more personalized. I made the size of the button equal to the size of the control's client area and also set its Anchor property to the combination of all possible styles - 'Top, Bottom, Left, Right'. The background color is 'HotTrack' and ForeColor is 'Info'. Anchor ForeColor The BandObject control has several properties specific to the Band Objects (and so classes derived from it) - Title , MinSize, MaxSize and IntegralSize. I set Title for HelloWorldBar to "Hello Bar" and both MinSize and Size to '150, 24'. Oh, and in button's On Click event handler I put code that displays a message box. This is what my final code looks like (and most of it was generated by VS.Net): Title MinSize MaxSize IntegralSize Size using System; using System.ComponentModel; using System.Windows.Forms; using BandObjectLib; using System.Runtime.InteropServices; namespace SampleBars { { private System.Windows.Forms.Button button1; private System.ComponentModel.Container components = null; public HelloWorldBar() { InitializeComponent(); } protected override void Dispose( bool disposing ) { if( disposing ) { if( components != null ) components.Dispose(); } base.Dispose( disposing ); } #region Component Designer generated code private void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // button1 // this.button1.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.button1.BackColor = System.Drawing.SystemColors.HotTrack; this.button1.ForeColor = System.Drawing.SystemColors.Info; this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(150, 24); this.button1.TabIndex = 0; this.button1.Text = "Say Hello"; this.button1.Click += new System.EventHandler(this.button1_Click); // // HelloWorldBar // this.Controls.AddRange(new System.Windows.Forms.Control[] { this.button1 }); this.MinSize = new System.Drawing.Size(150, 24); this.Name = "HelloWorldBar"; this.Size = new System.Drawing.Size(150, 24); this.Title = "Hello Bar"; this.ResumeLayout(false); } #endregion private void button1_Click(object sender, System.EventArgs e) { MessageBox.Show("Hello, World!"); } } } Ok, now we are ready to build SampleBars.dll but its not enough to see it in explorer yet. We have to put our assembly into the GAC as well as register it as a COM server. There are tools - gacutil.exe and regasm.exe that do just this. The C++ utility project named Register in my version of the SampleBars solution liberates me from using these tools manually. It has no files in it, just the following post-build command (debug version): cd $(ProjectDir)..\bin\Debug gacutil /if SampleBars.dll regasm SampleBars.dll Of cause you have to make sure that Register project is the last one to be built in the solution using Project Dependencies / Build Order. After building the solution, and executing the gacutil and regasm commands, we are finally ready to start Explorer and see our toolbar and explorer bar. And if you did everything right you should be able to see something like the picture at the top of the article. On this picture you can also see how HelloWorldBar looks in the Windows Taskbar. To achieve this all you need to do is to modify BandObject attribute adding the BandObjectStyle.TaskbarToolBar flag. BandObjectStyle.TaskbarToolBar There are several issues that you might face developing a band object. First of all, every time you rebuild your project Visual Studio tends to generate new version of the assembly. It does this because of the following line in AssemblyInfo.cs: [assembly: AssemblyVersion("1.0.*")] I recommend using something like "1.0.0.0" or you'll end up with multiple versions of your assembly in GAC. As a matter of fact, according to Jeffrey Richter, the auto increment feature of assembly version is a bug; the original intent was to increment the version of a file, not the assembly. Another issue, more specific to BandObjects, is that explorer caches COM components. This means that even after you deployed a new version of your assembly into GAC, Explorer will not use it until restarted. What may help is setting the 'Launch folder windows in separate process' Explorer setting on. Also if you are getting "Unexpected error creating debug information file..." it is also due to the fact that previous version of your assembly is loaded into Explorer's process space. Ok, now we can look inside the BandObject class implementation. Lets start with ComComInterop.cs file. Explorer requires band objects to implement a set of COM interfaces - IObjectWithSite, IDeskBand and others. Unfortunately these interfaces are not available in the required form of type library so you cannot start using them just by adding a new reference to your project. These interfaces declarations are available in the form of C++ classes and MIDL interfaces. So before using them in .NET you have to convert these declarations into one of the .Net languages. This file also contains several structs and enums used by these interfaces. The whole process of converting is quite straightforward - you see HWND make it IntPtr, IUnknown - Object etc. Probably the most difficult for me was dealing with the DESKBANDINFO structure. You see, in the C++ version one of its parameters is declared as IObjectWithSite IDeskBand HWND IntPtr IUnknown Object DESKBANDINFO WCHAR wszTitle[256]; It took quite a lot of debugging until I figured out what the C# version should look like. Note the use of CharSet.Unicode and that SizeConst is set to 255 not to 256. CharSet.Unicode SizeConst [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)] public struct DESKBANDINFO { public UInt32 dwMask; public Point ptMinSize; public Point ptMaxSize; public Point ptIntegral; public Point ptActual; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=255)] public String wszTitle; public DBIM dwModeFlags; public Int32 crBkgnd; }; And so the BandObject class implements required interfaces. The entry point is the IDeskBand.GetBandInfo method. Its implementation simply gets the values of the Size, MinSize, IntegralSize and Title properties, and populates the DESKBANDINFO structure. That gives Explorer hints how to display and resize band object. IDeskBand.GetBandInfo The implementation of other methods of IDeskBand interface was easy: ShowDW() delegates to Control.Show() or Hide(), CloseDW() calls Dispose() and GetWindow() simply returns the Handle property of the control. ShowDW() Control.Show() Hide() CloseDW() Dispose() GetWindow() Handle IObjectWithSite is equired to establish communication with the hosting Explorer process. Inside the SetSite() method of the BandObject control tries to get a reference to an IWebBrowser interface - an interface implemented by the top-level object of Explorer. It will be available through the BandObject.Explorer property. In the case of a taskbar toolbar there is no IWebBrowser interface so it handles this situation gracefully. As soon as a pointer to IWebBrowser is retrived, BandObject fires the ExplorerAttached event. Handling this event is useful when you want to add extra initialization code - subscribing to Web Browser events etc. SetSite() IWebBrowser BandObject.Explorer ExplorerAttached The IInputObject implementation is more interesting. This interface is required if you want your band object to participate in processing of keyboard input. The user can navigate from one explorer interface object (address bar, folder view) to another by pressing 'Tab' or 'Shift+Tab'. When it is your band object's turn to be activated or deactivated, Explorer calls the UIActivateIO() method. BandObject's implementation of it simply calls Select() on one of its child controls that acquires focus. Which control to select depends on the tab order of controls and whether user navigates forward or backward (with Shift key). BandObject also makes sure that focus can leave it (in case last control is selected and user presses Tab). This logic is implemented inside the TranslateAcceleratorIO() method. It first checks if the 'Tab' or 'F6' keys were pressed. Then depending on the state of 'Shift' key it tries to move focus from one child control to another using the SelectNextControl() method. The last parameter of SelectNextControl is false as we don't want to cycle through controls forever (from last to first and vice versa). If there is no next control we return zero which signals to Explorer that we don't know how to process this command. So Explorer itself processes the command, moving focus to an appropriate user interface object. IInputObject UIActivateIO() TranslateAcceleratorIO() SelectNextControl() SelectNextControl false And finally my favorite part: the Register() and Unregister() methods. These methods are adorned with Com{Un}registerFunction attributes so the regasm.exe tool knows to call them when assembly is registered as a COM server. Register function checks its input parameter for presence of BandObjectAttribute. If it is present then its Name, Style and HelpText properties are used to create apropriate registry settings. For instance, to make your COM component to be considered as a 'Browser Communication Band' you have to mark it as implementing the 'Browser Communication Band' COM category. To make it an Explorer toolbar you have to register its CLSID under SOFTWARE\Microsoft\Internet Explorer\Toolbar. But you don't have to worry about these details. All you need to know is what BandObjectStyle flag to use and Register() takes care of the rest. Similarly, the Unregister() method takes care of what have to be removed from the registry when assembly is unregistered. Unregister() Com{Un}registerFunction BandObjectAttribute Name Style HelpText CLSID BandObject.
http://www.codeproject.com/Articles/2219/Extending-Explorer-with-Band-Objects-using-NET-and?msg=3083367
CC-MAIN-2014-23
refinedweb
2,148
50.23
I am wondering how to create forgiving dictionary (one that returns a default value if a KeyError is raised). In the following code example I would get a KeyError; for example a = {'one':1,'two':2} print a['three'] import collections a = collections.defaultdict(lambda: 3) a.update({'one':1,'two':2}) print a['three'] emits 3 as required. You could also subclass dict yourself and override __missing__, but that doesn't make much sense when the defaultdict behavior (ignoring the exact missing key that's being looked up) suits you so well... Edit ...unless, that is, you're worried about a growing by one entry each time you look up a missing key (which is part of defaultdict's semantics) and would rather get slower behavior but save some memory. For example, in terms of memory...: >>> import sys >>> a = collections.defaultdict(lambda: 'blah') >>> print len(a), sys.getsizeof(a) 0 140 >>> for i in xrange(99): _ = a[i] ... >>> print len(a), sys.getsizeof(a) 99 6284 ...the defaultdict, originally empty, now has the 99 previously-missing keys that we looked up, and takes 6284 bytes (vs. the 140 bytes it took when it was empty). The alternative approach...: >>> class mydict(dict): ... def __missing__(self, key): return 3 ... >>> a = mydict() >>> print len(a), sys.getsizeof(a) 0 140 >>> for i in xrange(99): _ = a[i] ... >>> print len(a), sys.getsizeof(a) 0 140 ...entirely saves this memory overhead, as you see. Of course, performance is another issue: $ python -mtimeit -s'import collections; a=collections.defaultdict(int); r=xrange(99)' 'for i in r: _=a[i]' 100000 loops, best of 3: 14.9 usec per loop $ python -mtimeit -s'class mydict(dict): > def __missing__(self, key): return 0 > ' -s'a=mydict(); r=xrange(99)' 'for i in r: _=a[i]' 10000 loops, best of 3: 92.9 usec per loop Since defaultdict adds the (previously-missing) key on lookup, it gets much faster when such a key is next looked up, while mydict (which overrides __missing__ to avoid that addition) pays the "missing key lookup overhead" every time. Whether you care about either issue (performance vs memory footprint) entirely depends on your specific use case, of course. It is in any case a good idea to be aware of the tradeoff!-)
https://codedump.io/share/MuhURHFPtAXg/1/a-forgiving-dictionary
CC-MAIN-2017-26
refinedweb
384
67.65
Specification link: 15.4 The listener element script-handle-202-t ← index → script-listener-202-t This test tests the assertion from the Namespaces in XML specification, "The namespace prefix, unless it is xml or xmlns, MUST have been declared in a namespace declaration attribute in either the start-tag of the element where the prefix is used or in an ancestor element (i.e. an element in whose content the prefixed markup occurs)." The root element doesn't declare the XML Event namespace for the prefix "ev". The test has passed if handlers are implemented (the handler with xml:id="passhandler" has run) but the handler with xml:id="failhandler" has not run. If the handler is run then the text in the testcase will show "Test failed: magic prefixes!". If handlers are not implemented at all, the testcase will show "Test failed: handlers not implemented." The test is also passed if the implementation states somehow that the test case is not namespace well formed (by overlaying it on the image, informing the user in the error console, not showing the document at all, etc.).
http://www.w3.org/Graphics/SVG/Test/20080912/htmlObjectHarness/script-listener-201-t.html
CC-MAIN-2015-14
refinedweb
186
58.11
Easy to use AngularDart gallery component.! Your user can navigate through your gallery by simply pressing the left/right buttons or on mobile also by swiping to left or right.'; We recommended to use *ngIf to show and hide the gallery. <fnx-gallery> emits (close) event, which indicates that the user clicked on the close button (or pressed ESC key etc.). Hide the gallery after this event. You use some of these AngularDart inputs to modify the element: Fill-in a bugreport or feature request on Github issue tracking. Add this to your package's pubspec.yaml file: dependencies: fnx_gallery: "^0.0.7" You can install packages from the command line: with pub: $ pub get Alternatively, your editor might support pub get. Check the docs for your editor to learn more. Now in your Dart code, you can use: import 'package:fnx_gallery/fnx_gallery.dart'; We analyzed this package on Jun 12, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using: Detected platforms: web Primary library: package:fnx_gallery/fnx_gallery.dartwith components: html. Maintain CHANGELOG.md. Changelog entries help clients to follow the progress in your code. Fix analysis and formatting issues. Analysis or formatting checks reported 1 error 3 hints. Strong-mode analysis of lib/src/fnx_gallery/fnx_gallery.dartfailed with the following error: line: 107 col: 36 The argument type '(String) → Null' can't be assigned to the parameter type '(dynamic) → FutureOr<dynamic>'. Run dartfmtto format lib/fnx_gallery.dart. Similar analysis of the following files failed: lib/src/image fnx_gallery.dart.
https://pub.dartlang.org/packages/fnx_gallery
CC-MAIN-2018-26
refinedweb
257
60.31
I have a very basic question being a novice. It might be silly to you but I really want to know the fact. Let’s say you have a java program. Can you have two classes in one java file? What is the reason behind it? Thanks for your clearance. Yes, we can. All we have to do is make sure that only one of them is public. A java file can’t run without a public class. The below example will help you to understand it well. If you still have any questions, just reply to this thread. public class MyTestClass { int a = 5; } class MyOtherClass { public static void main(String[] args) { MyTestClass myOb = new MyTestClass(); System.out.println(myOb.a); } } Thanks.
https://kodlogs.com/37976/multiple-classes-in-one-java-file
CC-MAIN-2021-21
refinedweb
123
78.55
ASP.NET - Writing Clean Code in ASP.NET Core with Dependency Injection By Steve Smith | May 2016 | Get the Code: C# ASP.NET Core 1.0 is a complete rewrite of ASP.NET, and one of the main goals for this new framework is a more modular design. That is, apps should be able to leverage only those parts of the framework they need, with the framework providing dependencies as they’re requested.. Tight Coupling Tight coupling is fine for demo software. If you look at the typical sample application showing how to build ASP.NET MVC (versions 3 through 5) sites, you’ll most likely find code like this (from the NerdDinner MVC 4 sample’s DinnersController class): private NerdDinnerContext db = new NerdDinnerContext(); private const int PageSize = 25; public ActionResult Index(int? page) { int pageIndex = page ?? 1; var dinners = db.Dinners .Where(d => d.EventDate >= DateTime.Now).OrderBy(d => d.EventDate); return View(dinners.ToPagedList(pageIndex, PageSize)); } This kind of code is very difficult to unit test, because the NerdDinnerContext is created as part of the class’s construction, and requires a database to which to connect. Not surprisingly, such demo applications don’t often include any unit tests. However, your application might benefit from a few unit tests, even if you’re not test-driving your development, so it would be better to write the code so it could be tested. What’s more, this code violates the Don’t Repeat Yourself (DRY) principle, because every controller class that performs any data access has the same code in it to create an Entity Framework (EF) database context. This makes future changes more expensive and error-prone, especially as the application grows over time. When looking at code to evaluate its coupling, remember the phrase “new is glue.” That is, anywhere you see the “new” keyword instantiating a class, realize you’re gluing your implementation to that specific implementation code. The Dependency Inversion Principle (bit.ly/DI-Principle) states: “Abstractions should not depend on details; details should depend on abstractions.” In this example, the details of how the controller pulls together the data to pass to the view depend on the details of how to get that data—namely, EF. In addition to the new keyword, “static cling” is another source of tight coupling that makes applications more difficult to test and maintain. In the preceding example, there’s a dependency on the executing machine’s system clock, in the form of a call to DateTime.Now. This coupling would make creating a set of test Dinners to use in some unit tests difficult, because their EventDate properties would need to be set relative to the current clock’s setting. This coupling could be removed from this method in several ways, the simplest of which is to let whatever new abstraction returns the Dinners worry about it, so it’s no longer a part of this method. Alternatively, I could make the value a parameter, so the method might return all Dinners after a provided DateTime parameter, rather than always using DateTime.Now. Last, I could create an abstraction for the current time, and reference the current time through that abstraction. This can be a good approach if the application references DateTime.Now frequently. (It’s also worth noting that because these dinners presumably happen in various time zones, the DateTimeOffset type might be a better choice in a real application). Be Honest.” The DinnersController class has only a default constructor, which implies that it shouldn’t need any collaborators in order to function properly. But what happens if you put that to the test? What will this code do, if you run it from a new console application that references the MVC project? The first thing that fails in this case is the attempt to instantiate the EF context. The code throws an InvalidOperationException: “No connection string named ‘NerdDinnerContext’ could be found in the application config file.” I’ve been deceived! This class needs more to function than what its constructor claims! If the class needs a way to access collections of Dinner instances, it should request that through its constructor (or, alternatively, as parameters on its methods). Dependency Injection Dependency injection (DI) refers to the technique of passing in a class’s or method’s dependencies as parameters, rather than hardcoding these relationships via new or static calls. It’s an increasingly common technique in .NET development, because of the decoupling it affords to applications that employ it. Early versions of ASP.NET didn’t make use of DI, and although ASP.NET MVC and Web API made progress toward supporting it, neither went so far as to build full support, including a container for managing the dependencies and their object lifecycles, into the product. With ASP.NET Core 1.0, DI isn’t just supported out of the box, it’s used extensively by the product itself. ASP.NET Core not only supports DI,. I’ve created a spinoff of NerdDinner, called GeekDinner, for this article. EF Core is configured as shown here: With this in place, it’s quite simple to use DI to request an instance of GeekDinnerDbContext from a controller class like DinnersController: Notice there’s not a single instance of the new keyword; the dependencies the controller needs are all passed in via its constructor, and the ASP.NET DI container takes care of this for me. While I’m focused on writing the application, I don’t need to worry about the plumbing involved in fulfilling the dependencies my classes request through their constructors. Of course, if I want to, I can customize this behavior, even replacing the default container with another implementation entirely. Because my controller class now follows the explicit dependencies principle, I know that for it to function I need to provide it with an instance of a GeekDinnerDbContext. I can, with a bit of setup for the DbContext, instantiate the controller in isolation, as this Console application demonstrates: There’s a little bit more work involved in constructing an EF Core DbContext than an EF6 one, which just took a connection string. This is because, just like ASP.NET Core, EF Core has been designed to be more modular. Normally, you won’t need to deal with DbContextOptionsBuilder directly, because it’s used behind the scenes when you configure EF through extension methods like AddEntityFramework and AddSqlServer. But Can You Test It? Testing your application manually is important—you want to be able to run it and see that it actually runs and produces the expected output. But having to do that every time you make a change is a waste of time. One of the great benefits of loosely coupled applications is that they tend to be more amenable to unit testing than tightly coupled apps. Better still, ASP.NET Core and EF Core are both much easier to test than their predecessors were. To get started, I’ll write a simple test directly against the controller by passing in a DbContext that has been configured to use an in-memory store. I’ll configure the GeekDinnerDbContext using the DbContextOptions parameter it exposes via its constructor as part of my test’s setup code: var optionsBuilder = new DbContextOptionsBuilder<GeekDinnerDbContext>(); optionsBuilder.UseInMemoryDatabase(); _dbContext = new GeekDinnerDbContext(optionsBuilder.Options); // Add sample data _dbContext.Dinners.Add(new Dinner() { Title = "Title 1" }); _dbContext.Dinners.Add(new Dinner() { Title = "Title 2" }); _dbContext.Dinners.Add(new Dinner() { Title = "Title 3" }); _dbContext.SaveChanges(); With this configured in my test class, it’s easy to write a test showing that the correct data is returned in the ViewResult’s Model: [Fact] public void ReturnsDinnersInViewModel() { var controller = new OriginalDinnersController(_dbContext); var result = controller.Index(); var viewResult = Assert.IsType<ViewResult>(result); var viewModel = Assert.IsType<IEnumerable<Dinner>>( viewResult.ViewData.Model).ToList(); Assert.Equal(1, viewModel.Count(d => d.Title == "Title 1")); Assert.Equal(3, viewModel.Count); } Of course, there’s not a lot of logic to test here yet, so this test isn’t really testing that much. Critics will argue that this isn’t a terribly valuable test, and I would agree with them. However, it’s a starting point for when there’s more logic in place, as there soon will be. But first, although EF Core can support unit testing with its in-memory option, I’ll still avoid direct coupling to EF in my controller. There’s no reason to couple UI concerns with data access infrastructure concerns—in fact, it violates another principle, Separation of Concerns. Don’t Depend on What You Don’t Use The Interface Segregation Principle (bit.ly/LS-Principle) states that classes should depend only on functionality they actually use. In the case of the new DI-enabled DinnersController, it’s still depending on the entire DbContext. Instead of gluing the controller implementation to EF, an abstraction that provided the necessary functionality (and little or nothing more) could be used. What does this action method really need in order to function? Certainly not the entire DbContext. It doesn’t even need access to the full Dinners property of the context. All it needs is the ability to display the appropriate page’s Dinner instances. The simplest .NET abstraction representing this is IEnumerable<Dinner>. So, I’ll define an interface that simply returns an IEnumerable<Dinner>, and that will satisfy (most of) the requirements of the Index method: I’m calling this a repository because it follows that pattern: It abstracts data access behind a collection-like interface. If for some reason you don’t like the repository pattern or name, you can call it IGetDinners or IDinnerService or whatever name you prefer (my tech reviewer suggests ICanHasDinner). Regardless of how you name the type, it will serve the same purpose. With this in place, I now adjust DinnersController to accept an IDinnerRepository as a constructor parameter, instead of a GeekDinnerDbContext, and call the List method instead of accessing the Dinners DbSet directly: At this point, you can build and run your Web application, but you’ll encounter an exception if you navigate to /Dinners: InvalidOperationException: Unable to resolve service for type ‘GeekDinner.Core.Interfaces.IdinnerRepository’ while attempting to activate GeekDinner.Controllers.DinnersController. I haven’t yet implemented the interface, and once I do, I’ll also need to configure my implementation to be used when DI fulfills requests for IDinnerRepository. Implementing the interface is trivial: Note that it’s perfectly fine to couple a repository implementation to EF directly. If I need to swap out EF, I’ll just create a new implementation of this interface. This implementation class is a part of my application’s infrastructure, which is the one place in the application where my classes depend on specific implementations. To configure ASP.NET Core to inject the correct implementation when classes request an IDinnerRepository, I need to add the following line of code to the end of the ConfigureServices method shown earlier: This statement instructs the ASP.NET Core DI container to use a DinnerRepository instance whenever the container is resolving a type that depends on an IDinnerRepository instance. Scoped means that one instance will be used for each Web request ASP.NET handles. Services can also be added using Transient or Singleton lifetimes. In this case, Scoped is appropriate because my DinnerRepository depends on a DbContext, which also uses the Scoped lifetime. Here’s a summary of the available object lifetimes: - Transient: A new instance of the type is used every time the type is requested. - Scoped: A new instance of the type is created the first time it’s requested within a given HTTP request, and then re-used for all subsequent types resolved during that HTTP request. - Singleton: A single instance of the type is created once, and used by all subsequent requests for that type. The built-in container supports several ways of constructing the types it will provide. The most typical case is to simply provide the container with a type, and it will attempt to instantiate that type, providing any dependencies that type requires as it goes. You can also provide a lambda expression for constructing the type, or, for a Singleton lifetime, you can provide the fully constructed instance in ConfigureServices when you register it. With dependency injection wired up, the application runs just as before. Now, as Figure 1 shows, I can test it with this new abstraction in place, using a fake or mock implementation of the IDinnerRepository interface, instead of relying on EF directly in my test code. public class DinnersControllerIndex { private List<Dinner> GetTestDinnerCollection() { return new List<Dinner>() { new Dinner() {Title = "Test Dinner 1" }, new Dinner() {Title = "Test Dinner 2" }, }; } [Fact] public void ReturnsDinnersInViewModel() { var mockRepository = new Mock<IDinnerRepository>(); mockRepository.Setup(r => r.List()).Returns(GetTestDinnerCollection()); var controller = new DinnersController(mockRepository.Object, null); var result = controller.Index(); var viewResult = Assert.IsType<ViewResult>(result); var viewModel = Assert.IsType<IEnumerable<Dinner>>( viewResult.ViewData.Model).ToList(); Assert.Equal("Test Dinner 1", viewModel.First().Title); Assert.Equal(2, viewModel.Count); } } This test works regardless of where the list of Dinner instances comes from. You could rewrite the data access code to use another database, Azure Table Storage, or XML files, and the controller would work the same. Of course, in this case it’s not doing a whole lot, so you might be wondering … What About Real Logic? So far I haven’t really implemented any real business logic—it’s just been simple methods returning simple collections of data. The real value of testing comes when you have logic and special cases you need to have confidence will behave as intended. To demonstrate this, I’m going to add some requirements to my GeekDinner site. The site will expose an API that will allow anybody to RSVP for a dinner. However, dinners will have an optional maximum capacity and RSVPs should not exceed this capacity. Users requesting RSVPs beyond the maximum capacity should be added to a waitlist. Finally, dinners can specify a deadline by which RSVPs must be received, relative to their start time, after which they stop accepting RSVPs. I could code all of this logic into an action, but I believe that’s way too much responsibility to put into one method, especially a UI method that should be focused on UI concerns, not business logic. The controller should verify that the inputs it receives are valid, and it should ensure the responses it returns are appropriate to the client. Decisions beyond that, and especially business logic, don’t belong in controllers. The best place to keep business logic is in the application’s domain model, which shouldn’t depend on infrastructure concerns (like databases or UIs). The Dinner class makes the most sense to manage the RSVP concerns described in the requirements, because it will store the maximum capacity for the dinner and it will know how many RSVPs have been made so far. However, part of the logic also depends on when the RSVP occurs—whether or not it’s past the deadline—so the method also needs access to the current time. I could just use DateTime.Now, but this would make the logic difficult to test and would couple my domain model to the system clock. Another option is to use an IDateTime abstraction and inject this into the Dinner entity. However, in my experience it’s best to keep entities like Dinner free of dependencies, especially if you plan on using an O/RM tool like EF to pull them from a persistence layer. I don’t want to have to populate dependencies of the entity as part of that process, and EF certainly won’t be able to do it without additional code on my part. A common approach at this point is to pull the logic out of the Dinner entity and put it in some kind of service (such as DinnerService or RsvpService) that can have dependencies injected easily. This tends to lead to the anemic domain model antipattern (bit.ly/anemic-model), though, in which entities have little or no behavior and are just bags of state. No, in this case the solution is straightforward—the method can simply take in the current time as a parameter and let the calling code pass this in. With this approach, the logic for adding an RSVP is straightforward (see Figure 2). This method has a number of tests that demonstrate it behaves as expected; the tests are available in the sample project associated with this article. public RsvpResult AddRsvp(string name, string email, DateTime currentDateTime) { if (currentDateTime > RsvpDeadlineDateTime()) { return new RsvpResult("Failed - Past deadline."); } var rsvp = new Rsvp() { DateCreated = currentDateTime, EmailAddress = email, Name = name }; if (MaxAttendees.HasValue) { if (Rsvps.Count(r => !r.IsWaitlist) >= MaxAttendees.Value) { rsvp.IsWaitlist = true; Rsvps.Add(rsvp); return new RsvpResult("Waitlist"); } } Rsvps.Add(rsvp); return new RsvpResult("Success"); } By shifting this logic to the domain model, I’ve ensured that my controller’s API method remains small and focused on its own concerns. As a result, it’s easy to test that the controller does what it should, as there are relatively few paths through the method. Controller Responsibilities Part of the controller’s responsibility is to check ModelState and ensure it’s valid. I’m doing this in the action method for clarity, but in a larger application I would eliminate this repetitive code within each action by using an Action Filter: Assuming the ModelState is valid, the action must next fetch the appropriate Dinner instance using the identifier provided in the request. If the action can’t find a Dinner instance matching that Id, it should return a Not Found result: Once these checks have been completed, the action is free to delegate the business operation represented by the request to the domain model, calling the AddRsvp method on the Dinner class that you saw previously, and saving the updated state of the domain model (in this case, the dinner instance and its collection of RSVPs) before returning an OK response: Remember that I decided the Dinner class shouldn’t have a dependency on the system clock, opting instead to have the current time passed into the method. In the controller, I’m passing in _systemClock.Now for the currentDateTime parameter. This is a local field that’s populated via DI, which keeps the controller from being tightly coupled to the system clock, too. It’s appropriate to use DI on the controller, as opposed to a domain entity, because controllers are always created by ASP.NET services containers; this will fulfill any dependencies the controller declares in its constructor. _systemClock is a field of type IDateTime, which is defined and implemented in just a few lines of code: Of course, I also need to ensure the ASP.NET container is configured to use MachineClockDateTime whenever a class needs an instance of IDateTime. This is done in ConfigureServices in the Startup class, and in this case, although any object lifetime will work, I choose to use a Singleton because one instance of MachineClockDateTime will work for the whole application: With this simple abstraction in place, I’m able to test the controller’s behavior based on whether the RSVP deadline has passed, and ensure the correct result is returned. Because I already have tests around the Dinner.AddRsvp method that verify it behaves as expected, I won’t need very many tests of that same behavior through the controller to give me confidence that, when working together, the controller and domain model are working correctly. Next Steps Download the associated sample project to see the unit tests for Dinner and DinnersController. Remember that loosely coupled code is typically much easier to unit test than tightly coupled code riddled with “new” or static method calls that depend on infrastructure concerns. “New is glue” and the new keyword should be used intentionally, not accidentally, in your application. Learn more about ASP.NET Core and its support for dependency injection at docs.asp.net. Steve Smith is an independent trainer, mentor and consultant, as well as an ASP.NET MVP. He has contributed dozens of articles to the official ASP.NET Core documentation (docs.asp.net), and works with teams learning this technology. Contact him at ardalis.com or follow him on Twitter: @ardalis. Thanks to the following Microsoft technical expert for reviewing this article: Doug Bunting Doug Bunting is a developer working on the MVC team at Microsoft. He’s been doing this for a while and loves the new DI paradigm in the MVC Core rewrite. Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus. ASP.NET - Writing Clean Code in ASP.NET Core with Dependency Injection If we have more than 1 implementation of the interrace "IDinnerRepository" then how can we resolve them? Suppose the ChineseDinnerController needs ChineseDinnerRepository that intern implements "IDinnerRepository" and MaxicanDinnerController need Ma... Apr 12, 2017 ASP.NET - Writing Clean Code in ASP.NET Core with Dependency Injection Thanks for the article, I found it very useful. However, I'd like to ask you a question, imagine the following scenario: When a Dinner is created, you need to run some business logic, like for example, let's say create collection of Meal (populated w... Feb 20, 2017 ASP.NET - Writing Clean Code in ASP.NET Core with Dependency Injection The sample doesn't execute out of the box. I got 2261 errors such as "The dependency System.Numerics.Vectors >= 4.1.1-beta-23516 could not be resolved." It seems that since Microsoft is on the Open Source road, .NET development becomes as hard as usi... Nov 2, 2016 ASP.NET - Writing Clean Code in ASP.NET Core with Dependency Injection I was attempting to adopt the techniques in this article for API controllers and I found that it was necessary to change the unit test in Figure 1 to Assert.IsAssignableFrom(IEnumerable<MyType>) in order for this to work. Assert.IsType verifies tha... Aug 26, 2016 ASP.NET - Writing Clean Code in ASP.NET Core with Dependency Injection Sorry about that. Fixing the downloads now. It should be there shortly. May 5, 2016 ASP.NET - Writing Clean Code in ASP.NET Core with Dependency Injection You can certainly define your dependencies in a file - in fact that's how most of the early IOC containers all did it. It's only been more recently that most developers have preferred wiring things up in code, because it tends to be more robust. For ... May 5, 2016 ASP.NET - Writing Clean Code in ASP.NET Core with Dependency Injection There has been an issue with the download tool our production folks use to post code samples. We're hoping the issue will be resolved soon. I apologize for the inconvenience. May 5, 2016 ASP.NET - Writing Clean Code in ASP.NET Core with Dependency Injection Hi,. Thanks a lot for the article.i have a project initially we use masterdb connection string then after login based on user information we have to change the connection string. I have to pass connection string in dynamic. Thanks for you help... May 5, 2016 ASP.NET - Writing Clean Code in ASP.NET Core with Dependency Injection Same for me. No file to download. May 4, 2016 ASP.NET - Writing Clean Code in ASP.NET Core with Dependency Injection I am encountering an error when trying to download the code sample for this article. Both are returning an error "This site can't be reached"..... ".../Code_SmithCore0516.zip might be temporarily down or it may have moved permanently to a new we add... May 3, 2016 ASP.NET - Writing Clean Code in ASP.NET Core with Dependency Injection Thanks for the new DI article. I was hoping you, or someone could start to get into deeper scenarios. Each example I am seeing is a small permutation on Here is an object and here is how we inject it. I would be interested in seeing those objects rel... May 3, 2016 ASP.... May 2, 2016
https://msdn.microsoft.com/en-us/magazine/mt703433.aspx
CC-MAIN-2018-51
refinedweb
4,023
55.34
- Build - Mandelbrot overview - The code and image - Data.Complex - Magnitude - Instability - Pixel mapping - The magical math - Drawing the image - Adding colors We’ve used a package written by Cies Breijs that we found on GitHub to generate the header art for the Validation course pages. haskell-fractal on GitHub. We liked the image this package generates, and the author included some LaTeX to generate a PDF version of the art. In theory, we like the ability to print this out and hang it over our desks. We haven’t actually done that, yet, but we might! Build The project structure here is simple, and we didn’t feel the need to change it. But it can be tricky to build due to foreign dependencies; for us, the build instructions in the README did not work as stated. We added a stack.yaml so it can be built with Stack now, for those who want to do that. Our fork of haskell-fractal. Once we could build it, we found that it took a long time to generate the image. It makes a big image with lots of detail, although it took much less time when using the width and height values that we needed for our image. Just bear in mind that creating the image at the original size setting takes a little bit of time. Mandelbrot overview The original code, as we’ll explain in depth soon, produces a beautiful image, but it’s only grayscale and we wanted color. Initially, we were going to write a short post here about the changes that we made to generate a color image. However, as with a typical fractal program, color generation is intimately tied up with the image generation and fractal math itself. So we’re going to go ahead and analyze this code and talk about how fractals like the Mandelbrot set work. We’re assuming that you have at least seen images of the Mandelbrot set, and other fractal sets, and have some idea of their features. As we work through the code, we’ll get into more mathematical detail, but we want to start with a high-level overview of how programs like this work. If some of this is confusing or you don’t know some of the jargon, we encourage you to keep reading, because it will be explained in more detail and with concrete examples below. Programs that generate images of the Mandelbrot or Julia sets have at their core a fairly simple equation involving complex numbers. We can write the function in Haskell like this, where c and z are complex numbers: = z^2 + cf c z While the function is simple, what we care about is what happens under iteration; we need to keep calling f on the result of the previous calculation. Essentially, there are two patterns: for some complex numbers, the values of z under iteration remain stable within a certain bounded size, while for other points in the complex plane the iterates are not stable and will diverge – quickly or slowly – toward infinity. When we say “diverge toward infinity”, we mean that the magnitude of the z values will grow larger, although it might not be a steady monotonic growth. We’ll explain complex numbers and magnitude more below. For the Mandelbrot set, the initial value of z is always 0 and and we vary the value of c; for Julia sets, we fix the value of c and vary the values of z. We generate an image of the Mandelbrot set by assigning a complex number, c, to each pixel and seeing what the behavior is at that pixel. If it’s stable and does not ever diverge toward infinity, we paint that pixel one color; the Mandelbrot set is the set of those values c where the behavior of 0 under iteration is stable. If z is unstable and will eventually, under some number of iterations, head toward infinity, we paint that pixel another color. If we want to, we can use more than two colors by painting pixels depending on how fast they head toward infinity or how wildly unstable the orbits of the iterates are. This is often accomplished by using the number of iterations on a given pixel as one of the inputs to the function that assigns an RGB (or similar) value to that pixel. While we’re going to get into this in more detail below, let’s look at some concrete examples of what this means. For the Mandelbrot set, we want to fix the start value of z for every c at 0 and see what happens under iteration. For these examples, we’ll stick with real numbers because we think it’s fair to say that most of us have a harder time mentally following along with arithmetic over complex numbers, if only because we typically have less experience with it. However, all real numbers are also complex numbers, with the imaginary component being 0i. So, let’s begin by choosing 1 as our c value – we need to make our Haskell function above recursive as well, since iteration is the point: = f c z' f c z where z' = z^2 + c = 1 c = 0 z 1 0 = f 1 (0^2 + 1) f = f 1 (1^2 + 1) = f 1 (2^2 + 1) = f 1 (5^2 + 1) -- ... and so on That will never terminate as written, but we can already see what we need to see: the values of z will just keep getting larger and larger. So, this value of c (or, more precisely, the complex number associated with this real number, which would be 1 + 0i) is not in the Mandelbrot set. Let’s try another one, shall we – how about (-1) this time? = f c z' f c z where z' = z^2 + c = (-1) c = 0 z -1) 0 = f (-1) (0^2 + (-1)) f (= f (-1) ((-1)^2 + (-1)) = f (-1) (0^2 + (-1)) = f (-1) ((-1)^2 + (-1)) -- ... and so on The very picture of stability: the value of z just keeps bouncing back and forth between (-1) and 0. It will never diverge away from this orbit, no matter how many times we keep applying this function to the values of z. So, the complex number (-1 + 0i) is indeed in the Mandelbrot set. To some extent, using only real numbers for examples has given us an unfair picture of what stability and instability mean with regard to this equation. When we looked at the equation for c = 1, the values of z grow ever larger but they do so monotonically – they only ever grow larger – so what exactly is unstable about this? It’s difficult to see without using some more complex examples, so we’ll do that when we talk about complex numbers, below. Of course, we can’t apply the function infinitely many times to a given pixel, so in practice we choose a number of iterations and say, well, if z hasn’t grown really big after, say, 200 iterations, then it’s probably stable. On the other hand, if z ever attains a magnitude greater than 2, it will diverge toward infinity. If we were intending to draw Julia sets instead, we’d fix the value of c and look for values of z that are stable under the same iteration – we wouldn’t start z at 0 every time. The Mandelbrot set is all the values of c where z = 0 is stable; the Julia sets are all the values of z that are stable for a given, fixed value of c. One of the characteristics of the Mandelbrot set is that it demonstrates self-similarity across different scales, which is why we can zoom in on portions of the Mandelbrot set and find near-repeats of the shape of the Mandelbrot set itself. Using multiple colors that depend on the number of iterations we tried before you could tell it was heading toward infinity, as many of us know, highlights complex and repeating patterns along the borders between stable and unstable – we see degrees of instability; we see fractal complexity. Recursive equations that produce fractal complexity like these are the essence of chaos theory, because tiny changes in the value of c can produce large variations in behavior and it’s almost impossible to predict what they’ll be. The code and image OK, let’s start to make this more concrete. This is the code, as written, that we’ll be stepping through: import Codec.Picture (generateImage, writePng) import Data.Word (Word8) import Data.Complex (Complex(..), magnitude) aspectRatio :: Double aspectRatio = sqrt 2 -- nice cut for ISO216 paper size x0, y0, x1, y1 :: Double (x0, y0) = (-0.8228, -0.2087) (x1, y1) = (-0.8075, y0 + (x1 - x0) * aspectRatio) width, height :: Int (width, height) = (10000, round . (* aspectRatio) . fromIntegral $ width) maxIters :: Int maxIters = 1200 fractal :: RealFloat a => Complex a -> Complex a -> Int -> (Complex a, Int) fractal c z iter | iter >= maxIters = (1 :+ 1, 0) -- invert values inside the holes | magnitude z > 2 = (z', iter) | otherwise = fractal c z' (iter + 1) where z' = z * z + c realize :: RealFloat a => (Complex a, Int) -> a realize (z, iter) = (fromIntegral iter - log (log (magnitude z))) / fromIntegral maxIters render :: Int -> Int -> Word8 render xi yi = grayify . realize $ fractal (x :+ y) (0 :+ 0) 0 where (x, y) = (trans x0 x1 width xi, trans y0 y1 height yi) trans n0 n1 a ni = (n1 - n0) * fromIntegral ni / fromIntegral a + n0 grayify f = truncate . (* 255) . sharpen $ 1 - f sharpen v = 1 - exp (-exp ((v - 0.92) / 0.031)) main :: IO () main = writePng "out.png" $ generateImage render width height That code produces this image as output. We’ll work through the code mostly top to bottom, explaining the math in more detail than we did above as we go along. We’ll also show the changes we made to make a color image. It’s worth immediately noticing that the function we referenced earlier on, f c z = z^2 + c, is in the fractal function in this program. We’ll examine it in greater detail below.
https://typeclasses.com/art/mandelbrot
CC-MAIN-2021-43
refinedweb
1,694
64.75
Glamor In this guide, we’ll walk through setting up a site with the CSS-in-JS library Glamor. Glamor lets you write real CSS inline in your components using the same Object CSS syntax React supports for the style prop. Glamor easier to know how to edit a component’s CSS as there’s never any confusion about how and where CSS is being used. First, open a new terminal window and run the following to create a new site: gatsby new glamor-tutorial Second, install the Gatsby plugin for Glamor. npm install --save gatsby-plugin-glamor And then add it to your site’s gatsby-config.js: module.exports = { plugins: [`gatsby-plugin-glamor`], }; Then in your terminal run gatsby develop to start the Gatsby development server. Now let’s create a sample Glamor page at src/pages/index.js import React from "react"; import Container from "../components/container"; export default () => ( <Container> <h1>About Glamor</h1> <p>Glamor is cool</p> </Container> ); Let’s add a inline User component using Glamor’s css prop. import React from "react" import Container from "../components/container" const User = props => <div css={{ display: `flex`, alignItems: `center`, margin: `0 auto 12px auto`, "&:last-child": { marginBottom: 0 } }} > <img src={props.avatar} css={{ flex: `0 0 96px`, width: 96, height: 96, margin: 0 }} <div css={{ flex: 1, marginLeft: 18, padding: 12 }}> <h2 css={{ margin: `0 0 12px 0`, padding: 0 }}> {props.username} </h2> <p css={{ margin: 0 }}> {props.excerpt} </p> </div> </div> export default () => <Container> <h1>About Glamor</h1> <p>Glamor>
https://www.gatsbyjs.org/docs/glamor/
CC-MAIN-2018-05
refinedweb
255
55.44
The: Thank you so much. Thanks. I tried it on stable 7.3. I installed the plugin, I pointed to play framework, I created a project and I tried to run it. It does the same when I try to use autocompletion. This is the output when I try to run: :: USE VERBOSE OR DEBUG MESSAGE LEVEL FOR MORE DETAILS unresolved dependency: org.scala-sbt#sbt;0.11.3: not found Error during sbt execution: Error retrieving required libraries (see C:\Users\Mircea\Documents\play-2.1.0\framework\.\sbt\boot\update.log for complete log) Error: Could not retrieve sbt 0.11.3 java.lang.NullPointerExceptionat org.netbeans.play.PlayFramework.findFile(PlayFramework.java:120) at org.netbeans.play.PlayFramework.lookupPlayJarFile(PlayFramework.java:99) at org.netbeans.play.classpath.BootClassPathImplementation.getResources(BootClassPathImplementation.java:48) at org.netbeans.api.java.classpath.ClassPath.entries(ClassPath.java:350) at org.netbeans.api.java.classpath.ClassPath.getRoots(ClassPath.java:262) at org.netbeans.api.java.classpath.ClassPath.findResource(ClassPath.java:448) at org.netbeans.modules.java.source.parsing.JavacParser.validateSourceLevel(JavacParser.java:838) at org.netbeans.modules.java.source.parsing.JavacParser.createJavacTask(JavacParser.java:731) at org.netbeans.modules.java.source.parsing.JavacParser.createJavacTask(JavacParser.java:717) at org.netbeans.modules.java.source.parsing.CompilationInfoImpl.getJavacTask(CompilationInfoImpl.java:398) at org.netbeans.modules.java.source.parsing.JavacParser.getResult(JavacParser.java:495) at org.netbeans.modules.java.source.parsing.JavacParser.getResult(JavacParser.java:169) at org.netbeans.modules.parsing.impl.TaskProcessor.callGetResult(TaskProcessor.java:606) at org.netbeans.modules.parsing.impl.SourceCache.getResult(SourceCache.java:247) [catch] at org.netbeans.modules.parsing.impl.TaskProcessor$CompilationJob.run(TaskProcessor.java:718)) You can see very clearly what the problem is: unresolved dependency: org.scala-sbt#sbt;0.11.3: not found Anyway, instead of creating a project, can you try to open one of the samples, such as the one that you can see in the screenshot above, that comes with the Play distribution? I'm curious to know if you'll get the same error then. PS: Possibly the Scala samples and Scala projects don't work right now. Could you try the Java samples and a Java project instead? I'll be blogging about Scala, Play, and NetBeans IDE 7.3 soon. No, even with Scala projects, there's no problem at all in compiling. However, code completion doesn't work, unless you have the NetBeans Scala plugin installed, more on that in another blog entry. Maybe this will help, though it took me 2 minutes to find via Google, so I'm guess you've seen this: Identified the problem and fixed it. Better solution is needed, but please download the the plugin again and try again, for me, I can see code completion working fine now. Also, for Scala support in NetBeans IDE 7.3, you'll need this plugin: Something else is that the templates for creating new projects needs to be updated, I'll do that in the plugin sources soon, but in the meantime, do the following manually after creating a new project: In project/build.properties, change the content to this: sbt.version=0.12.2 In project/plugins.sbt, change the last line to this: addSbtPlugin("play" % "sbt-plugin" % Option(System.getProperty("play.version")).getOrElse("2.0")) I removed the old, then I installed the new plugin. I added your settings into project files and I was able to run it. The problem is that it doesn't see all the classes. I tried to open one of the samples and it's the same. I created an empty project. It worked like that. Still, it can't find some methods/classes/packages. Moreover, just after I create a Java Play project I get this error in NetBeans: java.lang.IllegalArgumentException: Malformed \uxxxx encoding.at java.util.Properties.loadConvert(Properties.java:568) at java.util.Properties.load0(Properties.java:391) at java.util.Properties.load(Properties.java:341) at org.netbeans.play.sbt.SbtHelper$1.run(SbtHelper.java:45) at org.openide.util.RequestProcessor$Task.run(RequestProcessor.java:1454) [catch] at org.openide.util.RequestProcessor$Processor.run(RequestProcessor.java:2048) From the default Application.java contained into the Java Play new project it doesn't find "index": package controllers; import play.*; import play.mvc.*; import views.html.*; public class Application extends Controller { public static Result index() { return ok(index.render("Your new application is ready.")); } } One more question: what about templates? Right now NetBeans doesn't seem to like it. It shows many html errors. Is it because I don't have Scala plugin installed? What does "doesn't see all the classes" mean? And what does "it can't find some methods/classes/packages"? Does it mean that code completion doesn't work for some (which?) classes? Does it mean that red error marks are shown for some (which?) classes? What does "it doesn't find 'index' mean"? Red error marks? What, exactly? "I tried to open one of the samples and it's the same." -- which sample, specifically? Can you help me by giving me steps to reproduce what you're describing? Ah, seeing the problems now -- all classpath related. Working on fixing them. Sorry for not providing all the info, but I was very tired. :) Glad to see that you found the errors. Does the plugin only support play 2? Or play 1 as well? Hi Gj, Are you using the latest package from plugins.netbeans.org? if so, it's ok. Or if it's from sourceforge.net, you'll need nbscala-7.x_2.10.x-1.6.1.1.zip instead of nbscala-7.x_2.10.x-1.6.1.zip. The newest one, I fixed some issues related to multiple sources folders under Play!, for example, managed_sources. And you may also need to clear/delete NetBeans cache so as to let NetBeans Scala module re-scan/indexing them. Will there be a play 1 plug in? I prefer using the old play 1.2.5... is this plugin could also be used for creating scala - play projects Very interesting plugin. However when trying to open the sample Play 2.1.0 projects or the project created as part of the Play TodoList tutorial I get red error marks in quite a few places in my Java classes. For example it seems to not recognise any import in play.data (although it does recognise play.mvc) as well as the routes managed class, so I get a red error mark for return redirect(routes.Application.tasks()); yea, I added some new dependencies, but no code completion. I also tried checking out and building with no sucess... I guess I'll wait for an update. Brian, can you be slightly specific so that I can try to reproduce your scenario? Hi Geertjan, can you please advise how to get rid of red errors such as import package play.data.* and using the Form class in the sample project Zentasks? Is necessary to install scala plugins for java projects? Thanks I'm having the same issues with code completion :/ Here's a screenshot of what netbeans confronts me with: It would be great if anyone could help! Thanks in advance, David Hi Geertjan, Could you add an update xml. so one can get updates as soon as they come? Hi Geertjan, I'm looking into play and having been a long-term Netbeans user, I thought things would be pretty straightforward. The first issue, outside of what you have here, is that Play's website points you to a "sbt-netbeans-plugin" that is a couple of years old and won't compile ... Second, I've installed the plugin that this page mentions and I too am having a raft of CLASSPATH issues with packages and classes not being found. I can send screen shots and more than happy to pitch-in where I can to help resolve this for the platform. Regards, Anthony has anyone been able to fix this classpath issues? Are any of the commenters here interested in contributing code to the plugin? That would help a lot to improve it, it's definitely not complete and a work in progress. Hi Geertjan, I took your challenge to contribute. I pulled the plugin code from SVN and was faxed with more "red marks" than I could poke a stick at :( Knowing that my problem was class related I went for a walk through the code... in "BootClassPathImplementation", line 55, there is a hard-coded reference to Scala 2.9.1 - My install, a recent one is 2.9.2 so I'm guess that's part of the problem. The issue then is how to avoid using hard-coded pathing like this? I'm willing to go further but I have a series of "lock" icons on each of the directories ... Anthony Hi, I am finding it tough to select the right startup book for building web applications with java (servlets and jsp) specifically in netbeans. Any body with the much needed help? I really need your help.... Thanks Hi Geertjan, thanks for your plugin, do you plan to fix the classpath issue ? It doesn't recognize stuff like : "import javax.persistence", "import play.*" "import com.avaje.ebean.*" ... Do you think we can have a working syntax highligther for scala.html template ? (I think there is a template for sublime2 here ) Hi Geertjan, Thanks for the plugin. I am interested in Java and Play development and planning to contribute to this plugin. Just one question - is this plugin forward compatible with NB 7.4 and onwards? Because, I hate to work on "legacy" stuff. Hi Geertjan, Thank you for this plugin developed. I'm a fan of NetBeans and Play framework. Unfortunately some of the files included in the creation of a Play project with this plugin are no longer compatible with the latest versions of Play as the latest Play 2.2.1 October 2013. I changed some files and give them to you below. Please could you recreate a release of this plugin with the changes that I give you, because I have no idea how to do this in NetBeans (creating a plugin). Thank you in advance. ---plugins.sbt--- // Comment to get more information during initialization logLevel := Level.Warn // The Typesafe repository resolvers += "Typesafe repository" at "" // Use the Play sbt plugin for Play projects addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.2.1") ---build.properties--- sbt.version=0.13.0 ---build.scala--- import sbt._ import Keys._ import play.Project._ object ApplicationBuild extends Build { val appName = "PlayProject3" val appVersion = "1.0-SNAPSHOT" val appDependencies = Seq( // Add your project dependencies here, javaCore ) val main = play.Project(appName, appVersion, appDependencies).settings( // Add your own project settings here ) } Hi Geertjan, Thank you for this plugin developed. I'm a fan of NetBeans and Play framework. Unfortunately some of the files included in the creation of a Play project are no longer compatible with the latest versions of Play as the latest Play 2.2.1 October 2013. I changed some files and can send you 3 files that change. Please could you recreate a release of this plugin with the changes that I give you, because I have no idea how to do this in NetBeans (create plugin). Thank you in advance. Picked up Play 2.2.1 and installed the plugin. Now, with complete respect, I understand that the plugin doesn't really support this level of Play. When I open an project (created via the "play new" command") I get and exception java.lang.NullPointerExceptionat org.netbeans.play.PlayFramework.findFile(PlayFramework.java:128) at org.netbeans.play.PlayFramework.lookupPlayJarFile(PlayFramework.java:99) . . . I tracked this down to a change the Play frameworks repository from "repository/local/play/play_2.10/" to "repository/local/com.typesafe.play/" As I think has already being mentioned, this is not the only change. Curios to know if this is the only place this might be a problem?. Hey guys, Wonderful plugin, many kudos for writing it. Due to the latest changes in Play framework, however, the path in settings for locating Play's installation folder doesn't work anymore. Consequently, the plugin cannot find the sources because 'play' command has been dropped in favor of a more generic tool called 'activator'. It would be great if the plugin is also upgraded to account for that? Thanks in advance. /O58 instralled the play plugin as of aug 27 2014, am using NB 7.4 " invalid home play path" do I need to go back to 7.3 regard rob r
https://blogs.oracle.com/geertjan/play-in-netbeans-ide-73
CC-MAIN-2018-09
refinedweb
2,106
60.92
user authentication I'm still working on this page, please no body else edit Other languages : français | ... Problem You want a system to authenticate users. Solution A user authentication system is made up of a few parts. Adding users, logging users in, logging users out and checking if users are logged in. It also requires a database. For this example we'll be using MD5 and SQLite. # import hashlib import web def POST(self): i = web.input() authdb = sqlite3.connect('users.db') pwdhash = hashlib.md5(i.password).hexdigest() check = authdb.execute('select * from users where username=? and password=?', (i.username, pwdhash)) if check: session.loggedin = True session.username = i.username raise web.seeother('/results') else: return render.base("Those login details don't work.") Notes Do not use this code on real site - this is only for illustration.
http://webpy.org/cookbook/userauth
CC-MAIN-2014-42
refinedweb
138
56.11
The first step to start doing data analysis in Python is to import your data from a certain source (in my first post we saw that pandas is great for data analysis).. This second post is different from the first one. In the first one we learned the theoretical stuff. On the other hand, this post will be more practical so I would appreciate if you code along with me. If you have any questions please feel free to use the comments section below. Note [1]: I made a Jupyter Notebook available on my GitHub with the code used in this post. Before we start This is a pandas tutorial, so the first step is to import it by typing the following in your Python runner: import pandas as pd You may have noticed that I didn't just import pandas but I also gave an alias to it. Then, everytime I need to use the pandas library I can refer to it as pd. Reading a file What is your file extension? First of all you need to know what is the file type you'll work on. It's common to have data in .csv (Comma Separated Value) files. But keep in mind that you can work with other file types, like .xls, .xlsx, .txt, .json, .html, and so on. To analyse the data, the first step is to import it from the file into a dataframe. To do this is easy with pandas since it provides functions for each file type, as you can see here. But in this post we're working with .csv files because it is one of the most common or maybe the most common. The second important thing to know is where is your file, i.e. you need to know what is the path directory of your file to allow pandas to find it. Knowing this, let's download our working file. !wget Now, open your file and make observations on it, like: Is there a head, i.e. the first line represents the column names? What is the column separator? This two questions are important to import the file into a dataframe. To do that use the read_csv() function: pd.read_csv('restaurant_orders.csv', delimiter=',') As you can see the file has no head and pandas will considerate the first line a head by default, thus let's add the column names to it. column_names = ['order_number', 'order_date', 'item_name', 'quantity', 'product_price'] pd.read_csv('restaurant_orders.csv', delimiter=',', names=column_names) Now let's store our dataframe into a variable because we'll work a lot with it. orders = pd.read_csv('restaurant_orders.csv', delimiter=',', names=column_names) Now, you can see the whole dataframe through the variable we just introduced. orders Note [2]: Did you notice how this file has so many rows (observations)? To be exact there are 74818 rows. Wow! And we are going to work with this dataset. Before we move on, pay attention to our dataset and try to understand what it means. It represents orders from Indian takeaway restaurant in London, UK. Each row is a single product within the order, i.e. one order can have more than one row. There are 5 columns: order_number, order_date, item_name, quantity, and product_price. I believe that the names are self explanatory, but if you have any questions about the dataset, let me know through the comments. You also can verify the type of orders variable. As we know, it's a DataFrame object. type(orders) Basic DataFrame operations Printing samples head and tail These functions will print the first and last rows, respectively. They are commonly used to see a sample of Series or DataFrame object. By default they will print five rows, but you can pass a number as an argument. orders.head() orders.tail() Sample It's one more function to have a sample of Series or DataFrame. However you need to pass the number as an argument and then it will sort the rows randomly. orders.sample(5) Selecting specific rows and columns Other ways to get a subset of your dataframe is by selecting a specific set of rows and columns you want. Rows To select rows you only need to pass the rows interval between brackets. It's important to highlight that pandas is based-indexing zero, i.e. the first element is zero which is included, and the last index is excluded. orders[0:7] But if you don't want to specify the begin or the end of your subset, you can simply omit this information. It will consider the first index or the last index for omitted ones, respectively. orders[:6] Columns To select columns, if you want to get a DataFrame object, use double brackets. orders[['item_name']] But if your need is to have a Series object, there are two ways to access it. orders['item_name'] orders.item_name As you'll see at the end of this post, you can chain operations and it will follow the linear logic. So you can do something like this. orders[['item_name']][:6] But I will explain it in more details in the end. .iloc, .loc The selection of rows and columns also can be made by some attributes, such as .iloc and .loc. The general syntax for these attributes is dataframe.attribute[<row selection>, <column selection>]. In these cases you can omit the <column selection>, but you need to inform the row ones. I am going to show you some examples. .iloc is based on position. orders.iloc[0:7] orders.iloc[:, 2:4] orders.iloc[-1] Note [3]: Negative index will consider from the bottom to the top. Then, in this case it returns the last row. Ah, and it works in the same logic to columns as well. Note [4]: .iloc returns a pandas Series when one row is selected, and a pandas DataFrame when multiple rows are selected or if any column in full is selected. If you want a DataFrame use double brackets. .loc is based on label. However our label for rows was not changed so by default it is the index. orders.loc[0:7, ['order_number', 'item_name']] orders.loc[[1, 3, 5], ['order_number', 'item_name']] Filtering by specific values What if you need to select rows that contain specific values? Let's say we want to select only the order 16118 to see the items of it. orders[orders.order_number == 16118] In this way we can see all the items listed for this order. But how it works? First pandas check the condition between brackets orders.order_number == 16118. If you just compile this part, it returns a pandas Series object with Boolean value where each one is the result of the condition for all rows in the dataframe. Then, in the second part orders[...] pandas prints just the correspondent rows for values that were True. It works like a 'where' clause in SQL. One more example is to filter by day. orders[(orders.order_date == '2019-08-03') | (orders.order_date == '2019-08-02')] Note [5]: In these examples I'm using the two ways to access a column in a dataframe. As I explained at the beginning of this post, I can access column using brackets or dot notation. As you probably noticed we can use some logical operators ( &, | to represent 'and', 'or') as well as comparison operators ( ==, !=, <>, <, >, <=, >=) in our conditions. Adding rows and columns In order to not compromise our dataframe, for this subsection and the next one, we'll create a copy of our dataframe and then work from it. orders_copy = orders.copy() orders_copy.head() Note [6]: To create a copy you need to use copy() function. If you just assign orders to orders_copy you are creating a reference to it which means that changing orders_copy will change orders too. Rows To add new rows to a dataframe is easy. We can use the append() function and as an argument we pass a Series list, or Dictionary to represent the row. Pay attention about the type of the values, they don't need to match with the data types of each dataframe column, but you don't want to mess up your dataframe and consequently your analysis. So be sure that you are adding the right values in the correct columns. orders_copy = orders_copy.append( pd.Series([123456, '2019-08-04', 'Product Test', 4, 1.00], index=orders_copy.columns), ignore_index=True) orders_copy.tail() It's also possible to do it by using the .loc attribute directly. Although it's not considered a good practice since you should rely more on the object API instead of changing directly their internal state. row = [12134567, '2019-08-04', 'Product Test', 4, 1.70] orders_copy.loc[len(orders_copy)] = row orders_copy.tail() Columns There are some ways to add columns in a dataframe. You can do that using list, but in this case you need to assign for each row a value. Then, in our case we'd need to create a list with 74820 values. In general we do this by assigning a function or an expression to the column. But, if you want to assign the same values for all rows, you can do this just like the example below. Let's say that all items had a discount. orders_copy['discount_pct'] = 10 orders_copy.head() It doesn't look so useful, does it? But in our case we'll use it to give the discount for each product price. So let's see the interesting part. You can use an expression to fill the column. And here we're going to create the column that represents discount through price. orders_copy['discount_price'] = (orders_copy['product_price'] * (orders_copy['discount_pct'])) / 100 orders_copy.head() So all the discount_price column is representing the discounted value for each product (row). You can also add columns using assign() function. Let's create the total discount taking into account the quantity of products. orders_copy = orders_copy.assign( discount_subtotal=lambda row: (row['quantity'] * row['discount_price'])) orders_copy.head() One more way to do add columns is through the apply() function. In this case you'll create a column using a function that will be applied for each row. Like the examples above. orders_copy['subtotal'] = orders_copy.apply( lambda row: (row['quantity'] * (row['product_price'] - row['discount_price'])), axis=1) orders_copy.head() The axis=1 means that we are working with column. Deleting rows and columns It's important to evaluate the decision of deleting something before doing it. You can do some filters to check if it's really what you want to delete. Here we are working with the dataframe copy, so we don't need to worry about that. To both, rows and columns, we use drop() function. Row Let's delete the row that we added. But before, let's check the row index. orders_copy[orders_copy.item_name == 'Product Test'] Now we know that the index is 74818. Let's drop it. orders_copy = orders_copy.drop(orders_copy.index[74818]) Check if it was deleted. orders_copy[orders_copy.index == 74818] It doesn't exist anymore. Column In the same way, let's delete the columns that were created. orders_copy = orders_copy.drop(['discount_pct', 'discount_price', 'discount_subtotal', 'subtotal'], axis=1) The axis=1 refers that it's a column, not a row. Check it is was deleted. orders_copy.head() Linear logic The pandas logic is very linear (compared to SQL, for example), you can chain operations one after the other. The input of the latter function is the output of the previous one. Let's see some examples. Get the first 3 different products bought at '2019-08-03' . Consider that the dataset is sorted by the orders. Print only the product name. orders[orders.order_date == '2019-08-03']['item_name'].head(3) First we filtered by the orders at '2019-08-03', then we selected just the product name column and finally we printed the first 3 products. Get the 3 last different products which was buying. Print the product name and the quantity. orders[['item_name','quantity']].tail(3) As you can see we selected the right columns and then we applied the tail function to get the last 3. Similarly we would first apply the tail function and then select the columns. The output would be the same. And finally, let's print the five last orders that happened on '2019-08-03' and have a 'Plain Papadum' on it. orders[(orders.order_date == '2019-08-03') & (orders.item_name == 'Plain Papadum')].tail() As you can see, in this case we used the & operator to filter our dataset. Wrapping up In this post we learned how to create a dataframe by reading a file. We saw how it is easy with pandas. We saw the main information we need to know to read a file, such as file extension, how it is organized, and the file path directory. We also learned about dataframe basic operations. Such as print sample of our dataframe; select, append and delete rows and columns; and filter specific rows through conditions. Finally, I showed to you about how to do chained operations in only one line of code, explaining about the pandas linear logic. In the next post we'll see about aggregation and grouping. How we can apply some interesting methods, like for example sum(), mean(), avg(), and grouping our dataset by a collection of elements in common. I'm looking forward to show you interesting things we can do with pandas. Dataset original reference: Takeaway Food Orders Discussion
https://practicaldev-herokuapp-com.global.ssl.fastly.net/gtrindadi/pandas-2-reading-files-and-basic-dataframe-operations-38l2
CC-MAIN-2020-50
refinedweb
2,237
66.94
Proposed features/Railway tracks on highway Proposal Notify that a section of a highway factually has some type of railway tracks running on it, and this space is shared with other vehicles, although the rails are mapped as separate ways. The value of the tag should always follow that of the railway=*-tag it shadows. Only railway=monorail should be explicitly exempted, since the monorails run above highways and never embedded in it. Also e.g. values railway=miniature and railway=funicular may see rare use, but there's no obvious reason to explicitly exempt them (see below for examples of some railway=*-tag values around the world). Rationale The railway=tram wiki page suggests mapping tramway tracks always alongside highways as a separate way (though possibly using the same nodes as the highway) even if they in fact run on the highway. There are many good reasons for this convention and it need not be changed. There are also cases where a subway rails (railway=subway) or a railway railway=rail, (see e.g.: here. Thank you to user Graeme Fitzpatrick for noticing this!) run embedded on a highway. Other traffic should be notified that there is a track, physically, running on the highway. The need for such notification is particularly acute for bicycles, mopeds and other vehicles that have narrow tyres. Railway tracks have deep indentations that narrow wheels can easily and dangerously slip into. This danger alone warrants a note to routing programs so that they can avoid routing e.g. bicycles through such streets. Because the tracks are mapped as separate ways, a new tag is needed for the highway. One earlier proposal was to map these highways with a bicycle access-tag (since the current proposal somewhat resembles the bicycle=use_sidepath-tag), but this was wisely deemed as too narrow a tagtype for this use. Also the tag-value proposal of railway=separately_mapped received mixed approval in voting because it was thought that it e.g. misused already existing tag-namespace and would have been confusing regarding rendering. The current tag-value proposal was originally suggested by users Mateusz Konieczny and Rainero, thank you to both! See the previous proposal and votes here Examples Tagging Tagging is applicable only to highways on which there in fact are tracks. If the tracks run on a physically separate lane between highways or next to a highway, these adjacent highways should not be tagged. So, for example If only a subset of lanes on a multi-lane highway have embedded tracks, this can be handled as usual with the lanes-tagging scheme. Applies to Ways. Nodes do not warrant a notification since a highway running (even almost) tangentially to or intersecting with tracks does not pose the danger mentioned above to narrow tyres. Rendering No need to render as the existence of the railways is obvious in a glance of the map, but routing programs need this extra tag. Features/Pages affected External discussions Please comment on the discussion page. Voting Voting on this proposal has been closed. It was approved with 21 votes for, 1 vote against and 1 abstention. The feature was approved, but the community raised some issues. See the Follow-up proposal I approve this proposal. --EneaSuper (talk) 09:51, 21 January 2019 (UTC) I approve this proposal. --Dr Centerline (talk) 01:49, 12 January 2019 (UTC) I approve this proposal. --Tolstoi21 (talk) 09:14, 12 January 2019 (UTC) I approve this proposal. –SelfishSeahorse (talk) 10:59, 12 January 2019 (UTC) I approve this proposal. --حبيشان (talk) 13:20, 15 January 2019 (UTC) I approve this proposal. --AgusQui (talk) 03:32, 17 January 2019 (UTC) I approve this proposal. --Michalfabik (talk) 08:18, 20 January 2019 (UTC) I approve this proposal. --Hholzgra (talk) 09:03, 20 January 2019 (UTC) I approve this proposal. okay --Zverik (talk) 11:36, 20 January 2019 (UTC) I have comments but abstain from voting on this proposal. There are important pieces of information missing. How is this scheme supposed to play along with lanes and lanes tagging? If there are several lanes on a road, it is important information which of the lanes is shared with rails (e.g. are they in the bus lane? Are bicycles forced to cross the rails).The proposal also completely lacks any examples of tagging. --Mueschel (talk) 14:17, 20 January 2019 (UTC) - Thank you for your input! However, did you notice that the proposal did suggest that if only a subset of lanes in a multi-lane highway has embedded rails, this could be handled as usual with the lanes tagging scheme. Also the question of crossing was considered to be moot (tagging applies only to ways, not nodes), since the motivating worry of deep indentations in the railway tracks does not pose a problem if one crosses them even close to perpendicularly (in a 90 degree angle.) --Tolstoi21 (talk) 14:34, 20 January 2019 (UTC) - Thanks, this was hard to spot under the images. I changed my vote. My comment on examples still holds as it will improve clarity. --Mueschel (talk) 14:43, 20 January 2019 (UTC) - You are indeed right about the clarity issue! In the event that the vote passes for the proposal, the eventual wiki page will have to be quite fundamentally restructred from this proposal page and made much more explicit and clear. I'll also add clear example cases for the lanes-tagging. Thank you for pointing this out. --Tolstoi21 (talk) 08:25, 21 January 2019 (UTC) I approve this proposal. --Ropino (talk) 17:18, 20 January 2019 (UTC) I approve this proposal. --Nospam2005 (talk) 20:05, 20 January 2019 (UTC) I approve this proposal. I like the more detailed proposal :) --Rainero (talk) 22:14, 20 January 2019 (UTC) I approve this proposal. --Robert46798 (talk) 07:37, 21 January 2019 (UTC) I approve this proposal. --Kazing (talk) 08:57, 21 January 2019 (UTC) I approve this proposal. although I have to agree with Mueschel that you could have made it clearer which new tag is proposed (repeat it in the text) and could havbe tried to better prevent confusion about the older ideas (remove tag template from railway=separately_mapped) --Dieterdreist (talk) 10:07, 21 January 2019 (UTC) I approve this proposal. --Gallseife (talk) 13:09, 21 January 2019 (UTC) I approve this proposal. --TheBlackMan (talk) 13:36, 21 January 2019 (UTC) I approve this proposal. --CMartin (talk) 17:30, 21 January 2019 (UTC) I approve this proposal. This is relevant information for bicycle routing and it would be great to be able to map this! Please provide more complete tagging examples though. --Evod (talk) 08:44, 22 January 2019 (UTC) I approve this proposal. --Pathmapper (talk) 18:21, 23 January 2019 (UTC) I approve this proposal. I see no problems --Mateusz Konieczny (talk) 13:16, 24 January 2019 (UTC) I oppose this proposal. Such a tag should not shadow (copy) any information given by other tags. This proposal does not provide a definition of the proposed values (abandoned/construction/...) in resepect of the new tag. As far as I understand, a embedded_rails=yes should be enough for the intended purpose. I oppose indroducing tags more complex than necessary or with vaguely defined meaning. --Halbtax (talk) 16:19, 25 January 2019 (UTC) Follow-up Proposal The proposal was accepted, but there were some issues raised. Thank you again very much to everyone who voted, commented and/or participated in the discussion on the mailing list! The main issue raised was that the proposal page was, rightfully, seen as somewhat lacking in clarity and detail. It has become obvious that the eventual wiki page for the feature will have to be completely restructured from the proposal page to make all the features of the proposal clearer. This will take me some time to complete. In the following days I will create the wiki page, following the highway-key page as a template (as proposed in the Proposal_process page). I'll add entries and examples of all the different key values in the proposal. I will also add an explicit entry and an example on lanes tagging, where only a subset of lanes have embedded tracks. After the wiki page is complete, I will add links and a short description to the feature to the railway wiki page, and a very short (perhaps one-line) description and link to all the railway-tag key pages (railway=rail, railway=subway, etc).
https://wiki.openstreetmap.org/wiki/Proposed_features/Railway_tracks_on_highway
CC-MAIN-2021-04
refinedweb
1,411
63.7
[ ] Nguyen Thanh Son Daniel commented on DIGESTER-120: -------------------------------------------------- Simon, 1- The parser being used is identified by the following maven artifact: groupId: xerces artifactId: xercesImpl version: 2.6.2 also, stepping in the code reveals that it is the parser being used. 2- i am not aware of the location where i should be getting the patch. can you let me know how i should proceed to access your patch ? > digesting xml content with NodeCreateRule swallows spaces. > ---------------------------------------------------------- > > Key: DIGESTER-120 > URL: > Project: Commons Digester > Issue Type: Bug > Affects Versions: 1.8 > Environment: jdk 1.4.2_08, digester 1.8 > Reporter: Nguyen Thanh Son Daniel > Attachments: digester-patch.txt > > > i need to process an xml file that contains entities: ie: > <?xml version="1.0" encoding="UTF-8"?> > <top> > <body>A A</body> > </top> > i'm using digester as follows: > Digester digester = new Digester (); > digester.addRule ("top", new ObjectCreateRule (MyContent.class)); > digester.addRule ("top/body", new NodeCreateRule ()); > digester.addSetNext ("top/body", "setBody"); > then > ... > digester.parse (file); > MyContent class transforms the node into text as follows: > public class MyContent > { > public void setBody (Element node) > { > String content = serializeNode (node); > System.out.println (content); > } > ... > } > the content displayed is in this case: <body>AA</body> > if the body was encoded in the xml file as: <top><body>A A</body></top>, the content would then be correctly displayed as: > <body>A A</body> > looking at the NodeCreateRule.NodeBuilder.characters () implementation, the following code generates the problem: > String str = new String(ch, start, length); > if (str.trim().length() > 0) { > top.appendChild(doc.createTextNode(str)); > when entities are being used; the characters () method is called for 'A', ' ' and 'A' in the first case. in the second case, it is called once with 'A A'. -- This message is automatically generated by JIRA. - You can reply to this email to add a comment to the issue online.
http://mail-archives.apache.org/mod_mbox/commons-issues/200803.mbox/%3C61476373.1205589864584.JavaMail.jira@brutus%3E
CC-MAIN-2015-27
refinedweb
307
59.3
Consistently, one of the more popular stocks people enter into their stock options watchlist at Stock Options Channel is American Capital Agency Corp (Symbol: AGNC). So this week we highlight one interesting put contract, and one interesting call contract, from the January 2016 expiration for AGNC. The put contract our YieldBoost algorithm identified as particularly interesting, is at the $17 strike, which has a bid at the time of this writing of 34 cents. Collecting that bid as the premium represents a 2% return against the $17 commitment, or a 3.4% annualized rate of return (at Stock Options Channel we call this the YieldBoost ). Selling a put does not give an investor access to AGNC's upside potential the way owning shares would, because the put seller only ends up owning shares in the scenario where the contract is exercised. So unless American Capital Agency Corp sees its shares fall 14.7% and the contract is exercised (resulting in a cost basis of $16.66 per share before broker commissions, subtracting the 34 cents from $17), the only upside to the put seller is from collecting that premium for the 3.4% annualized rate of return. Turning to the other side of the option chain, we highlight one call contract of particular interest for the January 2016 expiration, for shareholders of American Capital Agency Corp (Symbol: AGNC) looking to boost their income beyond the stock's 12.1% annualized dividend yield. Selling the covered call at the $20 strike and collecting the premium based on the 54 cents bid, annualizes to an additional 4.6% rate of return against the current stock price (this is what we at Stock Options Channel refer to as the YieldBoost ), for a total of 16.7% annualized rate in the scenario where the stock is not called away. Any upside above $20 would be lost if the stock rises there and is called away, but AGNC shares would have to climb 0.3% American Capital Agency Corp, highlighting in green where the $17 strike is located relative to that history, and highlighting the $20 strike in red: American Capital Agency Corp (considering the last 252 trading day AGNC historical stock prices using closing values, as well as today's price of $19.92) to be 14%. In mid-afternoon trading on Monday, the put volume among S&P 500 components was 866,115 contracts, with call volume at 866,115, AGNC.
https://www.nasdaq.com/articles/one-put-one-call-option-know-about-american-capital-agency-2015-06-15
CC-MAIN-2019-47
refinedweb
408
59.03
SQL Server Backup and Restore - Blaze Walton - 2 years ago - Views: Transcription 1 The Red Gate Guide SQL Server Backup and Restore Shawn McGehee ISBN: 2 SQL Server Backup and Restore By Shawn McGehee First published by Simple Talk Publishing April 2012 3 Copyright April 2012 ISBN The right of Shawn McGehee to be identified as the author of this work has been asserted by him in accordance with the Copyright, Designs and Patents Act that in which it is published and without a similar condition including this condition being imposed on the subsequent publisher. Technical Review by Eric Wisdahl Cover Image by Andy Martin Edited by Tony Davis Typeset & Designed by Peter Woodhouse & Gower Associates 4 Table of Contents Introduction 12 Software Requirements and Code Examples 18 Chapter 1: Basics of Backup and Restore 19 Components of a SQL Server Database 20 Data files 20 Filegroups 22 Transaction log 24 SQL Server Backup Categories and Types 28 SQL Server database backups 29 SQL Server transaction log backups 32 File backups 36 Recovery Models 39 Simple 41 Full 43 Bulk Logged 44 Restoring Databases 46 Restoring system databases 47 Restoring single pages from backup 48 Summary 49 Chapter 2: Planning, Storage and Documentation 50 Backup Storage 50 Local disk (DAS or SAN) 52 Network device 58 Tape 59 Backup Tools 60 5 Maintenance plan backups 61 Custom backup scripts 62 Third-party tools 63 Backup and Restore Planning 64 Backup requirements 65 Restore requirements 68 An SLA template 69 Example restore requirements and backup schemes 71 Backup scheduling 73 Backup Verification and Test Restores 75 Back up WITH CHECKSUM 76 Verifying restores 77 DBCC CHECKDB 77 Documenting Critical Backup Information 78 Summary 83 Chapter 3: Full Database Backups 84 What is a Full Database Backup? 84 Why Take Full Backups? 85 Full Backups in the Backup and Restore SLA 86 Preparing for Full Backups 87 Choosing the recovery model 88 Database creation 88 Creating and populating the tables 94 Taking Full Backups 96 Native SSMS GUI method 97 Native T-SQL method 106 Native Backup Compression 111 6 Verifying Backups 113 Building a Reusable and Schedulable Backup Script 114 Summary 115 Chapter 4: Restoring From Full Backup 116 Full Restores in the Backup and Restore SLA 116 Possible Issues with Full Database Restores 117 Large data volumes 118 Restoring databases containing sensitive data 118 Too much permission 120 Performing Full Restores 122 Native SSMS GUI full backup restore 122 Native T-SQL full restore 129 Forcing Restore Failures for Fun 133 Considerations When Restoring to a Different Location 136 Restoring System Databases 137 Restoring the msdb database 138 Restoring the master database 140 Summary 143 Chapter 5: Log Backups 144 A Brief Peek Inside a Transaction Log 145 Three uses for transaction log backups 148 Performing database restores 149 Large database migrations 150 Log shipping 151 Log Backups in the Backup and Restore SLA 152 7 Preparing for Log Backups 153 Choosing the recovery model 154 Creating the database 155 Creating and populating tables 157 Taking a base full database backup 159 Taking Log Backups 161 The GUI way: native SSMS log backups 161 T-SQL log backups 166 Forcing Log Backup Failures for Fun 170 Troubleshooting Log Issues 172 Failure to take log backups 173 Other factors preventing log truncation 174 Excessive logging activity 175 Handling the 9002 Transaction Log Full error 176 Log fragmentation 177 Summary 181 Chapter 6: Log Restores 182 Log Restores in the SLA 182 Possible Issues with Log Restores 183 Missing or corrupt log backup 183 Missing or corrupt full backup 184 Minimally logged operations 184 Performing Log Restores 187 GUI-based log restore 188 T-SQL point-in-time restores 194 Possible difficulties with point-in-time restores 198 Forcing Restore Failures for Fun 200 Summary 204 8 Chapter 7: Differential Backup and Restore 205 Differential Backups, Overview 206 Advantages of differential backups 207 Differential backup strategies 208 Possible issues with differential backups 212 Differentials in the backup and restore SLA 215 Preparing for Differential Backups 216 Recovery model 216 Sample database and tables plus initial data load 217 Base backup 218 Taking Differential Backups 218 Native GUI differential backup 219 Native T-SQL differential backup 221 Compressed differential backups 223 Performing Differential Backup Restores 225 Native GUI differential restore 225 Native T-SQL differential restore 227 Restoring compressed differential backups 230 Forcing Failures for Fun 231 Missing the base 231 Running to the wrong base 232 Recovered, already 235 Summary 237 Chapter 8: Database Backup and Restore with SQL Backup Pro _238 Preparing for Backups 238 Full Backups 241 SQL Backup Pro full backup GUI method 241 SQL Backup Pro full backup using T-SQL 253 9 Log Backups 256 Preparing for log backups 256 SQL Backup Pro log backups 258 Differential Backups 261 Building a reusable and schedulable backup script 263 Restoring Database Backups with SQL Backup Pro 267 Preparing for restore 267 SQL Backup Pro GUI restore to the end of a log backup 269 SQL Backup Pro T-SQL complete restore 277 SQL Backup Pro point-in-time restore to standby 279 Restore metrics: native vs. SQL Backup Pro 289 Verifying Backups 291 Backup Optimization 292 Summary 294 Chapter 9: File and Filegroup Backup and Restore 295 Advantages of File Backup and Restore 296 Common Filegroup Architectures 298 File Backup 303 Preparing for file backups 306 SSMS native full file backups 309 Native T-SQL file differential backup 310 SQL Backup Pro file backups 314 File Restore 318 Performing a complete restore (native T-SQL) 321 Restoring to a point in time (native T-SQL) 326 Restoring after loss of a secondary data file 328 Quick recovery using online piecemeal restore 335 10 Common Issues with File Backup and Restore 340 File Backup and Restore SLA 341 Forcing Failures for Fun 343 Summary 346 Chapter 10: Partial Backup and Restore 348 Why Partial Backups? 349 Performing Partial Database Backups 350 Preparing for partial backups 351 Partial database backup using T-SQL 354 Differential partial backup using T-SQL 355 Performing Partial Database Restores 357 Restoring a full partial backup 357 Restoring a differential partial backup 359 Special case partial backup restore 360 SQL Backup Pro Partial Backup and Restore 362 Possible Issues with Partial Backup and Restore 364 Partial Backups and Restores in the SLA 365 Forcing Failures for Fun 366 Summary 367 Appendix A: SQL Backup Pro Installation and Configuration_ 368 SQL Backup Pro GUI Installation 368 SQL Backup Pro Services Installation 370 SQL Backup Pro Configuration 376 File management 376 settings 378 11 About the author Shawn McGehee Shawn. Shawn is also a contributing author on the Apress book, Pro SQL Server Reporting Services Acknowledgements I would like to thank everyone who helped and supported me through the writing of this book. I would especially like to thank my editor, Tony Davis, for sticking with me during what was a long and occasionally daunting process, and helping me make my first single-author book a reality. I also need to give a special thank you to all of my close friends and family for always being there for me during all of life's adventures, good and bad. Shawn McGehee About the technical reviewer Eric Wisdahl Eric is a development DBA working in the e-commerce industry. He spends what little free time he has reading, playing games, or spending time with his wife and dogs. In a past life he has worked as an ETL/BI Specialist in the insurance industry, a pizza boy, patent examiner, Pro-IV code monkey and.net punching bag. xi 12 Introduction My first encounter with SQL Server, at least from an administrative perspective, came while I was still at college, working in a small web development shop. We ran a single SQL Server 6.5 instance, on Windows NT, and it hosted every database for every client that the company serviced. There was no dedicated administration team; just a few developers and the owner. One day, I was watching and learning from a fellow developer while he made code changes to one of our backend administrative functions. Suddenly, the boss stormed into the room and demanded everyone's immediate attention. Whatever vital news he had to impart is lost in the sands of time, but what I do remember is that when the boss departed, my friend returned his attention to the modified query and hit Execute, an action that was followed almost immediately by a string of expletives so loud they could surely have been heard several blocks away. Before being distracted by the boss, he'd written the DELETE portion of a SQL statement, but not the necessary WHERE clause and, upon hitting Execute, he had wiped out all the data in a table. Fortunately, at least, he was working on a test setup, with test data. An hour later we'd replaced all the lost test data, no real harm was done and we were able to laugh about it. As the laughter subsided, I asked him how we would have gotten that data back if it had been a live production database for one of the clients or, come to think of it, what we would do if the whole server went down, with all our client databases on board. He had no real answer, beyond "Luckily it's never happened." There was no disaster recovery plan; probably because there were no database backups that could be restored! It occurred to me that if disaster ever did strike, we would be in a heap of trouble, to the point where I wondered if the company as a whole could even survive such an event. It was a sobering thought. That evening I did some online research on database backups, and the very next day performed a full database backup of every database on our server. A few days later, I had 12 13 Introduction jobs scheduled to back up the databases on a regular basis, to one of the local hard drives on that machine, which I then manually copied to another location. I told the boss what I'd done, and so began my stint as the company's "accidental DBA." Over the coming weeks and months, I researched various database restore strategies, and documented a basic "crash recovery" plan for our databases. Even though I moved on before we needed to use even one of those backup files, I felt a lot better knowing that, with the plan that I'd put in place, I left the company in a situation where they could recover from a server-related disaster, and continue to thrive as a business. This, in essence, is the critical importance of database backup and restore: it can mean the difference between life or death for a business, and for the career of a DBA. The critical importance of database backup and restore The duties and responsibilities of a Database Administrator (DBA) make at the top of every administrative DBA's list of tasks. 13 14 Introduction Such a plan needs to be developed for each and every user database in your care, as well as supporting system databases, and it should be tailored to the specific requirements of each database, based on the type of data being stored (financial, departmental, personal, and so on), the maximum acceptable risk of potential data loss (day? hour? minute?), and the maximum acceptable down-time in the event of a disaster. Each of these factors will help decide the types of backup required, how often they need to be taken, how many days' worth of backup files need to be stored locally, and so on. All of this should be clearly documented so that all parties, both the DBAs and application/ database owners, understand the level of service that is expected for each database, and what's required in the plan to achieve it. At one end of the scale, for a non-frontline, infrequently-modified database, the backup and recovery scheme may be simplicity itself, involving a nightly full database backup, containing a complete copy of all data files, which can be restored if and when necessary. At the opposite end of the scale, a financial database with more or less zero tolerance to data loss will require a complex scheme consisting of regular (daily) full database backups, probably interspersed with differential database backups, capturing all changes since the last full database backup, as well as very regular transaction log backups, capturing the contents added in the database log file, since the last log backup. For very large databases (VLDBs), where it may not be possible to back up the entire database in one go, the backup and restore scheme may become more complex still, involving backup of individual data files, for filegroups, as well as transaction logs. All of these backups will need to be carefully planned and scheduled, the files stored securely, and then restored in the correct sequence, to allow the database to be restored to the exact state in which it existed at any point in time in its history, such as the point just before a disaster occurred. It sounds like a daunting task, and if you are not well prepared and well practiced, it will be. However, with the tools, scripts, and techniques provided in this book, and with the requisite planning and practice, you will be prepared to respond quickly and efficiently to a disaster, whether it's caused by disk failure, malicious damage, database corruption or the accidental deletion of data. This book will walk you step by step through the process of capturing all types of backup, from basic full database backups, to transaction log 14 15 Introduction backups, to file and even partial backups. It will demonstrate how to perform all of the most common types of restore operation, from single backup file restores, to complex point-in-time restores, to recovering a database by restoring just a subset of the files that make up the database. As well as allowing you to recover a database smoothly and efficiently in the face of one of the various the "doomsday scenarios," your well-rounded backup and recovery plan, developed with the help of this book, will also save you time and trouble in a lot of other situations including, but not limited to those below. Refreshing development environments periodically, developers will request that their development environments be refreshed with current production data and objects. Recovering from partial data loss occasionally, a database has data "mysteriously disappear from it." Migrating databases to different servers you will eventually need to move databases permanently to other servers, for a variety of reasons. The techniques in this book can be used for this purpose, and we go over some ways that different backup types can cut down on the down-time which this process may cause. Offloading reporting needs reporting on data is becoming more and more of a high priority in most IT shops. With techniques like log shipping, you can create cheap and quick reporting solutions that can provide only slightly older reporting data than High Availability solutions. I learned a lot of what I know about backup and restore the hard way, digging through innumerable articles on Books Online, and various community sites. I hope my book will serve as a place for the newly-minted and accidental DBA to get a jump on backups and restores. It can be a daunting task to start planning a Backup and Restore SLA from scratch, even in a moderately-sized environment, and I hope this book helps you get a good start. 15 16 Introduction How the book is structured. Broadly, the book breaks down into four sections. Prerequisites everything you need to know and consider before you start performing backup and restore. Chapter 1 describes the data and log files that comprise a database, and all the basic types of backup that are possible for these file, and explains the available database recovery models and what they mean. Chapter 2 takes a detailed look at all of the major aspects of planning a backup and recovery strategy, from choosing and configuring hardware, gathering and documenting the requirements for each database, selecting the appropriate backup tool, scheduling considerations, running backup verification checks, and more. Basic backup and restore how to capture and restore all of the basic backup types, using SSMS and T-SQL. Chapters 3 and 4 cover how to take standard and compressed full database backups, and restore them. 16 17 Introduction Chapters 5 and 6 cover how to take transaction log backups, and then use them in conjunction with a full database backup to restore a database to a particular point in time. They also cover common transaction log problems and how to resolve them. Chapter 7 covers standard and compressed differential database backup and restore. Basic backup and restore with SQL Backup how to capture and restore all basic backup types using Red Gate SQL Backup. Chapter 8 third-party tools such as Red Gate SQL backup aren't free, but they do offer numerous advantages in terms of the ease with which all the basic backups can be captured, automated, and then restored. Many organizations, including my own, rely on such tools for their overall backup and restore strategy. Advanced backup and restore how to capture and restore file and filegroup backups, and partial database backups. Chapter 9 arguably the most advanced chapter in the book, explaining the filegroup architectures that enable file-based backup and restore, and the complex process of capturing the necessary file backups and transaction log backups, and using them in various restore operations. Chapter 10 a brief chapter on partial database backups, suitable for large databases with a sizeable portion of read-only data. Finally, Appendix A provides a quick reference on how to download, install, and configure the SQL Backup tool from Red Gate Software, so that you can work through any examples in the book that use this tool. 17 18 Introduction Who this book is for This book is targeted toward the novice Database Administrator with less than a year of experience, and toward what I call "accidental" or "inheritance" DBAs, who are those who have inherited the duties of a DBA, by luck or chance, without any training or prior experience. If you have some experience, feel free to skip through some of the more basic topics and head to the more advanced sections. If you are one of our newly-minted DBA brothers and sisters, or someone who's had these duties thrust upon you unexpectedly, reading these prerequisite and basic sections will be a very worthwhile task. Software Requirements and Code Examples Throughout this book are scripts demonstrating various ways to take and restore backups, using either native T-SQL or SQL Backup scripts. All the code you need to try out the examples in this book can be obtained from the following URL: Examples in this book were tested on SQL Server 2008 and SQL Server 2008 R2 Standard Edition, with the exception of the online piecemeal restore in Chapter 9, which requires Enterprise Edition. Red Gate SQL Backup v was used in all SQL Backup examples, in Chapters 8 and 9 of this book. 18 19 Chapter 1: Basics of Backup and Restore Before we dive into the mechanisms for taking and restoring backups, we need to start with a good basic understanding of the files that make up a SQL Server database, what they contain, how and when they can be backed up, and the implications this has with regard to potential data loss in the event of a disaster in which a database is damaged, or specific data accidentally lost, and needs to be restored. Specifically, in this chapter, we will cover: components of a SQL Server database primary and secondary files and filegroups, plus log files how SQL Server uses the transaction log and its significance in regard to restore capabilities possible types of SQL Server backup full and differential database backups, transaction log backups and file backups SQL Server database recovery models the available recovery models and what they mean in terms of backups restoring databases the various available types of database restore, plus special restores, such as system database restores. 19 20 Chapter 1: Basics of Backup and Restore Components of a SQL Server Database Ultimately, a relational database is simply a set of files that store data. When we make backups of these files, we capture the objects and data within those files and store them in a backup file. So, put simply, a database backup is just a copy of the database as it existed at the time the backup was taken. Before we dive into the backup files themselves, however, we need to briefly review the files that comprise a SQL Server database. At its simplest, a database is composed of two files, both created automatically upon execution of a CREATE DATABASE command: a data file and a log file. However, in larger, more complex databases, the data files may be broken down into multiple filegroups, each one containing multiple files. Let's discuss each of these components in a little more detail; we won't be delving too deep right now, but we need at least to cover what each file contains and what roles it plays in a day-to-day database backup and recovery strategy. Data files Data files in a SQL Server database refer to the individual data containers that are used to store the system and user-defined data and objects. In other words, they contain the data, tables, views, stored procedures, triggers and everything else that is accessed by you, and your end-users and applications. These files also include most of the system information about your database, including permission information, although not including anything that is stored in the master system database.; if you enjoy confusing your fellow DBAs, you can apply any extensions you wish to these files. 20 21 Chapter 1: Basics of Backup and Restore The primary data file will contain: all system objects and data by default, all user-defined objects and data (assuming that only the MDF file exists in the PRIMARY filegroup) the location of any secondary data files. Many of the databases we'll create in this book will contain just a primary data file, in the PRIMARY filegroup, although in later chapters we'll also create some secondary data files to store user-defined objects and data. Writes to data files occur in a random fashion, as data changes affect random pages stored in the database. As such, there is a potential performance advantage to be had from being able to write simultaneously to multiple data files. Any secondary data files are typically denoted with the NDF extension, and can be created in the PRIMARY filegroup or in separate user-defined filegroups (discussed in more detail in the next section). When multiple data files exist within a single filegroup, SQL Server writes to these files using a proportional fill algorithm, where the amount of data written to a file is proportionate to the amount of free space in that file, compared to other files in the filegroup. Collectively, the data files for a given database are the cornerstone of your backup and recovery plan. If you have not backed up your live data files, and the database becomes corrupted or inaccessible in the event of a disaster, you will almost certainly have lost some or all of your data. As a final point, it's important to remember that data files will need to grow, as more data is added to the database. The manner in which this growth is managed is often a point of contention among DBAs. You can either manage the growth of the files manually, adding space as the data grows, or allow SQL Server to auto-grow the files, by a certain value or percentage each time the data file needs more space. Personally, I advocate leaving auto-growth enabled, but on the understanding that files are sized initially to cope with current data and predicted data growth (over a year, say) without undergoing an excessive 21 22 Chapter 1: Basics of Backup and Restore number of auto-growth events. We'll cover this topic more thoroughly in the Database creation section of Chapter 3, but for the rest of the discussion here, we are going to assume that the data and log files are using auto-growth. Filegroups A filegroup is simply a logical collection of one or more data files. Every filegroup can contain one or more data files. When data is inserted into an object that is stored in a given filegroup, SQL Server will distribute that data evenly across all data files in that filegroup. For example, let's consider the PRIMARY filegroup, which in many respects is a "special case." The PRIMARY filegroup will always be created when you create a new database, and it must always hold your primary data file, which will always contain the pages allocated for your system objects, plus "pointers" to any secondary data files. By default, the PRIMARY filegroup is the DEFAULT filegroup for the database and so will also store all user objects and data, distributed evenly between the data files in that filegroup. However, it is possible to store some or all of the user objects and data in a separate filegroup. For example, one commonly cited best practice with regard to filegroup architecture is to store system data separately from user data. In order to follow this practice, we might create a database with both a PRIMARY and a secondary, or user-defined, filegroup, holding one or more secondary data files. All system objects would automatically be stored in the PRIMARY data file. We would then ALTER the database to set the secondary filegroup as the DEFAULT filegroup for that database. Thereafter, any user objects will, by default, be stored in that secondary filegroup, separately from the system objects.. 22 23 Chapter 1: Basics of Backup and Restore CREATE TABLE TableName ( ColumnDefinitionList ) ON [SecondaryFilegroupName] Any data files in the secondary filegroup can, and typically will, be stored on separate physical storage from those in the PRIMARY filegroup. When a BACKUP DATABASE command is issued it will, by default, back up all objects and data in all data files in all filegroups. However, it's possible to specify that only certain filegroups, or specific files within a filegroup are backed up, using file or filegroup backups (covered in more detail later in this chapter, and in full detail in Chapter 9, File and Filegroup Backup and Restore). It's also possible to perform a partial backup (Chapter 10, Partial Backup and Restore), excluding any read-only filegroups. Given these facts, there's a potential for both performance and administrative benefits, from separating your data across filegroups. For example, if we have certain tables that are exclusively read-only then we can, by storing this data in a separate filegroup, exclude this data from the normal backup schedule. After all, performing repeated backups of data that is never going to change is simply a waste of disk space. If we have tables that store data that is very different in nature from the rest of the tables, or that is subject to very different access patterns (e.g. heavily modified), then there can be performance advantages to storing that data on separate physical disks, configured optimally for storing and accessing that particular data. Nevertheless, it's my experience that, in general, RAID (Redundant Array of Inexpensive Disks) technology and SAN (Storage Area Network) devices (covered in Chapter 2) automatically do a much better job of optimizing disk access performance than the DBA can achieve by manual placement of data files. Also, while carefully designed filegroup architecture can add considerable flexibility to your backup and recovery scheme, it will also add administrative burden. There are certainly valid reasons for using secondary files and filegroups, such as separating system and user data, and there are certainly cases where they might be a necessity, for example, 23 24 Chapter 1: Basics of Backup and Restore for databases that are simply too large to back up in a single operation. However, they are not required on every database you manage. Unless you have experience with them, or know definitively that you will gain significant performance with their use, then sticking to a single data file database will work for you most of the time (with the data being automatically striped across physical storage, via RAID). Finally, before we move on, it's important to note that SQL Server transaction log files are never members of a filegroup. Log files are always managed separately from the SQL Server data files. Transaction log A transaction log file contains a historical account of all the actions that have been performed on your database. All databases have a transaction log file, which is created automatically, along with the data files, on creation of the database and is conventionally denoted with the LDF extension. It is possible to have multiple log files per database but only one is required. Unlike data files, where writes occur in a random fashion, SQL Server always writes to the transaction log file sequentially, never in parallel. This means that it will only ever write to one log file at a time, and having more than one file will not boost write-throughput or speed. In fact, having more multiple files could result in performance degradation, if each file is not correctly sized or differs in size and growth settings from the others. Some inexperienced DBAs don't fully appreciate the importance of the transaction log file, both to their backup and recovery plan and to the general day-to-day operation of SQL Server, so it's worth taking a little time out to understand how SQL Server uses the transaction log (and it's a topic we'll revisit in more detail in Chapter 5, Log Backups). Whenever a modification is made to a database object (via Data Definition Language, DDL), or the data it contains (Data Manipulation Language, DML), the details of the change are recorded as a log record in the transaction log. Each log record contains 24 25 Chapter 1: Basics of Backup and Restore details of a specific action within the database (for example, starting a transaction, or inserting a row, or modifying a row, and so on). Every log record will record the identity of the transaction that performed the change, which pages were changed, and the data changes that were made. Certain log records will record additional information. For example, the log record recording the start of a new transaction (the LOP_BEGIN_XACT log record) will contain the time the transaction started, and the LOP_COMMIT_XACT (or LOP_ABORT_XACT) log records will record the time the transaction was committed (or aborted). From the point of view of SQL Server and the DBA looking after it, the transaction log performs the following critical functions: ensures transactional durability and consistency enables, via log backups, point-in-time restore of databases.. As noted previously, the database's log file provides a record of all transactions performed against that database. When a data modification is made, the relevant data pages are read from the data cache, first being retrieved from disk if they are not already in the cache. Data is modified in the data cache, and the log records describing the effects of the transaction are created in the log cache. Any page in the cache that has been modified since being read from disk is called a "dirty" page. When a periodic CHECKPOINT operation occurs, all dirty pages, regardless of whether they relate to committed or uncommitted transactions, are flushed to disk. The WAL protocol dictates that, before a data page is 25 26 Chapter 1: Basics of Backup and Restore modified in non-volatile storage (i.e. on disk), the description of the change must first be "hardened" to stable storage. SQL Server or, more specifically, the buffer manager, makes sure that the change descriptions (log records) are written to the physical transaction log file before the data pages are written to the physical data files. The Lazy Writer Another process that scans the data cache, the Lazy Writer, may also write dirty data pages to disk, outside of a checkpoint, if forced to do so by memory pressures. By always writing changes to the log file first, SQL Server. This process of reconciling the contents of the data and log files occurs during the database recovery process (sometimes called Crash Recovery), which is initiated automatically whenever SQL Server restarts, or as part of the RESTORE command. Say, for example, a database crashes after a certain transaction (T1) is "hardened" to the transaction log file, but before the actual data is written from memory to disk. When the database restarts, a recovery process is initiated, which reconciles the data file and log file. All of the operations that comprise transaction T1, recorded in the log file, will be "rolled forward" (redone) so that they are reflected in the data files. During this same recovery process, any data modifications on disk that originate from incomplete transactions, i.e. those for which neither a COMMIT nor a ROLLBACK have been issued, are "rolled back" (undone), by reading the relevant operations from the log file, and performing the reverse physical operation on the data. More generally, this rollback process occurs if a ROLLBACK command is issued for an explicit transaction, or if an error occurs and XACT_ABORT is turned on, or if the database detects that communication has been broken between the database and the client that instigated the 26 27 Chapter 1: Basics of Backup and Restore transactions., and so guarantees data consistency and integrity during normal day-to-day operation. Log backups and point-in-time restore As we've discussed, each log record contains the details of a specific change that has been made to the database, allowing that change to be performed again as a part of REDO, or undone as a part of UNDO, during crash recovery. Once captured in a log backup file, the log records can be subsequently applied to a full database backup in order to perform a database restore, and so re-create the database as it existed at a previous point in time, for example right before a failure. As such, regular backups of your log files are an essential component of your database backup and restore strategy for any database that requires point-in-time restore. The other very important reason to back up the log is to control its size. Since your log file has a record of all of the changes that have been made against it, it will obviously take up space. The more transactions that have been run against your database, the larger this log file will grow. If growth is left uncontrolled, the log file may even expand to the point where it fills your hard drive and you receive the dreaded "9002 (transaction log full)" error, and the database will become read-only, which we definitely do not want to happen. We'll discuss this in more detail in Chapter 5. 27 28 Chapter 1: Basics of Backup and Restore SQL Server Backup Categories and Types The data files, filegroups, and log files that make up a SQL Server database can, and generally should, be backed up as part of your database backup and recovery strategy. This includes both user and system databases. There are three broad categories of backup that a DBA can perform: database backups, file backups and transaction log backups, and within these categories several different types of backup are available. Database backups copy into a backup file the data and objects in the primary data file and any secondary data files. Full database backup backs up all the data and objects in the data file(s) for a given database. Differential database backup backs up any data and objects in data file(s) for a given database that have changed since the last full backup. Transaction log backups copy into a backup file all the log records inserted into the transaction log LDF file since the last transaction log backup. File backups copy into a backup file the data and objects in a data file or filegroup. Full file backup backs up all the data and objects in the specified data files or filegroup. Differential file backup backs up the data and objects in the specified data files or filegroup that have changed since the last full file backup. Partial backup backs up the complete writable portion of the database, excluding any read-only files/filegroups (unless specifically included). Differential partial backup backs up the data and objects that have changed since the last partial backup. In my experience as a DBA, it is rare for a database to be subject to file backups, and some DBAs never work with a database that requires them, so the majority of this book 28 29 Chapter 1: Basics of Backup and Restore (Chapters 3 to 8) will focus on database backups (full and differential) and transaction log backups. However, we do cover file backups in Chapters 9 and 10. Note that the exact types of backup that can be performed, and to some extent the restore options that are available, depend on the recovery model in which the database is operating (SIMPLE, FULL or BULK_LOGGED). We'll be discussing this topic in more detail shortly, in the Recovery Models section, but for the time being perhaps the most notable point to remember is that it is not possible to perform transaction log backups for a database operating in SIMPLE recovery model, and so log backups play no part of a database RESTORE operation for these databases. Now we'll take a look at each of these types of backup in a little more detail. SQL Server database backups The database backup, which is a backup of your primary data file plus any secondary database files, is the cornerstone of any enterprise's backup and recovery plan. Any database that is not using file backups will require a strategy for performing database backups. Consider, for example, the situation in which a SQL Server database crashes, perhaps due to a hardware failure, and the live data file is no longer accessible. If no backups (copies) of this file exist elsewhere, then you will suffer 100% data loss; the "meltdown" scenario that all DBAs must avoid at all costs. Let's examine the two types of database backup, full and differential. Each of them contains the same basic type of information: the system and user data and objects stored in the database. However, viewed independently, the former contains a more complete picture of the data than the latter. 29 30 Full database backups Chapter 1: Basics of Backup and Restore You can think of the full database backup file as a complete and total archive of your database as it existed when you began the backup. Note though that, despite what the term "full" might suggest, a full backup does not fully back up all database files, only the data files; the transaction log must be backed up separately.. Generally speaking, we can consider that restoring a full database backup will return the database to the state it was in at the time the backup process started. However, it is possible that the effects of a transaction that was in progress when the backup started will still be included in the backup. Before SQL Server begins the actual data backup portion of the backup operation, it reads the Log Sequence Number (LSN; see Chapter 5), then reads all the allocated data extents, then reads the LSN again; as long as the transaction commits before the second LSN read, the change will be reflected in the full backup. Full database backups will most likely be your most commonly used backup type, but may not be the only type of backup you need, depending on your data recovery requirements. For example, let's say that you rely exclusively on full backups, performing one every day at midnight, and the server experiences a fatal crash at 11 p.m. one night. In this case, you would only be able to restore the full database backup taken at midnight the previous day, and so you would have lost 23 hours' worth of data. 30 31 Chapter 1: Basics of Backup and Restore If that size of potential loss is unacceptable, then you'll need to either take more frequent full backups (often not logistically viable, especially for large databases) or take transaction log backups and, optionally, some differential database backups, in order to minimize the risk of data loss. A full database backup serves as the base for any subsequent differential database backup. Copy-only full backups There is a special type of full backup, known as a copy-only full backup, which exists independently of the sequence of backup files required to restore a database, and cannot act as the base for differential database backups. This topic is discussed in more detail in Chapter 3, Full Database Backups. Differential database backups. If you're interested to know how SQL Server knows which data has changed, it works like this: for all of the data extents in the database the server will keep a bitmap page that contains a bit for each separate extent (an extent is simply a collection of consecutive pages stored in your database file; eight of them, to be exact). If the bit is set to 1, it means that the data in one or more of the pages in the extent has been modified since the base backup, and those eight pages will be included in the differential backup. If the bit for a given extent is still 0, the system knows that it doesn't need to include that set of data in the differential backup file. 31 32 Chapter 1: Basics of Backup and Restore Some DBAs avoid taking differential backups where possible, due to the perceived administrative complexity they add to the backup and restore strategy; they prefer instead to rely solely on a mix of full and regular transaction log backups. Personally, however, I find them to be an invaluable component of the backup strategy for many of my databases. Furthermore, for VLDBs, with a very large full backup footprint, differential backups may become a necessity. Even so, it is still important, when using differential backups, to update the base backup file at regular intervals. Otherwise, if the database is large and the data changes frequently, our differential backup files will end up growing to a point in size where they don't give us much value. We will discuss differential backups further in Chapter 7, where we will dive much deeper into best practices for their use as part of a backup and recovery strategy. SQL Server transaction log backups As a DBA, you will in many cases need to take regular backups of the transaction log file for a given database, in addition to performing database backups. This is important both for enabling point-in-time restore of your database, and for controlling the size of the log file. A full understanding of log backups, how they are affected by the database recovery model, and how and when space inside the log is reused, requires some knowledge of the architecture of the transaction log. We won't get to this till Chapter 5, so we'll keep things as simple as possible here, and get into the details later. Essentially, as discussed earlier, a transaction log file stores a series of log records that provide a historical record of the modifications issued against that database. As long as the database is operating in the FULL or BULK LOGGED recovery model then these log records will remain in the live log file, and never be overwritten, until a log backup operation is performed. 32 33 Chapter 1: Basics of Backup and Restore Therefore, the full transaction "history" can be captured into a backup file by backing up the transaction log. These log backups can then be used as part of a database RESTORE operation, in order to roll the database forward to a point in time at, or very close to, when some "disaster" occurred. The log chain For example, consider our previous scenario, where we were simply taking a full database backup once every 24 hours, and so were exposed to up to 24 hours of data loss. It is possible to perform differential backups in between the full backups, to reduce the risk of data loss. However both full and differential backups are I/O intensive processes and are likely to affect the performance of the database, so they should not be run during times when users are accessing the database. If a database holds business-critical data and you would prefer your exposure to data loss to be measured in minutes rather than hours, then you can use a scheme whereby you take a full database backup, followed by a series of frequent transaction log backups, followed by another full backup, and so on. As part of a database restore operation, we can then restore the most recent full backup (plus differentials, if taken), followed by the chain of available log file backups, up to one covering the point in time to which we wish to restore the database. In order to restore a database to a point in time, either to the end of a particular log backup or to a point in time within a particular log backup, there must exist a full, unbroken chain of log records, from the first log backup taken after a full (or differential backup), right up to the point to which you wish to recover. This is known as the log chain. If the log chain is broken (for example, by switching a database to SIMPLE recovery model, then it will only be possible to recover the database to some point in time before the event occurred that broke the chain. The chain can be restarted by returning the database to FULL (or BULK LOGGED) recovery model and taking a full backup (or differential backup, if a full backup was previously taken for that database). See Chapter 5, Log Backups, for further details. 33 34 Chapter 1: Basics of Backup and Restore Tail log backups. Of course, any sort of tail log backup will only be possible if the log file is still accessible and undamaged but, assuming this is the case, it should be possible to restore right up to the time of the last transaction committed and written to the log file, before the failure occurred. Finally, there is a special case where a tail log backup may not succeed, and that is if there are any minimally logged transactions, recorded while a database was operating in BULK_LOGGED recovery model, in the live transaction log, and a data file is unavailable 34 35 Chapter 1: Basics of Backup and Restore as a result of the disaster. A tail log backup using NO_TRUNCATE may "succeed" (although with reported errors) in these circumstances but a subsequent attempt to restore that tail log backup will fail. This is discussed in more detail in the Minimally logged operations section of Chapter 6. Log space reuse (a.k.a. log truncation) When using any recovery model other than SIMPLE, it is vital to take regular log backups, not only for recovery purposes, but also to control the growth of the log file. The reason for this relates to how and when space in the log is made available for reuse; a process known as log truncation. We'll go into deeper detail in Chapter 5 but, briefly, any segment of the log that contains only log records that are no longer required is deemed "inactive," and any inactive segment can be truncated, i.e. the log records in that segment can be overwritten by log records detailing new transactions. These "segments" of the log file are known as virtual log files (VLFs). If a VLF contains even just a single log record that relates to an open (uncommitted) transaction, or that is still required by some other database process (such as replication), or contains log records that are more recent than the log record relating to the oldest open or still required transaction, it is deemed "active." Any active VLF can never be truncated. Any inactive VLF can be truncated, although the point at which this truncation can occur depends on the recovery model of the database. In the SIMPLE recovery model, truncation can take place immediately upon occurrence of a CHECKPOINT operation. Pages in the data cache are flushed to disk, having first "hardened" the changes to the log file. The space in any VLFs that becomes inactive as a result, is made available for reuse. Therefore, the space in inactive portions of the log is continually overwritten with new log records, upon CHECKPOINT; in other words, a complete "log record history" is not maintained. 35 36 Chapter 1: Basics of Backup and Restore In the FULL (or BULK LOGGED) recovery model, once a full backup of the database has been taken, the inactive portion of the log is no longer marked as reusable on CHECKPOINT, so records in the inactive VLFs are retained alongside those in the active VLFs. Thus we maintain a complete, unbroken series of log records, which can be captured in log backups, for use in point-in-time restore operations. Each time a BACKUP LOG operation occurs, it marks any VLFs that are no longer necessary as inactive and hence reusable. This explains why it's vital to back up the log of any database running in the FULL (or BULK LOGGED) recovery model; it's the only operation that makes space in the log available for reuse. In the absence of log backups, the log file will simply continue to grow (and grow) in size, unchecked. File backups In addition to the database backups discussed previously, it's also possible to take file backups. Whereas database backups back up all data files for a given database, with file backups we can back up just a single, specific data file, or a specific group of data files (for example, all the data files in a particular filegroup). For a VLDB that has been "broken down" into multiple filegroups, file backups (see Chapter 9) can decrease the time and disk space needed for the backup strategy and also, in certain circumstances, make disaster recovery much quicker. For example, let's assume that a database's architecture consists of three filegroups: a primary filegroup holding only system data, a secondary filegroup holding recent business data and a third filegroup holding archive data, which has been specifically designated as a READONLY filegroup. If we were to perform database backups, then each full backup file would contain a lot of data that we know will never be updated, which would simply be wasting disk space. Instead, we can take frequent, scheduled file backups of just the system and business data. 36 37 Chapter 1: Basics of Backup and Restore Furthermore, if a database suffers corruption that is limited to a single filegroup, we may be able to restore just the filegroup that was damaged, rather than the entire database. For instance, let's say we placed our read-only filegroup on a separate drive and that drive died. Not only would we save time by only having to restore the read-only filegroup, but also the database could remain online and just that read-only data would be unavailable until after the restore. This latter advantage only holds true for user-defined filegroups; if the primary filegroup goes down, the whole ship goes down as well. Likewise, if the disk holding the file storing recent business data goes down then, again, we may be able to restore just that filegroup; in this case, we would also have to restore any transaction log files taken after the file backup to ensure that the database as a whole could be restored to a consistent state. Finally, if a catastrophe occurs that takes the database completely offline, and we're using SQL Server Enterprise Edition, then we may be able to perform an online restore, restoring the primary data file and bringing the database back online before we've restored the other data files. We'll cover all this in a lot more detail, with examples, in Chapter 9. The downside of file backups is the significant complexity and administrative burden that they can add to the backup strategy. Firstly, it means that a "full backup" will consist of capturing several backup files, rather than just a single one. Secondly, in addition, we will have to take transaction log backups to cover the time between file backups of different file groups. We'll discuss this in fuller detail in Chapter 9 but, briefly, the reason for this is that while the data is stored in separate physical files it will still be relationally connected; changes made to data stored in one file will affect related data in other files, and since the individual file backups are taken at different times, SQL Server needs any subsequent log backup files to ensure that it can restore a self-consistent version of the database. Keeping track of all of the different backup jobs and files can become a daunting task. This is the primary reason why, despite the potential benefits, most people prefer to deal with the longer backup times and larger file sizes that accompany full database backups. 37 38 Chapter 1: Basics of Backup and Restore Full and differential file backups As noted earlier, a full file backup differs from the full database backup in that it doesn't back up the entire database, but just the contents of one or more files or filegroups. Likewise, differential file backups capture all of the data changes made to the relevant files or filegroups, since the last full file backup was taken. In VLDBs, even single files or filegroups can grow large, necessitating the use of differential file backups. The same caveat exists as for differential database backups: the longer the interval between refreshing the base file backup, the larger the differential backups will get. Refresh the base full file backup at least once per week, if taking differential file backups. Partial and differential partial backups Partial backups, and differential partial backups, are a relative innovation, introduced in SQL Server They were specifically designed for use with databases that are comprised of at least one read-only filegroup and their primary use case was for databases operating within the SIMPLE recovery model (although they are valid for any of the available recovery models). By default, a partial backup will create a full backup of the primary filegroup plus any additional read/write filegroups. It will not back up any read-only filegroups, unless explicitly included in the partial backup. A typical use case for partial backups would be for a very large database (VLDB) that contains a significant portion of read-only data. In most cases, these read-only file groups contain files of archived data, which are still needed by the front end application for reference purposes. However, if this data is never going to be modified again, we don't want to waste time, CPU, and disk space backing it up every time we run a full database backup. 38 39 Chapter 1: Basics of Backup and Restore So, a partial full backup is akin to a full database backup, but omits all READONLY filegroups. Likewise, a partial differential backup is akin to a differential database backup, in that it only backs up data that has been modified since the base partial backup and, again, does not explicitly back up the READONLY filegroups within the database. Differential partial backups use the last partial backup as the base for any restore operations, so be sure to keep the base partial on hand. It is recommended to take frequent base partial backups to keep the differential partial backup file size small and manageable. Again, a good rule of thumb is to take a new base partial backup at least once per week, although possibly more frequently than that if the read/write filegroups are frequently modified. Finally, note that we can only perform partial backups via T-SQL. Neither SQL Server Management Studio nor the Maintenance Plan Wizard supports either type of partial backup. Recovery Models A recovery model is a database configuration option, chosen when creating a new database, which determines whether or not you need to (or even can) back up the transaction log, how transaction activity is logged, and whether or not you can perform more granular restore types that are available, such as file and page restores. All SQL Server database backup and restore operations occur within the context of one of three available recovery models for that database. SIMPLE recovery model certain operations can be minimally logged. Log backups are not supported. Point-in-time restore and page restore are not supported. File restore support is limited to secondary data files that are designated as READONLY. 39 40 Chapter 1: Basics of Backup and Restore. Each model has its own set of requirements and caveats, so we need to choose the appropriate one for our needs, as it will dramatically affect the log file growth and level of recoverability. In general operation, a database will be using either the SIMPLE or FULL recovery model. Can we restore just a single table? Since we mentioned the granularity of page and file restores, the next logical question is whether we can restore individual tables. This is not possible with native SQL Server tools; you would have to restore an entire database in order to extract the required table or other object. However, certain third-party tools, including Red Gate's SQL Compare, do support object-level restores of many different object types, from native backups or from Red Gate SQL Backup files. By default, any new database will inherit the recovery model of the model system database. In the majority of SQL Server editions, the model database will operate with the FULL recovery model, and so all new databases will also adopt use of this recovery model. This may be appropriate for the database in question, for example if it must support point-in-time restore. However, if this sort of support is not required, then it may be more appropriate to switch the database to SIMPLE recovery model after creation. This will remove the need to perform log maintenance in order to control the size of the log. Let's take a look at each of the three recovery models in a little more detail. 40 41 Chapter 1: Basics of Backup and Restore Simple Of the three recovery models for a SQL Server database, SIMPLE recovery model databases are the easiest to manage. In the SIMPLE recovery model, we can take full database backups, differential backups and file backups. The one backup we cannot take, however, is the transaction log backup. As discussed earlier, in the Log space reuse section, whenever a CHECKPOINT operation occurs, the space in any inactive portions of the log file belonging to any database operating SIMPLE recovery model, becomes available for reuse. This space can be overwritten by new log records. The log file does not and cannot maintain a complete, unbroken series of log records since the last full (or differential) backup, which would be a requirement for any log backup to be used in a point-in-time restore operation, so a log backup would be essentially worthless and is a disallowed operation. Truncation and the size of the transaction log There is a misconception that truncating the log file means that log records are deleted and the file reduces in size. It does not; truncation of a log file is merely the act of making space available for reuse. This process of making log space available for reuse is known as truncation, and databases using the SIMPLE recovery model are referred to as being in auto-truncate mode. In many respects, use of the SIMPLE recovery model greatly simplifies log file management. The log file is truncated automatically, so we don't have to worry about log file growth unless caused, for example, by some large and/or long-running batch operation. If a huge number of operations are run as a single batch, then the log file can grow in size rapidly, even for databases running in SIMPLE recovery (it's better to run a series of smaller batches). 41 42 Chapter 1: Basics of Backup and Restore We also avoid the administrative burden of scheduling and testing the log backups, and the storage overhead required for all of the log backup files, as well as the CPU and disk I/O burden placed on the server while performing the log backups. The most obvious and significant limitation of working in SIMPLE model, however, is that we lose the ability to perform point-in-time restores. As discussed earlier, if the exposure to potential data loss in a given database needs to be measured in minutes rather than hours, then transaction log backups are essential and the SIMPLE model should be avoided for that database. However, not every database in your environment needs this level of recoverability, and in such cases the SIMPLE model can be a perfectly sensible choice. For example, a Quality Assurance (QA) server is generally subject to a very strict change policy and if any changes are lost for some reason, they can easily be recovered by redeploying the relevant data and objects from a development server to the QA machine. As such, most QA servers can afford to operate in SIMPLE model. Likewise, if a database that gets queried for information millions of time per day, but only receives new information, in a batch, once per night, then it probably makes sense to simply run in SIMPLE model and take a full backup immediately after each batch update. Ultimately, the choice of recovery model is a business decision, based on tolerable levels of data loss, and one that needs to be made on a database-by-database basis. If the business requires full point-in-time recovery for a given database, SIMPLE model is not appropriate. However, neither is it appropriate to use FULL model for every database, and so take transaction log backups, "just in case," as it represents a considerable resource and administrative burden. If, for example, a database is read-heavy and a potential 12-hours' loss of data is considered bearable, then it may make sense to run in SIMPLE model and use midday differential backups to supplement nightly full backups. 42 43 Chapter 1: Basics of Backup and Restore Full In FULL recovery model, all operations are fully logged in the transaction log file. This means all INSERT, UPDATE and DELETE operations, as well as the full details for all rows inserted during a bulk data load or index creation operations. Furthermore, unlike in SIMPLE model, the transaction log file is not auto-truncated during CHECKPOINT operations and so an unbroken series of log records can be captured in log backup files. As such, FULL recovery model supports restoring a database to any point in time within an available log backup and, assuming a tail log backup can be made, right up to the time of the last committed transaction before the failure occurred. If someone accidentally deletes some data at 2:30 p.m., and we have a full backup, plus valid log backups spanning the entire time from the full backup completion until 3:00 p.m., then we can restore the database to the point in time directly before that data was removed. We will be looking at performing point-in-time restores in Chapter 6, Log Restores, where we will focus on transaction log restoration. The other important point to reiterate here is that inactive VLFs are not truncated during a CHECKPOINT. The only action that can cause the log file to be truncated is to perform a backup of that log file; it is only once a log backup is completed that the inactive log records captured in that backup become eligible for truncation. This means that log backups play a vital dual role: firstly in allowing point-in-time recovery, and secondly in controlling the size of the transaction log file. In the FULL model, the log file will hold a full and complete record of the transactions performed against the database since the last time the transaction log was backed up. The more transactions your database is logging, the faster it will fill up. If your log file is not set to auto-grow (see Chapter 3 for further details), then this database will cease to function correctly at the point when no further space is available in the log. If auto-grow is enabled, the log file will grow and grow until either you take a transaction log backup or the disk runs out of space; I would recommend the first of these two options. 43 44 Chapter 1: Basics of Backup and Restore In short, when operating in FULL recovery model, you must be taking transaction log backups to manage the growth of data in the transaction log; a full database backup does not cause the log file to be truncated. Once you take a transaction log backup, space in inactive VLFs will be made available for new transactions (except in rare cases where you specify a copy-only log backup, or use the NO_TRUNCATE option, which will not truncate the log). Bulk Logged The third, and least-frequently used, recovery model is BULK_LOGGED. It operates in a very similar manner to FULL model, except in the extent to which bulk operations are logged, and the implications this can have for point-in-time restores. All standard operations (INSERT, UPDATE, DELETE, and so on) are fully logged, just as they would be in the FULL recovery model, but many bulk operations, such as the following, will be minimally logged: bulk imports using the BCP utility BULK INSERT INSERT SELECT * FROM OPENROWSET(bulk ) SELECT INTO inserting or appending data using WRITETEXT or UPDATETEXT index rebuilds (ALTER INDEX REBUILD). In FULL recovery model, every change is fully logged. For example, if we were to use the BULK INSERT command to load several million records into a database operating in FULL recovery model, each of the INSERTs would be individually and fully logged. This puts a tremendous overhead onto the log file, using CPU and disk I/O to write each of the transaction records into the log file, and would also cause the log file to grow at a tremendous rate, slowing down the bulk load operation and possibly causing disk usage issues that could halt your entire operation. 44 45 Chapter 1: Basics of Backup and Restore In BULK_LOGGED model, SQL Server uses a bitmap image to capture only the extents that have been modified by the minimally logged operations. This keeps the space required to record these operations in the log to a minimum, while still (unlike in SIMPLE model) allowing backup of the log file, and use of those logs to restore the database in case of failure. Note, however, that the size of the log backup files will not be reduced, since SQL Server must copy into the log backup file all the actual extents (i.e. the data) that were modified by the bulk operation, as well as the transaction log records. Tail log backups and minimally logged operations If the data files are unavailable as a result of a database failure, and the tail of the log contains minimally logged operations recorded while the database was operating in BULK_LOGGED recovery model, then it will not be possible to do a tail log backup, as this would require access to the changed data extents in the data file. The main drawback of switching to BULK_LOGGED model to perform bulk operations, and so ease the burden on the transaction log, is that it can affect your ability to perform point-in-time restores. The series of log records is always maintained but, if a log file contains details of minimally logged operations, it is not possible to restore to a specific point in time represented within that log file. It is only possible to restore the database to the point in time represented by the final transaction in that log file, or to a specific point in time in a previous, or subsequent, log file that does not contain any minimally logged transactions. We'll discuss this in a little more detail in Chapter 6, Log Restores. There is a time and place for use of the BULK_LOGGED recovery model. It is not recommended that this model be used for the day-to-day operation of any of your databases. What is recommended is that you switch from FULL recovery model to BULK_LOGGED recovery model only when you are using bulk operations. After you have completed these operations, you can switch back to FULL recovery. You should make the switch in a way that minimizes your exposure to data loss; this means taking an extra log backup immediately before you switch to BULK_LOGGED, and then another one immediately after you switch the database back to FULL recovery. 45 46 Chapter 1: Basics of Backup and Restore Restoring Databases Of course, the ultimate goal of our entire SQL Server backup strategy is to prepare ourselves for the, hopefully rare, cases where we need to respond quickly to an emergency situation, for example restoring a database over one that has been damaged, or creating a second copy of a database (see aspx) in order to retrieve some data that was accidentally lost from that database. In non-emergency scenarios, we may simply want to restore a copy of a database to a development or test server. For a user database operating in FULL recovery model, we have the widest range of restore options available to us. As noted throughout the chapter, we can take transaction log backups and use them, in conjunction with full and differential backups, to restore a database to a specific point within a log file. In fact, the RESTORE LOG command supports several different ways to do this. We can: recover to a specific point in time we can stop the recovery at a specific point in time within a log backup file, recovering the database to the point it was in when the last transaction committed, before the specified STOPAT time recover to a marked transaction if a log backup file contains a marked transaction (defined using BEGIN TRAN TransactionName WITH MARK 'Description ') then we can recover the database to the point that this transaction starts (STOPBE- FOREMARK) or completes (STOPATMARK) recover to a Log Sequence Number stop the recovery at a specific log record, identified by its LSN (see Chapter 6, Log Restores). We'll cover several examples of the first option (which is by far the most common) in this book. In addition, we can perform more "granular" restores. For example, in certain cases, we can recover a database by restoring only a single data file (plus transaction logs), rather than the whole database. We'll cover these options in Chapters 9 and 47 Chapter 1: Basics of Backup and Restore For databases in BULK_LOGGED model, we have similar restore options, except that none of the point-in-time restore options listed previously can be applied to a log file that contains minimally logged transactions. For SIMPLE recovery model databases, our restore options are more limited. In the main, we'll be performing straightforward restores of the full and differential database backup files. In many cases, certainly for a development database, for example, and possibly for other "non-frontline" systems, this will be perfectly adequate, and will greatly simplify, and reduce the time required for, the backup and restore strategies for these databases. Finally, there are a couple of important "special restore" scenarios that we may run into from time to time. Firstly, we may need to restore one of the system databases. Secondly, if only a single data page is damaged, it may be possible to perform a page restore, rather than restoring the whole database. Restoring system databases The majority of the discussion of backing up and restoring databases takes place in the context of protecting an organization's business data. However, on any SQL Server instance there will also be a set of system databases, which SQL Server maintains and that are critical to its operation, and which also need to be backed up on a regular schedule. The full list of these databases can be found in Books Online (. com/en-us/library/ms aspx), but there are three in particular that must be included in your backup and recovery strategy. The master database holds information on all of your other databases, logins and much more. If you lose your master database you are in a bad spot unless you are taking backups and so can restore it. A full backup of this database, which operates in SIMPLE recovery model, should be part of your normal backup procedures for each SQL Server instance, along with all the user databases on that instance. You should also back up 47 48 Chapter 1: Basics of Backup and Restore master after a significant RDBMS update (such as a major Service Pack). If you find yourself in a situation where your master database has to be rebuilt, as in the case where you do not have a backup, you would also be rebuilding the msdb and model databases, unless you had good backups of msdb and model, in which case you could simply restore them. The msdb database contains SQL Agent jobs, schedules and operators as well as historical data regarding the backup and restore operations for databases on that instance. A full backup of this database should be taken whenever the database is updated. That way, if a SQL Server Agent Job is deleted by accident, and no other changes have been made, you can simply restore the msdb database and regain that job information. Finally, the model database is a "template" database for an instance; all user databases created on that instance will inherit configuration settings, such as recovery model, initial file sizes, file growth settings, collation settings and so on, from those stipulated for the model database. By default, this database operates in the FULL recovery model. It should rarely be modified, but will need a full backup whenever it is updated. Personally, I like to back it up on a similar rotation to the other system databases, so that it doesn't get overlooked. We'll walk through examples of how to restore the master and the msdb databases in Chapter 4, Restoring From Full Backup. Restoring single pages from backup There is another restore type that can be performed on SQL Server databases that can save you a huge amount of time and effort. When you see corruption in a database, it doesn't have to be corruption of the entire database file. You might find that only certain segments of data are missing or unusable. In this situation, you can restore single or multiple pages from a database backup. With this method, you only have to take your database down for a short period of time to restore the missing data, which is extremely helpful when dealing with VLDBs. We won't cover an example in this book, but further details can be found at 48 49 Chapter 1: Basics of Backup and Restore Summary In this chapter, we've covered a lot of necessary ground, discussing the files that comprise a SQL Server database, the critical role played by each, why it's essential that they are backed up, the types of backup that can be performed on each, and how this is impacted by the recovery model chosen for the database. We're now ready to start planning, verifying and documenting our whole backup strategy, answering questions such as: Where will the backups be stored? What tools will be used to take the backups? How do I plan and implement an appropriate backup strategy for each database? How do I verify that the backups are "good?" What documentation do I need? To find out the answers to these questions, and more, move on to Chapter 2. 49 50 Chapter 2: Planning, Storage and Documentation Having covered all of the basic backup types, what they mean, and why they are necessary, we're now ready to start planning our overall backup and restore strategy for each of the databases that are in our care. We'll start our discussion at the hardware level, with consideration of the appropriate storage for backup files, as well as the live data and log files, and then move on to discuss the tools available to capture and schedule the backup operations. Then, in the heart of the chapter, we'll describe the process of planning a backup and restore strategy, and developing a Service Level Agreement that sets out this strategy. The SLA is a vital document for setting appropriate expectations with regard to possible data loss and database down-time, as well as the time and cost of implementing the backup strategy, for both the DBA, and the application owners. Finally, we'll consider how best to gather vital details regarding the file architecture and backup details for each database into one place and document. Backup Storage Hopefully, the previous chapter impressed on you the need to take database backups for all user and system databases, and transaction log backups for any user databases that are not operating in SIMPLE recovery mode. One of our basic goals, as a DBA, is to create an environment where these backups are stored safely and securely, and where the required backup operations are going to run as smoothly and quickly as possible. 50 51 Chapter 2: Planning, Storage and Documentation The single biggest factor in ensuring that this can be achieved (alongside such issues as careful backup scheduling, which we'll discuss later in the chapter) is your backup storage architecture. In the examples in this book, we back up our databases to the same disk drive that stores the live data and log files; of course, this is purely a convenience, designed to make the examples easy to practice on your laptop. In reality, we'd never back up to the same local disk; after all if you simply store them on the same drive as the live files, and that drive becomes corrupt, then not only have you lost the live files, but the backup files too! There are three basic options, which we'll discuss in turn: local disk storage, network storage, and tape storage. Each of these media types has its pros and cons so, ultimately, it is a matter of preference which you use and how. In many cases, a mixture of all three may be the best solution for your environment. For example, you might adopt the scheme below. 1. Back up the data and log files to local disk storage either Direct Attached Storage (DAS) or a Storage Area Network (SAN). In either case, the disks should be in a RAID configuration. This will be quicker for the backup to complete, but you want to make sure your backups are being moved immediately to a separate location, so that a server crash won't affect your ability to restore those files. 2. Copy the backup files to a redundant network storage location again, this space should be driven by some sort of robust storage solution such as SAN, or a RAID of local physical drives. This will take a bit longer than the local drive because of network overhead, but you are certain that the backups are in a separate/secure location in case of emergency. 3. Copy the files from the final location to a tape backup library for storage in an offsite facility. I recommend keeping the files on disk for at least three days for daily backups and a full seven days for weekly (or until the next weekly backup has been taken). If you need files older than that, you can retrieve them from the tape library. 51 52 Chapter 2: Planning, Storage and Documentation The reason I offer the option to write the backups to local storage initially, instead of straight to network storage, is that it avoids the bottleneck of pushing data through the network. Generally speaking, it's possible to get faster write speeds, and so faster backups, to a local drive than to a drive mapped from another network device, or through a drive space shared out through a distributed file system (DFS). However, with storage networks becoming ever faster, it is becoming increasingly viable to skip Step 1, and back up the data and log files directly to network storage. Whether you write first to locally attached storage, or straight to a network share, you'll want that disk storage to be as fast and efficient as possible, and this means that we want to write, not to a single disk, but to a RAID unit, provided either as DAS, or by a SAN. We also want, wherever possible, to use dedicated backup storage. For example, if a particular drive on a file server, attached from the SAN, is designated as the destination for our SQL Server backup files, we don't want any other process storing their data in that location, competing with our backups for space and disk I/O. Local disk (DAS or SAN) Next on our list of backup media is the local disk drive. The main benefit of backing up to disk, rather than tape is simply that the former will be much faster (depending on the type and speed of the drive). Of course, any consideration of local disk storage for backup files is just as relevant to the storage of the online data and log files, since it's likely that the initial backup storage will just be a separate area in the same overall SQL Server storage architecture. Generally speaking, SQL Server storage tends to consist of multiple disk drives, each set of disks forming, with a controller, a Redundant Array of Inexpensive Disks (RAID) device, configured appropriately according the files that are being stored. 52 53 Chapter 2: Planning, Storage and Documentation These RAID-configured disks are made available to SQL Server either as part of Directly Attached Storage, where the disks (which could be SATA, SCSI or SAS) are built into the server or housed in external expansion bays that are attached to the server using a RAID controller, or as Storage Area Network in layman's terms, a SAN is a big box of hard drives, available via a dedicated, high performance network, with a controller that instructs individual "volumes of data" known as Logical Unit Numbers (LUNs) to interact with certain computers. These LUNs appear as local drives to the operating system and SQL Server. Generally, the files for many databases will be stored on a single SAN. RAID configuration The RAID technology allows a collection of disks to perform as one. For our data and log files RAID, depending on the exact RAID configuration, can offer some or all of the advantages below. Redundancy if one of the drives happens to go bad, we know that, depending on the RAID configuration, either the data on that drive will have been mirrored to a second drive, or it will be able to be reconstructed, and so will still be accessible, while the damaged drive is replaced. Improved read and write I/O performance reading from and writing to multiple disk spindles in a RAID array can dramatically increase I/O performance, compared to reading and writing from a single (larger) disk. Higher storage capacity by combining multiple smaller disks in a RAID array, we overcome the single-disk capacity limitations (while also improving I/O performance). For our data files we would, broadly speaking, want a configuration optimized for maximum read performance and, for our log file, maximum write performance. For backup files, the simplest backup storage, if you're using DAS, may just be a separate, single physical drive. 53 54 Chapter 2: Planning, Storage and Documentation However, of course, if that drive were to become corrupted, we would lose the backup files on that drive, and there isn't much to be done, beyond sending the drive to a recovery company, which can be both time consuming and expensive, with no guarantee of success. Therefore, for backup files it's just as important to take advantage of the redundancy advantages offered by RAID storage. Let's take just a brief look at the more popular of the available RAID configurations, as each one provides different levels of protection and performance. RAID 0 (striping) This level of RAID is the simplest and provides only performance benefits. A RAID 0 configuration uses multiple disk drives and stripes the data across these disks. Striping is simply a method of distributing data across multiple disks, whereby each block of data is written to the next disk in the stripe set. This also means that I/O requests to read and write data will be distributed across multiple disks, so improving performance. There is, however, a major drawback in a RAID 0 configuration. There is no fault tolerance in a RAID 0 setup. If one of the disks in the array is lost, for some reason, the entire array will break and the data will become unusable. RAID 1 (mirroring) In a RAID 1 configuration we use multiple disks and write the same data to each disk in the array. This is called mirroring. This configuration offers read performance benefits (since the data could be read from multiple disks) but no write benefits, since the write speed is still limited to the speed of a single disk. However, since each disk in the array has a mirror image (containing the exact same data) RAID 1 does provide redundancy and fault tolerance. One drive in the mirror set can be lost without losing data, or that data becoming inaccessible. As long as one of the disks in the mirror stays online, a RAID 1 system will remain in working order but will take a hit in read performance while one of the disks is offline. 54 55 Chapter 2: Planning, Storage and Documentation RAID 5 (striping with parity) RAID 5 disk configurations use block striping to write data across multiple disks, and so offer increased read and write performance, but also store parity data on every disk in the array, which can be used to rebuild data from any failed drive. Let's say, for example, we had a simple RAID 5 setup of three disks and were writing data to it. The first data block would be written to Disk 1, the second to Disk 2, and the parity data on Disk 3. The next data blocks would be written to Disks 1 and 3, with parity data stored on Disk 2. The next data blocks would be written to Disks 2 and 3, with the parity being stored on Disk 1. The cycle would then start over again. This allows us to lose any one of those disks and still be able to recover the data, since the parity data can be used in conjunction with the still active disk to calculate what was stored on the failed drive. In most cases, we would also have a hot spare disk that would immediately take the place of any failed disk, calculate lost data from the other drives using the parity data and recalculate the parity data that was lost with the failure. This parity does come at a small cost, in that the parity has to be calculated for each write to disk. This can give a small hit on the write performance, when compared to a similar RAID 10 array, but offers excellent read performance since data can be read from all drives simultaneously. RAID 10 (striped pairs of mirrors) RAID 10 is a hybrid RAID solution. Simple RAID does not have designations that go above 9, so RAID 10 is actually RAID 1+0. In this configuration, each disk in the array has at least one mirror, for redundancy, and the data is striped across all disks in the array. RAID 10 does not require parity data to be stored; recoverability is achieved from the mirroring of data, not from the calculations made from the striped data. 55 56 Chapter 2: Planning, Storage and Documentation RAID 10 gives us the performance benefits of data striping, allowing us to read and write data faster than single drive applications. RAID 10 also gives us the added security that losing a single drive will not bring our entire disk array down. In fact, with RAID 10, as long as at least one of the mirrored drives from any set is still online, it's possible that more than one disk can be lost while the array remains online with all data accessible. However, loss of both drives from any one mirrored set will result in a hard failure. With RAID 10 we get excellent write performance, since we have redundancy with the need to deal with parity data. However, read performance will generally be lower that a RAID 5 configuration with the same number of disks, since data can be read simultaneously from only half the disks in the array. Choosing the right storage configuration All SQL Server file storage, including storage for database backup files, should be RAIDconfigured, both for redundancy and performance. For the backup files, what we're mainly after is the "safety net" of storage redundancy, and so the simplest RAID configuration for backup file storage would be RAID 1. However, in my experience, it's quite common that backup files simply get stored on the slower disks of a SAN, in whatever configuration is offered (RAID 5, in my case). Various configurations of RAID-level drive failure protection are available from either DAS or SAN storage. So, in cases where a choice exists, which one should we choose? SAN vs. DAS With the increasing capacity and decreasing cost of hard drives, along with the advent of Solid State Drives, it's now possible to build simple but pretty powerful DAS systems. Nevertheless, there is an obvious physical limit to how far we can expand a server by attaching more hard drives. For VLDBs, this can be a problem and SAN-attached storage is still very popular in today's IT infrastructure landscape, even in smaller businesses. 56 57 Chapter 2: Planning, Storage and Documentation For the added cost and complexity of SAN storage, you have access to storage space far in excess of what a traditional DAS system could offer. This space is easily expandable (up to the SAN limit) simply by adding more disk array enclosures (DAEs), and doesn't take up any room in the physical server. Multiple database servers can share a single SAN, and most SANs offer many additional features (multiple RAID configurations, dynamic snapshots, and so on). SAN storage is typically provided over a fiber optic network that is separated from your other network traffic in order to minimize any network performance or latency issues; you don't have to worry about any other type of network activity interfering with your disks. RAID 5 vs. RAID 10 There is some debate over which of these two High Availability RAID configurations is best for use when storing a relational database. The main point of contention concerns the write penalty of recalculating the parity data after a write in a RAID 5 disk array. This was a much larger deal for RAID disks a few years ago than it is in most of today's implementations. The parity recalculation is no longer an inline operation and is done by the controller. This means that, instead of the parity recalculation happening before you can continue with I/O operations, the controller takes care of this work separately and no longer holds up the I/O queue. You do still see some overhead when performing certain types of write, but for the most part this drawback has been obfuscated by improved hardware design. Nevertheless, my general advice, where a choice has to be made, is to go for a RAID 10 configuration for a database that is expected to be subject to "heavy writes" and RAID 5 for read-heavy databases. However, in a lot of cases, the performance gain you will see from choosing one of these RAID configurations over the other will be relatively small. 57 58 Chapter 2: Planning, Storage and Documentation My experience suggests that advances in controller architecture along with increases in disk speed and cache storage have "leveled the playing field." In other words, don't worry overly if your read-heavy database is on RAID 10, or a reasonably write-heavy database is on RAID 5; chances are it will still perform reliably, and well. Network device The last option for storing our backup files is the network device. Having each server backing up to a separate folder on a network drive is a great way to organize all of the backups in one convenient location, which also happens to be easily accessible when dumping those files to tape media for offsite storage. We don't really care what form this network storage takes, as long as it is as stable and fault tolerant as possible, which basically means RAID storage. We can achieve this via specialized Network Attached Storage (NAS), or simply a file server, backed by physical disks or SAN-attached space. However, as discussed earlier, backing up directly to a network storage device, across a highly utilized network, can lead to latency and network outage problems. That's why I generally still recommend to backup to direct storage (DAS or SAN) and then copy the completed backup files to the network storage device. A good solution is to use a scheduled job, schedulable utility or, in some cases, a third-party backup tool to back up the databases to a local drive and then copy the results to a network share. This way, we only have to worry about latency issues when copying the backup file, but at least at this stage we don't put any additional load on the SQL Server service; if a file copy fails, we just restart it. Plus, with utilities such as robocopy, we have the additional safety net of the knowing the copy will automatically restart if any outage occurs. 58 59 Chapter 2: Planning, Storage and Documentation Tape Firstly, I will state that tape backups should be part of any SQL Server backup and recovery plan and, secondly, that I have never in my career backed up a database or log file directly to tape. The scheme to go for is to back up to disk, and then archive to tape. There are several reasons to avoid backing up directly to tape, the primary one being that writing to tape is slow, with the added complication that the tape is likely to be attached via some sort of relatively high-latency network device. This is a big issue when dealing with backup processes, especially for large databases. If we have a network issue after our backup is 90% completed, we have wasted a lot of time and resources that are going to have to be used again. Writing to a modern, single, physical disk, or to a RAID device, will be much faster than writing to tape. Some years ago, tape storage might still have had a cost advantage over disk but, since disk space has become relatively cheap, the cost of LTO-4 tape media storage is about the same as comparable disk storage. Finally, when backing up directly to tape, we'll need to support a very large tape library in order to handle the daily, weekly and monthly backups. Someone is going to have to swap out, label and manage those tapes and that is a duty that most DBAs either do not have time for, or are just not experienced enough to do. Losing, damaging, or overwriting a tape by mistake could cost you your job. Hopefully, I've convinced you not to take SQL Server backups directly to tape, and instead to use some sort of physical disk for initial storage. However, and despite their other shortcomings, tape backups certainly do have a role to play in most SQL Server recovery plans. The major benefit to tape media is portability. Tapes are small, take up relatively little space and so are ideal for offsite storage. Tape backup is the last and best line of defense for you and your data. There will come a time when a restore operation relies on a backup file that is many months old, and you will be glad you have a copy stored on tape somewhere. 59 60 Chapter 2: Planning, Storage and Documentation With tape backups stored offsite, we also have the security of knowing that we can recover that data even in the event of a total loss of your onsite server infrastructure. In locations where the threat of natural disasters is very real and very dangerous, offsite storage is essential (I have direct experience of this, living in Florida). Without it, one hurricane, flood, or tornado can wipe out all the hard work everyone put into backing up your database files. Storing backup file archive on tape, in a secure and structurally reinforced location, can mean the difference between being back online in a matter of hours and not getting back online at all. Most DBA teams let their server administration teams handle the task of copying backups to tape; I know mine does. The server admins will probably already be copying other important system backups to tape, so there is no reason they cannot also point a backup-to-tape process at the disk location of your database and log backup files. Finally, there is the prosaic matter of who handles all the arrangements for the physical offsite storage of the tapes. Some smaller companies can handle this in-house, but I recommend that you let a third-party company that specializes in data archiving handle the long-term secure storage for you. Backup Tools Having discussed the storage options for our data, log, and backup files, the next step is to configure and schedule the SQL Server backup jobs. There are several tools available to do this, and we'll consider the following: maintenance plans the simplest, but also the most limited solution, offering ease of use but limited options, and lacking flexibility custom backup scripts offers full control over how your backup jobs execute, but requires considerable time to build, implement, and maintain 60 61 Chapter 2: Planning, Storage and Documentation third-party backup tools many third-party vendors offer powerful, highly configurable backup tools that offer backup compression and encryption, as well as well-designed interfaces for ease of scheduling and monitoring. All environments are different and the choice you make must be dictated by your specific needs. The goal is to get your databases backed up, so whichever one you decide on and use consistently is going to be the right choice. Maintenance plan backups The Maintenance Plan Wizard and Designer is a built-in SQL Server tool that allows DBAs to automate the task of capturing full and differential database backups, and log backups. It can also be used to define and schedule other essential database maintenance tasks, such as index reorganization, consistency checks, statistics updates, and so on. I list this tool first, not because it is the best way to automate these tasks, but because it is a simple-to-use, built-in option, and because scheduling backup and other maintenance tasks this way sure is better than not scheduling them at all! In fact, however, from a SQL Server backup perspective, maintenance plans are the weakest choice of the three we'll discuss, for the following reasons: backup options are limited file or partial backups are not supported configurability is limited we are offered a strict set of options in configuring the backup task and we cannot make any other modifications to the process, although it's possible (via the designer) to include some pre- and post-backup logic some important tasks are not supported such as proper backup verification (see later in the chapter). 61 62 Chapter 2: Planning, Storage and Documentation Under the covers, maintenance plans are simply SSIS packages that define a number of maintenance tasks, and are scheduled for execution via SQL Server Agent jobs. The Maintenance Plan Wizard and Designer makes it easy to build these packages, while removing a lot of the power and flexibility available when writing such packages directly in SSIS. For maintenance tasks of any reasonable complexity, it is better to use Business Intelligence Design Studio to design the maintenance packages that suit your specific environment and schedule them through SQL Server Agent. It may not be a traditional maintenance plan in the same sense as one that the wizard would have built, but it is a maintenance package none the less. Custom backup scripts Another option is to write a custom maintenance script, and run it in a scheduled job via SQL Server Agent or some other scheduling tool. Traditionally, DBAs have chosen T-SQL scripts or stored procedures for this task, but PowerShell scripting is gaining in popularity due to its versatility (any.net library can be used inside of a PowerShell script). Custom scripting is popular because it offers the ultimate flexibility. Scripts can evolve to add more and more features and functionality. In this book, we'll create custom scripts that, as well as backing up our databases, will verify database status and alert users on failure and success. However, this really only scratches the surface of the tasks we can perform in our customized backup scripts. The downside of all this is that "ultimate flexibility" tends to go hand in hand with increasing complexity and diminishing consistency, and this problem gets exponentially worse as the number of servers to be maintained grows. As the complexity of a script increases, so it becomes more likely that you'll encounter bugs, especially the kind that might not manifest themselves immediately as hard errors. 62 63 Chapter 2: Planning, Storage and Documentation If a script runs on three servers, this is no big deal; just update the code on each server and carry on. What if it must run on 40 servers? Now, every minor improvement to the backup script, or bug fix, will entail a major effort to ensure that this is reflected consistently on all servers. In such cases, we need a way to centralize and distribute the code so that we have consistency throughout the enterprise, and a quick and repeatable way to make updates to each machine, as needed. Many DBA teams maintain on each server a "DBA database" that holds the stored procedures for all sorts of maintenance tasks, such as backups, index maintenance and more. For example, my team maintains a "master" maintenance script, which will create this database on a server, or update the objects within the database if the version on the server is older than what exists in our code repository. Whenever the script is modified, we have a custom.net tool that will run the script on every machine, and automatically upgrade all of the maintenance code. Third-party tools The final option available to the DBA is to create and schedule the backup jobs using a third-party tool. Several major vendors supply backup tools but the one used in my team, and in this book, is Red Gate SQL Backup ( sql-backup/). Details of how to install this tool can be found in Appendix A, and backup examples can be found in Chapter 8. With SQL Backup, we can create a backup job just as easily as we could with the maintenance plan wizard, and with a lot more flexibility. We can create SQL Server Agent jobs that take full, differential, transaction log or file and filegroup backups from a GUI wizard. We can set up a custom schedule for the backups. We can configure numerous options for the backup files, including location, retention, dynamic naming convention, compression, encryption, network resilience, and more. 63 64 Chapter 2: Planning, Storage and Documentation Be aware, though, that a tool that offers flexibility and ease of use can lead down the road of complex backup jobs. Modifying individual steps within such jobs requires T-SQL proficiency or, alternatively, you'll need to simply drop the job and build it again from scratch (of course, a similar argument applies to custom scripts and maintenance plan jobs). Backup and Restore Planning The most important point to remember is that, as DBAs, we do not devise plans to back up databases successfully; we devise plans to restore databases successfully. In other words, if a database owner expects that, in the event of an outage, his database and data will be back online within two hours, with a maximum of one hour's data loss, then we must devise a plan to support these requirements, assuming we believe them to be reasonable. Of course, a major component of this plan will be the details of the types of backup that will be taken, and when, but never forget that the ultimate goal is not just to take backups, but to support specific restore requirements. This backup and restore plan will be agreed and documented in a contract with the database users, called a Service Level Agreement, or SLA, which will establish a certain level of commitment regarding the availability and recoverability of their database and data. Planning an SLA is a delicate process, and as DBAs we have to consider not only our own experiences maintaining various databases and servers, but also the points of view of the application owners, managers, and end-users. This can be a tricky task, since most owners and users typically feel that their platform is the most important in any enterprise and that it should get the most attention to detail, and highest level of service. We have to be careful not to put too much emphasis on any one system, but also to not let anything fall through the cracks. 64 65 Chapter 2: Planning, Storage and Documentation So how do we get started, when devising an appropriate backup and restore plan for a new database? As DBAs, we'd ideally be intimately familiar with the inner and outer workings of every database that is in our care. However, this is not always feasible. Some DBAs administer too many servers to know exactly what is on each one, or even what sort of data they contain. In such cases, a quick 15-minute discussion with the application owner can provide a great deal of insight into the sort of database that we are dealing with. Over the coming sections, we'll take a look at factors that affect each side of the backuprestore coin, and the sorts of questions we need to ask of our database owners and users. Backup requirements The overriding criterion in determining the types of backup we need to take, and how frequently, is the maximum toleration to possible data loss, for a particular database. However, there are a few other factors to consider as well. On what level of server does this database reside? For example, is it a development box, a production server or a QA machine? We may be able to handle losing a week's worth of development changes, but losing a week's work of production data changes could cost someone their job, especially if the database supports a business-critical, front-line application Do we need to back up this database at all? Not all data loss is career-ending and, as a DBA, you will run into plenty of situations where a database doesn't need to be backed up at all. For example, you may have a development system that gets refreshed with production data on a set schedule. If you and your development team are comfortable not taking backups of data that is refreshed every few days anyway, then go for it. Unless there is a good reason to do so (perhaps the 65 66 Chapter 2: Planning, Storage and Documentation data is heavily modified after each refresh) then you don't need to waste resources on taking backups of databases that are just copies of data from another server, which does have backups being taken. How much data loss is acceptable? Assuming this is a system that has limits on its toleration of data loss, then this question will determine the need to take supplemental backups (transaction log, differential) in addition to full database (or file) backups, and the frequency at which they need to be taken. Now, the application owner needs to be reasonable here. If they state that they cannot tolerate any down-time, and cannot lose any data at all, then this implies the need for a very high availability solution for that database, and a very rigorous backup regime, both of which are going to cost a lot of design, implementation and administrative effort, as well as a lot of money. If they offer more reasonable numbers, such as one hour's potential data loss, then this is something that can be supported as part of a normal backup regime, taking hourly transaction log backups. Do we need to take these hourly log backups all day, every day, though? Perhaps, yes, but it really depends on the answer to next question. At what times of the day is this database heavily used? What we're trying to find out here is when, and how often, backups need to be taken. Full backups of large databases should be carried out at times when the database is least used, and supplemental backups need to be fitted in around our full backup schedule. We'll need to start our log backup schedules well in advance of the normal database use schedules, in order to capture the details of all data changes, and end them after the traffic subsides. Alternatively, we may need to run these log file backups all day, which is not a bad idea, since then we will never have large gaps in time between the transaction log backup files. 66 67 Chapter 2: Planning, Storage and Documentation What are the basic characteristics of the database? Here, we're interested in other details that may impact backup logistics. We'll want to find out, for example: How much data is stored the size of the database will impact backup times, backup scheduling (to avoid normal database operations being unduly affected by backups), amount of storage space required, and so on. How quickly data is likely to grow this may impact backup frequency and scheduling, since we'll want to control log file size, as well as support data loss requirements. We will also want to plan for the future data growth to make sure our SQL Server backup space doesn't get eaten up. The nature of the workload. Is it OLTP, with a high number of both reads and writes? Or mainly read-only? Or mixed and, if so, are certain tables exclusively read-only? Planning for backup and restore starts, ideally, right at the very beginning of a database's life, when we are planning to create it, and define the data and log file properties and architecture for the new database. Answers to questions such as these will not only help define our backup requirements, but also the appropriate file architecture (number of filegroups and data files) for the database, initial file sizes and growth characteristics, as well as the required hardware capacity and configuration (e.g. RAID level). Data and log file sizing and growth We'll discuss this in more detail in Chapter 3, but it's worth noting that the initial size, and subsequent auto-growth characteristics, of the data and log files will be inherited from the properties of the model database for that instance, and there is a strong chance that these will not be appropriate for your database. 67 68 Chapter 2: Planning, Storage and Documentation Restore requirements As well as ensuring we have the appropriate backups, we need a plan in place that will allow us to perform "crash recovery." In other words, we need to be sure that we can restore our backups in such a way that we meet the data loss requirements, and complete the operation within an acceptable period of down-time. An acceptable recovery time will vary from database to database depending on a number of factors, including: the size of the database much as we would like to, we cannot magically restore a full backup of a 500 GB database, and have it back online with all data recovered in 15 minutes where the backup files are stored if they are on site, we only need to account for the time needed for the restore and recovery process; if the files are in offsite storage, we'll need to plan extra time to retrieve them first the complexity of the restore process if we just need to restore a full database backup, this is fairly straightforward process; but if we need to perform a complex point-in-time restore involving full, differential, and log files, this is more complex and may require more time or at least we'll need to practice this type of restore more often, to ensure that all members of our team can complete it successfully and within the required time. With regard to backup file locations, an important, related question to ask your database owners is something along the lines of: How quickly, in general, will problems be reported? That may sound like a strange question, but its intent is to find out how long it's necessary to retain database backup files on network storage before deleting them to make room for more backup files (after, of course, transferring these files to tape for offsite storage). 68 69 Chapter 2: Planning, Storage and Documentation The location of the backup file will often affect how quickly a problem is solved. For example, let's say the company policy is to keep backup files on site for three days, then archive them to tape, in offsite storage. If a data loss occurs and the error is caught quickly, the necessary files will be at hand. If, however, it's only spotted five days later, the process of getting files back from the offsite tape backups will push the recovery time out, and this extra time should be clearly accounted for in the SLA. This will save the headache of having to politely explain to an angry manager why a database or missing data is not yet back online. An SLA template Having asked all of these question, and more, it's time to draft the SLA for that database. This document is a formal agreement regarding the backup regime that is appropriate for that database, and also offers a form of insurance to both the owners and the DBA. You do not, as a DBA, want to be in a position of having a database owner demanding to know why you can't perform a log restore to get a database back how it was an hour before it went down, when you know that they told you that only weekly full backups were required for that database, but you have no documented proof. Figure 2-1 offers a SLA template, which will hopefully provide a good starting point for your Backup SLA contract. It might not have everything you need for your environment, but you can download the template from the supplemental material and modify it, or just create your own from scratch. 69 70 Chapter 2: Planning, Storage and Documentation Server Name: Server Category: Application Name: Application Owner: MYCOMPANYDB1 Production / Development / QA / Staging Sales-A-Tron Sal Esman Database Name : Data Loss: Recovery Time: 4 Hours salesdb 2 Hours Full Backups: Daily / Weekly / Monthly Diff Backups: Daily / Weekly Log Backups: Hour Intervals File Backups: Daily / Weekly / Monthly File Differentials: Daily / Weekly Database Name : Data Loss: Recovery Time: 6 Hours salesarchives 4 Hours Full Backups: Daily / Weekly / Monthly Diff Backups: Daily / Weekly Log Backups: Hour Intervals File Backups: Daily / Weekly / Monthly File Differentials: Daily / Weekly Database Name : Data Loss: Recovery Time: 3 Hours resourcedb 2 Hours Full Backups: Daily / Weekly / Monthly Diff Backups: Daily / Weekly Log Backups: Hour Intervals File Backups: Daily / Weekly / Monthly File Differentials: Daily / Weekly Database Administrator: Application Owner: Date of Agreement: Figure 2-1: An example backup and restore SLA. 70 71 Chapter 2: Planning, Storage and Documentation Example restore requirements and backup schemes Based on all the information gathered for the SLA, we can start planning the detailed backup strategy and restore for each database. By way of demonstrating the process, let's walk through a few common scenarios and the recommended backup strategy. Of course, examples are only intended as a jumping-off point for your own SQL Server backup and restore plans. Each server in your infrastructure is different and may require completely different backup schedules and structures. Scenario 1: Development server, VLDB, simple file architecture Here, we have a development machine containing one VLDB. This database is not structurally complex, containing only one data file and one log file. The developers are happy to accept data loss of up to a day. All activity on this database takes place during the day, with a very few transactions happening after business hours. In this case, it might be appropriate to operate the user database in SIMPLE recovery model, and implement a backup scheme such as the one below. 1. Perform full nightly database backups for the system databases. 2. Perform a full weekly database backup for the VLDB, for example on Sunday night. 3. Perform a differential database backup for the VLDB on the nights where you do not take the full database backups. In this example, we would perform these backups on Monday through Saturday night. 71 72 Chapter 2: Planning, Storage and Documentation Scenario 2: Production server, 3 databases, simple file architecture, 2 hours' data loss In the second scenario, we have a production server containing three actively-used databases. The application owner informs us that no more than two hours of data loss can be tolerated, in the event of corruption or any other disaster. None of the databases are complex structurally, each containing just one data file and one log file. With each database operating in FULL recovery model, an appropriate backup scheme might be as below. 1. Perform full nightly database backups for every database (plus the system databases). 2. Perform log backups on the user databases every 2 hours, on a schedule starting after the full backups are complete and ending before the full backup jobs starts. Scenario 3: Production server, 3 databases, complex file architecture, 1 hour's data loss In this final scenario, we have a production database system that contains three databases with complex data structures. Each database comprises multiple data files split into two filegroups, one read-only and one writable. The read-only file group is updated once per week with newly archived records. The writable file groups have an acceptable data loss of 1 hour. Most database activity on this server will take place during the day. With the database operating in FULL recovery model, the backup scheme below might work well. 1. Perform nightly full database backups for all system databases. 2. Perform a weekly full file backup of the read-only filegroups on each user database, after the archived data has been loaded. 72 73 Chapter 2: Planning, Storage and Documentation 3. Perform nightly full file backups of the writable file groups on each user database. 4. Perform hourly log backups for each user database; the log backup schedule should start after the nightly full file backups are complete, and finish one hour before the full file backup processes start again. Backup scheduling It can be a tricky process to organize the backup schedule such that all the backups that are required to support the Backup and Restore SLA fit into the available maintenance windows, don't overlap, and don't cause undue stress on the server. Full database and file backups, especially of large databases, can be CPU- and Disk I/0-intensive processes, and so have the propensity to cause disruption, if they are run at times when the database is operating under its normal business workload. Ideally, we need to schedule these backups to run at times when the database is not being accessed, or at least is operating under greatly reduced load, since we don't want our backups to suffer because they are fighting with other database processes or other loads on the system (and vice versa). This is especially true when using compressed backups, since a lot of the load that would be done on disk is moved to the CPU in the compression phase. Midnight is usually a popular time to run large backup jobs, and if your shop consists of just a few machines, by all means schedule all your full nightly backups to run at this time. However, if you administer 20, 30, or more servers, then you may want to consider staggering your backups throughout the night, to avoid any possible disk or network contention issues. This is especially true when backing up directly to a network storage device. These devices are very robust and can perform a lot of operations per second, but there is a limit to how much traffic any device can handle. By staggering the backup jobs, you can help alleviate any network congestion. 73 74 Chapter 2: Planning, Storage and Documentation The scheduling of differential backups will vary widely, depending on their role in the backup strategy. For a VLDB, we may be taking differential backups every night, except for on the night of the weekly full backup. At other times, we may run differential backups at random times during the day, for example as a way to safeguard data before performing a large modification or update. Transaction log backups are, in general, much less CPU- and I/O-intensive operations and can be safely run during the day, alongside the normal database workload. In fact, there isn't much point having a transactional backup of your database if no one is actually performing any transactions! The scheduling of log backups may be entirely dictated by the agreed SLA; if no more than five minutes of data can be lost, then take log backups every five minutes! If there is some flexibility, then try to schedule consecutive backups close enough so that the log file does not grow too much between backups, but far enough apart that it does not put undue stress on the server and hardware. As a general rule, don't take log backup much more frequently than is necessary to satisfy the SLA. Remember, the more log backups you take, the more chance there is that one will fail and possibly break your log chain. However, what happens when you have two databases on a server that both require log backups to be taken, but at different intervals? For example, Database A requires a 30-minute schedule, and Database B, a 60-minute schedule. You have two choices: 1. create two separate log backup jobs, one for DB_A running every 30 minutes and one for DB_B, every 60 minutes; this means multiple SQL Agent / scheduled jobs and each job brings with it a little more maintenance and management workload 2. take log backups of both databases using a single job that runs every 30 minutes; you'll have fewer jobs to schedule and run, but more log backup files to manage, heightening the risk of a file being lost or corrupted. My advice in this case would be to create one log backup job, taking log backups every 30 minutes; it satisfies the SLA for both databases and is simpler to manage. The slight downside is that the time between log backups for databases other than the first one in 74 75 Chapter 2: Planning, Storage and Documentation the list might be slightly longer than 30 minutes, since the log backup for a given database in the queue can't start till the previous one finishes. However, since the backups are frequent and so the backup times short, any discrepancy is likely to be very small. Backup Verification and Test Restores Whether there are 10 databases in our environment or 1,000, as DBAs, we must ensure that all backups are valid and usable. Without good backups, we will be in a very bad spot when the time comes to bring some data back from the dead. Backup verification is easy to integrate into normal backup routines, so let's discuss a few tips on how to achieve this. The first, and most effective, way to make sure that the backups are ready for use is simply to perform some test restores. This may seem obvious, but there are too many DBAs who simply assume that their backups are good and let them sit on the shelf. We don't need to restore every backup in the system to check its health, but doing random spot checks now and again is an easy way to gain peace of mind regarding future restores. Each week, choose a random database, and restore its last full backup. If that database is subject to differential and log backups as well, choose a point-in-time test restore that uses a full, differential and a few log backup files. Since it's probably unrealistic to perform regular test restores on every single database, there are a few other practices that a DBA can adopt to maximize the likelihood that backup files are free of any corruption and can be smoothly restored. 75 76 Chapter 2: Planning, Storage and Documentation Back up WITH CHECKSUM We can use the WITH CHECKSUM option, as part of a backup operation, to instruct SQL Server to test each page with its corresponding checksum to makes sure that no corruption has happened in the I/O subsystem. BACKUP DATABASE <DatabaseName> TO DISK = '<Backup_location>' WITH CHECKSUM Listing 2-1: Backup WITH CHECKSUM syntax. If it finds a page that fails this test, the backup will fail. If the backup succeeds then the backup is valid or maybe not. In fact, this type of validation has gotten many DBAs into trouble. It does not guarantee that a database backup is corruption free. The CHECKSUM only verifies that we are not backing up a database that was already corrupt in some way; if the corruption occurs in memory or somehow else during the backup operation, then it will not be detected. As a final note, my experience and that of many others, suggests that, depending on the size of the database that is being used, enabling checksums (and other checks such as torn page detection) will bring with it a small CPU overhead and may slow down your backups (often minimally). However, use of the WITH CHECKSUM option during backups is a valuable safeguard and, if you can spare the few extra CPU cycles and the extra time the backups will take, go ahead. These checks are especially valuable when used in conjunction with restore verification. 76 77 Chapter 2: Planning, Storage and Documentation Verifying restores Since we cannot rely entirely on page checksums during backups, we should also be performing some restore verifications to make sure our backups are valid and restorable. As noted earlier, the surest way to do this is by performing test restores. However, a good additional safety net is to use the RESTORE VERIFYONLY command. This command will verify that the structure of a backup file is complete and readable. It attempts to mimic an actual restore operation as closely as possible without actually restoring the data. As such, this operation only verifies the backup header; it does not verify that the data contained in the file is valid and not corrupt. However, for databases where we've performed BACKUP WITH CHECKSUM, we can then re-verify these checksums as part of the restore verification process. RESTORE VERIFYONLY FROM DISK= '<Backup_location>' WITH CHECKSUM Listing 2-2: RESTORE VERIFYONLY WITH CHECKSUM syntax. This will recalculate the checksum on the data pages contained in the backup file and compare it against the checksum values generated during the backup. If they match, it's a good indication that the data wasn't corrupted during the backup process. DBCC CHECKDB One of the best ways to ensure that databases remain free of corruption, so that this corruption does not creep into backup files, making mincemeat of our backup and restore planning, is to run DBCC CHECKDB on a regular basis, to check the logical and physical integrity of all the objects in the specified database, and so catch corruption as early as possible. 77 78 Chapter 2: Planning, Storage and Documentation We will not discuss this topic in detail in this book, but check out the information in Books Online ( aspx) and if you are not already performing these checks regularly, you should research and start a DBCC CHECKDB regimen immediately. Documenting Critical Backup Information Properly documenting your backup and restore plan goes beyond the SLA which we have previously discussed. There is a lot more information that you must know, and document, for each of the databases in your care, and the backup scheme to which they are subject. The following checklist summarizes just some of the items that should be documented. For further coverage, Brad McGehee is currently writing a series of articles on documenting SQL Server databases, covering the information listed below, and much more. See, for example, database-properties-health-check/. Database File Information Physical File Name: MDF Location: NDF Location(s) (add more rows as needed): Filegroup(s) (add more rows as needed): Includes Partitioned Tables/Indexes: Database Size: Has Database File Layout Been Optimized: 78 79 Chapter 2: Planning, Storage and Documentation Log File Information Physical File Name: LDF Location: Log Size: Number of Virtual Log Files: Backup Information Types of Backups Performed (Full, Differential, Log): Last Full Database Backup: Last Differential Database Backup: Last Transaction Log Backup: How Often are Transaction Logs Backed Up: Average Database Full Backup Time: Database Full Backup Size: Average Transaction Log Backup Size: Number of Full Database Backup Copies Retained: Backups Encrypted: Backups Compressed: Backup To Location: Offsite Backup Location: Backup Software/Agent Used: 79 80 Chapter 2: Planning, Storage and Documentation This information can be harvested in a number of different ways, but ideally will be scripted and automated. Listing 2-3 shows two scripts that will capture just some of this information; please feel free to adapt and amend as is suitable for your environment. SELECT d.name, MAX(d.recovery_model), is_password_protected, --Backups Encrypted: --Last Full Database Backup: MAX(CASE WHEN type = 'D' THEN backup_start_date ELSE NULL END) AS [Last Full Database Backup], --Last Transaction Log Backup: MAX(CASE WHEN type = 'L' THEN backup_start_date ELSE NULL END) AS [Last Transaction Log Backup], --Last Differential Log Backup: MAX(CASE WHEN type = 'I' THEN backup_start_date ELSE NULL END) AS [Last Differential Backup], --How Often are Transaction Logs Backed Up: DATEDIFF(Day, MIN(CASE WHEN type = 'L' THEN backup_start_date ELSE 0 END), MAX(CASE WHEN type = 'L' THEN backup_start_date ELSE 0 END)) / NULLIF(SUM(CASE WHEN type = 'I' THEN 1 ELSE 0 END), 0) [Logs BackUp count], --Average backup times: SUM(CASE WHEN type = 'D' THEN DATEDIFF(second, backup_start_date, Backup_finish_date) ELSE 0 END) / NULLIF(SUM(CASE WHEN type = 'D' THEN 1 ELSE 0 END), 0) AS [Average Database Full Backup Time], SUM(CASE WHEN type = 'I' THEN DATEDIFF(second, backup_start_date, Backup_finish_date) ELSE 0 END) / NULLIF(SUM(CASE WHEN type = 'I' THEN 1 80 81 Chapter 2: Planning, Storage and Documentation ELSE 0 END), 0) AS [Average Differential Backup Time], SUM(CASE WHEN type = 'L' THEN DATEDIFF(second, backup_start_date, Backup_finish_date) ELSE 0 END) / NULLIF(SUM(CASE WHEN type = 'L' THEN 1 ELSE 0 END), 0) AS [Average Log Backup Time], SUM(CASE WHEN type = 'F' THEN DATEDIFF(second, backup_start_date, Backup_finish_date) ELSE 0 END) / NULLIF(SUM(CASE WHEN type = 'F' THEN 1 ELSE 0 END), 0) AS [Average file/filegroup Backup Time], SUM(CASE WHEN type = 'G' THEN DATEDIFF(second, backup_start_date, Backup_finish_date) ELSE 0 END) / NULLIF(SUM(CASE WHEN type = 'G' THEN 1 ELSE 0 END), 0) AS [Average Differential file Backup Time], SUM(CASE WHEN type = 'P' THEN DATEDIFF(second, backup_start_date, Backup_finish_date) ELSE 0 END) / NULLIF(SUM(CASE WHEN type = 'P' THEN 1 ELSE 0 END), 0) AS [Average partial Backup Time], SUM(CASE WHEN type = 'Q' THEN DATEDIFF(second, backup_start_date, Backup_finish_date) ELSE 0 END) / NULLIF(SUM(CASE WHEN type = 'Q' THEN 1 ELSE 0 END), 0) AS [Average Differential partial Backup Time], MAX(CASE WHEN type = 'D' THEN backup_size ELSE 0 END) AS [Database Full Backup Size], 81 82 Chapter 2: Planning, Storage and Documentation SUM(CASE WHEN type = 'L' THEN backup_size ELSE 0 END) / NULLIF(SUM(CASE WHEN type = 'L' THEN 1 ELSE 0 END), 0) AS [Average Transaction Log Backup Size], --Backup compression?: CASE WHEN SUM(backup_size - compressed_backup_size) <> 0 THEN 'yes' ELSE 'no' END AS [Backups Compressed] FROM master.sys.databases d LEFT OUTER JOIN msdb.dbo.backupset b ON d.name = b.database_name WHERE d.database_id NOT IN ( 2, 3 ) GROUP BY d.name, is_password_protected --HAVING MAX(b.backup_finish_date) <= DATEADD(dd, -7, GETDATE()) ; -- database characteristics SELECT d.name, f.name, LOWER(f.type_Desc), physical_name AS [Physical File Name], [size] / 64 AS [Database Size (Mb)], CASE WHEN growth = 0 THEN 'fixed size' WHEN is_percent_growth = 0 THEN CONVERT(VARCHAR(10), growth / 64) ELSE CONVERT(VARCHAR(10), ( [size] * growth / 100 ) / 64) END AS [Growth (Mb)], CASE WHEN max_size = 0 THEN 'No growth allowed' WHEN max_size = -1 THEN 'unlimited Growth' WHEN max_size = THEN '2 TB' ELSE CONVERT(VARCHAR(10), max_size / 64) + 'Mb' END AS [Max Size], CASE WHEN growth = 0 THEN 'no autogrowth' WHEN is_percent_growth = 0 THEN 'fixed increment' ELSE 'percentage' END AS [Database Autogrowth Setting] FROM master.sys.databases d INNER JOIN master.sys.master_files F ON f.database_id = d.database_id ORDER BY f.name, f.file_id Listing 2-3: Collecting database file and backup file information. 82 83 Chapter 2: Planning, Storage and Documentation Summary With the first two chapters complete, the foundation is laid; we've covered database file architecture, the types of backup that are available, and how this, and the overall backup strategy, is affected by the recovery model of the database. We've also considered hardware storage requirements for our database and backup files, the tools available to capture the backups, and how to develop an appropriate Service Level Agreement for a given database, depending on factors such as toleration for data loss, database size, workload, and so on. We are now ready to move on to the real thing; actually taking and restoring different types of backup. Over the coming chapters, we'll build some sample databases, and demonstrate all the different types of backup and subsequent restore, using both native scripting and a third-party tool (Red Gate SQL Backup). 83 84 Chapter 3: Full Database Backups A full database backup is probably the most common type of backup in the SQL Server world. It is essentially a backup of the data file(s) associated with a database. This chapter will demonstrate how to perform these full database backups, using both GUI-driven and T-SQL techniques. We'll create and populate a sample database, then demonstrate how to capture a full database backup using both the SQL Server Management Studio (SSMS) GUI, and T-SQL scripts. We'll capture and store some metrics (backup time, size of backup file) for both full backup techniques. We'll then take a look at the native backup compression feature, which became part of SQL Server Standard edition in SQL Server 2008, and we'll demonstrate how much potential disk storage space (and backup time) can be saved using this feature. By the end of Chapter 3, we'll be ready to restore a full backup file, and so return our sample database to the exact state that it existed at the time the full database backup process was taken. In Chapter 8, we'll see how to automate the whole process of taking full, as well as differential and transaction log, backups using Red Gate SQL Backup. What is a Full Database Backup? As discussed in Chapter 1, a full database backup (herein referred to simply as a "full backup") is essentially an "archive" of your database as it existed at the point in time of the backup operation. 84 85 Chapter 3: Full Database Backups It's useful to know exactly what is contained in this "archive" and a full backup contains: a copy of the database at the time of backup creation all user objects and data system information pertinent to the database user information permissions information system tables and views enough of the transaction log to be able to bring the database back online in a consistent state, in the event of a failure. Why Take Full Backups? Full backups are the cornerstone of a disaster recovery strategy for any user database, in the event of data corruption, or the loss of a single disk drive, or even a catastrophic hardware failure, where all physical media for a server is lost or damaged. In such cases, the availability of a full backup file, stored securely in a separate location, may be the only route to getting an online business back up and running on a new server, with at least most of its data intact. If there are also differential backups (Chapter 7) and log backups (Chapter 5), then there is a strong chance that we can recover the database to a state very close to that in which it existed shortly before the disaster. If a full backup for a database has never been taken then, by definition, there also won't be any differential or log backups (a full backup is a prerequisite for both), and there is very little chance of recovering the data. In the event of accidental data loss or data corruption, where the database is still operational, then, again, the availability of a full backup (in conjunction with other backup types, if appropriate) means we can restore a secondary copy of the database to a previous 85 86 Chapter 3: Full Database Backups point in time, where the data existed, and then transfer that data back into the live database, using a tool such as SSIS or T-SQL (we cover this in detail in Chapter 6, Log Restores). It is important to stress that these methods, i.e. recovering from potential data loss by restoring backup files, represent the only sure way to recover all, or very nearly all, of the lost data. The alternatives, such as use of specialized log recovery tools, or attempting to recover data from secondary or replica databases, offer relatively slim chances of success. Aside from disaster recovery scenarios, there are also a few day-to-day operations where full backups will be used. Any time that we want to replace an entire database or create a new database containing the entire contents of the backup, we will perform a full backup restore. For example: moving a development project database into production for the first time; we can restore the full backup to the production server to create a brand new database, complete with any data that is required. refreshing a development or quality assurance system with production data for use in testing new processes or process changes on a different server; this is a common occurrence in development infrastructures and regular full backup restores are often performed on an automated schedule. Full Backups in the Backup and Restore SLA For many databases, an agreement regarding the frequency and scheduling of full database backups will form only one component of a wider Backup and Restore SLA, which also covers the need for other backup types (differential, log, and so on). However, for certain databases, the SLA may well specify a need for only full backups. These full backups will, in general, be taken either nightly or weekly. If a database is 86 87 Chapter 3: Full Database Backups subject to a moderate level of data modification, but the flexibility of full point-in-time restore, via log backups, is not required, then the Backup SLA can stipulate simply that nightly full database backups should be taken. The majority of the development and testing databases that I look after receive only a nightly full database backup. In the event of corruption or data loss, I can get the developers and testers back to a good working state by restoring the previous night's full backup. In theory, these databases are exposed to a maximum risk of losing just less than 24 hours of data changes. However, in reality, the risk is much lower since most development happens during a much narrower daytime window. This risk is usually acceptable in development environments, but don't just assume this to be the case; make sure you get sign-off from the project owners. For a database subject only to very infrequent changes, it may be acceptable to take only a weekly full backup. Here the risk of loss is just under seven days, but if the database really is only rarely modified then the overall risk is still quite low. Remember that the whole point of a Backup SLA is to get everyone with a vested interest to "sign off" on acceptable levels of data loss for a given database. Work with the database owners to determine the backup strategy that works best for their databases and for you as the DBA. You don't ever want to be caught in a situation where you assumed a certain level of data loss was acceptable and it turned out you were wrong. Preparing for Full Backups We're going to run through examples of how to take full backups only, using both SSMS and T-SQL scripts. Chapter 4 will show how to restore these backups, and then Chapters 5 and 6 will show how to take and restore log backups, and Chapter 7 will cover differential backup and restore. In Chapter 8, we'll show how to manage full, differential and log backups, using a third-party tool (Red Gate SQL Backup) and demonstrate some of the advantages that such tools offer. 87 88 Chapter 3: Full Database Backups Before we get started taking full backups, however, we need to do a bit of preparatory work, namely choosing an appropriate recovery model for our example database, and then creating that database along with some populated sample tables. Choosing the recovery model For the example database in this chapter, we're going to assume that our Backup SLA expresses a tolerance to potential data loss of 24 hours, as might be appropriate for a typical development database. We can satisfy this requirement using just full database backups, so differential and log backups will not form part of our backup strategy, at this stage. Full database backups can be taken in any one of the three supported recovery models; SIMPLE, FULL or BULK LOGGED (see Chapter 1 for details). Given all this, it makes strategic and administrative sense to operate this database in the SIMPLE recovery model. This will enable us to take the full backups we need, and will also greatly simplify the overall management of this database, since in SIMPLE recovery the transaction log is automatically truncated upon CHECKPOINT (see Chapter 1), and so space in the log is regularly made available for reuse. If we operated the database in FULL recovery, then we would end up taking log backups just to control the size of the log file, even though we don't need those log backups for database recovery purposes. This would generate a needless administrative burden, and waste system resources. Database creation The sample database for this chapter will be about as simple as it's possible to get. It will consist of a single data (mdf) file contained in a single filegroup; there will be no secondary data files or filegroups. This one data file will contain just a handful of tables where we will store a million rows of data. Listing 3-1 shows our fairly simple database creation script. Note that in a production database the data and log files would be placed on separate drives. 88 89 Chapter 3: Full Database Backups CREATE DATABASE [DatabaseForFullBackups] ON PRIMARY ( NAME = N'DatabaseForFullBackups', FILENAME = N'C:\SQLData\DatabaseForFullBackups.mdf', SIZE = KB, FILEGROWTH = KB ) LOG ON ( NAME = N'DatabaseForFullBackups_log', FILENAME = N'C:\SQLData\DatabaseForFullBackups_log.ldf', SIZE = KB, FILEGROWTH = 10240KB ) Listing 3-1: Creating the DatabaseForFullBackups sample database. This is a relatively simple CREATE DATABASE statement, though even it is not quite as minimal as it could be; CREATE DATABASE [DatabaseForFullBackups] would work, since all the arguments are optional in the sense that, if we don't provide explicit values for them, they will take their default values from whatever is specified in the model database. Nevertheless, it's instructive, and usually advisable, to explicitly supply values for at least those parameters shown here. We have named the database DatabaseForFullBackups, which is a clear statement of the purpose of this database. Secondly, via the NAME argument, we assign logical names to the physical files. We are adopting the default naming convention for SQL Server 2008, which is to use the database name for logical name of the data file, and append _log to the database name for the logical name of the log file. File size and growth characteristics The FILENAME argument specifies the path and file name used by the operating system. Again, we are using the default storage path, storing the files in the default data directory, and the default file name convention, which is to simply append.mdf and.ldf to the logical file names. 89 90 Chapter 3: Full Database Backups The optional SIZE and FILEGROWTH arguments are the only cases where we use some non-default settings. The default initial SIZE settings for the data and log files, inherited from the model database properties, are too small (typically, 3 MB and 1 MB respectively) for most databases. Likewise the default FILEGROWTH settings (typically 1 MB increments for the data files and 10% increments for the log file) are also inappropriate. In busy databases, they can lead to fragmentation issues, as the data and log files grow in many small increments. The first problem is physical file fragmentation, which occurs when a file's data is written to non-contiguous sectors of the physical hard disk (SQL Server has no knowledge of this). This physical fragmentation is greatly exacerbated if the data and log files are allowed to grow in lots of small auto-growth increments, and it can have a big impact on the performance of the database, especially for sequential write operations. As a best practice it's wise, when creating a new database, to defragment the disk drive (if necessary) and then create the data and log files pre-sized so that they can accommodate, without further growth in file size, the current data plus estimated data growth over a reasonable period. In a production database, we may want to size the files to accommodate, say, a year's worth of data growth. There are other reasons to avoid allowing your database files to grow in multiple small increments. Each growth event will incur a CPU penalty. This penalty can be mitigated for data files by instant file initialization (enabled by granting the perform volume maintenance tasks right to the SQL Server service account). However, the same optimization does not apply to log files. Furthermore, growing the log file in many small increments can cause log fragmentation, which is essentially the creation of a very large number of small VLFs, which can deteriorate the performance of crash recovery, restores, and log backups (in other words, operations that read the log file). We'll discuss this in more detail in Chapter 5. 90 91 Chapter 3: Full Database Backups In any event, in our case, we're just setting the SIZE and FILEGROWTH settings such that SQL Server doesn't have to grow the files while we pump in our test data. We've used an initial data files size of 500 MB, growing in 100 MB increments, and an initial size for the log file of 100 MB, growing in 10 MB increments. When you're ready, execute the script in Listing 3-1, and the database will be created. Alternatively, if you prefer to create the database via the SSMS GUI, rather than using a script, simply right-click on the Databases node in SSMS, select New Database, and fill out the General tab so it looks like that shown in Figure 3-1. Figure 3-1: Creating a database via SSMS. Setting database properties If, via SSMS, we generate a CREATE script for an existing database, it will contain the expected CREATE DATABASE section, specifying the values for the NAME, FILENAME, SIZE, MAXSIZE and FILEGROWTH arguments. However, this will be followed by a swathe of ALTER DATABASE commands that set various other database options. To see them all, simply browse the various Properties pages for any database. All of these options are, under the covers, assigned default values according to those specified by the model system database; hence the name model, since it is used as a model from which to create all user databases. Listing 3-2 shows a script to set six of the more important options. 91 92 Chapter 3: Full Database Backups ALTER DATABASE [DatabaseForFullBackups] SET COMPATIBILITY_LEVEL = 100 ALTER DATABASE [DatabaseForFullBackups] SET AUTO_SHRINK OFF ALTER DATABASE [DatabaseForFullBackups] SET AUTO_UPDATE_STATISTICS ON ALTER DATABASE [DatabaseForFullBackups] SET READ_WRITE ALTER DATABASE [DatabaseForFullBackups] SET RECOVERY SIMPLE ALTER DATABASE [DatabaseForFullBackups] SET MULTI_USER Listing 3-2: Various options of the ALTER DATABASE command. The meaning of each of these options is as follows: COMPATIBILITY_LEVEL This lets SQL Server know with which version of SQL Server to make the database compatible. In all of our examples, we will be using 100, which signifies SQL Server AUTO_SHRINK This option either turns on or off the feature that will automatically shrink your database files when free space is available. In almost all cases, this should be set to OFF. AUTO_UPDATE_STATISTICS When turned ON, as it should be in most cases, the optimizer will automatically keep statistics updated, in response to data modications. READ_WRITE This is the default option and the one to use if you want users to be able to update the database. We could also set the database to READ_ONLY to prevent any users making updates to the database. RECOVERY SIMPLE This tells SQL Server to set the recovery model of the database to SIMPLE. Other options are FULL (the usual default) and BULK_LOGGED. 92 93 Chapter 3: Full Database Backups MULTI_USER For the database to allow connections for multiple users, we need to set this option. Our other choice is SINGLE_USER, which allows only one connection to the database at a time. The only case where we are changing the usual default value is the command to set the recovery model to SIMPLE; in most cases, the model database will, by default, be operating in the FULL recovery model and so this is the recovery model that will be conferred on all user databases. If the default recovery model for the model database is already set to SIMPLE, for your instance, then you won't need to execute this portion of the ALTER script. If you do need to change the recovery model, just make sure you are in the correct database before running this command, to avoid changing another database's recovery model. Alternatively, simpy pull up the Properties for our newly created database and change the recovery model manually, on the Options page, as shown in Figure 3-2. Figure 3-2: The Options page for a database, in SSMS. 93 94 Chapter 3: Full Database Backups Creating and populating the tables Now that we have a brand new database created on our instance, we need to create a few sample tables. Listing 3-3 shows the script to create two message tables, each with the same simple structure. USE [DatabaseForFullBackups] SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON] Listing 3-3: Table creation script. MessageTable1 and MessageTable2 are both very simple tables, comprised of only two columns each. The MessageData column will contain a static character string, mainly to fill up data space, and the MessageDate will hold the date and time that the message was inserted. 94 95 Chapter 3: Full Database Backups Now that we have our tables set up, we need to populate them with data. We want to pack in a few hundred thousand rows so that the database will have a substantial size. However, we won't make it so large that it will risk filling up your desktop/laptop drive. Normally, a DBA tasked with pumping several hundred thousand rows of data into a table would reach for the BCP tool and a flat file, which would be the fastest way to achieve this goal. However, since coverage of BCP is out of scope for this chapter, we'll settle for a simpler, but much slower, T-SQL method, as shown in Listing 3-4. USE [DatabaseForFullBackups] dbo.messagetable1 VALUES GETDATE()) Listing 3-4: Populating MessageTable1. The code uses a neat trick that allows us to INSERT the same data into the MessageTable1 table multiple times, without using a looping mechanism. The statement is normally used as a batch separator, but in this case we pass it a parameter defining the number of times to run the code in the batch. So, our database is now at a decent size, somewhere around 500 MB. This is not a large database by any stretch of the imagination, but it is large enough that it will take more than a few seconds to back up. 95 96 Chapter 3: Full Database Backups Generating testing data Getting a decent amount of testing data into a database can be a daunting task, especially when the database becomes much more complex than our example. Red Gate offers a product, SQL Data Generator, which will scan your database and table structure to give you a very robust set of options for automatically generating test data. You can also write custom data generators for even the most specific of projects. See Taking Full Backups We are now set to go and we're going to discuss taking full backups the "GUI way," in SSMS, and by using native T-SQL Backup commands. As you work through the backup examples in this chapter, and throughout the book, for learning purposes, you may occasionally want to start again from scratch, that is, to drop the example database, re-create it, and retake the backups. The best way to do this is to delete the existing backup files for that database, and then drop the database in a way that also clears out the backup history for that database, which is stored in the msdb database. This will prevent SQL Server from referencing any old backup information. Listing 3-5 shows how to do this. EXEC = N'DatabaseName' USE [master] DROP DATABASE [DatabaseName] Listing 3-5: Dropping a database and deleting backup history. 96 97 Chapter 3: Full Database Backups Alternatively, using the SSMS GUI, simply right-click on the database, and select Delete; by default, the option to Delete backup and restore history information for databases will be checked and this will clear out the msdb historical information. Native SSMS GUI method Taking full backups using the SSMS GUI is a fairly straightforward process. I use this technique mainly to perform a one-time backup, perhaps before implementing some heavy data changes on the database. This provides an easy way to revert the database to the state it was in before the change process began, should something go wrong. We're going to store the backup files on local disk, in a dedicated folder. So go ahead now and create a new folder on the root of the C:\ drive of the SQL Server instance, called SQLBackups and then create a subfolder called Chapter3 where we'll store all the full backup files in this chapter. Again, we use the same drive as the one used to store the online data and log files purely as a convenience; in a production scenario, we'd stored the backups on a separate drive! The Backup Database wizard We are now ready to start the full backup process. Open SQL Server Management Studio, connect to your server, expand the Databases node and then right-click on the DatabaseForFullBackups database, and navigate Tasks Backup, as shown in Figure 98 Chapter 3: Full Database Backups Figure 3-3: Back Up Database menu option. This will start the backup wizard and bring up a dialog box titled Back Up Database DatabaseForFullBackups, shown in Figure 3-4, with several configuration options that are available to the T-SQL BACKUP DATABASE command. Don't forget that all we're really doing here is using a graphical interface to build and run a T-SQL command. 98 99 Chapter 3: Full Database Backups Figure 3-4: Back Up Database wizard. The General page comprises three major sections: Source, Backup set and Destination. In the Source section, we specify the database to be backed up and what type of backup to perform. The Backup type drop-down list shows the types of backup that are available to your database. In our example we are only presented with two options, Full and Differential, since our database is in SIMPLE recovery model. 99 100 Chapter 3: Full Database Backups You will also notice a check box with the label Copy-only backup. A copy-only full backup is one that does not affect the normal backup operations of a database and is used when a full backup is needed outside of a normal scheduled backup plan. When a normal full database backup is taken, SQL Server modifies some internal archive points in the database, to indicate that a new base file has been created, for use when restoring subsequent differential backups. Copy-only full backups preserve these internal archive points and so cannot be used as a differential base. We're not concerned with copy-only backups at this point. The Backup component section is where we specify either a database or file/filegroup backup. The latter option is only available for databases with more than one filegroup, so it is deactivated in this case. We will, however, talk more about this option when we get to Chapter 9, on file and filegroup backups. In the Backup set section, there are name and description fields used to identify the backup set, which is simply the set of data that was chosen to be backed up. The information provided here will be used to tag the backup set created, and record its creation in the MSDB backup history tables. There is also an option to set an expiration date on our backup set. When taking SQL Server backups, it is entirely possible to store multiple copies of a database backup in the same file or media. SQL Server will just append the next backup to the end of the backup file. This expiration date lets SQL Server know how long it should keep this backup set in that file before overwriting it. Most DBAs do not use this "multiple backups per file" feature. There are only a few benefits, primarily a smaller number of files to manage, and many more drawbacks: larger backup files and single points of failure, to name only two. For simplicity and manageability, throughout this book, we will only deal with backups that house a single backup per file. The Destination section is where we specify the backup media and, in the case of disk, the location of the file on this disk. The Tape option button will be disabled unless a tape drive device is attached to the server. 100 101 Chapter 3: Full Database Backups As discussed in Chapter 1, even if you still use tape media, as many do, you will almost never back up directly to tape; instead you'll back up to disk and then transfer older backups to tape. When using disk media to store backups, we are offered three buttons to the right of the file listing window, for adding and removing disk destinations, as well as looking at the different backup sets that are already stored in a particular file. The box will be pre-populated with a default file name and destination for the default SQL Server backup folder. We are not going to be using that folder (simply because we'll be storing our backups in separate folders, according to chapter) so go ahead and use the Remove button on that file to take it out of the list. Now, use the only available button, the Add button to bring up the Select Backup Destination window. Make sure you have the File name option selected, click the browse ( ) button to bring up the Locate Database Files window. Locate the SQLBackups\Chapter3 directory that you created earlier, on the machine and then enter a name for the file, DatabaseForFullBackups_Full_Native_1.bak as shown in Figure 3-5. Figure 3-5: Backup file configuration. 101 102 Chapter 3: Full Database Backups Once this has been configured, click OK to finalize the new file configuration and click OK again on the Select Backup Destination dialog box to bring you back to the Back Up Database page. Now that we are done with the General page of this wizard, let's take a look at the Options Page, shown in Figure 3-6. Figure 3-6: Configuration options for backups. 102 103 Chapter 3: Full Database Backups The Overwrite media section is used in cases where a single file stores multiple backups and backup sets. We can set the new backup to append to the existing backup set or to overwrite the specifically named set that already exists in the file. We can also use this section to overwrite an existing backup set and start afresh. We'll use the option of Overwrite all existing backup sets since we are only storing one backup per file. This will make sure that, if we were to run the same command again in the event of an issue, we would wind up with just one backup set in the file. The Reliability section provides various options that can be used to validate the backup, as follows: Verify backup when finished Validates that the backup set is complete, after the backup operation has completed. It will make sure that each backup in the set is readable and ready for use. Perform checksum before writing to media SQL Server performs a checksum operation on the backup data before writing it to the storage media. As discussed in Chapter 2, a checksum is a special function used to make sure that the data being written to the disk/tape matches what was pulled from the database or log file. This option makes sure your backup data is being written correctly, but might also slow down your backup operation. Continue on error Instructs SQL Server to continue with all backup operations even after an error has been raised during the backup operation. The Transaction log section offers two important configuration options for transaction log backups, and will be covered in Chapter 5. The Tape Drive section of the configuration is only applicable if you are writing your backups directly to tape media. We have previously discussed why this is not the best way for backups to be taken in most circumstances, so we will not be using these options (and they aren't available here anyway, since we've already elected to back up to disk). 103 104 Chapter 3: Full Database Backups The final Compression configuration section deals with SQL Server native backup compression, which is an option that we'll ignore for now, but come back to later in the chapter. Having reviewed all of the configuration options, go ahead and click OK at the bottom of the page to begin taking a full database backup of the DatabaseForFullBackups database. You will notice the progress section begin counting up in percentage. Once this reaches 100%, you should receive a dialog box notifying you that your backup has completed. Click OK on this notification and that should close both the dialog box and the Back Up Database wizard. Gathering backup metrics, Part 1 That wasn't so bad! We took a full backup of our database that has one million rows of data in it. On a reasonably laptop or desktop machine, the backup probably would have taken seconds. On a decent server, it will have been much quicker. However, it's useful to have slightly more accurate timings so that we can compare the performance of the various methods of taking full backups. We also need to check out the size of the backup file, so we can see how much storage space it requires and, later, compare this to the space required for compressed backup files. To find out the size of the backup file, simple navigate to the SQLBackups\Chapter2 folder in Windows Explorer and check out the size of the DatabaseForFullBackups_ Full_Native_1.bak file. You should find that it's roughly the same size as the data (mdf) file, i.e. about 500 MB, or half of a gigabyte. This doesn't seem bad now, but given that some databases are over 1 TB in size, you can begin to appreciate the attraction of backup compression. Checking the exact execution time for the backup process is a little trickier. If we don't want to use a stopwatch to measure the start and stop of the full backup, we can use the backupset system table in MSDB to give us a more accurate backup time. Take a look 104 105 Chapter 3: Full Database Backups at Listing 3-6 for an example of how to pull this information from your system. I'm only returning a very small subset of the available columns, so examine the table more closely, to find more information that you might find useful. USE msdb SELECT database_name, DATEDIFF(SS, backup_start_date, backup_finish_date) AS [RunTImeSec], database_creation_date FROM dbo.backupset ORDER BY database_creation_date DESC Listing 3-6: Historical backup runtime query. Figure 3-7 shows some sample output. Figure 3-7: Historical backup runtime results. On my machine the backup takes 49 seconds. That seems fairly good, but we have to consider the size of the test database. It is only 500 MB, which is not a typical size for most production databases. In the next section, we'll pump more data into the database and take another full backup (this time using T-SQL directly), and we'll get to see how the backup execution time varies with database size. 105 106 Chapter 3: Full Database Backups Native T-SQL method Every DBA needs to know how to write a backup script in T-SQL. Scripting is our route to backup automation and, in cases where we don't have access to a GUI, it may be the only option available; we can simply execute our backups scripts via the osql or sqlcmd command line utilities. Here, however, for general readability, we'll execute the scripts via SSMS. Remember that the commands in this section are essentially the same ones that the GUI is generating and executing against the server when we use the Backup wizard. Before we move on to take another full backup of our DatabaseForFullBackups database, this time using T-SQL, we're first going add a bit more data. Let's put a new message into our second table with a different date and time stamp. We are going to use the same method to fill the second table as we did for the first. The only thing that is going to change is the text that we are entering. Take a look at Listing 3-7 and use this to push another million rows into the database. USE [DatabaseForFull 3-7: Populating the MessageTable2 table. 106 107 Chapter 3: Full Database Backups This script should take about a few minutes to fill the secondary table. Once it is populated with another million rows of the same size and structure as the first, our database file should be hovering somewhere around 1 GB in size, most likely just slightly under. Now that we have some more data to work with, let's move on to taking native SQL Server backups using T-SQL only. A simple T-SQL script for full backups Take a look at Listing 3-8, which shows a script that can be used to take a full backup of the newly populated DatabaseForFullBackups database. USE master BACKUP DATABASE [DatabaseForFullBackups] TO DISK = N'C:\SQLBackups\Chapter3\DatabaseForFullBackups_Full_Native_2.bak' WITH FORMAT, INIT, NAME = N'DatabaseForFullBackups-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10 Listing 3-8: Native full backup T-SQL script. This script may look like it has some extra parameters, compared to the native GUI backup that we did earlier, but this is the scripted output of that same backup, with only the output file name modified, and a few other very minor tweaks. So what do each of these parameters mean? The meaning of the first line should be fairly obvious; it is instructing SQL Server to perform a full backup of the DatabaseForFullBackups database. This leads into the second line where we have chosen to back up to disk, and given a complete file path to the resulting backup file. The remainder of the parameters are new, so let's go through each one. 107 108 Chapter 3: Full Database Backups. 108 109 Chapter 3: Full Database Backups STATS This option may prove useful to you when performing query-based backups. The STATS parameter defines the time intervals on which SQL Server should update the "backup progress" messages. For example, using stats=10 will cause SQL Server to send a status message to the query output for each 10 percent of the backup completion. As noted, if we wished to overwrite an existing backup set, we'd want to specify the INIT parameter but, beyond that, none of these secondary parameters, including the backup set NAME descriptor, are required. As such, we can actually use a much simplified BACKUP command, as shown in Listing 3-9. BACKUP DATABASE [DatabaseForFullBackups] TO DISK = N'C:\SQLBackups\Chapter3\DatabaseForFullBackups_Full_Native_2.bak' Listing 3-9: Slimmed-down native T-SQL backup code. Go ahead and start Management Studio and connect to your test server. Once you have connected, open a new query window and use either Listing 3-8 or 3-9 to perform this backup in SSMS. Once it is done executing, do not close the query, as the query output contains some metrics that we want to record. Gathering backup metrics, Part 2 Now that the backup has completed, let's take a look at the query output window to see if we can gather any information about the procedure. Unlike the native GUI backup, we are presented with a good bit of status data in the messages tab of the query window. The post-backup message window should look as shown in Figure 3-8 (if you ran Listing 3-8, it will also contain ten "percent processed" messages, which are not shown here). 109 110 Chapter 3: Full Database Backups Figure 3-8: Native T-SQL backup script message output. This status output shows how many database pages the backup processed as well as how quickly the backup was completed. On my machine, the backup operation completed in just under 80 seconds. Notice here that that the backup processes all the pages in the data file, plus two pages in the log file; the latter is required because a full backup needs to include enough of the log that the backup can produce a consistent database, upon restore. When we ran our first full backup, we had 500 MB in our database and the backup process took 49 seconds to complete. Why didn't it take twice as long this time, now that we just about doubled the amount of data? The fact is that the central process of writing data to the backup file probably did take roughly twice as long, but there are other "overhead processes" associated with the backup task that take roughly the same amount of time regardless of how much data is being backed up. As such, the time to take backups will not increase linearly with increasing database size. But does the size of the resulting backup file increase linearly? Navigating to our SQL Server backup files directory, we can see clearly that the size is nearly double that of the first backup file (see Figure 3-9). The file size of your native SQL Server backups will grow at nearly the same rate as the database data files grow. 110 111 Chapter 3: Full Database Backups Figure 3-9: Comparing native SQL Server backup file sizes. We will compare these metrics against the file sizes and speeds we get from backing up the same files using Red Gate's SQL Backup in Chapter 8. Native Backup Compression In SQL Server 2008 and earlier versions, backup compression was a feature only available in the Enterprise Edition (or Developer Edition) of SQL Server. However, starting with SQL Server 2008 R2, backup compression has been made available in all editions, so let's take a quick look at what savings it can offer over non-compressed backups, in terms of backup file size and the speed of the backup operation. Generally speaking, third-party backup tools still offer a better compression ratio, better speed and more options (such as compressed and encrypted backups) than native backup compression. However, we'll put that to the test in Chapter 8. All we're going to do is perform a compressed backup of the DatabaseForFull- Backups, using the script shown in Listing USE [master] BACKUP DATABASE [DatabaseForFullBackups] TO DISK = N'C:\SQLBackups\Chapter3\SQLNativeCompressionTest.bak' WITH COMPRESSION, STATS = 10 Listing 3-10: SQL native compression backup test. 111 112 Chapter 3: Full Database Backups The only difference between this and our backup script in Listing 3-9, is the use here of the COMPRESSION keyword, which instructs SQL Server to make sure this database is compressed when written to disk. If you prefer to run the compressed backup using the GUI method, simply locate the Compression section, on the Options page of the Backup Wizard, and change the setting from Use the default server setting to Compress backup. Note that, if desired, we can use the sp_configure stored procedure to make backup compression the default behavior for a SQL Server instance. On completion of the backup operation, the query output window will display output similar to that shown in Figure Figure 3-10: Compressed backup results. If you recall, a non-compressed backup of the same database took close to 80 seconds and resulted in a backup file size of just over 1 GB. Here, we can see that use of compression has reduced the backup time to about 32 seconds, and it results in a backup file size, shown in Figure 3-11, of only 13 KB! Figure 3-11: Compressed backup file size. 112 113 Chapter 3: Full Database Backups These results represent a considerable saving, in both storage space and processing time, over non-compressed backups. If you're wondering whether or not the compression rates should be roughly consistent across all your databases, then the short answer is no. Character data, such as that stored in our DatabaseForFullBackups database compresses very well. However, some databases may contain data that doesn't compress as readily such as FILESTREAM and image data, and so space savings will be less. Verifying Backups Having discussed the basic concepts of backup verification in Chapter 2, Listing 3-11 shows a simple script to perform a checksum during a backup of our DatabaseForFullBackups database, followed by a RESTORE VERIFYONLY, recalculating the checksum. BACKUP DATABASE [DatabaseForFullBackups] TO DISK = N'C:\SQLBackups\Chapter3\DatabaseForFullBackups_Full_Native_Checksum.bak' WITH CHECKSUM RESTORE VERIFYONLY FROM DISK = N'C:\SQLBackups\Chapter3\DatabaseForFullBackups_Full_Native_Checksum.bak' WITH CHECKSUM Listing 3-11: Backup verification examples. Hopefully you'll get output to the effect that the backup is valid! 113 114 Chapter 3: Full Database Backups Building a Reusable and Schedulable Backup Script Ad hoc database and transaction log backups can be performed via simple T-SQL scripts or the GUI, in SQL Server Management Studio. However, for production systems, the DBA will need a way to automate these backups, verify that the backups are valid, schedule and monitor them, and so on. Some of the options for automating backups are listed below. SSMS Maintenance Plans Wizard and Designer two tools, built into SSMS, which allow you to configure and schedule a range of core database maintenance tasks, including full database backups and transaction log backups. The DBA can also run DBCC integrity checks, schedule jobs to remove old backup files, and so on. An excellent description of these tools, and their limitations, can be found in Brad McGehee's book, Brad's Sure Guide to SQL Server Maintenance Plans. T-SQL scripts you can write custom T-SQL scripts to automate your backup tasks. A well established and respected set of maintenance scripts is provided by Ola Hallengren (). His scripts create a variety of stored procedures, each performing a specific database maintenance task, including backups, and automated using SQL Agent jobs. PowerShell / SMO scripting more powerful and versatile than T-SQL scripting, but with a steeper learning curve for many DBAs, PowerShell can be used to script and automate almost any maintenance task. There are many available books and resources for learning PowerShell. See, for example, powershell/64316/. Third-party backup tools several third-party tools exist that can automate backups, as well as verify and monitor them. Most offer backup compression and encryption as well as additional features to ease backup management, verify backups, and so on. Examples include Red Gate's SQL Backup, and Quest's LiteSpeed. 114 115 Chapter 3: Full Database Backups In my role as a DBA, I use a third-party backup tool, namely SQL Backup, to manage and schedule all of my backups. Chapter 8 will show how to use this tool to build a script that can be used in a SQL Agent job to take scheduled backups of databases. Summary This chapter explained in detail how to capture full database backups using either SSMS Backup Wizard or T-SQL scripts. We are now ready to move on to the restoration piece of the backup and restore jigsaw. Do not to remove any of the backup files we have captured; we are going to use each of these in the next chapter to restore our DatabaseForFullBackups database. 115 116 Chapter 4: Restoring From Full Backup In the previous chapter, we took two full backups of our DatabaseForFullBackups database, one taken when the database was about 500 MB in size and the second when it was around 1 GB. In this chapter, we're going to restore those full backup files, to re-create the databases as they existed at the point in time that the respective backup processes were taken. In both of our examples we will be restoring over existing databases in order to demonstrate some of the issues that may arise in that situation. In Chapter 6, we'll look at some examples that restore a new copy of a database. Full database restores are the cornerstone of our disaster recovery strategy, but will also be required as part of our regular production and development routines, for example, when restoring to development and test instances. However, for large databases, they can be a time- and disk space-consuming task, as well as causing the DBA a few strategic headaches, which we'll discuss as we progress through the chapter. Full Restores in the Backup and Restore SLA For a database that requires only full backups, the restore process is relatively straightforward, requiring only the relevant full backup file, usually the most recent backup. However, as discussed in Chapter 2, we still need to take into consideration the size of the database being restored, and the location of the backup files, when agreeing an appropriate maximum amount of time that the crash recovery process should take. For example, let's say someone accidentally deleted some records from a table and they need to be recovered. However, by the time the application owner has been notified of the issue, and in turn notified you, five days have passed since the unfortunate event. If local backup files are retained for only three days, then recovering the lost data will involve retrieving data from tape, which will add time to the recovery process. The SLA 116 117 Chapter 4: Restoring From Full Backup needs to stipulate file retention for as long as is reasonably necessary for such data loss or data integrity issues to be discovered. Just don't go overboard; there is no need to keep backup files for 2 weeks on local disk, when 3 5 days will do the trick 99.9% of the time. Possible Issues with Full Database Restores When we restore a database from a full backup file, it's worth remembering that this backup file includes all the objects, data and information that were present in the database at that time, including: all user-defined objects, including stored procedures, functions, views tables, triggers, database diagrams and the rest all data contained in each user-defined table system objects that are needed for regular database use and maintenance all data contained in the system tables user permissions for all objects on the database, including not only default and custom database roles, but also extended object permissions for all explicit permissions that have been set up for any user log file information that is needed to get the database back online, including size, location, and some internal information that is required. In other word, the backup file contains everything needed to re-create an exact copy of the database, as it existed when the backup was taken. However, there may be times when we might not want all of this data and information to be present in the restored database. Let's look at a few examples. 117 118 Chapter 4: Restoring From Full Backup Large data volumes As noted previously, full database restores can be a time-consuming process for large databases, and can quickly eat away at disk space, or even fill up a disk completely. In disaster recovery situations where only a small subset of data has been lost, it often feels frustrating to have to go through a long, full restore process in order to extract what might be only a few rows of data. However, when using only native SQL Server tools, there is no real alternative. If you have licenses for third-party backup and/or data comparison tools, it's worth investigating the possibility of performing what is termed object-level restore. In the case of Red Gate tools, the ones with which I am familiar, their backup products (both SQL Backup and Hyperbac), and SQL Data Compare, offer this functionality. With them, you can compare a backup file directly to a live database, and then restore only the missing object and data, rather than the whole database. Furthermore, Red Gate also offers a different kind of tool to accommodate these large database restore situations, namely SQL Virtual Restore. This tool allows you to mount compressed backups as databases without going through the entire restore process. Since I've yet to use this tool in a production scenario, I won't be including any examples in this book. However, to learn more, check out Brad McGehee's article on Simple Talk, at Restoring databases containing sensitive data If we simply go ahead and perform a full database restore of a production database onto one of our development or testing instances, we could inadvertently be breaking a lot of rules. It's possible that the production instance stores sensitive data and we do not want every developer in the company accessing social security numbers and bank account information, which would be encrypted in production, on their development machines! 118 119 Chapter 4: Restoring From Full Backup It would only take one rogue employee to steal a list of all clients and their sensitive information to sell to a competitor or, worse, a black market party. If you work at a financial institution, you may be dealing on a daily basis with account numbers, passwords and financial transaction, as well as sensitive user information such as social security numbers and addresses. Not only will this data be subject to strict security measures in order to keep customers' information safe, it will also be the target of government agencies and their compliance audits. More generally, while the production servers receive the full focus of attempts to deter and foil hackers, security can be a little lacking in non-production environments. This is why development and QA servers are a favorite target of malicious users, and why having complete customer records on such servers can cause big problems, if a compromise occurs. So, what's the solution? Obviously, for development purposes, we need the database schemas in our development and test servers to be initially identical to the schema that exists in production, so it's common practice, in such situations, to copy the schema but not the data. There are several ways to do this. Restore the full database backup, but immediately truncate all tables, purging all sensitive data. You may then need to shrink the development copy of your database; you don't want to have a 100 GB database shell if that space is never going to be needed. Note that, after a database shrink, you should always rebuild your indexes, as they will get fragmented as a result of such an operation. Use a schema comparison tool, to synch only the objects of the production and development databases. Wipe the database of all user tables and use SSIS to perform a database object transfer of all required user objects. This can be set up to transfer objects only and to ignore any data included in the production system. 119 120 Chapter 4: Restoring From Full Backup Of course, in each case, we will still need a complete, or at least partial, set of data in the development database, so we'll need to write some scripts, or use a data generation tool, such as SQL Data Generator, to establish a set of test data that is realistic but doesn't flout regulations for the protection of sensitive data. Too much permission Imagine now a situation where we are ready to push a brand new database into production, to be exposed to the real world. We take a backup of the development database, restore it on the production machine, turn on the services and website, and let our end-users go wild. A few weeks later, a frantic manager bursts through the door, screaming that the database is missing some critical data. It was there yesterday, but is missing this morning! Some detective work reveals that one of the developers accidentally dropped a table, after work hours the night before. How did this happen? At most, the developer should have had read-only access (via the db_datareader role) for the production machine! Upon investigation of the permissions assigned to that user for the production database, it is revealed that the developer is actually a member of the db_owner database role. How did the user get such elevated permissions? Well, the full database backup includes the complete permission set for the database. Each user's permissions are stored in the database and are associated to the login that they use on that server. When we restore the database from development to production, all database internal permissions are restored as well. If the developer login was assigned db_owner on the development machine, then this permission level will exist on production too, assuming the login was also valid for the production SQL Server. Similarly, if the developer login had db_owner in development but only db_datareader in production, then restoring the development database over the existing production database will effectively elevate the developer to db_owner in 120 121 Chapter 4: Restoring From Full Backup production. Even if a user doesn't have a login on the production database server, the restored database still holds the permissions. If that user is eventually given access to the production machine, he or she will automatically have that level of access, even if it wasn't explicitly given by the DBA team. The only case when this may not happen is when the user is using SQL Server authentication and the internal SID, a unique identifying value, doesn't match on the original and target server. If two SQL logins with the same name are created on different machines, the underlying SIDs will be different. So, when we move a database from Server A to Server B, a SQL login that has permission to access Server A will also be moved to Server B, but the underlying SID will be invalid and the database user will be "orphaned." This database user will need to be "de-orphaned" (see below) before the permissions will be valid. This will never happen for matching Active Directory accounts since the SID is always the same across a domain. In order to prevent this from happening in our environments, every time we restore a database from one environment to another we should: audit each and every login never assume that if a user has certain permissions in one environment they need the same in another; fix any internal user mappings for logins that exist on both servers, to ensure no one gets elevated permissions perform orphaned user maintenance remove permissions for any users that do not have a login on the server to which we are moving the database; the sp_change_ users_login stored procedure can help with this process, reporting all orphans, linking a user to its correct login, or creating a new login to which to link: EXEC sp_change_users_login 'Report' EXEC sp_change_users_login 'Auto_Fix', 'user' EXEC sp_change_users_login 'Auto_Fix', 'user', 'login', 'password' 121 122 Chapter 4: Restoring From Full Backup Don't let these issues dissuade you from performing full restores as and when necessary. Diligence is a great trait in a DBA, especially in regard to security. If you apply this diligence, keeping a keen eye out when restoring databases between mismatched environments, or when dealing with highly sensitive data of any kind, then you'll be fine. Performing Full Restores We are now ready to jump in and start restoring databases! This chapter will mimic the structure of Chapter 3, in that we'll first perform a full restore the "GUI way," in SSMS, and then by using native T-SQL RESTORE commands. In Chapter 8, we'll perform full restores using the Red Gate SQL Backup tool. Native SSMS GUI full backup restore Using the SSMS GUI, we're going to restore the first of the two full backups (Database- ForFullBackups_Full_Native_1.bak) that we took in Chapter 3, which was taken when the database contained about 500 MB of data. First, however, we need to decide whether we are going to restore this file over the current "live" version of the Database- ForFullBackups database, or simply create a new database. In this case, we are going to restore over the existing database, which is a common requirement when, for example, providing a weekly refresh of a development database. But wait, you might be thinking, the current version of DatabaseForFullBackups contains about 1 GB of data. If we do this, aren't we going to lose half that data? Indeed we are, but rest assured that all of those precious rows of data are safe in our second full database backup file, and we'll be bringing that data backup to life later in this chapter. So, go ahead and start SSMS, connect to your test instance, and then expand the databases tree menu as shown in Figure 123 Chapter 4: Restoring From Full Backup Figure 4-1: Getting SSMS prepared for restoration. To start the restore process, right-click on the database in question, DatabaseForFull- Backups, and navigate Tasks Restore Database..., as shown in Figure 4-2. This will initiate the Restore wizard. Figure 4-2: Starting the database restore wizard. 123 124 Chapter 4: Restoring From Full Backup The Restore Database window appears, with some options auto-populated. For example, the name of the database we're restoring to is auto-filled to be the same as the source database that was backed up. Perhaps more surprisingly, the backup set to restore is also auto-populated, as shown in Figure 4-3. What's happened is that SQL Server has inspected some of the system tables in the msdb database and located the backups that have already been taken for this database. Depending on how long ago you completed the backups in Chapter 3, the window will be populated with the backup sets taken in that chapter, letting us choose which set to restore. Figure 4-3: The Restore Database screen. 124 125 Chapter 4: Restoring From Full Backup We are not going to be using this pre-populated form, but will instead configure the restore process by hand, so that we restore our first full backup file. In the Source for restore section, choose the From device option and then click the ellipsis button ( ). In the Specify Backup window, make sure that the media type shows File, and click the Add button. In the Locate Backup File window, navigate to the C:\SQLBackups\Chapter3 folder and click on the DatabaseForFullBackups_Full_Native_1.bak backup file. Click OK twice to get back to the Restore Database window. We will now be able to see which backups are contained in the selected backup set. Since we only ever stored one backup per file, we only see one backup. Tick the box under the Restore column to select that backup file as the basis for the restore process, as shown in Figure 4-4. Figure 4-4: General configurations for full native restore. Next, click to the Options page on the left side of the restore configuration window. This will bring us to a whole new section of options to modify and validate (see Figure 4-5). 125 126 Chapter 4: Restoring From Full Backup Figure 4-5: The options page configurations for a full database restore. The top of the screen shows four Restore options as shown below. Overwrite the existing database the generated T-SQL command will include the REPLACE option, instructing SQL Server to overwrite the currently existing database information. Since we are overwriting an existing database, in this example we want to check this box. Note that it is advised to use the REPLACE option with care, due to the potential for overwriting a database with a backup of a different database. See 126 127 Chapter 4: Restoring From Full Backup Preserve the replication settings only for use in a replication-enabled environment. Basically allows you to re-initialize replication, after a restore, without having to reconfigure all the replication settings. Prompt before restoring each backup receive a prompt before each of the backup files is processed. We only have one backup file here, so leave this unchecked. Restrict access to the restored database restricts access to the restored database to only members of the database role db_owner and the two server roles sysadmin and dbcreator. Again, don't select this option here. The next portion of the Options page is the Restore the database files as: section, where we specify the location for the data (mdf) and log (ldf) files for the restored database. This will be auto-populated with the location of the original files, on which the backup was based. We have the option to move them to a new location on our drives but, for now, let's leave them in their original location, although it's wise to double-check that this location is correct for your system. Finally, we have the Recovery state section, where we specify the state in which the database should be left once the current backup file has been restored. If there are no further files to restore, and we wish to return the database to a useable state, we pick the first option, RESTORE WITH RECOVERY. When the restore process is run, the backup file will be restored and then the final step of the restore process, database recovery (see Chapter 1), will be carried out. This is the option to choose here, since we're restoring just a single full database backup. We'll cover the other two options later in the book, so we won't consider them further here. Our restore is configured and ready to go, so click OK and wait for the progress section of the restore window to notify us that the operation has successfully completed. If the restore operating doesn't show any progress, the probable reason is that there is another active connection to the database, which will prevent the restore operation from starting. Stop the restore, close any other connections and try again. A convenience of scripting, as we'll see a little later, is that we can check for, and close, any other connections before we attempt the restore operation. 127 128 How do we know it worked? Chapter 4: Restoring From Full Backup Let's run a few quick queries, shown in Listing 4-1, against our newly restored DatabaseForFullBackups database to verify that the data that we expect to be here is actually here. USE [DatabaseForFullBackups] SELECT MessageData, COUNT(MessageData) AS MessageCount FROM MessageTable1 GROUP BY MessageData SELECT MessageData, COUNT(MessageData) AS MessageCount FROM MessageTable2 GROUP BY MessageData Listing 4-1: Checking our restored data. The first query should return a million rows, each containing the same message. The second query, if everything worked in the way we intended, should return no rows. Collecting restore metrics Having run the full backup, in Chapter 3, we were able to interrogate msdb to gather some metrics on how long the backup process took. Unfortunately, when we run a restore process using SSMS, there is no record of the length of the operation, not even in the SQL Server log files. The only way to capture the time is to script out the RESTORE command and run the T-SQL. I won't show this script here, as we're going to run a T-SQL RESTORE command very shortly, but if you want to see the stats for yourself, right now, you'll need to 128 129 Chapter 4: Restoring From Full Backup re-create the Restore Database pages as we had them configured in Figures , and then click the Script drop-down button, and select Script Action to New Query Window. This will generate the T-SQL RESTORE command that will be the exact equivalent of what would be generated under the covers when running the process through the GUI. When I ran this T-SQL command on my test system, the restore took just under 29 seconds and processed 62,689 pages of data, as shown in Figure 4-6. Figure 4-6: Full native restore output. Native T-SQL full restore We are now going to perform a second full database restore, this time using a T-SQL script, and the second full backup file from Chapter 3 (DatabaseForFullBackups_ Full_Native_2.bak), which was taken after we pushed another 500 MB of data into the database, bringing the total size of the database to just under 1 GB. You may recall from Chapter 3 that doubling the size of the database did increase the backup time, but it was not a linear increase. We'll see if we get similar behavior when performing restores. Once again, we are going to overwrite the existing DatabaseForFullBackups database. This means that we want to kill all connections that are open before we begin our RESTORE operation, which we can do in one of two ways. The first involves going through the list of processes in master.sys.sysprocesses and killing each SPID associated with the database in question. However, this doesn't always do the trick, since it won't kill connections that run on a different database, but access tables in the database we wish to restore. We need a global way to stop any user process that accesses the database in question. 129 130 Chapter 4: Restoring From Full Backup For this reason, the second and most common way is to place the database into OFFLINE mode for a short period. This will drop all connections and terminate any queries currently processing against the database, which can then immediately be switched back to ONLINE mode, for the restore process to begin. Just be sure not to kill any connections that are processing important data. Even in development, we need to let users know before we just go wiping out currently running queries. Here, we'll be employing the second technique and so, in Listing 4-2, you'll see that we set the database to OFFLINE mode and use option, WITH ROLLBACK IMMEDIATE, which instructs SQL Server to roll those processes back immediately, without waiting for them to COMMIT. Alternatively, we could have specified WITH ROLLBACK AFTER XX SECONDS, where XX is the number of seconds SQL Server will wait before it will automatically start rollback procedures. We can then return the database to ONLINE mode, free of connections and ready to start the restore process. USE [master] ALTER DATABASE [DatabaseForFullBackups] SET OFFLINE WITH ROLLBACK IMMEDIATE ALTER DATABASE [DatabaseForFullBackups] SET ONLINE Listing 4-2: Dropping all user connections before a restore. Go ahead and give this a try. Open two query windows in SSMS; in one of them, start the long-running query shown in Listing 4-3 then, in the second window, run Listing 4-2. USE [DatabaseForFullBackups] WAITFOR DELAY '00:10:00' Listing 4-3: A long-running query. 130 131 Chapter 4: Restoring From Full Backup You'll see that the session with the long-running query was terminated, reporting a severe error and advising that any results returned be discarded. In the absence of a third-party tool, which will automatically take care of existing sessions before performing a restore, this is a handy script. You can include it in any backup scripts you use or, perhaps, convert it into a stored procedure which is always a good idea for reusable code. Now that we no longer have to worry about pesky user connections interfering with our restore process, we can go ahead and run the T-SQL RESTORE command in Listing 4-4. USE [master] RESTORE DATABASE [DatabaseForFullBackups] FROM DISK = N'C:\SQLBackups\Chapter3\DatabaseForFullBackups_Full_Native_2.bak' WITH FILE = 1, STATS = 25 Listing 4-4: Native SQL Server full backup restore. The RESTORE DATABASE command denotes that we wish to restore a full backup file for the DatabaseForFullBackups database. The next portion of the script configures the name and location of the backup file to be restored. If you chose a different name or location for this file, you'll need to amend this line accordingly. Finally, we specify a number of WITH options. The FILE argument identifies the backup set to be restored, within our backup file. As discussed in Chapter 2, backup files can hold more than one backup set, in which case we need to explicitly identify the number of the backup set within the file. Our policy in this book is "one backup set per file," so we'll always set FILE to a value of 1. The STATS argument is also one we've seen before, and specifies the time intervals at which SQL Server should update the "backup progress" messages. Here, we specify a message at 25% completion intervals. Notice that even though we are overwriting an existing database without starting with a tail log backup, we do not specify the REPLACE option here, since DatabaseForFull- Backups is a SIMPLE recovery model database, so the tail log backup is not possible. SQL 131 132 Chapter 4: Restoring From Full Backup Server will still overwrite any existing database on the server called DatabaseForFull- Backups, using the same logical file names for the data and log files that are recorded within the backup file. In such cases, we don't need to specify any of the file names or paths for the data or log files. Note, though, that this only works if the file structure is the same! The backup file contains the data and log file information, including the location to which to restore the data and log files so, if we are restoring a database to a different machine from the original, and the drive letters, for instance, don't match up, we will need to use the WITH MOVE argument to point SQL Server to a new location for the data and log files. This will also be a necessity if we need to restore the database on the same server with a different name. Of course, SQL Server won't be able to overwrite any data or log files if they are still in use by the original database. We'll cover this topic in more detail later in this chapter, and again in Chapter 6. Go ahead and run the RESTORE command. Once it is done executing, do not close the query session, as the query output contains some metrics that we want to record. We can verify that the restore process worked, at this point, by simply opening a new query window and executing the code from Listing 4-1. This time the first query should return a million rows containing the same message, and the second query should also return a million rows containing the same, slightly different, message. Collecting restore metrics, Part 2 Let's take a look at the Message window, where SQL Server directs non-dataset output, to view some metrics for our native T-SQL restore process, as shown in Figure 4-7. The first full restore of the 500 MB database processed 62,689 pages and took almost 29 seconds, on my test server. This restore, of the 1 GB database, processed roughly double the number of pages (125,201) and took roughly twice as long (almost 67 seconds). So, our database restore timings seem to exhibit more linear behavior than was observed for backup time. 132 133 Chapter 4: Restoring From Full Backup Figure 4-7: Results from the second native full backup restore. Before we move on, you may be wondering whether any special options or commands are necessary if restoring a native SQL Server backup file that is compressed. The answer is "No;" it is exactly the same process as restoring a normal backup file. Forcing Restore Failures for Fun The slight problem with the friendly demos found in most technical books is that the reader is set up for success, and often ends up bewildered when errors start occurring. As such, through this book, we'll be looking at common sources of error when backing up and restoring databases, and how you can expect SQL Server to respond. Hopefully this will better arm you to deal with such unexpected errors, as and when they occur in the real world. Here, we're going to start with a pretty blatant mistake, but nevertheless one that I've seen novices make. The intent of the code in Listing 4-5 is, we will assume, to create a copy of DatabaseForFullBackups as it existed when the referenced backup file was taken, and name the new copy DatabaseForFullBackups2. 133 134 Chapter 4: Restoring From Full Backup RESTORE DATABASE [DatabaseForFullBackups2] FROM DISK = N'C:\SQLBackups\Chapter3\DatabaseForFullBackups_Full_Native_2.bak' WITH RECOVERY Listing 4-5 A RESTORE command that will fail. Assuming you have not deleted the DatabaseForFullBackups database, attempting to run Listing 4-5 will result in the following error message (truncated for brevity; basically the same messages are repeated for the log file): Msg 1834, Level 16, State 1, Line 2 The file 'C:\SQLData\DatabaseForFullBackups.mdf' cannot be overwritten. It is being used by database 'DatabaseForFullBackups'. Msg 3156, Level 16, State 4, Line 2 File 'DatabaseForFullBackups' cannot be restored to ' C:\SQLData\DatabaseForFullBackups.mdf'. Use WITH MOVE to identify a valid location for the file. The problem we have here, and even the solution, is clearly stated by the error messages. In Listing 4-5, SQL Server attempts to use, for the DatabaseForFullBackups2 database being restored, the same file names and paths for the data and log files as are being used for the existing DatabaseForFullBackups database, which was the source of the backup file. In other words, it's trying to create data and log files for the DatabaseForFullBackups2 database, by overwriting data and log files that are being used by the DatabaseForFullBackups database. We obviously can't do that without causing the DatabaseForFullBackups database to fail. We will have to either drop the first database to free those file names or, more likely, and as the second part of the error massage suggests, identify a valid location for the log and data files for the new, using WITH MOVE, as shown in Listing 135 Chapter 4: Restoring From Full Backup RESTORE DATABASE [DatabaseForFullBackups2] FROM DISK = 'C:\SQLBackups\Chapter3\DatabaseForFullBackups_Full_Native_2.bak' WITH RECOVERY, MOVE 'DatabaseForFullBackups' TO 'C:\SQLData\DatabaseForFullBackups2.mdf', MOVE 'DatabaseForFullBackups_log' TO 'C:\SQLData\DatabaseForFullBackups2_log.ldf' Listing 4-6: A RESTORE command that renames the data and log files for the new database. We had two choices to fix the script; we could either rename the files and keep them in the same directory or keep the file names the same but put them in a different directory. It can get very confusing if we have a database with the same physical file name as another database, so renaming the files to match the database name seems like the best solution. Let's take a look at a somewhat subtler error. For this example, imagine that we wish to replace an existing copy of the DatabaseForFullBackups2 test database with a production backup of DatabaseForFullBackups. At the same time, we wish to move the data and log files for the DatabaseForFullBackups2 test database over to a new drive, with more space. USE master go RESTORE DATABASE [DatabaseForFullBackups2] FROM DISK = 'C:\SQLBackups\DatabaseForFileBackups_Full_Native_1.bak' WITH RECOVERY, REPLACE, MOVE 'DatabaseForFileBackups' TO 'D:\SQLData\DatabaseForFileBackups2.mdf', MOVE 'DatabaseForFileBackups_log' TO 'D:\SQLData\DatabaseForFileBackups2_log.ldf' Listing 4-7: An "error" while restoring over an existing database. 135 136 Chapter 4: Restoring From Full Backup In fact, no error message at all will result from running this code; it will succeed. Nevertheless, a serious mistake has occurred here: we have inadvertently chosen a backup file for the wrong database, DatabaseForFileBackups instead of DatabaseForFull- Backups, and used it to overwrite our existing DatabaseForFullBackups2 database! This highlights the potential issue with misuse of the REPLACE option. We can presume a DBA has used it here because the existing database is being replaced, without performing a tail log backup (see Chapter 6 for more details). However, there are two problems with this, in this case. Firstly, DatabaseForFullBackups2 is a SIMPLE recovery model database and so REPLACE is not required from the point of view of bypassing a tail log backup, since log backups are not possible. Secondly, use of REPLACE has bypassed the normal safety check that SQL Server would perform to ensure the database in the backup matches the database over which we are restoring. If we had run the exact same code as shown in Listing 4-7, but without the REPLACE option, we'd have received the following, very useful error message: Msg 3154, Level 16, State 4, Line 1 The backup set holds a backup of a database other than the existing 'DatabaseForFullBackups2' database. Msg 3013, Level 16, State 1, Line 1 RESTORE DATABASE is terminating abnormally. Note that we don't have any further use for the DatabaseForFullBackups2 database, so once you've completed the example, you can go ahead and delete it. Considerations When Restoring to a Different Location When restoring a database to a different server or even a different instance on the same server, there are quite a few things to consider, both before starting and after completing the restore operation. 136 137 Chapter 4: Restoring From Full Backup Version/edition of SQL Server used in the source and destination You may receive a request to restore a SQL Server 2008 R2 database backup to a SQL Server 2005 server, which is not a possibility. Likewise, it is not possible to restore a backup of a database that is using enterprise-only options (CDC, transparent data encryption, data compression, partitioning) to a SQL Server Standard Edition instance. What SQL Server agent jobs or DTS/DTSX packages might be affected? If you are moving the database permanently to a new server, you need to find which jobs and packages that use this database will be affected and adjust them accordingly. Also, depending on how you configure your database maintenance jobs, you may need to add the new database to the list of databases to be maintained. What orphaned users will need to be fixed? What permissions should be removed? There may be SQL Logins with differing SIDs that we need to fix. There may be SQL logins and Active Directory users that don't need access to the new server. You need to be sure to comb the permissions and security of the new location before signing off the restore as complete. Restoring System Databases As discussed briefly in Chapter 2, there are occasions when we may need to restore one of the system databases, such as master, model or msdb, either due to the loss of one of these databases or, less tragically, the loss of a SQL agent job, for example. Restoring system databases in advance of user databases can also be a time saver. Imagine that we need to migrate an entire SQL Server instance to new hardware. We could restore the master, model and msdb databases and already have our permissions, logins, jobs and a lot of other configuration taken care of in advance. In the case of an emergency, of course, knowledge of how to perform system database restores is essential. 137 138 Chapter 4: Restoring From Full Backup In this section, we'll look at how to perform a restore of both the master and the msdb system databases, so the first thing we need to do is make sure we have valid backups of these databases, as shown in Listing 4-8. USE [master] BACKUP DATABASE [master] TO DISK = N'C:\SQLBackups\Chapter4\master_full.bak' WITH INIT BACKUP DATABASE [msdb] TO DISK = N'C:\SQLBackups\Chapter4\msdb_full.bak' WITH INIT BACKUP DATABASE [model] TO DISK = N'C:\SQLBackups\Chapter4\model_full.bak' WITH INIT Listing 4-8: Taking backups of our system databases. Restoring the msdb database We can restore the msdb or model database without making any special modifications to the SQL Server engine or the way it is running, which makes it a relatively straightforward process (compared to restoring the master database). We will work with the msdb database for the examples in this section. In order to restore the msdb database, SQL Server needs to be able to take an exclusive lock on it, which means that we must be sure to turn off any applications that might be using it; specifically SQL Server Agent. There are several ways to do this, and you can choose the one with which you are most comfortable. For example, we can stop it directly from SSMS, use the NET STOP command in a command prompt, use a command script, or stop it from the services snap-in tool. 138 139 Chapter 4: Restoring From Full Backup We'll choose the latter option, since we can use the services snap-in tool to view and control all of the services running on our test machine. To start up this tool, simply pull up the Run prompt and type in services.msc while connected locally or through RDP to the test SQL Server machine. This will bring up the services snap-in within the Microsoft Management Console (MMC). Scroll down until you locate any services labeled SQL Server Agent (instance); the instance portion will either contain the unique instance name, or contain MSSQLSERVER, if it is the default instance. Highlight the agent service, right-click and select Stop from the control menu to bring the SQL Server Agent to a halt, as shown in Figure 4-8. Figure 4-8: Stopping SQL Server Agent with the services snap-in With the service stopped (the status column should now be blank), the agent is offline and we can proceed with the full database backup restore, as shown in Listing 140 Chapter 4: Restoring From Full Backup USE [master] RESTORE DATABASE [msdb] FROM DISK = N'C:\SQLBackups\Chapter4\msdb_full.bak' Listing 4-9: Restoring the msdb database. With the backup complete, restart the SQL Server Agent service from the services MMC snap-in tool and you'll find that all jobs, schedules, operators, and everything else stored in the msdb database, are all back and ready for use. This is a very simple task, with only the small change being that we need to shut down a service before performing the restore. Don't close the services tool yet, though, as we will need it to restore the master database. Restoring the master database The master database is the control database for a SQL Server instance, and restoring it is a slightly trickier task; we can't just restore master while SQL Server is running in standard configuration. The first thing we need to do is turn the SQL Server engine service off! Go back to the services management tool, find the service named SQL Server (instance) and stop it, as described previously. You may be prompted with warnings that other services will have to be stopped as well; go ahead and let them shut down. Once SQL Server is offline, we need to start it again, but using a special startup parameter. In this case, we want to use the m switch to start SQL Server in single-user mode. This brings SQL Server back online but allows only one user (an administrator) to connect, which is enough to allow the restore of the master database. 140 141 Chapter 4: Restoring From Full Backup To start SQL Server in single-user mode, open a command prompt and browse to the SQL Server installation folder, which contains the sqlservr.exe file. Here are the default locations for both SQL Server 2008 and 2008 R2: <Installation Path>\MSSQL10.MSSQLSERVER\MSSQL\Binn <Installation Path>\MSSQL10_50.MSSQLSERVER\MSSQL\Binn From that location, issue the command sqlservr.exe m. SQL Server will begin the startup process, and you'll see a number of messages to this effect, culminating (hopefully) in a Recovery is complete message, as shown in Figure 4-9. Figure 4-9: Recovery is complete and SQL Server is ready for admin connection. Once SQL Server is ready for a connection, open a second command prompt and connect to your test SQL Server with sqlcmd. Two examples of how to do this are given below, the first when using a trusted connection and the second for a SQL Login authenticated connection. 141 142 Chapter 4: Restoring From Full Backup sqlcmd -SYOURSERVER E sqlcmd SYOURSERVER UloginName Ppassword At the sqlcmd prompt, we'll perform a standard restore to the default location for the master database, as shown in Listing 4-10 (if required, we could have used the MOVE option to change the master database location or physical file). RESTORE DATABASE [master] FROM DISK = 'C:\SQLBackups\Chapter4\master_full.bak' Listing 4-10: Restoring the master database. In the first sqlcmd prompt, you should see a standard restore output message noting the number of pages processed, notification of the success of the operation, and a message stating that SQL Server is being shut down, as shown in Figure Figure 4-10: Output from restore of master database. 142 143 Chapter 4: Restoring From Full Backup Since we just restored the master database, we need the server to start normally to pick up and process all of the internal changes, so we can now start the SQL Server in normal mode to verify that everything is back online and working fine. You have now successfully restored the master database! Summary Full database backups are the cornerstone of a DBA's backup and recovery strategy. However, these backups are only useful if they can be used successfully to restore a database to the required state in the event of data loss, hardware failure, or some other disaster. Hopefully, as a DBA, the need to restore a database to recover from disaster will be a rare event, but when it happens, you need to be 100% sure that it's going to work; your organization, and your career as a DBA, my depend on it. Practice test restores for your critical databases on a regular schedule! Of course, many restore processes won't be as simple as restoring the latest full backup. Log backups will likely be involved, for restoring a database to a specific point in time, and this is where things get more interesting. 143 144 Chapter 5: Log Backups When determining a backup strategy and schedule for a given database, one of the major considerations is the extent to which potential data loss can be tolerated in the event of an errant process, or software or hardware failure. If toleration of data loss is, say, 24 hours, then we need do nothing more than take a nightly full backup. However, if exposure to the risk of data loss is much lower than this for a given database, then it's likely that we'll need to operate that database in FULL recovery model, and supplement those nightly full backups with transaction log backups (and possibly differential database backups see Chapter 7). With a log backup, we capture the details of all the transactions that have been recorded for that database since the last log backup (or since the last full backup,if this is the firstever log backup). In this chapter, we'll demonstrate how to capture these log backups using either the SSMS GUI or T-SQL scripts. However, we'll start by taking a look at how space is allocated and used within a log file; this is of more than academic interest, since it helps a DBA understand and troubleshoot certain common issues relating to the transaction log, such as explosive log growth, or internal log fragmentation. Capturing an unbroken sequence of log backups means that we will then, in Chapter 6, be able restore a full backup, then apply this series of log backups to "roll forward" the database to the state in which it existed at various, successive points in time. This adds a great deal of flexibility to our restore operations. When capturing only full (and differential) database backups, all we can do is restore one of those backups, in its entirety. With log backups, we can restore a database to the state in which it existed when a given log backup completed, or to the state in which it existed at some point represented within that log backup. 144 145 Chapter 5: Log Backups A Brief Peek Inside a Transaction Log A DBA, going about his or her daily chores, ought not to be overly concerned with the internal structure of the transaction log. Nevertheless, some discussion on this topic is very helpful in understanding the appropriate log maintenance techniques, and especially in understanding the possible root cause of problems such as log file fragmentation, or a log file that is continuing to grow and grow in size, despite frequent log backups. However, we will keep this "internals" discussion as brief as possible. As discussed in Chapter 1, a transaction log stores a record of the operations that have been performed on the database with which it is associated. Each log record contains the details of a specific change, relating to object creation/modification (DDL) operations, as well any data modification (DML) operations. When SQL Server undergoes database recovery (for example, upon start up, or during a RESTORE operation), it, will roll back (undo) or roll forward (redo) the actions described in these log records, as necessary, in order to reconcile the data and log files, and return the database to a consistent state. Transaction log files are sequential files; in other words SQL Server writes to the transaction log sequentially (unlike data files, which tend to be written in a random fashion, as data is modified in random data pages). Each log record inserted into the log file is stamped with a Log 5-1 depicts a transaction log composed of eight VLFs, and marks the active portion of the log, known as the active log. 145 146 Chapter 5: Log Backups Figure 5-1: A transaction log with 8 VLFs. The concept of the active log is an important one. A VLF can either be "active," if it contains any part of what is termed the active log, or "inactive," if it doesn't. Any log record relating to an open transaction is required for possible rollback and so must be part of the active log. In addition, there are various other activities in the database, including replication, mirroring and CDC (Change Data Capture) that use the transaction log and need transaction log records to remain in the log until they have been processed. These records will also be part of the active log. The log record with the MinLSN, shown in Figure 5-1, is defined as the "oldest log record that is required for a successful database-wide rollback or by another activity or operation in the database." This record marks the start of the active log and is sometimes referred to as the "head" of the log. Any more recent log record, regardless of whether it is still open or required, is also part of the active log; this is an important point as it explains why it's a misconception to think of the active portion of the log as containing only records relating to uncommitted transactions. The log record with the highest LSN (i.e. the most recent record added) marks the end of the active log. 146 147 Chapter 5: Log Backups Therefore, we can see that a log record is no longer part of the active log only when each of the following three conditions below is met. 1. It relates to a transaction that is committed and so is no longer required for rollback. 2. It is no longer required by any other database process, including a transaction log backup when using FULL or BULK LOGGED recovery models. 3. It is older (i.e. has a lower LSN) than the MinLSN record. Any VLF that contains any part of the active log is considered active and can never be truncated. For example, VLF3, in Figure 5-1, is an active VLF, even though most of the log records it contains are not part of the active log; it cannot be truncated until the head of the logs moves forward into VLF4. The operations that will cause the head of the log to move forward vary depending on the recovery model of the database. For databases in the SIMPLE recovery model, the head of the log can move forward upon CHECKPOINT, when pages are flushed from cache to disk, after first being written to the transaction log. As a result of this operation, many log records would now satisfy the first requirement listed above, for no longer being part of the active log. We can imagine that if, as a result, the MinLSN record in Figure 5-1, and all subsequent records in VLF3, satisfied both the first and second criteria, then the head would move forward and VLF3 could now be truncated. Therefore, generally, space inside the log is made available for reuse at regular intervals. Truncation does not reduce the size of the log file It's worth reiterating that truncation does not affect the physical size of the log; it will still take up the same physical space on the drive. Truncation is merely the act of marking VLFs in the log file as available for reuse, in the recording of subsequent transactions. 147 148 Chapter 5: Log Backups For databases using FULL or BULK LOGGED recovery, the head can only move forward as a result of a log backup. Any log record that has not been previously backed up is considered to be still "required" by a log backup operation, and so will never satisfy the second requirement above, and will remain part of the active log. If we imagine that the MinLSN record in Figure 5-1 is the first record added to the log after the previous log backup, then the head will remain in that position till the next log backup, at which point it can move forward (assuming the first requirement is also satisfied). I've stressed this many times, but I'll say it once more for good measure: this is the other reason, in addition to enabling point-in-time restore, why it's so important to back up the log for any database operating in FULL (or BULK_LOGGED) recovery; if you don't, the head of the log is essentially "pinned," space will not be reused, and the log will simply grow and grow in size. The final question to consider is what happens when the active log reaches the end of VLF8. Simplistically, it is easiest to think of space in the log file as being reused in a circular fashion. Once the logical end of the log reaches the end of a VLF, SQL Server will start to reuse the next sequential VLF that is inactive, or the next, so far unused, VLF. In Figure 5-1, this could be VLF8, followed by VLFs 1 and 2, and so. Three uses for transaction log backups The primary reason to take log backups is in order to be able to restore them; in other words, during a RESTORE operation, we can restore a full (plus differential) backup, followed by a complete chain of log backup files. As we restore the series of log backups files, we will essentially "replay" the operations described within in order to re-create the database as it existed at a previous point in time. 148 149 Chapter 5: Log Backups However, the log backups, and subsequent restores, can also be very useful in reducing the time required for database migrations, and for offloading reporting from the Production environment, via log shipping. Performing database restores By performing a series of log backup operations, we can progressively capture the contents of the live log file in a series of log backup files. Once captured in log backup files, the series of log records within these files can, assuming the chain of log records is unbroken, be subsequently applied to full (and differential) database backups as part of a database restore operation. We can restore to the end of one of these backup files, or even to some point in time in the middle of the file, to re-create the database as it existed at a previous point in time, for example, right before a failure. When operating in SIMPLE recovery model, we can only take full and differential backups i.e. we can only back up the data files and not the transaction log. Let's say, for example, we rely solely on full database backups, taken every day at 2 a.m. If a database failure occurs at 1 a.m. one night, all we can do is restore the database as it existed at 2 a.m. the previous day and have lost 23 hours' worth of data. We may be able to reduce the risk of data loss by taking differential backups, in between the nightly full backups. However, both full and differential backups are resource-intensive operations and if you need your risk of data loss to be measured in minutes rather than hours, the only viable option is to operate the database in FULL recovery model and take transaction log backups alongside any full and differential backups. If we operate the database in FULL recovery, and take transaction log backups, say, every 30 minutes then, in the event of our 2 a.m. disaster, we can restore the previous 2 a.m. full backup, followed by a series of 48 log backup files, in order to restore the database as it existed at 1.30 a.m., losing 30 minutes' worth of data. If the live transaction log were still available we could also perform a tail log backup and restore the database to a time directly before the disaster occurred. 149 150 Chapter 5: Log Backups The frequency with which log backups are taken will depend on the tolerable exposure to data loss, as expressed in your Backup and Restore SLA (discussed shortly). Large database migrations It is occasionally necessary to move a database from one server to another, and you may only have a short window of time in which to complete the migration. For example, let's say a server has become overloaded, or the server hardware has reached the end of its life, and a fresh system needs to be put in place. Just before we migrate the database to the new server, we need to disconnect all users (so that no data is committed after your final backup is taken), and our SLA dictates a maximum of an hour down-time, so we've got only one hour to get them all connected again on the new server! Given such constraints, we won't have the time within that window to take a full backup of the database, transfer it across our network, and then restore it on the target server. Fortunately, however, we can take advantage of the small file footprint of the transaction log backup in order to reduce the time required to perform the task. For example, prior to the migration window, we can transfer, to the target server, a full database backup from the night before. We can restore that file to the new server using the WITH NORECOVERY option (discussed in Chapter 6), to put the database into a restoring state and allow transaction log backups to be applied to the database at a later time. After this, we can take small transaction log backups of the migrating database over the period of time until the migration is scheduled. These log backup files are copied over to the target server and applied to our restoring target database (stipulating NORECOVERY as each log backup is applied, to keep the database in a restoring state, so more log backups can be accepted). 150 151 Chapter 5: Log Backups At the point the migration window opens, we can disconnect all users from the original database, take a final log backup, transfer that final file to the target server, and apply it to the restoring database, specifying WITH RECOVERY so that the new database is recovered, and comes online in the same state it was in when you disconnected users from the original. We still need to bear in mind potential complicating factors related to moving databases to different locations, as discussed in Chapter 4. Orphaned users, elevated permissions and connectivity issues would still need to be addressed after the final log was applied to the new database location. Log shipping Almost every DBA has to make provision for business reporting. Often, the reports produced have to be as close to real time as possible, i.e. they must reflect as closely as possible the data as it currently exists in the production databases. However, running reports on a production machine is never a best practice, and the use of High Availability solutions (real-time replication, CDC solutions, log reading solutions, and so on) to get that data to a reporting instance can be expensive and time consuming. Log shipping is an easy and cheap way to get near real-time data to a reporting server. The essence of log shipping is to restore a full database to the reporting server using the WITH STANDBY option, then regularly ship log backup files from the production to the reporting server and apply them to the standby database to update its contents. The STANDBY option will keep the database in a state where more log files can be applied, but will put the database in a read-only state, so that it always reflects the data in the source database at the point when the last applied log backup was taken. 151 152 Chapter 5: Log Backups This means that the reporting database will generally lag behind the production database by minutes or more. This sort of lag is usually not a big problem and, in many cases, log shipping is an easy way to satisfy, not only the production users, but the reporting users as well. Practical log shipping It is out of scope to get into the full details of log shipping here, but the following article offers a practical guide to the process: pop-rivetts-sql-server-faq-no.4-pop-does-log-shipping/. Log Backups in the Backup and Restore SLA As discussed in detail in Chapter 2, determining whether or not log backups are required for a database and, if so, how frequently, will require some conversations with the database owners. The first rule is not to include log backups in the SLA for a given database, unless they are really required. Log backups bring with them considerable extra administrative overhead, with more files to manage, more space required to store them, more jobs to schedule, and so on. While we need to make sure that these operations are performed for every database that needs them, we definitely don't want to take them on all databases, regardless of need. If it's a development database, we most likely won't need to take transaction log backups, and the database can be operated in SIMPLE recovery model. If it's a production database, then talk to the project manager and developers; ask them questions about the change load on the data; find out how often data is inserted or modified, how much data is modified, at what times of the day these modifications take place, and the nature of the data load/modification processes (well defined or ad hoc). 152 153 Chapter 5: Log Backups If it's a database that's rarely, if ever, modified by end-users, but is subject to daily, welldefined data loads, then it's also unlikely that we'll need to perform log backups, so we can operate the database in SIMPLE recovery model. We can take a full database backup after each data load, or simply take a nightly full backup and then, if necessary, restore it, then replay any data load processes that occurred subsequently. If a database is modified frequently by ad hoc end-user processes, and toleration of data loss is low, then it's very likely that transaction log backups will be required. Again, talk with the project team and find out the acceptable level of data loss. You will find that, in most cases, taking log backups once per hour will be sufficient, meaning that the database could lose up to 60 minutes of transactional data. For some databases, an exposure to the risk of data loss of more than 30 or 15 minutes might be unacceptable. The only difference here is that we will have to take, store, and manage many more log backups, and more backup files means more chance of something going wrong; losing a file or having a backup file become corrupted. Refer back to the Backup scheduling section of Chapter 2 for considerations when attempting to schedule all the required backup jobs for a given SQL Server instance. Whichever route is the best for you, the most important thing is that you are taking transaction log backups for databases that require them, and only for those that required them. Preparing for Log Backups In this chapter, we'll run through examples of how to take log backups using both SSMS and T-SQL scripts. In Chapter 8, we'll show how to manage your log and other backups, using a third-party tool (Red Gate SQL Backup) and demonstrate some of the advantages that such tools offer. 153 154 Chapter 5: Log Backups Before we get started taking log backups, however, we need to do a bit of prep work, namely choosing an appropriate recovery model for our example database, and then creating that database along with some populated sample tables. Choosing the recovery model We're going to assume that the Service Level Agreement for our example database expresses a tolerance to potential data loss of no more than 60 minutes. This immediately dictates a need to take log backups at this interval (or shorter), in order that we can restore a database to a state no more than 60 minutes prior to the occurrence of data being lost, or the database going offline. This rules out SIMPLE as a potential recovery model for our database since, as discussed, in this model a database operates in "auto-truncate" mode and any inactive VLFs are made available for reuse whenever a database CHECKPOINT operation occurs. With the inactive VLFs being continuously overwritten, we cannot capture a continuous chain of log records into our log backups, and so can't use these log backups as part of a database RESTORE operation. In fact, it isn't even possible to take log backups for a database that is operating in SIMPLE recovery. This leaves us with a choice of two recovery models: FULL or BULK LOGGED. All databases where log backups are required should be operating in the FULL recovery model, and that's the model we're going to use. However, a database operating in FULL recovery may be switched temporarily to the BULK LOGGED model in order to maximize performance, and minimize the growth of the transaction log, during bulk operations, such as bulk data loads or certain index maintenance operations. When a database is operating in BULK LOGGED model, such operations are only minimally logged, and so require less space in the log file. This can save a DBA the headache of having log files growing out of control, and can save a good deal of time when bulk loading data into your database. 154 155 Chapter 5: Log Backups However, use of BULK LOGGED has implications that make it unsuitable for long-term use in a database where point-in-time restore is required, since it is not possible to restore a database to a point in time within a log file that contains minimally logged operations. We'll discuss this in more detail in the next chapter, along with the best approach to minimizing risk when a database does need to be temporarily switched to BULK LOGGED model. For now, however, we're going to choose the FULL recovery model for our database. Creating the database Now that we know that FULL recovery is the model to use, let's go ahead and get our new database created so we can begin taking some log backups. We are going to stick with the naming convention established in previous chapters, and call this new database DatabaseForLogBackups. We can either create the database via the SSMS GUI or use the script shown in Listing 5-1. USE [master] CREATE DATABASE [DatabaseForLogBackups] ON PRIMARY ( NAME = N'DatabaseForLogBackups', FILENAME = N'C:\SQLData\DatabaseForLogBackups.mdf', SIZE = KB, FILEGROWTH = 51200KB ) LOG ON ( NAME = N'DatabaseForLogBackups_log', FILENAME = N'C:\SQLData\DatabaseForLogBackups_log.ldf', SIZE = 51200KB, FILEGROWTH = 51200KB ) ALTER DATABASE [DatabaseForLogBackups] SET RECOVERY FULL Listing 5-1: Creating our new DatabaseForLogBackups database. 155 156 Chapter 5: Log Backups This script will create for us a new DatabaseForLogBackups database, with the data and log files for this database stored in the C:\SQLData directory. Note that, if we didn't specify the FILENAME option, then the files would be auto-named and placed in the default directory for that version of SQL Server (for example, in SQL Server 2008, this is \Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA). We have assigned some appropriate values for the initial sizes of these files and their file growth characteristics. As discussed in Chapter 3, it's generally not appropriate to accept the default file size and growth settings for a database, and we'll take a deeper look at the specific problem that can arise with a log file that grows frequently in small increments, later in this chapter. For each database, we should size the data and log files as appropriate for their current data requirements, plus predicted growth over a set period. In the case of our simple example database, I know how exactly much data I plan to load into our tables (you'll find out shortly!), so I have chosen an initial data file size that makes sense for that purpose, 500 MB. We don't want the file to grow too much but if it does, we want it to grow in reasonably sized chunks, so I've chosen a growth step of 50 MB. Each time the data file needs to grow, it will grow by 50 MB, which provides enough space for extra data, but not so much that we will have a crazy amount of free space after each growth. For the log file, I've chosen an initial size of 50 MB, and I am allowing it to grow by an additional 50 MB whenever it needs more room to store transactions. Immediately after creating the database, we run an ALTER DATABASE command to ensure that our database is set up to use our chosen recovery mode, namely FULL. This is very important, especially if the model database on the SQL Server instance is set to a different recovery model, since all users' databases will inherit that setting. Now that we have a new database, set to use the FULL recovery model, we can go ahead and start creating and populating the tables we need for our log backup tests. 156 157 Chapter 5: Log Backups Creating and populating tables We are going to use several simple tables that we will populate with a small initial data load. Subsequently, we'll take a full database backup and then perform another data load. This will make it possible to track our progress as we restore our log backups, in the next chapter. USE [DatabaseForLogBackups] SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON CREATE TABLE [dbo].[messagetable1] ( [Message] [nvarchar](100) NOT NULL, [DateTimeStamp] [datetime2] NOT NULL ) ON [PRIMARY] CREATE TABLE [dbo].[messagetable2] ( [Message] [nvarchar](100) NOT NULL, [DateTimeStamp] [datetime2] NOT NULL ) ON [PRIMARY] CREATE TABLE [dbo].[messagetable3] ( [Message] [nvarchar](100) NOT NULL, [DateTimeStamp] [datetime2] NOT NULL ) ON [PRIMARY] Listing 5-2: Creating the tables. 157 158 Chapter 5: Log Backups Listing 5-2 creates three simple message tables, each of which will store simple text messages and a time stamp so that we can see exactly when each message was inserted into the table. Having created our three tables, we can now pump a bit of data into them. We'll use the same technique as in Chapter 3, i.e. a series of INSERT commands, each with the X batch separator, to insert ten rows into each of the three tables, as shown in Listing 5-3. USE [DatabaseForLogBackups] INSERT INTO dbo.messagetable1 VALUES ('This is the initial data for MessageTable1', GETDATE()) 10 INSERT INTO dbo.messagetable2 VALUES ('This is the initial data for MessageTable2', GETDATE()) 10 INSERT INTO dbo.messagetable3 VALUES ('This is the initial data for MessageTable3', GETDATE()) 10 Listing 5-3: Initial population of tables. We'll be performing a subsequent data load shortly, but for now we have a good base of data from which to work, and we have a very important step to perform before we can even think about taking log backups. Even though we set the recovery model to FULL, we won't be able to take log backups (in other words, the database is still effectively in autotruncate mode) until we've first performed a full backup. Before we do that, however, let's take a quick look at the current size of our log file, and its space utilization, using the DBCC SQLPERF (LOGSPACE); command. This will return results for all databases on the instance, but for the DatabaseForLogBackups we should see results similar to those shown in Figure 159 Chapter 5: Log Backups Backup Stage Log Size Space Used Before full backup 50 MB 0.65 % Figure 5-2: DBCC SQLPERF (LOGSPACE) output before full backup. This shows us that we have a 50 MB log file and that it is only using a little more than one half of one percent of that space. Taking a base full database backup Before we can even take log backups for our DatabaseForLogBackups database, we need to take a base full backup of the data file. We've covered all the details of taking full backups in Chapter 3, so simply run Listing 5-4 to take a full backup of the database, placing the backups in a central folder location, in this case C:\SQLBackups\Chapter5 so they are readily available for restores. You've probably noticed that, for our simple example, the backup files are being stored on the same drive as the data and log files. In the real world, you'd store the data, log, and backup files on three separate disk drives. USE [master] BACKUP DATABASE [DatabaseForLogBackups] TO DISK = N'C:\SQLBackups\Chapter5\DatabaseForLogBackups_Native_Full.bak' WITH NAME = N'DatabaseForLogBackups-Full Database Backup', STATS = 10, INIT Listing 5-4: Taking a native full backup. 159 160 Chapter 5: Log Backups So, at this stage, we've captured a full backup of our new database, containing three tables, each with ten rows of data. We're ready to start taking log backups now, but let's run the DBCC SQLPERF(LOGSPACE) command again, and see what happened to our log space. Backup Stage Log Size Space Used Before full backup 50 MB 0.65 % After full backup 50 MB 0.73% Figure 5-3: DBCC SQLPERF (LOGSPACE) output after full backup. What's actually happened here isn't immediately apparent from these figures, so it needs a little explanation. We've discussed earlier how, for a FULL recovery model database, only a log backup can free up log space for reuse. This is true, but the point to remember is that such a database is actually operating in auto-truncate mode until the first full backup of that database completes. The log is truncated as a result of this first-ever full backup and, from that point on, the database is truly in FULL recovery, and a full backup will never cause log truncation. So, hidden in our figures is the fact that the log was truncated as a result of our first full backup, and the any space taken up by the rows we added was made available for reuse. Some space in the log would have been required to record the fact that a full backup took place, but overall the space used shows very little change. Later in the chapter, when taking log backups with T-SQL, we'll track what happens to these log space statistics as we load a large amount of data into our tables, and then take a subsequent log backup. 160 161 Chapter 5: Log Backups Taking Log Backups We're going to discuss taking log backups the "GUI way," in SSMS, and by using native T-SQL Backup commands. However, before taking that elusive first log backup, let's quickly insert ten new rows of data into each of our three tables, as shown in Listing 5-5. Having done so, we'll have ten rows of data for each table that is captured in a full database backup, and another ten rows for each table that is not in the full database backup, but where the details of the modifications are recorded in the live transaction log file. USE [DatabaseForLogBackups] INSERT INTO MessageTable1 VALUES ('Second set of data for MessageTable1', GETDATE()) 10 INSERT INTO MessageTable2 VALUES ('Second set of data for MessageTable2', GETDATE()) 10 INSERT INTO MessageTable3 VALUES ('Second set of data for MessageTable3', GETDATE()) 10 Listing 5-5: A second data load. The GUI way: native SSMS log backups Open SSMS, connect to your test server, locate the DatabaseForLogBackups database, right-click on it and select the Tasks Back Up option. Select the Back Up menu item to bring up the General page of the Back Up Database window, with which you should be familiar from Chapter 3, when we performed full database backups. The first set of configurable options is shown in Figure 162 Chapter 5: Log Backups Figure 5-4: The Source section configuration for log backup. Notice that we've selected the DatabaseForLogBackups database and, this time, we've changed the Backup type option to Transaction Log, since we want to take log backups. Once again, we leave the Copy-only backup option unchecked. COPY_ONLY backups of the log file When this option is used, when taking a transaction log backup, the log archiving point is not affected and does not affect the rest of our sequential log backup files. The transactions contained within the log file are backed up, but the log file is not truncated. This means that the special COPY_ONLY log backup can be used independently of conventional, scheduled log backups, and would not be needed when performing a restore that included the time span where this log backup was taken. The Backup component portion of the configuration is used to specify full database backup versus file or filegroup backup; we're backing up the transaction log here, not the data files, so these options are disabled. The second set of configurable options for our log backup, shown in Figure 5-5, is titled Backup set and deals with descriptions and expiration dates. The name field is auto-filled and the description will be left blank. The backup set expiration date can also be left with 162 163 Chapter 5: Log Backups the default values. As discussed in Chapter 3, since we are only storing one log backup set per file, we do not need to worry about making sure backup sets expire at a given time. Storing multiple log backups would reduce the number of backup files that we need to manage, but it would cause that single file to grow considerably larger with each backup stored in it. We would also run the risk of losing more than just one backup if the file were to become corrupted or was lost. Figure 5-5: The Backup set section configuration for log backups. The final section of the configuration options is titled Destination, where we specify where to store the log backup file and what it will be called. If there is a file already selected for use, click the Remove button because we want to choose a fresh file and location. Now, click the Add button to bring up the backup destination selection window. Click the browse ( ) button and navigate to our chosen backup file location (C:\SQLBackups\ Chapter5) and enter the file name DatabaseForLogBackups_Native_Log_1.trn at the bottom, as shown in Figure 164 Chapter 5: Log Backups Figure 5-6: Selecting the path and filename for your log backup file. Note that, while a full database backup file is identified conventionally by the.bak extension, most DBAs identify log backup files with the.trn extension. You can use whatever extension you like, but this is the standard extension for native log backups and it makes things much less confusing if everyone sticks to a familiar convention. When you're done, click the OK buttons on both the Locate Database Files and Select Backup Destination windows to bring you back to the main backup configuration window. Once here, select the Options menu on the upper left-hand side of the window to bring up the second page of backup options. We are going to focus here on just the Transaction log section of this Options page, shown in Figure 5-7, as all the other options on this page were covered in detail in Chapter 165 Chapter 5: Log Backups Figure 5-7: Configuration options for transaction log backup. The Transaction log section offers two important configuration option configurations. For all routine, daily log backups, the default option of Truncate the transaction log is the one you want; on completion of the log backup the log file will be truncated, if possible (i.e. space inside the file will be made available for reuse). The second option, Back up the tail of the log, is used exclusively in response to a disaster scenario; you've lost data, or the database has become corrupt in some way, and you need to restore it to a previous point in time. Your last action before attempting a RESTORE operation should be to back up the tail of the log, i.e. capture a backup of the remaining contents (those records added since the last log backup) of the live transaction log file, assuming it is still available. This will put the database into a restoring state, and assumes that the next action you wish to perform is a RESTORE. This is a vital option in database recovery, and we'll demonstrate it in Chapter 6, but it won't be a regular maintenance task that is performed. Having reviewed all of the configuration options, go ahead and click OK, and the log backup will begin. A progress meter will appear in the lower left-hand side of the window but since we don't have many transactions to back up, the operation will probably complete very quickly and you'll see a notification that your backup has completed and was successful. If, instead, you receive an error message, you'll need to check your configuration settings and to attempt to find what went wrong. We have successfully taken a transaction log backup! As discussed in Chapter 3, various metrics are available regarding these log backups, such as the time it took to complete, and the size of the log backup file. In my test, the backup time was negligible in this case (measured in milliseconds). However, for busy databases, handling hundreds or thousands of transactions per second, the speed of these log backups can be a very 165 166 Chapter 5: Log Backups important consideration and, as was demonstrated for full backups in Chapter 3, use of backup compression can be beneficial. In Chapter 8, we'll compare the backup speeds and compression ratios obtained for native log backups, versus log backups with native compression, versus log backups with SQL Backup compression. Right now, though, we'll just look at the log backup size. Browse to the C:\SQLBackups\ Chapter5\ folder, or wherever it is that you stored the log backup file and simply note the size of the file. In my case, it was 85 KB. T-SQL log backups Now that we have taken a log backup using the GUI method, we'll insert some new rows into our DatabaseForLogBackups table and then take a second log backup, this time using a T-SQL script. Rerun DBCC SQLPERF(LOGSPACE)before we start. Since we've only added a small amount of data, and have performed a log backup, the live log file is still 50 MB in size, and less than 1% full. Listing 5-6 shows the script to insert our new data; this time we're inserting considerably more rows into each of the three tables (1,000 into the first table, 10,000 into the second and 100,000 into the third) and so our subsequent transaction log backup should also be much larger, as a result. Notice that we print the date and time after inserting the rows into MessageTable2, and then use the WAITFOR DELAY command before proceeding with the final INSERT command; both are to help us when we come to perform some point-in-time restores, in Chapter 167 Chapter 5: Log Backups USE [DatabaseForLogBackups] INSERT INTO dbo.messagetable1 VALUES ( 'Third set of data for MessageTable1', GETDATE() ) 1000 INSERT INTO dbo.messagetable2 VALUES ( 'Third set of data for MessageTable2', GETDATE() ) Note this date down as we'll need it in the next chapter PRINT GETDATE() WAITFOR DELAY '00:02:00' INSERT INTO dbo.messagetable3 VALUES ( 'Third set of data for MessageTable3', GETDATE() ) Listing 5-6: Third data insert for DatabaseForLogBackups (with 2-minute delay). Go ahead and run this script in SSMS (it will take several minutes). Before we perform a T-SQL log backup, let's check once again on the size of the log file and space usage for our DatabaseForLogBackups database. Backup Stage Log Size Space Used Initial stats 50 MB 0.8 % After third data data load 100 MB 55.4% Figure 5-8: DBCC SQLPERF (LOGSPACE) output after big data load. 167 168 Chapter 5: Log Backups We now see a more significant portion of our log being used. The log actually needed to grow above its initial size of 50 MB in order to accommodate this data load, so it jumped in size by 50 MB, which is the growth rate we set when we created the database. 55% of that space is currently in use. When we used the SSMS GUI to build our first transaction log backup, a T-SQL BACKUP LOG command was constructed and executed under the covers. Listing 5-7 simply creates directly in T-SQL a simplified version of the backup command that the GUI would have generated. USE [master] BACKUP LOG [DatabaseForLogBackups] TO DISK = N'C:\SQLBackups\Chapter5\DatabaseForLogBackups_Native_Log_2.trn' WITH NAME = N'DatabaseForLogBackups-Transaction Log Backup', STATS = 10 Listing 5-7: Native T-SQL transaction log backup code. The major difference between this script, and the one we saw for a full database backup in Chapter 3, is that the BACKUP DATABASE command is replaced by the BACKUP LOG command, since we want SQL Server to back up the transaction log instead of the data files. We use the TO DISK parameter to specify the backup location and name of the file. We specify our central SQLBackups folder and, once again, apply the convention of using.trn to identify our log backup. The WITH NAME option allows us to give the backup set an appropriate set name. This is informational only, especially since we are only taking one backup per file/set. Finally, we see the familiar STATS option, which dictates how often the console messages will be updated during the operation. With the value set to 10, a console message should display when the backup is (roughly) 10%, 20%, 30% complete, and so on, as shown in Figure 5-9, along with the rest of the statistics from the successful backup. 168 169 Chapter 5: Log Backups Figure 5-9: Successful transaction log backup message. Notice that this log backup took about 3.5 seconds to complete; still not long, but much longer than our first backup took. Also, Figure 5-10 shows that the size of our second log backup file weighs in at 56 MB. This is even larger than our full backup, which is to be expected since we just pumped in 3,700 times more records into the database than were there during the full backup. The log backup file size is also broadly consistent with what we would have predicted, given the stats we got from DBCC SQLPERF (LOGSPACE), which indicated a 100 MB log which was about 55% full. Figure 5-10: Second log backup size check. 169 170 Chapter 5: Log Backups Let's check the log utilization one last time with the DBCC SQLPERF (LOGSPACE) command. Backup Stage Log Size Space Used Initial stats 50 MB 0.8 % After third data data load After T-SQL log backup 100 MB 55.4% 100 MB 5.55% Figure 5-11: DBCC SQLPERF (LOGSPACE) output after big data load. This is exactly the behavior we expect; as a result of the backup operation, the log has been truncated, and space in inactive VLFs made available for reuse, so only about 5% of the space is now in use. As discussed earlier, truncation does not affect the physical size of the log, so it remains at 100 MB. Forcing Log Backup Failures for Fun Having practiced these log backups a few times, it's rare for anything to go wrong with the actual backup process itself. However, it's still possible to stumble into the odd gotcha. Go ahead and run Listing 5-8 in an SSMS query window; try to work out what the error is going to be before you run it. 170 171 Chapter 5: Log Backups CREATE DATABASE [ForceFailure] -- Using the NO_WAIT option so no rollbacks -- of current transactions are attempted ALTER DATABASE [ForceFailure] SET RECOVERY SIMPLE WITH NO_WAIT BACKUP DATABASE [ForceFailure] TO DISK = 'C:\SQLBackups\Chapter5\ForceFailure_Full.bak' BACKUP LOG [ForceFailure] TO DISK = 'C:\SQLBackups\Chapter5\ForceFailure_Log.trn' --Tidy up once we're done as we no longer need this database DROP DATABASE ForceFailure Listing 5-8: Forcing a backup failure. You should see the message output shown in Figure Figure 5-12: Running a log backup on a SIMPLE model database. We can see that the database was successfully created, the BACKUP DATABASE operation was fine, but then we hit a snag with the log backup operation: Msg 4208, Level 16, State 1, Line 1 The statement BACKUP LOG is not allowed while the recovery model is SIMPLE. Use BACKUP DATABASE or change the recovery model using ALTER DATABASE. 171 172 Chapter 5: Log Backups The problem is very clear: we are trying to perform a log backup on a database that is operating in the SIMPLE recovery model, which is not allowed. The exact course of action, on seeing an error like this, depends on the reason why you were trying to perform the log backup. If you simply did not realize that log backups were not possible in this case, then lesson learned. If log backups are required in the SLA for this database, then the fact that the database is in SIMPLE recovery is a serious problem. First, you should switch it to FULL recovery model immediately, and take another full database backup, to restart the log chain. Second, you should find out when and why the database got switched to SIMPLE, and report what the implications are for point-in-time recovery over that period. An interesting case where a DBA might see this error is upon spotting that a log file for a certain database is growing very large, and assuming that the cause is the lack of a log backup. Upon running the BACKUP LOG command, the DBA is surprised to see the database is in fact in SIMPLE recovery. So, why would the log file be growing so large? Isn't log space supposed to be reused after each CHECKPOINT, in this case? We'll discuss possible reasons why you still might see log growth problems, even for databases in SIMPLE recovery, in the next section. Troubleshooting Log Issues The most common problem that DBAs experience with regard to log management is rapid, uncontrolled (or even uncontrollable) growth in the size of the log. In the worst case, a transaction log can grow until there is no further available space on its drive and so it can grow no more. At this point, you'll encounter Error 9002, the "transaction log full" error, and the database will become read-only. If you are experiencing uncontrolled growth of the transaction log, it is due, either to a very high rate of log activity, or to factors that are preventing space in the log file from being reused, or both. 172 173 Chapter 5: Log Backups As a log file grows and grows, a related problem is that the log can become "internally fragmented," if the growth occurs in lots of small increments. This can affect the performance of any operation that needs to read the transaction log (such as database restores). Failure to take log backups Still the most common cause of a rapidly growing log, sadly, is simple mismanagement; in other words failure to take log backups for a database operating in FULL recovery. Since log backups are the only operation that truncates the log, if they aren't performed regularly then your log file may grow rapidly and eat up most or all of the space on your drive. I rest more peacefully at night in the knowledge that, having read this chapter, this is a trap that won't catch you out. If you're asked to troubleshoot a "runaway" transaction log for a FULL recovery model database, then a useful first step is to interrogate the value of the log_reuse_wait_ desc column in sys.databases, as shown in Listing 5-9. USE master SELECT name, recovery_model_desc, log_reuse_wait_desc FROM sys.databases WHERE name = 'MyDatabase' Listing 5-9: Finding possible causes of log growth. If the value returned for the log_reuse_wait_desc column is LOG BACKUP, then the reason for the log growth is the lack of a log backup. If this database requires log backups, start taking them, at a frequency that will satisfy the terms of the SLA, and control the growth of the log from here in. If the database doesn't require point-in-time recovery, switch the database to SIMPLE recovery. 173 174 Chapter 5: Log Backups In either case, if the log has grown unacceptably large (or even full) in the meantime, refer to the forthcoming section on Handling the 9002 Transaction Log Full error. Other factors preventing log truncation There are a few factors, in addition to a lack of log backups, which can "pin" the head of the log, and so prevent space in the file from being reused. Some of these factors can cause the size of the log to grow rapidly, or prevent the log file from being truncated, even when operating in SIMPLE recovery model. The concept of the active log, and the criteria for log truncation, as discussed earlier in the chapter, also explains why a "rogue" long-running transaction, or a transaction that never gets committed, can cause very rapid log growth, regardless of the recovery model in use. If we have a single, very long-running transaction, then any log records that relate to transactions that started and committed after this transaction must still be part of the active log. This can prevent large areas of the log from being truncated, either by a log backup or by a CHECKPOINT, even though the vast majority of the log records are no longer required. Such problems manifest in a value of ACTIVE TRANSACTION for the log_reuse_wait_ desc column. The course of action in the short term is to discover which transaction is causing the problem and find out if it's possible to kill it. In the longer term, you need to work out how to tune very long-running transactions or break them down into smaller units, and to find out what application issues are causing transactions to remain uncommitted. DBCC OPENTRAN A tool that is useful in tracking down rogue transactions is DBCC OPENTRAN(DatabaseName). It will report the oldest active transaction for that database, along with its start time, and the identity of the session that started the transaction. 174 175 Chapter 5: Log Backups There are several other issues that can be revealed through the log_reuse_wait_ desc column, mainly relating to various processes, such as replication, which require log records to remain in the log until they have been processed. We haven't got room to cover them here, but Gail Shaw offers a detailed description of these issues in her article, Why is my transaction log full? at Transaction+Log/72488/. Excessive logging activity If no problems are revealed by the log_reuse_wait_desc column then the log growth may simply be caused by a very high rate of logging activity. For a database using the FULL recovery model, all operations are fully logged, including bulk data imports, index rebuilds, and so on, all of which will write heavily to the log file, causing it to grow rapidly in size. It is out of scope for this book to delve into the full details of bulk operations but, essentially, you need to find a way to either minimize the logging activity or, if that's not possible, then simply plan for it accordingly, by choosing appropriate initial size and growth settings for the log, as well as an appropriate log backup strategy. As noted in Chapter 1, certain bulk operations can be minimally logged, by temporarily switching the database from FULL to BULK_LOGGED recovery, in order to perform the operation, and then back again. Assuming your SLA will permit this, it is worth considering, given that any bulk logged operation will immediately prevent point-in-time recovery to a point within any log file that contains records relating to the minimally logged operations. We'll cover this option in a little more detail in Chapter 176 Chapter 5: Log Backups Handling the 9002 Transaction Log Full error As noted earlier, in the worst case of uncontrolled log growth you may find yourself facing down the dreaded "9002 Transaction Log Full" error. There is no more space within the log to write new records, there is no further space on the disk to allow the log file to grow, and so the database becomes read-only until the issue is resolved. Obviously the most pressing concern in such cases is to get SQL Server functioning normally again, either by making space in the log file, or finding extra disk space. If the root cause of the log growth turns out to be no log backups (or insufficiently frequent ones), then perform one immediately. An even quicker way to make space in the log, assuming you can get permission to do it, is to temporarily switch the database to SIMPLE recovery to force a log truncation, then switch it back to FULL and perform a full backup. The next step is to investigate all possible causes of the log growth, as discussed in the previous sections, and implement measures to prevent its recurrence. Having done so, however, you may still be left with a log file that has ballooned to an unacceptably large size. As a one-off operation, in such circumstances, it's acceptable to use DBCC SHRINKFILE to reclaim space in the log and reduce its physical size. The recommended way to do this is to disconnect all users from the database (or wait for a time when there is very low activity), take a log backup or just force a CHECKPOINT if the database is in SIMPLE recovery, and then perform the DBCC SHRINKFILE operation, as follows: DBCC SHRINKFILE(<logical name of log file>,truncateonly);. This will shrink the log to its smallest possible size. You can then resize the log appropriately, via an ALTER DATABASE command. This technique, when performed in this manner as a one-off operation, should resize the log and remove any fragmentation that occurred during its previous growth. 176 177 Chapter 5: Log Backups Finally, before moving on, it's worth noting that there is quite a bit of bad advice out there regarding how to respond to this transaction log issue. The most frequent offenders are suggestions to force log truncation using BACKUP LOG WITH TRUNCATE_ONLY (deprecated in SQL Server 2005) or its even more disturbing counterpart, BACKUP LOG TO DISK='NUL', which takes a log backup and discards the contents, without SQL Server having any knowledge that the log chain is broken. Don't use these techniques. The only correct way to force log truncation is to temporarily switch the database to SIMPLE recovery. Likewise, you should never schedule regular DBCC SHRINKFILE tasks as a means of controlling the size of the log as it can cause terrible log fragmentation, as discussed in the next section. Log fragmentation A fragmented log file can dramatically slow down any operation that needs to read the log file. For example, it can cause slow startup times (since SQL Server reads the log during the database recovery process), slow RESTORE operations, and more. Log size and growth should be planned and managed to avoid excessive numbers of growth events, which can lead to this fragmentation. A log is fragmented if it contains a very high number of VLFs. In general, SQL Server decides the optimum size and number of VLFs to allocate. However, a transaction log that auto-grows frequently in small increments, will suffer from log fragmentation. To see this in action, let's simply re-create our previous ForceFailure database, withal its configuration settings set at whatever the model database dictates, and then run the DBCC LogInfo command, which is an undocumented and unsupported command (at least there is very little written about it by Microsoft) but which will allow us to interrogate the VLF architecture. 177 178 Chapter 5: Log Backups CREATE DATABASE [ForceFailure] ALTER DATABASE [ForceFailure] SET RECOVERY FULL WITH NO_WAIT DBCC Loginfo; Listing 5-10: Running DBCC Loginfo on the ForceFailure database. The results are shown in Figure The DBCC LogInfo command returns one row per VLF and, among other things, indicates the Status of that VLF. A Status value of 2 indicates a VLF is active and cannot be truncated; a Status value of 0 indicates an inactive VLF. Figure 5-13: Five VLFs for our empty ForceFailure database. Five rows are returned, indicating five VLFs (two of which are currently active). We are not going to delve any deeper here into the meaning of any of the other columns returned. Now let's insert a large number of rows (one million) into a VLFTest table, in the ForceFailure database, using a script reproduced by kind permission of Jeff Moden (), and then rerun the DBCC LogInfo command, as shown in Listing 179 Chapter 5: Log Backups USE ForceFailure ; IF OBJECT_ID('dbo.VLFTest', 'U') IS NOT NULL DROP TABLE dbo.vlftest ; --===== AUTHOR: Jeff Moden --===== Create and populate 1,000,000 row test table. -- "SomeID" has range of 1 to unique numbers -- "SomeInt" has range of 1 to non-unique numbers -- "SomeLetters2";"AA"-"ZZ" non-unique 2-char strings -- "SomeMoney"; to non-unique numbers -- "SomeDate" ; >=01/01/2000 and <01/01/2010 non-unique -- "SomeHex12"; 12 random hex characters (ie, 0-9,A-F) SELECT TOP SomeID = IDENTITY( INT,1,1 ), SomeInt = ABS(CHECKSUM(NEWID())) % , SomeLetters2 = CHAR(ABS(CHECKSUM(NEWID())) % ) + CHAR(ABS(CHECKSUM(NEWID())) % ), SomeMoney = CAST(ABS(CHECKSUM(NEWID())) % / AS MONEY), SomeDate = CAST(RAND(CHECKSUM(NEWID())) * AS DATETIME), SomeHex12 = RIGHT(NEWID(), 12) INTO dbo.vlftest FROM sys.all_columns ac1 CROSS JOIN sys.all_columns ac2 ; DBCC Loginfo; --Tidy up once you're done as we no longer need this database DROP DATABASE ForceFailure Listing 5-11: Inserting one million rows and interrogating DBCC Loginfo. This time, the DBCC LogInfo command returns 131 rows, indicating 131 VLFs, as shown in Figure 180 Chapter 5: Log Backups Figure 5-14: 131 VLFs for our ForceFailure database, with one million rows. The growth properties inherited from the model database dictate a small initial size for the log files, then growth in relatively small increments. These properties are inappropriate for a database subject to this sort of activity and lead to the creation of a large number of VLFs. By comparison, try re-creating ForceFailure, but this time with some sensible initial size and growth settings (such as those shown in Listing 5-1). In my test, this resulted in an initial 4 VLFs, expanding to 8 VLFs after inserting a million rows. The "right" number of VLFs for a given database depends on a number of factors, including, of course, the size of the database. Clearly, it is not appropriate to start with a very small log and grow in small increments, as this leads to fragmentation. However, it might also cause problems to go to the opposite end of the scale and start with a huge (tens of GB) log, as then SQL Server would create very few VLFs, and this could affect log space reuse. Further advice on how to achieve a reasonable number of VLFs can be found in Paul Randal's TechNet article Top Tips for Effective Database Maintenance, at If you do diagnose a very fragmented log, you can remedy the situation using DBCC SHRINKFILE, as described in the previous section. Again, never use this as a general means of controlling log size; instead, ensure that your log is sized, and grows, appropriately. 180 181 Chapter 5: Log Backups Summary This chapter explained in detail how to capture log backups using either SSMS Backup Wizard or T-SQL scripts. We also explored, and discussed, how to avoid certain log-related issues such as explosive log growth and log fragmentation. Do not to remove any of the backup files we have captured; we are going to use each of these in the next chapter to perform various types of restore operation on our DatabaseForLogBackups database. 181 182 Chapter 6: Log Restores Whereas log backups will form a routine part of our daily maintenance tasks on a given database, log restores, at least in response to an emergency, will hopefully be a much rarer occurrence. However, whenever they need to be performed, it's absolutely vital the job is done properly. In this chapter, we're going to restore the full backup of our DatabaseForLogBackups database from Chapter 5, and then apply our series of log backups in order to return our databases to various previous states. We'll demonstrate how to perform a complete transaction log restore, and how to restore to a point in time within a log file. Log Restores in the SLA With an appropriate backup schedule in place, we know that with the right collection of files and enough time we can get a database back online and, with a point-in-time restore, get it back to a state fairly close to the one it was in before whatever unfortunate event befell it. However, as discussed in Chapter 2, the SLA needs to clearly stipulate an agreed maximum time for restoring a given database, which takes sensible account of the size of the database, where the necessary files are located, and the potential complexity of the restore. 182 183 Chapter 6: Log Restores Possible Issues with Log Restores There are several factors that could possibly affect our ability to perform a point-in-time log restore successfully or at least cause some disruption to the process: an incomplete series of log backup files a missing full backup database file minimally logged transactions in a log file. Let's take a look at each in turn. Missing or corrupt log backup A restore operation to a particular point will require an unbroken log backup chain; that is, we need to be able to apply each and every backup file, in an unbroken sequence, up to the one that contains the log records covering the time to which we wish to restore the database. If we don't have a complete sequence of log files describing a complete LSN chain right up to the point we wish to restore, then we will only be able to restore to the end of the last file before the sequence was broken. The most common cause of a broken log file sequence is a missing or corrupted backup file. However, another possibility is that someone manually forced a truncation of the log without SQL Server's knowledge (see the Handling the 9002 Transaction Log Full error section in Chapter 5). This could prove disastrous, especially in the case of a failure very late in a day. For example, if we are taking log backups each hour, but somehow lose the transaction log backup file that was taken at 1 p.m., a failure that happens at 8 p.m. will cost us eight full hours of data loss. 183 184 Chapter 6: Log Restores Missing or corrupt full backup If we find that the latest full backup file, on which we planned to base a RESTORE operation, is missing or corrupt, then there is still hope that we can perform our point-intime restore. Full backups do not break the log chain, and each log backup contains all the log records since the last log backup, so we can restore the previous good full backup and then restore the full chain of log files extending from this full backup up to the desired point of recovery. However, this is not a reason to skip full backups, or to adopt a cavalier attitude towards full backup failures. When performing a restore operation, the greatest chance of success comes when that operation involves the smallest number of files possible. The more files we have to restore, the greater the chance of failure. Minimally logged operations In Chapter 5, we discussed briefly the fact that it is not possible to restore a database to a point in time within a log file that contains minimally logged operations, recorded while the database was operating in the BULK_LOGGED recovery model. In order to visualize this, Figure 6-1 depicts an identical backup timeline for two databases, each of which we wish to restore to the same point in time (represented by the arrow). The green bar represents a full database backup and the yellow bars represent a series of log backups. The only difference between the two databases is that the first is operating in FULL recovery model, and the second in BULK LOGGED. 184 185 Chapter 6: Log Restores Figure 6-1: Database backup timeline. During the time span of the fifth log backup of the day, a BULK INSERT command was performed on each database, in order to load a set of data. This bulk data load completed without a hitch but, in an unrelated incident, within the time span of the fifth log backup, a user ran a "rogue" transaction and crucial data was lost. The project manager informs the DBA team and requests that the database is restored to a point just where the transaction that resulted in data loss started. (we'll see how to do this later in the chapter). In the BULK LOGGED database, we have a problem. We can restore to any point in time within the first four log backups, but not to any point in time within the fifth log backup, which contains the minimally logged operations. For that log file, we are in an "all or nothing" situation; we must apply none of the operations in this log file, so stopping the restore at the end of the fourth file, or we must apply all of them, proceeding to restore to any point in time within the sixth log backup. 185 186 Chapter 6: Log Restores In other words, we can restore the full database backup, again without recovery, and apply the first four log backups to the database. Unfortunately, we will not have the option to restore to any point in time within the fifth log., enter database recovery, and report the loss of any data changes that were made after this time. Hopefully, this will never happen to you and, unless your SLA adopts a completely "zero tolerance" attitude towards any risk of data loss, it is not a reason to avoid BULK_LOGGED recovery model altogether. There are valid reasons using this recovery model in order to reduce the load on the transaction log, and if we follow best practices, we should not find ourselves in this type of situation. USE [master] BACKUP LOG [SampleDB] TO DISK = '\\path\example\filename.trn' ALTER DATABASE [SampleDB] SET RECOVERY BULK_LOGGED WITH NO_WAIT -- Perform minimally logged transactions here -- Stop minimally logged transactions here ALTER DATABASE [SampleDB] SET RECOVERY FULL WITH NO_WAIT BACKUP LOG [SampleDB] TO DISK = '\\path\example\filename.trn' Listing 6-1: A template for temporarily switching a database to BULK_LOGGED recovery model. 186 187 Chapter 6: Log Restores If we do need to perform maintenance operations that can be minimally logged and we wish to switch to BULK_LOGGED model, the recommended practice is to take a log backup immediately before switching to BULK_LOGGED, and immediately after switching the database back to FULL recovery, as demonstrated in Listing 6-1. This will, as far as possible, isolate the minimally logged transactions in a single log backup file. Performing Log Restores Being prepared to restore your database and log backups is one of the DBAs most important jobs. All DBAs are likely, eventually, to find themselves in a situation where a crash recovery is required, and it can be a scary situation. However, the well-prepared DBA will know exactly where the required backup files are stored, will have been performing backup verification and some random test restores, and can exude a calm assurance that this database will be back online as quickly as possible. As we did for log backups, we're going to discuss how to perform log restores the "GUI way," in SSMS, and then by using native T-SQL Backup commands. We're going to be restoring to various states the DatabaseForLogBackups database from Chapter 5, so before we start, let's review, pictorially, our backup scheme for that database, and what data is contained within each backup file. With our first example, using the GUI, we'll restore the DatabaseForLogBackups database to the state in which it existed at the point after the first log backup was taken; in other words, we'll restore right to the end of the transaction log DatabaseForLog- Backups_Native_Log_1.trn, at which point we should have 20 rows in each of our three message tables. 187 188 Chapter 6: Log Restores Figure 6-2: Backup scheme for DatabaseForLogBackups. In our second example, using a T-SQL script, we'll restore to a specific point in time within the second log backup, just before the last 100,000 records were inserted into MessageTable3. This will leave the first two tables with their final row counts (1,020 and 10,020, respectively), but the third with just 20 rows. As discussed in Chapter 1, there are several different ways to restore to a particular point inside a log backup; in this case, we'll demonstrate the most common means, which is to use the STOPAT parameter in the RESTORE LOG command to restore the database to a state that reflects all transactions that were committed at the specified time. GUI-based log restore We will begin by using the native SQL Server backup files that we took in Chapter 5 to restore our database to the state that it was in after the first transaction log backup was taken. We are going to restore the entire transaction log backup in this example. Go ahead and get SSMS started and connected to your test SQL Server. 188 189 Chapter 6: Log Restores Right-click on DatabaseForLogBackups in the object explorer and select Tasks Restore Database to begin the restore process and you'll see the Restore Database screen, which we examined in detail in Chapter 4. This time, rather than restore directly over an existing database, we'll restore to a new database, basically a copy of the existing DatabaseForLogBackups but as it existed at the end of the first log backup. So, in the To database: section, enter a new database name, such as DatabaseForLogBackups_RestoreCopy. In the Source for restore section of the screen, you should see that the required backup files are auto-populated (SQL Server can interrogate the msdb database for the backup history). This will only be the case if all the backup files are in their original location (C:\ SQLBackups\Chapter5, if you followed through the examples). Therefore, as configured in Figure 6-3, our new copy database would be restored to the end of the second log backup, in a single restore operation. Alternatively, by simply deselecting the second log file, we could restore the database to the end of the first log file. Figure 6-3: Initial Restore Database screen for DatabaseForLogBackups. 189 190 Chapter 6: Log Restores However, if the backup files have been moved to a new location, we'd need to manually locate each of the required files for the restore process, and perform the restore process in several steps (one operation to restore the full backup and another the log file). Since it is not uncommon that the required backups won't still be in their original local folders, and since performing the restore in steps better illustrates the process, we'll ignore this useful auto-population feature for the backup files, and perform the restore manually. Click on From device: and choose the browse button to the right of that option, navigate to C:\SQLBackups\Chapter5 and choose the full backup file. Having done so, the relevant section of the Restore Database page should look as shown in Figure 6-4. Figure 6-4: Restore the full backup file. Next, click through to the Options page. We know that restoring the full backup is only the first step in our restore process, so once the full backup is restored we need the new DatabaseForLogBackups_RestoreCopy database to remain in a restoring state, ready to accept further log files. Therefore, we want to override the default restore state (RESTORE WITH RECOVERY) and choose instead RESTORE WITH NORECOVERY, as shown in Figure 191 Chapter 6: Log Restores Figure 6-5: Restore the full backup file while leaving the database in a restoring state. Note that SQL Server has automatically renamed the data and log files for the new database so as to avoid clashing with the existing DatabaseForLogBackups database, on which the restore is based. Having done this, we're ready to go. First, however, you might want to select the Script menu option, from the top of the General Page, and take a quick look at the script that has been generated under the covers. I won't show it here, as we'll get to these details in the next example, but you'll notice use of the MOVE parameter, to rename the data and log files, and the NORECOVERY parameter, to leave the database in a restoring state. Once the restore is complete, you should see the new DatabaseForLogBackups_RestoreCopy database in your object explorer, but with a green arrow on the database icon, and the word "Restoring " after its name. We're now ready to perform the second step, and restore our first transaction log. Rightclick on the new DatabaseForLogBackups_RestoreCopy database and select Tasks 191 192 Chapter 6: Log Restores Restore Transaction Log. In the Restore source section, we can click on From previous backups of database:, and then select DatabaseForLogBackups database. SQL Server will then retrieve the available log backups for us to select. Alternatively, we can manually select the required log backup, which is the route we'll choose here, so click on From file or tape: and select the first log backup file from its folder location (C:\ SQLBackups\Chapter5\DatabaseForLogBackups_Native_Log_1.trn). The screen should now look as shown in Figure 6-6. Figure 6-6: Preparing to restore the log file. 192 193 Chapter 6: Log Restores Now switch to the Options page and you should see something similar to Figure 6-7. Figure 6-7: Configuring the data and log files for the target database. This time we want to complete the restore and bring the database back online, so we can leave the default option, RESTORE WITH RECOVERY selected. Once you're ready, click OK and the log backup restore should complete and the DatabaseForLogBackups_ RestoreCopy database should be online and usable. As healthy, paranoid DBAs, our final job is to confirm that we have the right rows in each of our tables, which is easily accomplished using the simple script shown in Listing 6-2. USE DatabaseForLogBackups_RestoreCopy SELECT COUNT(*) FROM dbo.messagetable1 SELECT COUNT(*) FROM dbo.messagetable2 SELECT COUNT(*) FROM dbo.messagetable3 Listing 6-2: Checking our row counts. 193 194 Chapter 6: Log Restores If everything ran correctly, there should be 20 rows of data in each table. We can also run a query to return the columns from each table, to make sure that the data matches what we originally inserted. As is hopefully clear, GUI-based restores, when all the required backup files are still available in their original local disk folders, can be quick, convenient, and easy. However, if they are not, for example due to the backup files being moved, after initial backup, from local disk to network space, or after a backup has been brought back from long-term storage on tape media, then these GUI restores can be quite clunky, and the process is best accomplished by script. T-SQL point-in-time restores In this section, we will be performing a point-in-time restore. This operation will use all three of the backup files (one full, two log) to restore to a point in time somewhere before we finalized the last set of INSERT statements that were run against the DatabaseFor- LogBackups database. When doing a point-in-time restore, we are merely restoring completely all of the log backup files after the full database backup, except the very last log file, where we'll stop at a certain point and, during database recovery, SQL Server will only roll forward the transactions up to that specified point. In order to restore to the right point, in this example you will need to refer back to the timestamp value you saw in the output of Listing 5-6, the third data load for the DatabaseForLogBackups database. Hopefully, you will rarely be called upon to perform these types of restore but when you are, it's vital that you're well drilled, having practiced your restore routines many times, and confident of success, based on your backup validation techniques and random test restores. 194 195 Chapter 6: Log Restores GUI-based point-in-time restore It's entirely possible to perform point-in-time restores via the GUI. On the Restore Database page, we simply need to configure a specific date and time, in the To a point in time: option, rather than accept the default setting of most recent possible. We don't provide a full worked example in the GUI, but feel free to play around with configuring and executing these types of restore in the GUI environment. Don't worry; point-in-time restores are not as complicated as they may sound! To prove it, let's jump right into the script in Listing 6-3. The overall intent of this script is to restore the DatabaseForLogBackup full backup file over the top of the DatabaseForLogBackup_RestoreCopy database, created in the previous GUI restore, apply the entire contents of the first log backup, and then the contents of the second log backup, up to the point just before we inserted 100,000 rows into MessageTable3. USE [master] --STEP 1: Restore the full backup. Leave database in restoring state --STEP 2: Completely restore 1st log backup. Leave database in restoring state RESTORE LOG [DatabaseForLogBackups_RestoreCopy] FROM DISK = N'C:\SQLBackups\Chapter5\DatabaseForLogBackups_Native_Log.trn' WITH FILE = 1, NORECOVERY, STATS = 196 Chapter 6: Log Restores --STEP 3: P-I-T restore of 2nd log backup. Recover the database RESTORE LOG [DatabaseForLogBackups_RestoreCopy] FROM DISK = N'C:\SQLBackups\Chapter5\DatabaseForLogBackups_Native_Log_2.trn' WITH FILE = 1, NOUNLOAD, STATS = 10, STOPAT = N'January 30, :34 PM', -- configure your time here RECOVERY Listing 6-3: T-SQL script for a point-in-time restore of DatabaseForLogbackups. The first section of the script restores the full backup file to the restore copy database. We use the MOVE parameter for each file to indicate that, rather than use the data and log files for DatabaseForLogBackups as the target for the restore, we should use those for a different database, in this case DatabaseForLogBackup_RestoreCopy. The NORECOVERY parameter indicates that we wish to leave the target database, Database- ForLogBackup_RestoreCopy, in a restoring state, ready to accept further log backup files. Finally, we use the REPLACE parameter, since we are overwriting the data and log files that are currently being used by the DatabaseForLogBackup_RestoreCopy database. The second step of the restore script applies the first transaction log backup to the database. This is a much shorter command, mainly due to the fact that we do not have to specify a MOVE parameter for each data file, since we already specified the target data and log files for the restore, and those files will have already been placed in the correct location before this RESTORE LOG command executes. Notice that we again use the NORECOVERY parameter in order to leave the database in a non-usable state so we can move on to the next log restore and apply more transactional data. The second and final LOG RESTORE command is where you'll spot the brand new STOPAT parameter. We supply our specific timestamp value to this parameter in order to instruct SQL Server to stop applying log records at that point. The supplied timestamp value is important since we are instructing SQL Server to restore the database to the state it was in at the point of the last committed transaction at that specific time. We need to use the date time that was output when we ran the script in Chapter 5 (Listing 5-6). In my case, the time portion of the output was 3.33 p.m. 196 197 Chapter 6: Log Restores You'll notice that in Listing 6-3 I added one minute to this time, the reason being that the time output does not include seconds, and the transactions we want to include could have committed at, for example, 2:33:45. By adding a minute to the output and rounding up to 2:34:00, we will capture all the rows we want, but not the larger set of rows that inserted next, after the delay. Note, of course, that the exact format of the timestamp, and its actual value, will be different for you! This time, we specify the RECOVERY parameter, so that when we execute the command the database will enter recovery mode, and the database will be restored to the point of the last committed transaction at the specified timestamp. When you run Listing 6-3 as a whole, you should see output similar to that (3.369 MB/sec). 100 percent processed. Processed 0 pages for database 'DatabaseForLogBackups_RestoreCopy', file 'DatabaseForLogBackups' on file 1. Processed 9 pages for database 'DatabaseForLogBackups_RestoreCopy', file 'DatabaseForLogBackups_log' on file 1. RESTORE LOG successfully processed 9 pages in seconds (9.556 MB/sec). 10 percent processed. 20 percent processed. 31 percent processed. 40 percent processed. 50 percent processed. 61 percent processed. 71 percent processed. 80 percent processed. 90 percent processed. 100 percent processed. 197 198 Chapter 6: Log Restores Processed 0 pages for database 'DatabaseForLogBackups_RestoreCopy', file 'DatabaseForLogBackups' on file 1. Processed 7033 pages for database 'DatabaseForLogBackups_RestoreCopy', file 'DatabaseForLogBackups_log' on file 1. RESTORE LOG successfully processed 7033 pages in seconds ( MB/sec). Figure 6-8: Output from the successful point-in-time restore operation. We see the typical percentage completion messages as well as the total restore operation metrics after each file is completed. What we might like to see in the message output, but cannot, is some indication that we performed a point-in-time restore with the STOPAT parameter. There is no obvious way to tell if we successfully did that other than to double-check our database to see if we did indeed only get part of the data changes that are stored in our second log backup file. All we have to do is rerun Listing 6-2 and this time, if everything went as planned, we should have 1,020 rows in MessageTable1, 10,020 rows in MessageTable2, but only 20 rows in MessageTable3, since we stopped the restore just before the final 100,000 rows were added to that table. Possible difficulties with point-in-time restores When restoring a database in order to retrieve lost data after, for example, a rogue transaction erroneously deleted it, getting the exact time right can be the difference between stopping the restore just before the data was removed, which is obviously what we want, or going too far and restoring to the point after the data was removed. The less sure you are of the exact time to which you need to restore, the trickier the process can become. One option, which will be demonstrated in Chapter 8, is to perform a STANDBY restore, which leaves the target database in a restoring state, but keeps it read-only accessible. In this way you can roll forward, query to see if the lost data is still there, roll forward a bit further, and so on. 198 199 Chapter 6: Log Restores Aside from third-party log readers (very few of which offer support beyond SQL Server 2005), there are a couple of undocumented and unsupported functions that can be used to interrogate the contents of log files (fn_dblog) and log backups (fn_dump_dblog). So for example, we can look at the contents of our second log backup files as shown in Listing 6-4. SELECT * FROM fn_dump_dblog(default, DEFAULT, DEFAULT, DEFAULT, 'C:\SQLBackups\Chapter5\DatabaseForLogBackups_Native_Log_2.trn',); Listing 6-4: Exploring log backups with fn_dump_dblog. It's not pretty and it's not supported (so use with caution); it accepts a whole host of parameters, the only one we've defined being the path to the log backup, and it returns a vast array of information that we're not going to begin to get into here but, it does return the Begin Time for each of the transactions contained in the file, and it may give you some help in working out where you need to stop. An alternative technique to point-in-time restores using STOPAT, is to try to work out the LSN value associated with, for example, the start of the rogue transaction that deleted your data. We're not going to walk through an LSN-based restore here, but a good explanation of some of the practicalities involved can be found here: com/2010/07/25/alternative-to-restoring-to-a-point-in-time/. 199 200 Chapter 6: Log Restores Forcing Restore Failures for Fun After successfully performing two restore operations, let's get some first-hand experience with failure. Understanding how SQL Server responds to certain common mistakes is a great first step to being prepared when tragedy actually strikes. Take a look at the script in Listing 6-5, a restore of a full backup over the top of an existing database, and try to predict what's going to go wrong, and why., RECOVERY Listing 6-5: Spot the deliberate mistake, Part 1. Do you spot the mistake? It's quite subtle, so if you don't manage to, simply run the script and examine the error message: Msg 3159, Level 16, State 1, Line 1 The tail of the log for the database "DatabaseForLogBackups_RestoreCopy". The script in Listing 6-5 is identical to what we saw in Step 1 of Listing 6-3, except that here we are restoring over an existing database, and receive an error which is pretty descriptive. The problem is that we are about to overwrite the existing log file for the 200 201 Chapter 6: Log Restores DatabaseForLogBackups_RestoreCopy database, which is a FULL recovery model database, and we have not backed up the tail of the log, so we would lose any transactions that were not previously captured in a backup. This is a very useful warning message to get in cases where we needed to perform crash recovery and had, in fact, forgotten to do a tail log backup. In such cases, we could start the restore process with the tail log backup, as shown in Listing 6-6, and then proceed. USE master BACKUP LOG DatabaseForLogBackups_RestoreCopy TO DISK = 'D:\SQLBackups\Chapter5\DatabaseForLogBackups_RestoreCopy_log_tail.trn' WITH NORECOVERY Listing 6-6: Perform a tail log backup. In cases where we're certain that our restore operation does not require a tail log backup, we can use WITH REPLACE or WITH STOPAT. In this case, the error can be removed, without backing up the tail of the log, by adding the WITH REPLACE clause to Listing 6-5. Let's take a look at a second example failure. Examine the script in Listing 6-7 and see if you can spot the problem. --STEP 1: Restore the log backup, REPLACE 201 202 Chapter 6: Log Restores --Step 2: Restore to the end of the first log backup RESTORE LOG [DatabaseForLogBackups_RestoreCopy] FROM DISK = N'C:\SQLBackups\Chapter5\DatabaseForLogBackups_Native_Log_1.trn' WITH FILE = 1, RECOVERY, STATS = 10 Listing 6-7: Spot the deliberate mistake, Part 2. Look over each of the commands carefully and then execute this script; you should see results similar to those (1.521 MB/sec). Msg 3117, Level 16, State 1, Line 2 The log or differential backup cannot be restored because no files are ready to rollforward. Msg 3013, Level 16, State 1, Line 2 RESTORE LOG is terminating abnormally. Figure 6-9: Output from the (partially) failed restore. We can see that this time the full database backup restore, over the top of the existing database, was successful (note that we remembered to use REPLACE). It processed all of the data in what looks to be the correct amount of time. Since that operation completed, it must be the log restore that caused the error. Let's look at the error messages in the second part of the output, which will be in red. The first error we see in the output is the statement "The log or differential backup cannot be restored because no files are ready to rollforward." What does that mean? If you didn't catch the mistake in the script, it was that we left out an important parameter in the full database restore operation. Take a look again, and you will see that we don't have the NORECOVERY option in the command. Therefore, the first restore command finalized the 202 203 Chapter 6: Log Restores restore and placed the database in a recovered state, ready for user access (with only ten rows in each table!); no log backup files can then be applied as part of the current restore operation. Always specify NORECOVERY if you need to continue further with a log backup restore operation. Of course, there are many other possible errors that can arise if you're not fully paying attention during the restore process, and we can't cover them all. However, as one final example, take a look at Listing 6-8 and see if you can spot the problem., REPLACE RESTORE LOG [DatabaseForLogBackups] FROM DISK = N'C:\SQLBackups\Chapter5\DatabaseForLogBackups_Native_Log_2.trn' WITH FILE = 1, NORECOVERY, STATS = 10 RESTORE LOG [DatabaseForLogBackups] FROM DISK = N'C:\SQLBackups\Chapter5\DatabaseForLogBackups_Native_Log_1.trn' WITH FILE = 1, RECOVERY, STATS = 10 Listing 6-8: Forcing one more fun failure. Did you catch the problem before you ran the script? If not, take a look at your output, examine the error message you get when the first log file restore is attempted. I'm sure you'll be able to figure out what's wrong in short order! 203 204 Chapter 6: Log Restores Summary After reading and working through this chapter, you should also be fairly comfortable with the basics of log restore operations, and in particular with point-in-time restores. The key to successful restores is to be well organized and well drilled. You should know exactly where the required backup files are stored; you should have confidence the operation will succeed, based on your backup validations, and regular, random "spotcheck" restores. You may be under pressure to retrieve critical lost data, or bring a stricken database back online, as quickly as possible, but it's vital not to rush or panic. Proceed carefully and methodically, and your chances of success are high. 204 205 Chapter 7: Differential Backup and Restore A differential database backup in SQL Server is simply a copy of every page that has had a change made to it since the last full backup was taken. We capture, in a differential backup file, the changed data pages then, during a restore process, apply that differential backup to the last full backup, also known as the base backup, in order to roll the database forward to the state in which it existed at the point the differential backup was taken. In my experience, opinion is somewhat split within the DBA community as to the value of differential database backups. Some DBAs seem to regard this third type of backup as an unnecessary complication and prefer, where possible, to restrict their backup strategy to two types of backup: full and log. Others, however, find them to be a necessity, and a useful way of reducing the time required to take backups, space required to store local backup files, and the number of log files that may need to be applied during a point-intime restore. My opinion is that differential backups, used correctly and in the right situations, are a key recovery option in your environment. The basic structure of this chapter will be familiar, so we'll be moving at a quicker pace; after discussing why and when differential backups can form a useful part of your backup and restore strategy, and some pros and cons in their use, we'll walk through examples of taking and then restoring native differential backups, using the SSMS GUI and T-SQL, gathering metrics as we go. Finally, we'll take a look a few common errors that can arise when taking and restoring differential backups. 205 206 Chapter 7: Differential Backup and Restore Differential Backups, Overview As noted in the introduction, a differential database backup is a copy of every page that has changed since the last full backup. The last part of that sentence is worth stressing. It is not possible to take a differential database backup without first taking a full database backup, known as the base backup. Whenever a new full backup is taken, SQL Server will clear any markers in its internal tracking mechanism, which are stored to determine which data pages changed since the last full backup, and so would need to be included in any differential backup. Therefore, each new full backup becomes the base backup for any subsequent differential backups. If we lose a full backup, or it becomes corrupted, any differential backups that rely on that base will be unusable. This is the significant difference in the relationship between a differential backup and its associated full backup, and the relationship between log backups and their associated full backup. While we always restore a full backup before any log backups, the log backups are not inextricably linked to any single full backup; if a full backup file goes missing, we can still go back to a previous full backup and restore the full chain of log files, since every log backup contains all the log that was entered since the last log backup. A full backup resets the log chain, so that we have all the needed information to begin applying subsequent log backups, but doesn't break the chain. A differential backup always contains all changes since the last full backup, and so is tied to one specific full backup. Because the data changes in any differential backup are cumulative since the base backup, if we take one full backup followed by two differential backups then, during a restore process where we wish to return the database to a state as close as possible to that it was in at the time of the disaster, we only need to restore the full backup and the single, most recent differential backup (plus any subsequent transaction log backups). 206 207 Chapter 7: Differential Backup and Restore Advantages of differential backups Perhaps the first question to answer is why we would want to capture only the changed data in a backup; why not just take another full backup? The answer is simple: backup time and backup file space utilization. A full database backup process, for a large database, will be a time- and resource-consuming process, and it is usually not feasible to run this process during normal operational hours, due to the detrimental impact it could have on the performance of end-user and business processes. In most cases, a differential database backup will contain much less data, and require much less processing time than a full database backup. For a large database that is not subject to a huge number of changes, a differential backup can execute in 10% of the time it would take for a full backup. For a real-world example, let's consider one of my moderately-sized production databases. The processing time for a full database backup is usually about 55 minutes. However, the average differential backup takes only about 4 minutes to complete. This is great, since I still have a complete set of backups for recovery, but the processing time is greatly reduced. Remember that the larger a database, the more CPU will be consumed by the backup operation, the longer the backup operation will take, and the greater the risk will be of some failure (e.g. network) occurring during that operation. The other saving that we get with a differential backup, over a full backup, is the space saving. We are only storing the data pages that have been modified since the last full backup. This is typically a small fraction of the total size, and that will be reflected in the size of the differential backup file on disk. As such, a backup strategy that consists of, say, one daily full backup plus a differential backup, is going to consume less disk space than an equivalent strategy consisting of two full backups. 207 208 Chapter 7: Differential Backup and Restore Will differential backups always be smaller than full backups? For the most part, if you refresh your base backup on a regular schedule, you will find that a differential backup should be smaller in size than a full database backup. However, there are situations where a differential backup could become even larger than its corresponding base backup, for example if the base backup is not refreshed for a long period and during that time a large amount of data has been changed or added. We'll discuss this further shortly, in the Possible issues with differential backups section. Let's assume that the same moderately-sized production database, mentioned above, has a backup strategy consisting of a weekly full backup, hourly transaction log backups and daily differential backups. I need to retain on disk, locally, the backups required to restore the database to any point in the last three days, so that means storing locally the last three differential backups, the last three days' transaction log backups, plus the base full backup. The full backup size is about 22 GB, the log backups are, on average, about 3 GB each, and 3 days' worth of differential backups takes up another 3 GB, giving a total of about 28 GB. If I simply took full backups and log backups, I'd need almost 70 GB of space at any time for one database. Deciding exactly the right backup strategy for a database is a complex process. We want to strive as far as possible for simplicity, short backup times, and smaller disk space requirements, but at the same time we should never allow such goals to compromise the overall quality and reliability of our backup regime. Differential backup strategies In what situations can the addition of differential backups really benefit the overall database recovery scheme? Are there any other cases where they might be useful? 208 209 Reduced recovery times Chapter 7: Differential Backup and Restore The number one reason that most DBAs and organizations take differential backups is as a way of reducing the number of log files that would need to be restored in the case of an emergency thus, potentially, simplifying any restore process. For example, say we had a backup strategy consisting of a nightly full backup, at 2 a.m., and then hourly log backups. If a disaster occurred at 6.15 p.m., we'd need to restore 17 backup files (1 full backup and 16 log backups), plus the tail log backup, as shown in Figure 7-1. Figure 7-1: A long chain of transaction log backups. This is a somewhat dangerous situation since, as we have discussed, the more backup files we have to take, store, and manage the greater the chance of one of those files being unusable. This can occur for reasons from disk corruption to backup failure. Also, if any of these transaction log backup files is not usable, we cannot restore past that point in the database's history. If, instead, our strategy included an additional differential backup at midday each day, then we'd only need to restore eight files: the full backup, the differential backup, and six transaction log backups (11 16), plus a tail log backup, as shown in Figure 7-2. We would also be safe in the event of a corrupted differential backup, because we would still have all of the log backups since the full backup was taken. 209 210 Chapter 7: Differential Backup and Restore Figure 7-2: Using a differential backup can shorten the number of backup files to restore. In any situation that requires a quick turnaround time for restoration, a differential backup is our friend. The more files there are to process, the more time it will also take to set up the restore scripts, and the more files we have to work with, the more complex will be the restore operation, and so (potentially) the longer the database will be down. In this particular situation, the savings might not be too dramatic, but for mission-critical systems, transaction logs can be taken every 15 minutes. If we're able to take one or two differential backups during the day, it can cut down dramatically the number of files involved in any restore process. Consider, also, the case of a VLDB where full backups take over 15 hours and so nightly full backups cannot be supported. The agreed restore strategy must support a maximum data loss of one hour, so management has decided that weekly full backups, taken on Sunday, will be supplemented with transaction log backups taken every hour during the day. Everything is running fine until one Friday evening the disk subsystem goes out on that machine and renders the database lost and unrecoverable. We are now going to have to restore the large full backup from the previous Sunday, plus well over 100 transaction log files. This is a tedious and long process. Fortunately, we now know of a better way to get this done, saving a lot of time and without sacrificing too much extra disk space: we take differential database backups each night except Sunday as a supplemental backup to the weekly full one. Now, we'd only need to restore the full, differential and around 20 log backups. 210 211 Database migrations Chapter 7: Differential Backup and Restore In Chapters 3 and 5, we discussed the role of full and log backups in database migrations in various scenarios. Differential restores give us another great way to perform this common task and can save a lot of time when the final database move takes place. Imagine, in this example, that we are moving a large database, operating in SIMPLE recovery model, from Server A to Server B, using full backups. We obviously don't want to lose any data during the transition, so we kill any connections to the database and place it into single-user mode before we take the backup. We then start our backup, knowing full well that no new changes can be made to our database or data. After completion, we take the source database offline and begin the restore the database to Server B. The whole process takes 12 hours, during which time our database is down and whatever front-end application it is that uses that database is also offline. No one is happy about this length of down-time. What could we do to speed the process up a bit? A better approach would be to incorporate differential database backups. 16 hours before the planned migration (allowing a few hours' leeway on the 12 hours needed to perform the full backup and restore), we take a full database backup, not kicking out any users and so not worrying about any subsequent changes made to the database. We restore to Server B the full database backup, using the NORECOVERY option, to leave the database in a state where we can apply more backup files. Once the time has come to migrate the source database in its final state, we kill any connections, place it in single-user mode and perform a differential backup. We have also been very careful not to allow any other full backups to happen via scheduled jobs or other DBA activity. This is important, so that we don't alter the base backup for our newly created differential backup. Taking the differential backup is a fast process (10 15 minutes), and the resulting backup file is small, since it only holds data changes made in the last 12 to 16 hours. Once the backup has completed, we take the source database offline and immediately start the 211 212 Chapter 7: Differential Backup and Restore differential restore on the target server, which also takes only minutes to complete, and we are back online and running. We have successfully completed the migration, and the down-time has decreased from a miserable 12 hours to a scant 30 minutes. There is a bit more preparation work to be done using this method, but the results are the same and the uptime of the application doesn't need to take a significant hit. Possible issues with differential backups In most cases in my experience, the potential issues or downsides regarding differential backups are just minor inconveniences, rather than deal breakers, and usually do not outweigh the savings in disk space usage and backup time, especially for larger databases. Invalid base backup The biggest risk with differential backups is that we come to perform a restore, and find ourselves in a situation where our differential backup file doesn't match up to the base backup file we have ready (we'll see this in action later). This happens when a full backup is taken of which we are unaware. Full database backups are taken for many reasons outside of your nightly backup jobs. If, for example, someone takes a full backup in order to restore it to another system, and then deletes that file after they are done, our next differential is not going to be of much use, since it is using that deleted file as its base. The way to avoid this situation is to ensure that any database backups that are taken for purposes other than disaster recovery are copy-only backups. In terms of the data it contains and the manner in which it is restored, a copy-only backup is just like a normal full backup. However, the big difference is that, unlike a regular full backup, with a copy-only backup, SQL Server's internal mechanism for tracking data pages changed since the last full backup is left untouched and so the core backup strategy is unaffected. 212 213 Chapter 7: Differential Backup and Restore However, if this sort of disaster does strike, all we can do is look through the system tables in MSDB to identify the new base full backup file and hope that it will still be on disk or tape and so can be retrieved for use in your restore operation. If it is not, we are out of luck in terms of restoring the differential file. We would need to switch to using the last full backup and subsequent transaction log backups, assuming that you were taking log backups of that database. Otherwise, our only course of action would be to use the last available full database backup. Bottom line: make sure that a) only those people who need to take backups have the permissions granted to do so, and b) your DBA team and certain administrative users know how and when to use a copy-only backup operation. Missing or corrupt base backup Without a base full backup, there is no way to recover any subsequent differential backup files. If we need a base backup that has been archived to offsite tape storage, then there may be a significant delay in starting the restore process. We can prevent this from happening by making sure the mechanism of backup file cleanup leaves those base files on disk until a new one is created. I keep weekly base backups in a specially-named folder that isn't touched for seven days, so that I know the files will be available in that time span. If a base backup simply goes missing from your local file system, this is an issue that needs careful investigation. Only the DBA team and the Server Administration team should have access to the backup files and they should know much better than to delete files without good cause or reason. Finally, there is no getting around the fact that every restore operation that involves a differential backup will involve a minimum of two files (the base full and the differential) rather than one. Let's say, just for the sake of illustration, that your SLA dictates a maximum of 12 hours' data loss, so you take backups at midnight and midday. If we only take full backups, then we'll only ever need to restore one full backup file; if our midday 213 214 Chapter 7: Differential Backup and Restore backup is a differential, then we'll always need to restore the midnight full, followed by the midday differential. In the event of corruption or loss of a single backup file, the maximum exposure to data loss, in either case, is 24 hours. This really is a small risk to take for the great rewards of having differential backups in your rotation. I have taken many thousands of database backups and restored thousands of files as well. I have only run into corrupt files a few times and they were never caused by SQL Server's backup routines. To help alleviate this concern, we should do two things. Firstly, always make sure backups are being written to some sort of robust storage solution. We discussed this in Chapter 2, but I can't stress enough how important it is to have backup files stored on a redundant SAN or NAS system. These types of systems can cut the risk of physical disk corruptions down to almost nothing. Secondly, as discussed in Chapter 4, we should also perform spot-check restores of files. I like to perform at least one randomly-chosen test restore per week. This gives me even more confidence that my backup files are in good shape without having to perform CHECKSUM tests on each and every backup file. Infrequent base refresh and/or frequently updated databases The next possible issue regards the management and timing of the full base backup. If the base backup isn't refreshed regularly, typically on a weekly basis, the differentials will start to take longer to process. If a database is subject to very frequent modification, then differential backups get bigger and more resource-intensive and the benefits of differential over full, in terms of storage space and backup time reduction, will become more marginal. Ultimately, if we aren't refreshing the base backup regularly then the benefits obtained from differentials may not justify the complicating factor of an additional backup type to manage. 214 215 Chapter 7: Differential Backup and Restore Differentials in the backup and restore SLA So what does all this mean with regard to how differential backups fit into our overall Backup SLA? My personal recommendation is to use differential backups as part of your backup regimen on a SQL Server as often as possible. In the previous sections, we've discussed their reduced file size and faster backup times, compared to taking an additional full backup and the benefits that can bring, especially for large databases. We've also seen how they can be used to reduce the number of transaction log files that need to be processed during point-in-time restores. For some VLDBs, differential backups may be a necessity. I manage several databases that take 12 or more hours to have a full backup and, in these cases, nightly full backups would place undue strain not only on the SQL Server itself but the underlying file system. I would be wasting CPU, disk I/O and precious disk space every night. Performing a weekly full database backup and nightly differential backups has very little negative impact on our recoverability, compared to nightly full backups, and any concerns in this regard shouldn't stop you from implementing them. Nevertheless, some database owners and application managers feel skittish about relying on differential backups in the case of a recovery situation, and you may get some push back. They may feel that you are less protected by not taking a full backup each night and only recording the changes that have been made. This is normal and you can easily calm their nerves by explaining exactly how this type of backup works, and how any risks can be mitigated. 215 216 Chapter 7: Differential Backup and Restore Preparing for Differential Backups Before we get started taking differential backups, we need to do a bit of preparatory work, namely choosing an appropriate recovery model for our database, creating that database along with some populated sample tables, and then taking the base full backup for that database. I could have used the sample database from Chapter 3, plus the latest full backup from that chapter as the base, but I decided to make it easier for people who, for whatever reason, skipped straight to this chapter. Since we've been through this process several times now, the scripts will be presented more or less without commentary; refer back to Chapters 3 and 5 if you need further explanation of any of the techniques. Recovery model There are no recovery model limitations for differential backups; with the exception of the master database, we can take a differential backup of any database in any recovery model. The only type of backup that is valid for the master database is a full backup. For our example database in this chapter, we're going to assume that, in our Backup SLA, we have a maximum tolerance of 24 hours' potential data loss. However, unlike in Chapter 3, this time, we'll satisfy this requirement using a weekly full backup and nightly differential backups. Since we don't need to perform log backups, it makes sense, for ease of log management, to operate the database in SIMPLE recovery model. 216 217 Chapter 7: Differential Backup and Restore Sample database and tables plus initial data load Listing 7-1 shows the script to create the sample DatabaseForDiffBackups database, plus a very simple table (MessageTable), and then load it with an initial 100,000 rows of data. When creating the database, we place the data and log file in a specific, non-default folder, C:\SQLData\, and set appropriate initial size and growth characteristics for these files. We also set the database recovery model to SIMPLE. Feel free to modify the data and log file paths if you need to place them elsewhere on your server. USE [master] CREATE DATABASE [DatabaseForDiffBackups] ON PRIMARY ( NAME = N'DatabaseForDiffBackups', FILENAME = N'C:\SQLData\DatabaseForDiffBackups.mdf', SIZE = KB, FILEGROWTH = 10240KB ) LOG ON ( NAME = N'DatabaseForDiffBackups_log', FILENAME = N'C:\SQLData\DatabaseForDiffBackups_log.ldf', SIZE = 51200KB, FILEGROWTH = 10240KB ) ALTER DATABASE [DatabaseForDiffBackups] SET RECOVERY SIMPLE USE [DatabaseForDiffBackups] CREATE TABLE [dbo].[messagetable] ( [Message] [nvarchar](100) NOT NULL ) ON [PRIMARY] INSERT INTO MessageTable VALUES ( 'Initial Data Load: This is the first set of data we are populating the table with' ) Listing 7-1: DatabaseForDiffBackups database, MessageTable table, initial data load (100,000 rows). 217 218 Chapter 7: Differential Backup and Restore Base backup As discussed earlier, just as we can't take log backups without first taking a full backup of a database, so we also can't take a differential backup without taking a full base backup. Any differential backup is useless without a base. Listing 7-2 performs the base full backup for our DatabaseForDiffBackups database and stores it in the C:\SQLBackups\Chapter7 folder. Again, feel free to modify this path as appropriate f or your system. USE [master] BACKUP DATABASE [DatabaseForDiffBackups] TO DISK = N'C:\SQLBackups\Chapter7\DatabaseForDiffBackups_Full_Native.bak' WITH NAME = N'DatabaseForDiffBackups-Full Database Backup', STATS = 10 Listing 7-2: Base full backup for DatabaseForDiffBackups. We are not going to worry about the execution time for this full backup, so once the backup has completed successfully, you can close this script without worrying about the output. However, we will take a look at the backup size though, which should come out to just over 20 MB. We can take a look at how our differential backup file sizes compare, as we pump more data into the database. Taking Differential Backups As per our usual scheme, we're going to demonstrate how to take differential backups the "GUI way," in SSMS, and by using native T-SQL Backup commands. In Chapter 8, you'll see how to perform differential backups, as part of a complete and scheduled backup routine using the Red Gate SQL Backup tool. 218 219 Chapter 7: Differential Backup and Restore Before taking the first differential backup, we'll INSERT 10,000 more rows into MessageTable, as shown in Listing 7-3. This is typical of the type of load that we would typically find in a differential backup. USE [DatabaseForDiffBackups] INSERT INTO MessageTable VALUES ( 'Second Data Load: This is the second set of data we are populating the table with' ) Listing 7-3: Second data load (10,000 rows) for MessageTable. Native GUI differential backup We are now ready to take our first differential database backup, via the SSMS GUI backup configuration tool; this should all be very familiar to you by now if you worked through previous chapters, so we're going to move fast! In SSMS, right-click on the DatabaseForDiffBackups database, and navigate Tasks Backup to reach the familiar Backup Database configuration screen. In the Source section, double-check that the correct database is selected (a good DBA always doublechecks) and then change the Backup type to Differential. Leave the Backup set section as-is, and move on to the Destination section. Remove the default backup file (which would append our differential backup to the base full backup file) and add a new destination file at C:\SQLBackups\Chapter7\, called DatabaseForDiffBackups_Diff_Native_1.bak. The screen will look as shown in Figure 220 Chapter 7: Differential Backup and Restore Figure 7-3: Native GUI differential backup configuration. There's nothing to change on the Options page, so we're done. Click OK and the differential backup will be performed. Figure 7-4 summarizes the storage requirements and execution time metrics for our first differential backup. The execution time was obtained by scripting out the equivalent BACKUP command and running the T-SQL, as described in Chapter 3. The alternative method, querying the backupset table in msdb (see Listing 3-5), does not provide sufficient granularity for a backup that ran in under a second. 220 221 Chapter 7: Differential Backup and Restore Differential Backup Name Number of Rows Execution Time Storage Required DatabaseForDiffBackups_Diff_ Native_1.bak Seconds 3.16 MB Figure 7-4: Differential backup statistics, Part 1. Native T-SQL differential backup We are now going to take our second native differential backup using T-SQL code. First, however, let's INSERT a substantial new data load of 100,000 rows into MessageTable, as shown in Listing 7-4. USE [DatabaseForDiffBackups] INSERT INTO MessageTable VALUES ( 'Third Data Load: This is the third set of data we are populating the table with' ) Listing 7-4: Third data load (100,000 rows) for MessageTable. We're now ready to perform our second differential backup, and Listing 7-5 shows the code to do it. If you compare this script to the one for our base full backup (Listing 7-2), you'll see they are almost identical in structure, with the exception of the WITH DIFFER- ENTIAL argument that we use in Listing 7-5 to let SQL Server know that we are not going to be taking a full backup, but instead a differential backup of the changes made since the last full backup was taken. Double-check that the path to the backup file is correct, and then execute the script. 221 222 Chapter 7: Differential Backup and Restore USE [master] BACKUP DATABASE [DatabaseForDiffBackups] TO DISK = N'C:\SQLBackups\Chapter7\DatabaseForDiffBackups_Diff_Native_2.bak' WITH DIFFERENTIAL, NAME = N'DatabaseForDiffBackups-Differential Database Backup', STATS = 10 Listing 7-5: Native T-SQL differential backup for DatabaseForDiffBackups. Having run the command, you should see results similar to those shown in Figure 7-5. Figure 7-5: Native differential T-SQL backup script message output. Figure 7-6 summarizes the storage requirements and execution time metrics for our second differential backup, compared to the first differential backup. 222 223 Chapter 7: Differential Backup and Restore Differential Backup Name Number of Rows Execution Time (S) Storage Required (MB) DatabaseForDiffBackups_Diff_ Native_1.bak DatabaseForDiffBackups_Diff_ Native_2.bak Figure 7-6: Differential backup statistics, Part 2. So, compared to the first differential backup, the second one contains 11 times more rows, took about five times longer to execute, and takes up over six times more space. This all seems to make sense; don't forget that backup times and sizes don't grow linearly based on the number of records, since every backup includes in it, besides data, headers, backup information, database information, and other structures. Compressed differential backups By way of comparison, I reran the second differential backup timings, but this time using backup compression. Just as for full backups, the only change we need to make to our backup script is to add the COMPRESSION keyword, which will ensure the backup is compressed regardless of the server's default setting. Remember, this example will only work if you are using SQL Server 2008 R2 or above, or the Enterprise edition of SQL Server Note that, if you want to follow along, you'll need to restore full and first differential backups over the top of the existing DatabaseForDiffBackups database, and then rerun the third data load (alternatively, you could start again from scratch). 223 224 Chapter 7: Differential Backup and Restore USE [master] BACKUP DATABASE [DatabaseForDiffBackups] TO DISK = N'C:\SQLBackups\Chapter7\DatabaseForDiffBackups_Diff_Native_Compressed.bak' WITH NAME = N'DatabaseForDiffBackups-Diff Database Backup', STATS = 10, COMPRESSION Listing 7-6: Compressed differential backup. In my test, the compressed backup offered very little advantage in terms of execution time, but substantial savings in disk space, as shown in Figure 7-7. Differential Backup Name Number of Rows Execution Time (S) Storage Required (MB) DatabaseForDiffBackups_Diff_Native_1. bak DatabaseForDiffBackups_Diff_Native_2. bak DatabaseForDiffBackups_Diff_Native_ Compressed.bak Figure 7-7: Differential backup statistics, Part 225 Chapter 7: Differential Backup and Restore Performing Differential Backup Restores We are now ready to perform a RESTORE on each of our differential backup files, once using the SSMS GUI, and once using a T-SQL script. Native GUI differential restore We are going to restore our first differential backup file (_Diff_Native_1.bak) for the DatabaseForDiffBackups database, over the top of the existing database. If you have already removed this database, don't worry; as long as you've still got the backup files, it will not affect the example in this section. In SSMS, right-click on the DatabaseForDiffBackups database, and navigate Tasks Restore Database to reach the General page of the Restore Database configuration screen, shown in Figure 7-8. Figure 7-8: Starting the restore process for DatabaseForDiffBackups. 225 226 Chapter 7: Differential Backup and Restore Notice that the base full backup, and the second differential backups have been autoselected as the backups to restore. Remember that, to return the database to the most recent state possible, we only have to restore the base, plus the most recent differential; we do not have to restore both differentials. However, in this example we do want to restore the first rather than the second differential backup, so deselect the second differential in the list in favor of the first. Now, click over to the Options screen; in the Restore options section, select Overwrite the existing database. That done, you're ready to go; click OK, and the base full backup will be restored, followed by the first differential backup. Let's query our newly restored database in order to confirm that it worked as expected; if so, we should see a count of 100,000 rows with a message of Initial Data Load, and 10,000 rows with a message of Second Data Load, as confirmed by the output of Listing 7-7 (the message text is cropped for formatting purposes). USE [DatabaseForDiffBackups] SELECT Message, COUNT(Message) AS Row_Count FROM MessageTable GROUP BY Message Message Row_Count Initial Data Load: This is the first set of data Second Data Load: This is the second set of data (2 row(s) affected) Listing 7-7: Query to confirm that the differential restore worked as expected. 226 227 Chapter 7: Differential Backup and Restore Native T-SQL differential restore We're now going to perform a second differential restore, this time using T-SQL scripts. While we could perform this operation in a single script, we're going to split it out into two scripts so that we can see, more clearly than we could during the GUI restore, the exact steps of the process. Once again, our restore will overwrite the existing DatabaseForDiffBackups database. The first step will restore the base backup, containing 100,000 rows, and leave the database in a "restoring" state. The second step will restore the second differential backup file (_Diff_Native_2.bak), containing all the rows changed or added since the base backup (10,000 rows from the second data load and another 100,000 from the third), and then recover the database, returning it to a usable state. Without further ado, let's restore the base backup file, using the script in Listing 7-8. USE [master] RESTORE DATABASE [DatabaseForDiffBackups] FROM DISK = N'C:\SQLBackups\Chapter7\DatabaseForDiffBackups_Full_Native.bak' WITH NORECOVERY, STATS = 10 Listing 7-8: Base full database backup restore. Notice the WITH NORECOVERY argument, meaning that we wish to leave the database in a restoring state, ready to receive further backup files. Also note that we did not specify REPLACE since it is not needed here, since DatabaseForDiffBackups is a SIMPLE recovery model database. Having executed the script, refresh your object explorer window and you should see that the DatabaseForDiffBackups database now displays a Restoring message, as shown in Figure 228 Chapter 7: Differential Backup and Restore Figure 7-9: The DatabaseForDiffBackups database in restoring mode. We're now ready to run the second RESTORE command, shown in Listing 7-9, to get back all the data in the second differential backup (i.e. all data that has changed since the base full backup was taken) and bring our database back online. USE [master] RESTORE DATABASE [DatabaseForDiffBackups] FROM DISK = N'C:\SQLBackups\Chapter7\DatabaseForDiffBackups_Diff_Native_2.bak' WITH STATS = 10 Listing 7-9: Native T-SQL differential restore. We don't explicitly state the WITH RECOVERY option here, since RECOVERY is the default action. By leaving it out of our differential restore we let SQL Server know to recover the database for regular use. 228 229 Chapter 7: Differential Backup and Restore Once this command has successfully completed, our database will be returned to the state it was in at the time we started the second differential backup. As noted earlier, this is actually no reason, other than a desire here to show each step, to run Listings 7-8 and 7-9 separately. We can simply combine them and complete the restores process in a single script. Give it a try, and you should see a Messages output screen similar to that shown in Figure Figure 7-10: Native differential restore results. Remember that the differential backup file contained slightly more data than the base full backup, so it makes sense that a few more pages are processed in the second RESTORE. The faster backup time for the differential backup compared to the base full backup, even though the former had more data to process, can be explained by the higher overhead attached to a full restore; it must prepare the data and log files and create the space for the restore to take place, whereas the subsequent differential restore only needs to make sure there is room to restore, and start restoring data. 229 230 Chapter 7: Differential Backup and Restore Everything looks good, but let's put on our "paranoid DBA" hat and double-check. Rerunning Listing 7-7 should result in the output shown in Figure Figure 7-11: Data verification results from native T-SQL differential restore. Restoring compressed differential backups Listing 7-10 shows the script to perform the same overall restore process as the previous section, but using the compressed differential backup file. USE [master] RESTORE DATABASE [DatabaseForDiffBackups] FROM DISK='C:\SQLBackups\Chapter7\DatabaseForDiffBackups_Full_Native.bak' WITH NORECOVERY RESTORE DATABASE [DatabaseForDiffBackups] FROM DISK='C:\SQLBackups\Chapter7\DatabaseForDiffBackups_Diff_Native_Compressed.bak' WITH RECOVERY Listing 7-10: Restoring a compressed native differential backup. 230 231 Chapter 7: Differential Backup and Restore As you can see, it's no different than a normal differential restore. You don't have to include any special options to let SQL Server know the backup is compressed. That information is stored in the backup file headers, and SQL Server will know how to handle the compressed data without any special instructions from you in the script! You will undoubtedly see that the restore took just a bit longer that the uncompressed backup would take to restore. This is simply because more work is going on to decompress the data and it, and that extra step, cost CPU time, just as an encrypted backup file would also take slightly longer to restore. Forcing Failures for Fun Having scored several notable victories with our differential backup and restore processes, it's time to taste the bitter pill of defeat. Think of it as character building; it will toughen you up for when similar errors occur in the real world! We'll start with a possible error that could occur during the backup part of the process, and then look at a couple of possible errors that could plague your restore process. Missing the base Go ahead and run the script in Listing It creates a brand new database, then attempts to take a differential backup of that database. USE [master] CREATE DATABASE [ForcingFailures] ON PRIMARY ( NAME = N'ForcingFailures', FILENAME = N'C:\SQLDATA\ForcingFailures.mdf', SIZE = 5120KB, FILEGROWTH = 1024KB ) LOG ON ( NAME = N'ForcingFailures_log', FILENAME = N'C:\SQLDATA\ForcingFailures_log.ldf', SIZE = 1024KB, FILEGROWTH = 10%) 231 232 Chapter 7: Differential Backup and Restore BACKUP DATABASE [ForcingFailures] TO DISK = N'C:\SQLBackups\Chapter7\ForcingFailures_Diff.bak' WITH DIFFERENTIAL, STATS = 10 Listing 7-11: A doomed differential backup. If you hadn't already guessed why this won't work, the error message below will leave you in no doubt. Msg 3035, Level 16, State 1, Line 2 Cannot perform a differential backup for database "ForcingFailures", because a current database backup does not exist. Perform a full database backup by reissuing BACKUP DATABASE, omitting the WITH DIFFERENTIAL option. Msg 3013, Level 16, State 1, Line 2 BACKUP DATABASE is terminating abnormally. We can't take a differential backup of this database without first taking a full database backup as the base from which to track subsequent changes! Running to the wrong base Let's perform that missing full base backup of our ForcingFailures database, as shown in Listing USE [master] BACKUP DATABASE [ForcingFailures] TO DISK = N'C:\SQLBackups\Chapter7\ForcingFailures_Full.bak' WITH STATS = 10 Listing 7-12: Base full backup for ForcingFailures database. 232 233 Chapter 7: Differential Backup and Restore We are now fully prepared for some subsequent differential backups. However, unbeknown to us, someone sneaks in and performs a second full backup of the database, in order to restore it to a development server. USE [master] BACKUP DATABASE [ForcingFailures] TO DISK = N'C:\SQLBackups\ForcingFailures_DEV_Full.bak' WITH STATS = 10 Listing 7-13: A rogue full backup of the ForcingFailures database. Back on our production system, we perform a differential backup. USE [master] BACKUP DATABASE [ForcingFailures] TO DISK = N'C:\SQLBackups\Chapter7\ForcingFailures_Diff.bak' WITH DIFFERENTIAL, STATS = 10 Listing 7-14: A differential backup of the ForcingFailures database. Some time later, we need to perform a restore process, over the top of the existing (FULL recovery model) database, so prepare and run the appropriate script, only to get a nasty surprise. USE [master] RESTORE DATABASE [ForcingFailures] FROM DISK = N'C:\SQLBackups\Chapter7\ForcingFailures_Full.bak' WITH NORECOVERY, REPLACE, STATS = 234 Chapter 7: Differential Backup and Restore RESTORE DATABASE [ForcingFailures] FROM DISK = N'C:\SQLBackups\Chapter7\ForcingFailures_Diff.bak' WITH STATS = 10 Processed 176 pages for database 'ForcingFailures', file 'ForcingFailures' on file 1. Processed 1 pages for database 'ForcingFailures', file 'ForcingFailures_log' on file 1. RESTORE DATABASE successfully processed 177 pages in seconds ( MB/sec). Msg 3136, Level 16, State 1, Line 2 This differential backup cannot be restored because the database has not been restored to the correct earlier state. Msg 3013, Level 16, State 1, Line 2 RESTORE DATABASE is terminating abnormally. Listing 7-15: A failed differential restore of the ForcingFailures database. Due to the "rogue" second full backup, our differential backup does not match our base full backup. As a result, the differential restore operation fails and the database is left in a restoring state. This whole mess could have been averted if that non-scheduled full backup had been taken as a copy-only backup, since this would have prevented SQL Server assigning it as the new base backup for any subsequent differentials. However, what can we do at this point? Well, the first step is to examine the backup history in the msdb database to see if we can track down the rogue backup, as shown in Listing USE [MSDB] SELECT bs.type, bmf.physical_device_name, bs.backup_start_date, bs.user_name FROM dbo.backupset bs INNER JOIN dbo.backupmediafamily bmf ON bs.media_set_id = bmf.media_set_id WHERE bs.database_name = 'ForcingFailures' ORDER BY bs.backup_start_date ASC Listing 7-16: Finding our rogue backup. 234 235 Chapter 7: Differential Backup and Restore This query will tell us the type of backup taken (D = full database, I = differential database, somewhat confusingly), the name and location of the backup file, when the backup was started, and who took it. We can check to see if that file still exsists in the designated directory and use it to restore our differential backup (we can also roundly castigate whoever was responsible, and give them a comprehensive tutorial on use of copy-only backups). If the non-scheduled full backup file is no longer in that location and you are unable to track it down, then there is not a lot you can do at this point, unless you are also taking transaction log backups for the database. If not, you'll simply have to recover the database as it exists, as shown in Listing 7-17, and deal with the data loss. USE [master] RESTORE DATABASE [ForcingFailures] WITH RECOVERY Listing 7-17: Bringing our database back online. Recovered, already For our final example, we'll give our beleaguered ForcingFailures database a rest and attempt a differential restore on DatabaseForDiffBackups, as shown in Listing See if you can figure out what is going to happen before executing the command. USE [master] RESTORE DATABASE [DatabaseForDiffBackups] FROM DISK = N'C:\SQLBackups\Chapter7\DatabaseForDiffBackups_Full_Native.bak' WITH REPLACE, STATS = 10 RESTORE DATABASE [DatabaseForDiffBackups] FROM DISK = N'C:\SQLBackups\Chapter7\DatabaseForDiffBackups_Diff_Native_2.bak' WITH STATS = 10 Listing 7-18: Spot the mistake in the differential restore script. 235 236 Chapter 7: Differential Backup and Restore This script should look very familiar to you but there is one small omission from this version which will prove to be very important. Whether or not you spotted the error, go ahead and execute it, and you should see output similar to that shown in Figure Figure 7-12: No files ready to roll forward. The first RESTORE completes successfully, but the second one fails with the error message "The log or differential backup cannot be restored because no files are ready to rollforward." The problem is that we forgot to include the NORECOVERY argument in the first RESTORE statement. Therefore, the full backup was restored and database recovery process proceeded as normal, to return the database to an online and usable state. At this point, the database is not in a state where it can accept further backups. If you see this type of error when performing a restore that takes more than one backup file, differential, or log, you now know that there is a possibility that a previous RESTORE statement on the database didn't include the NORECOVERY argument that would allow for more backup files to be processed. 236 237 Chapter 7: Differential Backup and Restore Summary We have discussed when and why you should be performing differential backups. Differential backups, used properly, can help a DBA make database restores a much simpler and faster process than they would be with other backup types. In my opinion, differential backups should form an integral part of the daily backup arsenal. If you would like more practice with these types of backups, please feel free to modify the database creation, data population and backup scripts provided throughout this chapter. Perhaps you can try a differential restore of a database and move the physical data and log files to different locations. Finally, we explored some of the errors that can afflict differential backup and restore; if you know, up front, the sort of errors you might see, you'll be better armed to deal with them when they pop up in the real world. We couldn't cover every possible situation, of course, but knowing how to read and react to error messages will save you time and headaches in the future. 237 238 Chapter 8: Database Backup and Restore with SQL Backup Pro This chapter will demonstrate how to perform each of the types of database backup we've discussed in previous chapters (namely full and differential database backups and log backups), using Red Gate's SQL Backup Pro tool. At this stage, knowledge of the basic characteristics of each type of backup is assumed, based on prior chapters, in order to focus on the details of capturing the backups using either the SQL Backup GUI or SQL Backup scripts. One of the advantages of using such a tool is the relative ease with which backups can be automated a vital task for any DBA. We'll discuss a basic SQL Backup script that will allow you to take full, log, or differential backups of all selected databases on a SQL Server instance, store those backups in a central location, and receive notifications of any failure in the backup operation. Preparing for Backups As usual, we need to create our sample database, tables, and data. Listing 8-1 shows the script to create a DatabaseForSQLBackups database. USE master go CREATE DATABASE [DatabaseForSQLBackups] ON PRIMARY ( NAME = N'DatabaseForSQLBackups', FILENAME = N'C:\SQLData\DatabaseForSQLBackups.mdf', SIZE = KB, FILEGROWTH = KB ) LOG ON ( NAME = N'DatabaseForSQLBackups_log' 238 239 Chapter 8: Database Backup and Restore with SQL Backup Pro, FILENAME = N'C:\SQLData\DatabaseForSQLBackups_log.ldf', SIZE = KB, FILEGROWTH = 10240KB ) ALTER DATABASE [DatabaseForSQLBackups] SET RECOVERY SIMPLE Listing 8-1: Creating DatabaseForSQLBackups. Notice that we set the database, initially at least, to SIMPLE recovery model. Later we'll want to perform both differential database backups and log backups, so our main, operational model for the database will be FULL. However, as we'll soon be performing two successive data loads of one million rows each, and we don't want to run into the problem of bloating the log file (as described in the Troubleshooting Log Issues section of Chapter 5), we're going to start off in SIMPLE model, where the log will be auto-truncated, and only switch to FULL once these initial "bulk loads" have been completed. Listing 8-2 shows the script to create our two, familiar, sample tables, and then load MessageTable1 with 1 million rows. USE [DatabaseForSQLBackups]] USE [DatabaseForSQLBackups] 239 240 Chapter 8: Database Backup and Restore with SQL Backup Pro MessageTable1 VALUES GETDATE() ) Listing 8-2: Creating sample tables and initial million row data load for MessageTable1. Take a look in the C:\SQLData folder, and you should see that our data and log files are still at their initial sizes; the data file is approximately 500 MB in size (and is pretty much full), and the log file is still 100 MB in size. Therefore we have a total database size of about 600 MB. It's worth noting that, even if we'd set the database in FULL recovery model, the observed behavior would have been the same, up to this point. Don't forget that a database is only fully engaged in FULL recovery model after the first full backup, so the log may still have been truncated during the initial data load. If we'd performed a full backup before the data load, the log would not have been truncated and would now be double that of our data file, just over 1 GB. Of course, this means that the log file would have undergone many auto-growth events, since we only set it to an initial size of 100 MB and to grow in 10 MB steps. 240 241 Chapter 8: Database Backup and Restore with SQL Backup Pro Full Backups In this section, we'll walk through the process of taking a full backup of the example DatabaseForSQLBackups database, using both the SQL Backup GUI, and SQL Backup T-SQL scripts. In order to follow through with the examples, you'll need to have installed the Red Gate SQL Backup Pro GUI on your client machine, registered your test SQL Server instances, and installed the server-side components of SQL Backup. If you've not yet completed any part of this, please refer to Appendix A, for installation and configuration instructions. SQL Backup Pro full backup GUI method Open the SQL Backup management GUI, expand the server listing for your test server, in the left pane, right-click the DatabaseForSQLBackups database and select Back Up from the menu to enter Step 1 (of 5) in the Back Up wizard. The left pane lets you select the server to back up (which will be the test server housing our database) and the right pane allows you to select a backup template that you may have saved on previous runs through the backup process (at Step 5). Since this is our first backup, we don't yet have any templates, so we'll discuss this feature later. Step 2 is where we specify the database(s) to back up (DatabaseForSQLBackups will be preselected) and the type of backup to be performed (by default, Full). In this case, since we do want to perform a full backup, and only of the DatabaseForSQLBackups database, we can leave this screen exactly as it is (see Figure 8-1). 241 242 Chapter 8: Database Backup and Restore with SQL Backup Pro Figure 8-1: SQL Backup Configuration, Step 2. A few additional features to note on this screen are as follows: we can take backups of more than one database at a time; a useful feature when you need one-time backups of multiple databases on a system if we wish to backup most, but not all, databases on a server, we can select the databases we don't wish to backup, and select Exclude these from the top drop-down the Filter list check box allows you to screen out any databases that are not available for the current type of backup; for example, this would ensure that you don't attempt to take a log backup of a database that is running under the SIMPLE recovery model. Step 3 is where we will configure settings to be used during the backup. For this first run through, we're going to focus on just the central Backup location portion of this screen, for the moment, and the only two changes we are going to make are to the backup file 242 243 Chapter 8: Database Backup and Restore with SQL Backup Pro location and name. Adhering closely to the convention used throughout, we'll place the backup file in the C:\SQLBackups\Chapter8\ folder and call it DatabaseForSQLBackups_ Full_1.sqb. Notice the.sqb extension that denotes this as a SQL Backup-generated backup file. Once done, the screen will look as shown in Figure 8-2. Figure 8-2: SQL Backup Step 3 configuration. 243 244 Chapter 8: Database Backup and Restore with SQL Backup Pro There are two options offered below the path and name settings in the Backup location section that allow us to "clean up" our backup files, depending on preferences. Overwrite existing backup files Overwrite any backup files in that location that share the same name. Delete existing backup files Remove any files that are more than x days old, or remove all but the latest x files. We also have the option of cleaning these files up before we start a new backup. This is helpful if the database backup files are quite large and wouldn't fit on disk if room was not cleared beforehand. However, be sure that any backups targeted for removal have first been safely copied to another location. The top drop-down box of this screen offers the options to split or mirror a backup file (which we will cover at the end of this chapter). The Network copy location section allows us to copy the finished backup to a second network location, after it has completed. This is a good practice, and you also get the same options of cleaning up the files on your network storage. What you choose here doesn't have to match what you chose for your initial backup location; for example, you can store just one day of backups on a local machine, but three days on your network location. Backup compression and encryption Step 4 is where we configure some of the most useful features of SQL Backup, including backup compression. We'll compare how SQL Backup compression performs against the native uncompressed and native compressed backups that we investigated in previous chapters. For the time being, let's focus on the Backup processing portion of this screen, where we configure backup compression and backup encryption. 244 245 Chapter 8: Database Backup and Restore with SQL Backup Pro Figure 8-3: SQL Backup Step 4 configuration. Backup compression is enabled by default, and there are four levels of compression, offering progressively higher compression and slower backup speeds. Although the compressed data requires lower levels of disk I/O to write to the backup file, the overriding factor is the increased CPU time required in compressing the data in the first place. As you can probably guess, picking the compression level is a balancing act; the better the compression, the more disk space will be saved, but the longer the backups run, the more likely are issues with the backup operation. Ultimately, the choice of compression level should be guided by the size of the database and the nature of the data (i.e. its compressibility). For instance, binary data does not compress well, so don't spend CPU time attempting to compress a database full of binary images. In other cases, lower levels of compression may yield higher compression ratios. We can't tell until we test the database, which is where the Compression Analyzer comes in. Go ahead and click on the Compression Analyzer button and start a test against the DatabaseForSQLBackups database. Your figures will probably vary a bit, but you should see results similar to those displayed in Figure 246 Chapter 8: Database Backup and Restore with SQL Backup Pro Figure 8-4: SQL Backup Compression Analyzer. For our database, Levels 1 and 4 offer the best compression ratio, and since a backup size of about 4.5 MB (for database of 550 MB) is pretty good, we'll pick Level 1 compression, which should also provide the fastest backup times. Should I use the compression analyzer for every database? Using the analyzer for each database in your infrastructure is probably not your best bet. We saw very fast results when testing this database, because is it very small compared to most production databases. The larger the database you are testing, the longer this test will take to run. This tool is recommended for databases that you are having compression issues with, perhaps on a database where you are not getting the compression ratio that you believe you should be. 246 247 Chapter 8: Database Backup and Restore with SQL Backup Pro The next question we need to consider carefully is this: do we want to encrypt all of that data that we are writing to disk? Some companies operate under strict rules and regulations, such as HIPAA and SOX, which require database backups to be encrypted. Some organizations just like the added security of encrypted backups, in helping prevent a malicious user getting access to those files. If encryption is required, simply tick the Encrypt backup box, select the level of encryption and provide a secure password. SQL Backup will take care of the rest, but at a cost. Encryption will also add CPU and I/O overhead to your backups and restores. Each of these operations now must go through the "compress encrypt store on disk" process to back up, as well as the "retrieve from disk decrypt decompress" routines, adding an extra step to the both backup and restore processes. Store your encryption password in a safe and secure location! Not having the password to those backup files will stop you from ever being able to restore those files again, which is just as bad as not having backups at all! Our database doesn't contain any sensitive data and we are not going to use encryption on this example. Backup optimization and verification We're going to briefly review what options are available in the Optimization and On completion sections, and some of the considerations in deciding the correct values, but for our demo we'll leave all of them either disabled or at their default settings. 247 248 Chapter 8: Database Backup and Restore with SQL Backup Pro Figure 8-5a: Optimization and On completion options. Depending on the system, some good performance benefits can be had by allowing more threads to be used in the backup process. When using a high-end CPU, or many multi-core CPUs, we can split hefty backup operations across multiple threads, each of which can run in parallel on a separate core. This can dramatically reduce the backup processing time. The Maximum transfer size and Maximum data block options can be important parameters in relation to backup performance. The transfer size option dictates the maximum size of each block of memory that SQL Backup will write to the backup file, on disk. The default value is going to be 1,024 KB (i.e. 1 MB), but if SQL Server is experiencing memory pressure, it may be wise to lower this value so that SQL Backup can write to smaller memory blocks, and therefore isn't fighting so hard, with other applications, for memory. If this proves necessary, we can add a DWORD registry key to define a new default value on that specific machine. All values in these keys need to be in multiples of 65,536 (64 KB), up to a maximum of 1,048,576 (1,024 KB, the default). 248 249 Chapter 8: Database Backup and Restore with SQL Backup Pro HKEY_LOCAL_MACHINE\SOFTWARE\Red Gate\SQL Backup\ BackupSettingsGlobal\<instance name>\maxtransfersize (32-bit) HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Red Gate\SQL Backup\ BackupSettingsGlobal\<instance name>\maxtransfersize (64-bit) The maximum data block option (by default 2 MB) determines the size of the actual data blocks on disk, when storing backup data. For optimal performance, we want this value to match or fit evenly in the block size of the media to which the files are being written; if the data block sizes overlap the media block boundaries, it may result in performance degradation. Generally speaking, SQL Server will automatically select the correct block size based on the media. However, if necessary, we can create a registry entry to overwrite the default value: HKEY_LOCAL_MACHINE\SOFTWARE\Red Gate\SQL Backup\ BackupSettingsGlobal\<instance name>\maxdatablock (32-bit) HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Red Gate\SQL Backup\ BackupSettingsGlobal\<instance name>\maxdatablock (64-bit) The network resilience options determine how long to wait before retrying a failed backup operation, and how many times to retry; when the retry count has been exhausted, a failure message will be issued. We want to be able to retry a failed backup a few times, but we don't want to retry so many times that a problem in the network or disk subsystem is masked for too long; in other words, rather than extend the backup operation as it retries again and again, it's better to retry only a few times and then fail, therefore highlighting the network issue. This is especially true when performing full backup operations on large databases, where we'll probably want to knock that retry count down from a default of 10 to 2 3 times. Transaction log backups, on the other hand, are typically a short process, so retrying 10 times is not an unreasonable number in this case. 249 250 Chapter 8: Database Backup and Restore with SQL Backup Pro The On completion section gives us the option to verify our backup files after completion and send an once the operations are complete. The verification process is similar to the CHECKSUM operation in native SQL Server backups (see Chapter 2). SQL Backup will make sure that all data blocks have been written correctly and that you have a valid backup file. Note that, at the time of this book going to print, Red Gate released SQL Backup Pro Version 7, which expands the backup verification capabilities to allow standard backup verification (BACKUP WITH CHECKSUM) and restore verification (RESTORE VERIFYONLY), as shown in Figure 8-5b. We'll revisit the topic of backup verification with SQL Backup later in the chapter. Fig 8-5b: New Backup verification options in SQL Backup 7 The notification can be set to alert on any error, warning, or just when the backup has completed in any state including success. 250 251 Chapter 8: Database Backup and Restore with SQL Backup Pro Running the backup Step 5 of the wizard is simply a summary of the options we selected for our SQL Backup operation. Check this page carefully, making sure each of the selected options looks as it should. At the bottom is a check box that, when enabled, will allow us to save this backup operation configuration as a template, in which case we could then load it on Step 1 of the wizard and then skip straight to Step 5. We are not going to save this example as a template. The Script tab of this step allows us to view the T-SQL code that has been generated to perform this backup. Click on the Finish button and the backup will be executed on your server, and a dialog box will report the progress of the operation. Once it completes, the new window will (hopefully) display two green check marks, along with some status details in the lower portion of the window, as seen in Figure 8-6. Database size : MB Compressed data size: MB Compression rate : 99.40%-6: Status details from a successful SQL Backup GUI backup operation. Backup metrics: SQL Backup Pro vs. native vs. native compressed Figure 8-6 reports an initial database size of 600 MB, a backup file size of 3.6 MB and backup time of about 3 seconds. Remember, these metrics are ballpark figures and won't match exactly the ones you get on your system. Don't necessarily trust SQL Backup on the backup size; double-check it in the backup location folder (in my case it was 3.7 MB; pretty close!). 251 252 Chapter 8: Database Backup and Restore with SQL Backup Pro Figure 8-7 compares these metrics to those obtained for identical operations using native backup, compressed native backup, as well as SQL Backup using a higher compression level (3). Backup Operation Backup File Size in MB (on disk) Backup Time (seconds) % Difference compared to Native Full (+ = bigger / faster) Size Speed Native Full Native Full with Compression SQL Backup Full Compression Level SQL Backup Full Compression Level Figure 8-7: Comparing full backup operations for DatabaseForSQLBackups (0.5 GB). SQL Backup (Compression Level 1) produces a backup file that requires less than 1% of the space required for the native full backup file. To put this into perspective, in the space that we could store 3 days' worth of full native backups using native SQL Server, we could store nearly 400 SQL Backup files. It also increases the backup speed by about 84%. How does that work? Basically, every backup operation reads the data from the disk and writes to a backup-formatted file, on disk. By far the slowest part of the operation is writing the data to disk. When SQL Backup (or native compression) performs its task, it is reading all of the data, passing it through a compression tool and writing much smaller segments of data, so less time is used on the slowest operation. In this test, SQL Backup with Compression Level 1 outperformed the native compressed backup. However, for SQL Backup with Compression Level 3, their performance was almost identical. It's interesting to note that while Level 3 compression should, in theory, have resulted in a smaller file and a longer backup time, compared to Level 1, we in fact saw a larger file and a longer backup time! This highlights the importance of selecting the compression level carefully. 252 253 Chapter 8: Database Backup and Restore with SQL Backup Pro SQL Backup Pro full backup using T-SQL We're now going to perform a second full backup our DatabaseForSQLBackups database, but this time using a SQL Backup T-SQL script, which will look similar to the one we saw on the Script tab of Step 5 of the GUI wizard. Before we do so, let's populate MessageTable2 with a million rows of data of the same size and structure as the data in MessageTable1, so that our database file should be hovering somewhere around 1 GB in size. USE [DatabaseForSQL 8-3: Populating the MessageTable2 table. Take a look in the SQLData folder, and you'll now see that the data file is now about 1GB in size and the log file is still around 100 MB. Now that we have some more data to work with, Listing 8-4 shows the SQL Backup T-SQL script to perform a second full backup of our DatabaseForSQLBackups database. EXECUTE master..sqlbackup '-SQL "BACKUP DATABASE [DatabaseForSQLBackups] TO DISK = ''C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Full_2.sqb'' WITH DISKRETRYINTERVAL = 30, DISKRETRYCOUNT = 10, THREADCOUNT = 2, COMPRESSION = 1"' Listing 8-4: Second full backup of DatabaseForSQLBackups using SQL Backup T-SQL. 253 254 Chapter 8: Database Backup and Restore with SQL Backup Pro The first thing to notice is that the backup is executed via an extended stored procedure called sqlbackup, which resides in the master database and utilizes some compiled DLLs that have been installed on the server. We pass to this stored procedure a set of parameters as a single string, which provides the configuration settings that we wish to use for the backup operation. Some of the names of these settings are slightly different from what we saw for native backups but, nevertheless, the script should look fairly familiar. We see the usual BACKUP DATABASE command to signify that we are about to backup the DatabaseForSQLBackups database. We also see the TO DISK portion and the path to where the backup file will be stored. The latter portion of the script sets values for some of the optimization settings that we saw on Step 4 of the GUI wizard. These are not necessary for taking the backup, but it's useful to know what they do. DISKRETRYINTERVAL One of the network resiliency options; amount of time in seconds SQL Backup will wait before retrying the backup operation, in the case of a failure. DISKRETRYCOUNT Another network resiliency option; number of times a backup will be attempted in the event of a failure. Bear in mind that the more times we retry, and the longer the retry interval, the more extended will be the backup operation. THREADCOUNT Using multiple processors and multiple threads can offer a huge performance boost when taking backups. The only setting that could make much of a difference is the threadcount parameter, since on powerful multi-processor machines it can spread the load of backup compression over multiple processors. Go ahead and run the script now and the output should look similar to that shown in Figure 255 Chapter 8: Database Backup and Restore with SQL Backup Pro Backing up DatabaseForSQLBackups (full database) to: C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Full_2.sqb Database size : GB Compressed data size: MB Compression rate : 99.39%-8: SQL Backup T-SQL script results. We are now presented with two result sets. The first result set, shown in Figure 8-8, provides our detailed backup metrics, including database size, and the size and compression rate of the resulting backup file. The second result set (not shown) gives us the exit code from SQL Backup, an error code from SQL Server and a list of files used in the command. We can see from the first result set that the new backup file size is just under 7 MB, and if we take a look in our directory we can confirm this. Compared to our first Red Gate backup, we can see that this is a bit less than double the original file size, but we will take a closer look at the numbers in just a second. After these metrics, we see the number of pages processed. Referring back to Chapter 3 confirms that this is the same number of pages as for the equivalent native backup, which is as expected. We also see that the backup took just 6 seconds to complete which, again, is roughly double the figure for the first full backup. Figure 8-9 compares these metrics to those obtained for native backups, and compressed native backups. 255 256 Chapter 8: Database Backup and Restore with SQL Backup Pro Backup Operation Backup File Size in MB (on disk) Backup Time (seconds) % Difference compared to Native Full (+ = bigger / faster) Size Speed Native Full Native Full with Compression SQL Backup Full Compression Level SQL Backup Full Compression Level Figure 8-9: Comparing full backup operations for DatabaseForSQLBackups (1 GB). All the results are broadly consistent with those we achieved for the first full backup. It confirms that for this data, SQL Backup Compression Level 1 is the best-performing backup, both in terms of backup time and backup file size. Log Backups In this section, we'll walk through the process of taking log backups of the example DatabaseForSQLBackups database, again using either the SQL Backup GUI, or a SQL Backup T-SQL script. Preparing for log backups At this point, the database is operating in SIMPLE recovery model, and we cannot take log backups. In order to start taking log backups, and prevent the log file from being autotruncated from this point on, we need to switch the recovery model of the database to FULL, and then take another full backup, as shown in Listing 257 Chapter 8: Database Backup and Restore with SQL Backup Pro USE master ALTER DATABASE [DatabaseForSQLBackups] SET RECOVERY FULL EXECUTE master..sqlbackup '-SQL "BACKUP DATABASE [DatabaseForSQLBackups] TO DISK = ''C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Full_BASE.sqb'' WITH DISKRETRYINTERVAL = 30, DISKRETRYCOUNT = 10, THREADCOUNT = 2, COMPRESSION = 1"' Listing 8-5: Switching DatabaseForSQLBackups to FULL recovery and taking a full backup. The database is now operating in FULL recovery and this backup file, DatabaseFor SQLBackups_Full_BASE.sqb, will be the one to restore, prior to restoring any subsequent log backups. Finally, let's perform a third, much smaller, data load, adding ten new rows to each message table, as shown in Listing 8-6. USE [DatabaseForSQLBackups] INSERT INTO dbo.messagetable1 VALUES ( '1st set of short messages for MessageTable1', GETDATE() ) this is just to help with our point-in-time restore (Chapter 8) PRINT GETDATE() 257 258 Chapter 8: Database Backup and Restore with SQL Backup Pro --Dec :33PM INSERT INTO dbo.messagetable2 VALUES ( '1st set of short messages for MessageTable2', GETDATE() ) Listing 8-6: Loading new messages into our message tables. SQL Backup Pro log backups In this section, rather than perform two separate backups, one via the GUI and one via a SQL Backup script, we're just going to do one transaction log backup and let you decide whether you want to perform it via the GUI or the script. If you prefer the GUI approach, open up SQL Backup and start another a backup operation for the DatabaseForSQLBackups database. On Step 2 of the Wizard, select Transaction Log as the Backup type. You'll see that the option Remove inactive entries from transaction log is auto-checked. This means that the transaction log can be truncated upon backup, making the space in the log available for future entries. This is the behavior we want here, so leave it checked. However, if we were to uncheck it, we could take a log backup that leaves the transactions in the file (similar to a NO_TRUNCATE native backup or a copy-only log backup in that it won't affect future backups). The Databases to back up section may list several databases that are grayed out; these will be the ones that are ineligible for transaction log backups, usually because they are operating in SIMPLE recovery model, rather than FULL or BULK LOGGED. Checking the Filter list button at the bottom will limit the list to only the eligible databases. Make sure that only the DatabaseForSQLBackups database is selected, then click Next. 258 259 Chapter 8: Database Backup and Restore with SQL Backup Pro Figure 8-10: Selecting the type of backup and the target database. On Step 3, we set the name and location for our log backup file. Again, adhering to the convention used throughout the book, we'll place the backup file in the C:\SQLBackups\ Chapter8\ folder and call it DatabaseForSQLBackups_Log_1.sqb. Step 4 of the wizard is where we will configure the compression, optimization and resiliency options of our transaction log backup. The Compression Analyzer only tests full backups and all transaction logs are pretty much the same in terms of compressibility. We'll choose Compression Level 1, again, but since our transaction log backup will, in this case, process only a small amount of data, we could select maximum compression (Level 4) without affecting the processing time significantly. We're not going to change any of the remaining options on this screen, and we have discussed them all already, so go ahead and click on Next. If everything looks as expected on the Summary screen, click on Finish to start the backup. If all goes well, within a few seconds the appearance of two green checkmarks will signal that all pieces of the operation have been completed, and some backup metrics will be displayed. If you prefer the script-based approach, Listing 8-7 shows the SQL Backup T-SQL script that does directly what our SQL Backup GUI did under the covers. 259 260 Chapter 8: Database Backup and Restore with SQL Backup Pro USE [master] EXECUTE master..sqlbackup '-SQL "BACKUP LOG [DatabaseForSQLBackups] TO DISK = ''C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Log_1.sqb'' WITH DISKRETRYINTERVAL = 30, DISKRETRYCOUNT = 10, COMPRESSION = 1, THREADCOUNT = 2"' Listing 8-7: A transction log backup, using SQL Backup T-SQL. Whichever way you decide to execute the log backup, you should see backup metrics similar to those shown in Figure Backing up DatabaseForSQLBackups (transaction log) to: C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Log_1.sqb Backup data size : MB Compressed data size: MB Compression rate : 86.13% Processed 6261 pages for database 'DatabaseForSQLBackups', file 'DatabaseForSQLBackups_log' on file 1. BACKUP LOG successfully processed 6261 pages in seconds ( MB/sec). SQL Backup process ended. Figure 8-11: Backup metrics for transaction log backup on DatabaseForSQLBackups. The backup metrics report a compressed backup size of 7 MB, which we can verify by checking the actual size of the file in the C:\SQLBackups\Chapter8\ folder, and a processing time of about 0.7 seconds. Once again, Figure 8-12 compares these metrics to those obtained for native backups, compressed native backups and for SQL Backup with a higher compression level. 260 261 Chapter 8: Database Backup and Restore with SQL Backup Pro Backup Operation Backup File Size in MB (on disk) Backup Time (seconds) % Difference compared to Native (+ = bigger / faster) Size Speed Native Log Native Log with Compression SQL Backup Log Compression Level SQL Backup Log Compression Level Figure 8-12: Comparing log backup operations for DatabaseForSQLBackups. In all cases, there is roughly a 90% saving in disk space for compressed backups, over the native log backup. In terms of backup performance, native log backups, native compressed log backups, and SQL Backup Compression Level 1 all run in sub-second times, so it's hard to draw too many conclusions except to say that for smaller log files the time savings are less significant than for full backups, as would be expected. SQL Backup Compression Level 3 does offer the smallest backup file footprint, but the trade-off is backup performance that is significantly slower than for native log backups. Differential Backups Finally, let's take a very quick look at how to perform a differential database backup using SQL Backup. For full details on what differential backups are, and when they can be useful, please refer back to Chapter 7. First, simply adapt and rerun Listing 8-6 to insert a load of 100,000 rows into each of the message tables (also, adapt the message text accordingly). 261 262 Chapter 8: Database Backup and Restore with SQL Backup Pro Then, if you prefer the GUI approach, jump-start SQL Backup and work through in the exactly the same way as described for the full backup. The only differences will be: at Step 2, choose Differential as the backup type at Step 3, call the backup file DatabaseForSQLBackups_Diff_1.sqb and locate it in the C:\SQLBackups\Chapter8 folder at Step 4, choose Compression Level 1. If you prefer to run a script, the equivalent SQL Backup script is shown in Listing 8-8. USE [master] EXECUTE master..sqlbackup '-SQL "BACKUP DATABASE [DatabaseForSQLBackups] TO DISK = ''C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Diff_1.sqb'' WITH DISKRETRYINTERVAL = 30, DISKRETRYCOUNT = 10, COMPRESSION = 1, THREADCOUNT = 2, DIFFERENTIAL"' Listing 8-8: SQL Backup differential T-SQL backup code. Again, there is little new here; the command is more or less identical to the one for full backups, with the addition of the DIFFERENTIAL keyword to the WITH clause which instructs SQL Server to only backup any data changed since the last full backup was taken. Backing up DatabaseForSQLBackups (differential database) to: C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Diff_1.sqb Backup data size : MB Compressed data size: MB Compression rate : 99.04% Processed pages for database 'DatabaseForSQLBackups', file 'DatabaseForSQLBackups' on file 1. Processed 2 pages for database 'DatabaseForSQLBackups', file 'DatabaseForSQLBackups_log' on file 1. BACKUP DATABASE WITH DIFFERENTIAL successfully processed pages in seconds ( MB/sec). SQL Backup process ended. Figure 8-13: S QL Backup differential metrics (Compression Level 1). 262 263 Chapter 8: Database Backup and Restore with SQL Backup Pro Let's do a final metrics comparison for a range of differential backups. Backup Operation Backup File Size in MB (on disk) Backup Time (seconds) % Difference compared to Native (+ = bigger / faster) Size Speed Native Log Native Log with Compression SQL Backup Log Compression Level SQL Backup Log Compression Level Figure 8-14: Comparing differential backup operations for DatabaseForSQLBackups. Once again, the space and time savings from compressed backup are readily apparent, with SQL Backup Compression Level 1 emerging as the most efficient on both counts, in these tests. Building a reusable and schedulable backup script One of the objectives of this book is to provide the reader with a jumping-off point for their SQL Server backup strategy. We'll discuss how to create a SQL Backup script that can be used in a SQL Agent job to take scheduled backups of databases, and allow the DBA to: take a backup of selected databases on a SQL Server instance, including relevant system databases 263 264 Chapter 8: Database Backup and Restore with SQL Backup Pro configure the type of backup required (full, differential, or log) store the backup files using the default naming convention set up in Red Gate SQL Backup Pro capture a report of any error or warning codes during the backup operation. Take a look at the script in Listing 8-9, and then we'll walk through all the major sections. USE [master] NVARCHAR(4) -- Conifgure Options Here = N'\\NetworkServer\ShareName\' + + '\' = = N'DatabaseForDiffBackups_SB' = N'DIFF' -- Do Not Modify Below = WHEN N'FULL' THEN N'-SQL "BACKUP DATABASES [' + N'] TO DISK = ''' + N'<AUTO>.sqb'' WITH MAILTO_ONERRORONLY = ''' + N''', DISKRETRYINTERVAL = 30, DISKRETRYCOUNT = 10, COMPRESSION = 3, THREADCOUNT = 2"' WHEN N'LOG' THEN N'-SQL "BACKUP LOGS [' + N'] TO DISK = ''' + N'<AUTO>.sqb'' WITH MAILTO_ONERRORONLY = ''' 264 265 Chapter 8: Database Backup and Restore with SQL Backup Pro + N''', DISKRETRYINTERVAL = 30, DISKRETRYCOUNT = 10, COMPRESSION = 3, THREADCOUNT = 2"' WHEN N'DIFF' THEN N'-SQL "BACKUP DATABASES [' + N'] TO DISK = ''' + N'<AUTO>.sqb'' WITH MAILTO_ONERRORONLY = ''' + N''', DISKRETRYINTERVAL = 30, DISKRETRYCOUNT = 10, COMPRESSION = 3, THREADCOUNT = 2, DIFFERENTIAL"' END OUTPUT -- If our backup operations return any errors or warnings execute below IF >= 500 > 0 ) BEGIN -- Raise an error to fail your backup job RAISERROR(N'Backup operation error', 10,1) END Listing 8-9: Reusable database backup code. The script starts by declaring the required variables, and the sets the values of the four confugurable variables, as The backup path for our database backup files. This should be pointed at the centralized storage location. Also notice that the servername variable is used as a subdirectory. It is common practice to separate backup files by server, so this will use each server name as a subdirectory to store that set of backup We always want to know when backups fail. In some environments, manually checking all database backup operations is just not feasible. Having alerts sent to the DBA team on failure is a good measure to have in place. Be sure to 265 266 Chapter 8: Database Backup and Restore with SQL Backup Pro test the setting on each server occasionally, to guarantee that any failure alerts are getting through. Details of how to configure the settings are in Appendix A comma delimited text list that contains the names of any databases that we want to back up. SQL Backup allows you to back up any number of databases at one time with a single command. When backing up every database on a server, we can simply omit this parameter from the script and, in the BACKUP command, replace [' + '] with Used to determine what type of database backup will be taken. In this script there are three choices for this variable to take; full, log, and differential. In the next section of the script, we build the BACKUP commands, using the variables for which we have just configured values. We store the BACKUP command in variable, until we are ready to execute it. Notice that a simple CASE statement is used to determine the type of backup operation to be performed, according to the value stored We don't need to modify anything in this section of the script, unless making changes to the other settings being used in the BACKUP command, such as the compression level. Of course, we could also turn those into configurable parameters. The next section of the script is where we execute our BACKUP command, storing the ExitCode and ErrorCode output parameters in our defined variables, where: ExitCode is the output value from the SQL Backup extended stored procedure. Any number above 0 indicates some sort of issue with the backup execution. ExitCode >= 500 indicates a serious problem with at least one of the backup files and will need to investigate further. ExitCode < 500 is just a warning code. The backup operation itself may have run successfully, but there was some issue that was not critical enough to cause the entire operation to fail. 266 267 Chapter 8: Database Backup and Restore with SQL Backup Pro ErrorCode is the SQL Server return value. A value above 0 is returned only when SQL Server itself runs into an issue. Having an error code returned from SQL Server almost always guarantees a critical error for the entire operation. We test the value of each of these codes and, if a serious problem has occurred, we raise an error to SQL Server so that, if this were run in a SQL Server Agent job, it would guarantee to fail and alert someone, if the job were configured to do so. We do have it set up to send from SQL Backup on a failure, but also having the SQL Agent job alert on failure is a nice safeguard to have in place. What we do in this section is totally customizable and dictated by our needs. Restoring Database Backups with SQL Backup Pro Having performed our range of full, log and differential backups, using SQL Backup, it's time to demonstrate several useful restore examples, namely: restoring to the end of a given transaction log a complete restore, including restores of the tail log backup a restore to a particular point in time within a transaction log file. Preparing for restore In order to prepare for our restore operations, we're going to add a few new rows to MessageTable1, perform a log backup, and then add a few new rows to MessageTable2, as shown in Listing 268 Chapter 8: Database Backup and Restore with SQL Backup Pro USE [DatabaseForSQLBackups] INSERT INTO dbo.messagetable1 VALUES ( 'What is the meaning of life, the Universe and everything?', GETDATE() ) 21 USE [master] EXECUTE master..sqlbackup '-SQL "BACKUP LOG [DatabaseForSQLBackups] TO DISK = ''C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Log_2.sqb'' WITH DISKRETRYINTERVAL = 30, DISKRETRYCOUNT = 10, COMPRESSION = 1, INIT, THREADCOUNT = 2"' USE [DatabaseForSQLBackups] INSERT INTO dbo.messagetable2 VALUES ('What is the meaning of life, the Universe and everything?', GETDATE() ) 21 Listing 8-10: Add 21 rows, take a log backup, add 21 rows. So, to recap, we have 2 million rows captured in the base full backup. We switched the database from SIMPLE to FULL recovery model, added 100,000 rows to our tables, then did a log backup, so the TLog1 backup captures the details of inserting those 100,000 rows. We then added another 200,000 rows and took a differential backup. Differentials capture all the data added since the last full backup, so 300,000 rows in this case. We then added 21 rows and took a second log backup, so the TLog2 backup will capture details of 200,021 inserted rows (i.e. all the changes since the last log backup). Finally, we added another 21 rows which are not currently captured in any backup. The backup scheme seems quite hard to swallow when written out like that, so hopefully Figure 8-15 will make it easier to digest. 268 269 Chapter 8: Database Backup and Restore with SQL Backup Pro Figure 8-15: Current backup scheme. SQL Backup Pro GUI restore to the end of a log backup First, let's see how easy it is to perform a one-off restore via SQL Backup, using the GUI, especially if all the required files are still stored locally, in their original location. We'll then look at the process again, step by step, using scripts. In this first example, we're going to restore the database to the state in which it existed at the time we took the second transaction log backup (DatabaseForSQLBackups_Log_2.sqb). Start up the SQL Backup Restore wizard and, at Step 1, select the required transaction log backup, as shown in Figure In this case, all the required backup files are still stored locally, so they are available from the backup history. As such, we only have to select the last file to be restored and, when we click Next, SQL Backup will calculate which other files it needs to restore first, and will load them automatically. 269 270 Chapter 8: Database Backup and Restore with SQL Backup Pro Figure 8-16: Restore the latest transaction log file. However, if the restore is taking place several days or weeks after the backup, then the files will likely have been moved to a new location, and we'll need to manually locate each of the required files for the restore process before SQL Backup will let us proceed. To do so, select Browse for backup files to restore from the top drop-down box, and then click the Add Files button to locate each of the required files, in turn. We can select multiple files in the same directory by holding down the Ctrl button on the keyboard. We can also add a network location into this menu by using the Add Server button, or by pasting in a full network path in the file name box. Whether SQL Backup locates the files for us, or we do it manually, we should end up with a screen that looks similar to that shown in Figure 271 Chapter 8: Database Backup and Restore with SQL Backup Pro Figure 8-17: Identifying the required files for the restore process. In this example, we need our base full backup and our differential backup files. Note that the availability of the differential backup means we can bypass our first transaction log backup (DatabaseForSQLBackups_Log_1.sqb). However, if for some reason the differential backup was unavailable, then we could still complete the restore process using the full backup followed by both the log files. We're going to overwrite the existing DatabaseForSQLBackups database and leave the data and log files in their original C:\SQLData directory. Note that the handy File locations drop-down is an innovation in SQL Backup 6.5; if using an older version, you'll need to manually fill in the paths using the ellipsis ( ) buttons. 271 272 Chapter 8: Database Backup and Restore with SQL Backup Pro Figure 8-18: Overwrite the existing database. Click Next and, on the following screen, SQL Backup warns us that we've not performed a tail log backup and gives us the option to do so, before proceeding. We do not need to restore the tail of the log as part of this restore process as we're deliberately only restoring to the end of our second log backup file. However, remember that the details of our INSERTs into MessageTable2, in Listing 8-10, are not currently backed up, and we don't want to lose details of these transactions, so we're going to go ahead and perform this tail log backup. Accepting this option catapults us into a log backup operation and we must designate the name and location for the tail log backup, and follow through the process, as was described earlier in the chapter. 272 273 Chapter 8: Database Backup and Restore with SQL Backup Pro Figure 8-19: Backing up the tail of the log. Once complete, we should receive a message saying that the backup of the tail of the transaction log was successful and to click Next to proceed with the restore. Having done so, we re-enter Step 3 of our original restore process, offering a number of database restore options. Figure 8-20: Database restore options. 273 274 Chapter 8: Database Backup and Restore with SQL Backup Pro The first section of the screen defines the Recovery completion state, and we're going to stick with the first option, Operational (RESTORE WITH RECOVERY). This will leave our database in a normal, usable state once the restore process is completed. The other two options allow us to leave the database in a restoring state, expecting more backup files, or to restore a database in Standby mode. We'll cover each of these later in the chapter. The Transaction log section of the screen is used when performing a restore to a specific point in time within a transaction log backup file, and will also be covered later. The final section allows us to configure a few special operations, after the restore is complete. The first option will test the database for orphaned users. An orphaned user is created when a database login has permissions set internally to a database, but that user doesn't have a matching login, either as a SQL login or an Active Directory login. Orphaned users often occur when moving a database between environments or servers, and are especially problematic when moving databases between operationally different platforms, such as between development and production, as we discussed in Chapter 3. Be sure to take care of these orphaned users after each restore, by either matching the user with a correct SQL Server login or by removing that user's permission from the database. The final option is used to send an to a person or a group of people, when the operation has completed and can be configured such that a mail is sent regardless of outcome, or when an error or warning occurs, or on error only. This is a valuable feature for any DBA. Just as we wrote notification into our automated backup scripts, so we also need to know if a restore operation fails for some reason, or reports a warning. This may be grayed out unless the mail server options have been correctly configured. Refer to Appendix A if you want to try out this feature here. Another nice use case for these notifications is when performing time-sensitive restores on VLDBs. We may not want to monitor the restore manually as it may run long into the night. Instead, we can use this feature so that the DBA, and the departments that need the database immediately, get a notification when the restore operation has completed. 274 275 Chapter 8: Database Backup and Restore with SQL Backup Pro Click Next to reach the, by now familiar, Summary screen. Skip to the Script tab to take a sneak preview of the script that SQL Backup has generated for this operation. You'll see that it's a three-step restore process, restoring first the base full backup, then the differential backup, and finally the second log backup (you'll see a similar script again in the next section and we'll go over the full details there). EXECUTE master..sqlbackup '-SQL "RESTORE DATABASE [DatabaseForSQLBackups] FROM DISK = ''C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Full_BASE.sqb'' WITH NORECOVERY, REPLACE"' EXECUTE master..sqlbackup '-SQL "RESTORE DATABASE [DatabaseForSQLBackups] FROM DISK = ''C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Diff_1.sqb'' WITH NORECOVERY"' EXECUTE master..sqlbackup '-SQL "RESTORE LOG [DatabaseForSQLBackups] FROM DISK = ''C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Log_2.sqb'' WITH RECOVERY, ORPHAN_CHECK"' Listing 8-11: The SQL Backup script generated by the SQL Backup Wizard. As a side note, I'm a little surprised to see the REPLACE option in the auto-generated script; it's not necessary as we did perform a tail log backup. If everything is as it should be, click Finish and the restore process will start. All steps should show green check marks to let us know that everything finished successfully and some metrics for the restore process should be displayed, a truncated view of which is given in Figure <snip> Restoring DatabaseForSQLBackups (database) from: C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Full_BASE). SQL Backup process ended. <snip> 275 276 Chapter 8: Database Backup and Restore with SQL Backup Pro Restoring DatabaseForSQLBackups (database) from: C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Diff_1.sqb). SQL Backup process ended. <snip> Restoring DatabaseForSQLBackups (transaction logs) from: C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Log_2.sqb Processed 0 pages for database 'DatabaseForSQLBackups', file 'DatabaseForSQLBackups' on file 1. Processed pages for database 'DatabaseForSQLBackups', file 'DatabaseForSQLBackups_log' on file 1. RESTORE LOG successfully processed pages in seconds ( MB/sec). No orphaned users detected. SQL Backup process ended. <snip> Figure 8-21: Metrics for SQL Backup restore to end of the second log backup. We won't dwell on the metrics here as we'll save that for a later section, where we compare the SQL Backup restore performance with native restores. Being pessimistic DBAs, we won't believe the protestations of success from the output of the restore process, until we see with our own eyes that the data is as it should be. USE DatabaseForSQLBackups SELECT MessageData, COUNT(MessageData) FROM dbo.messagetable1 GROUP BY MessageData SELECT MessageData, COUNT(MessageData) FROM dbo.messagetable2 GROUP BY MessageData Listing 8-12: Verifying our data. 276 277 Chapter 8: Database Backup and Restore with SQL Backup Pro The result confirms that all the data is there from our full, differential, and second log backups, but that the 21 rows we inserted into MessageTable2 are currently missing. Figure 8-22: Results of data verification. Never fear; since we had the foresight to take a tail log backup, we can get those missing 21 rows back. SQL Backup T-SQL complete restore We're now going to walk through the restore process again, but this time we'll use a SQL Backup script, as shown in Listing 8-13, and we'll perform a complete restore, including the tail log backup. USE master go --step 1: Restore the base full backup EXECUTE master..sqlbackup '-SQL "RESTORE DATABASE [DatabaseForSQLBackups] FROM DISK = ''C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Full_BASE.sqb'' WITH NORECOVERY, DISCONNECT_EXISTING, REPLACE"' 277 278 Chapter 8: Database Backup and Restore with SQL Backup Pro --step 2: Restore the diff backup EXECUTE master..sqlbackup '-SQL "RESTORE DATABASE [DatabaseForSQLBackups] FROM DISK = ''C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Diff_1.sqb'' WITH NORECOVERY"' --step 3: Restore the second log backup EXECUTE master..sqlbackup '-SQL "RESTORE LOG [DatabaseForSQLBackups] FROM DISK = ''C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Log_2.sqb'' WITH NORECOVERY"' --step 4: Restore the tail log backup and recover the database EXECUTE master..sqlbackup '-SQL "RESTORE LOG [DatabaseForSQLBackups] FROM DISK = ''C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Log_Tail.sqb'' WITH RECOVERY, ORPHAN_CHECK"' Listing 8-13: A complete restore operation with SQL Backup T-SQL. There shouldn't be too much here that is new, but let's go over some of the WITH clause options. DISCONNECT_EXISTING Used in Step 1, this kills any current connections to the database. Without this option, we would need to use functionality similar to that which we built into our native restore script in Chapter 3 (see Listing 4-2). REPLACE This is required here, since we are now working with a new, freshlyrestored copy of the database and we aren't performing a tail log backup as the first step of this restore operation. SQL Server will use the logical file names and paths that are stored in the backup file. Remember that this only works if the paths in the backup file exist on the server to which you are restoring. NORECOVERY Used in Steps 1 3, this tells SQL Server to leave the database in a restoring state and to expect more backup files to be applied. ORPHAN_CHECK Used in Step 4, this is the orphaned user check on the database, after the restore has completed, as described in the previous section. RECOVERY Used in Step 4, this instructs SQL Server to recover the database to a normal usable state when the restore is complete. 278 279 Chapter 8: Database Backup and Restore with SQL Backup Pro Execute the script, then, while it is running, we can take a quick look at the SQL Backup monitoring stored procedure, sqbstatus, a feature that lets us monitor any SQL Backup restore operation, while it is in progress. Quickly open a second tab in SSMS and execute Listing EXEC master..sqbstatus Listing 8-14: Red Gate SQL Backup Pro monitoring stored procedure. The stored procedure returns four columns: the name of the database being restored; the identity of the user running the restore; how many bytes of data have been processed; and the number of compressed bytes that have been produced in the backup file. It can be useful to check this output during a long-running restore the first time you perform it, to gauge compression rates, or to get an estimate of completion time for restores and backups on older versions of SQL Server, where Dynamic Management Views are not available to tell you that information. Once the restore completes, you'll see restore metrics similar to those shown in Figure 8-21, but with an additional section for the tail log restore. If you rerun Listing 8-12 to verify your data, you should find that the "missing" 21 rows in MessageTable2 are back! SQL Backup point-in-time restore to standby In our final restore example, we're going to restore a standby copy of the DatabaseFor- SQLBackups database to a specific point in time in order to attempt to retrieve some accidentally deleted data. Standby servers are commonly used as a High Availability solution; we have a secondary, or standby, server that can be brought online quickly in the event of a failure of the primary server. We can restore a database to the standby server, and then successively 279 280 Chapter 8: Database Backup and Restore with SQL Backup Pro ship over and apply transaction logs, using the WITH STANDBY option, to roll forward the standby database and keep it closely in sync with the primary. In between log restores, the standby database remains accessible but in a read-only state. This makes it a good choice for near real-time reporting solutions where some degree of time lag in the reporting data is acceptable. However, this option is occasionally useful when in the unfortunate position of needing to roll forward through a set of transaction logs to locate exactly where a data mishap occurred. It's a laborious process (roll forward a bit, query the standby database, roll forward a bit further, query again, and so on) but, in the absence of any other means to restore a particular object or set of data, such as a tool that supports object-level restore (more on this a little later) it could be a necessity. In order to simplify our point-in-time restore, let's run another full backup, as shown in Listing EXECUTE master..sqlbackup '-SQL "BACKUP DATABASE [DatabaseForSQLBackups] TO DISK = ''C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Full_BASE2.sqb'' WITH DISKRETRYINTERVAL = 30, DISKRETRYCOUNT = 10, THREADCOUNT = 2, COMPRESSION = 1"' Listing 8-15: A new base full backup of DatabaseForSQLBackups. We'll then add some more data to each of our message tables, before simulating a disaster, in the form of someone accidentally dropping MessageTable2. USE [DatabaseForSQLBackups] INSERT INTO dbo.messagetable1 VALUES ( 'MessageTable1, I think the answer might be 41. No, wait...', GETDATE() ) 281 Chapter 8: Database Backup and Restore with SQL Backup Pro /* Find date of final INSERT from previous statement This is to help us with the RESTORE process USE DatabaseForSQLBackups SELECT TOP(1) MessageData,MessageDate FROM dbo.messagetable1 WHERE MessageData LIKE 'MessageTable1%' ORDER BY MessageDate DESC -- Output: :41: */ INSERT INTO dbo.messagetable2 VALUES ( 'MessageTable2, the true answer is 42!', GETDATE() ) final insert time: :42: Disaster strikes! DROP TABLE dbo.messagetable2 Listing 8-16: Disaster strikes MessageTable2. In this simple example, we have the luxury of knowing exactly when each event occurred. However, imagine this is a busy production database, and we only find out about the accidental table loss many hours later. Listing 8-17 simulates one of our regular, scheduled log backups, which runs after the data loss has occurred. USE [master] EXECUTE master..sqlbackup '-SQL "BACKUP LOG [DatabaseForSQLBackups] TO DISK = ''C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Log_3.sqb'' WITH DISKRETRYINTERVAL = 30, DISKRETRYCOUNT = 10, COMPRESSION = 1, THREADCOUNT = 2"' Listing 8-17: A post-disaster log backup. 281 282 Chapter 8: Database Backup and Restore with SQL Backup Pro Restore to standby using the SQL Backup Pro GUI Having contrived the data loss, we can now start the restore process. Right-click on DatabaseForSQLBackups, pick the latest transaction log backup (DatabaseForSQL- Backups_Log_3.sqb) and click Next. Again, since the files are still in their original location, SQL Backup will locate any other files it needs from further back down the chain, in this case, just the latest full backup. If you've moved the full backup file, locate it manually, as described before. Figure 8-23: Identifying the backup files for our PIT restore. Our intention here, as discussed, is to restore a copy of the DatabaseForSQLBackups database in Standby mode. This will give us read access to the standby copy as we attempt to roll forward to just before the point where we lost Messagetable2. So, this time, we'll restore to a new database, called DatabaseForSQLBackups_Standby, as shown in Figure 283 Chapter 8: Database Backup and Restore with SQL Backup Pro Figure 8-24: Restoring to a new, standby copy of the DatabaseForSQLBackups database. At Step 3, we're going to choose a new option for the completion state of our restored database, which is Read-only (RESTORE WITH STANDBY). In doing so, we must create an undo file for the standby database. As we subsequently apply transaction log backups to our standby database, to roll forward in time, SQL Server needs to be able to roll back the effects of any transactions that were uncommitted at the point in time to which we are restoring. However, the effects of these uncommitted transactions must be preserved. As we roll further forward in time, SQL Server may need to reapply the effects of a transaction it previously rolled back. If SQL Server doesn't keep a record of that activity, we wouldn't be able to keep our database relationally sound. All of this information regarding the rolled back transactions is managed through the undo file. We'll place the undo file in our usual SQLBackups directory. In the central portion of the screen, we have the option to restore the transaction log to a specific point in time; we're going to roll forward in stages, first to a point as close as we can after 10:41:36.540, which should be the time we completed the batch of 41 INSERTs into MessageTable1. Again, remember that in a real restore scenario, you will probably not know which statements were run when. 283 284 Chapter 8: Database Backup and Restore with SQL Backup Pro Figure 8-25: Restoring WITH STANDBY to a specific point in a transaction log. Click Next to reach the Summary screen, where we can also take a quick preview of the script that's been generated (we'll discuss this in more detail shortly). Click Finish to execute the restore operation and it should complete quickly and successfully, with the usual metrics output. Refresh the SSMS Object Explorer to reveal a database called DatabaseForSQLBackups_Standby, which is designated as being in a Standby/ Read-Only state. We can query it to see if we restored to the point we intended. USE DatabaseForSQLBackups_Standby SELECT MessageData, COUNT(MessageData) FROM dbo.messagetable1 GROUP BY MessageData 284 285 Chapter 8: Database Backup and Restore with SQL Backup Pro SELECT MessageData, COUNT(MessageData) FROM dbo.messagetable2 GROUP BY MessageData Listing 8-18: Querying the standby database. As we hoped, we've got both tables back, and we've restored the 41 rows in MessageTable1, but not the 42 in MessageTable2. Figure 8-26: Verifying our data, Part 1. To get these 42 rows back, so the table is back to the state it was when dropped, we'll need to roll forward a little further, but stop just before the DROP TABLE command was issued. Start another restore operation on DatabaseForSQLBackups, and proceed as before to Step 2. This time, we want to overwrite the current DatabaseForSQLBackups_ Standby database, so select it from the drop-down box. 285 286 Chapter 8: Database Backup and Restore with SQL Backup Pro Figure 8-27: Overwriting the current standby database. At Step 3, we'll specify another standby restore, using the same undo file, and this time we'll roll forward to just after we completed the load of 42 rows into Messagetable2, but just before that table got dropped (i.e. as close as we can to 10:42:45.897). 286 287 Chapter 8: Database Backup and Restore with SQL Backup Pro Figure 8-28: Rolling further forward. Once again, the operation should complete successfully, with metrics similar to those shown in Figure Restoring DatabaseForSQLBackups_Standby (database) from: C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Full_BASE2.sqb Processed pages for database 'DatabaseForSQLBackups_Standby', file 'DatabaseForSQLBackups' on file 1. Processed 3 pages for database 'DatabaseForSQLBackups_Standby', file 'DatabaseForSQLBackups_ log' on file 1. RESTORE DATABASE successfully processed pages in seconds ( MB/sec). SQL Backup process ended. Restoring DatabaseForSQLBackups_Standby (transaction logs) from: C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Log_3.sqb Processed 0 pages for database 'DatabaseForSQLBackups_Standby', file 'DatabaseForSQLBackups' on file 1. Processed 244 pages for database 'DatabaseForSQLBackups_Standby', file 'DatabaseForSQLBackups_ log' on file 1. RESTORE LOG successfully processed 244 pages in seconds ( MB/sec). No orphaned users detected. SQL Backup process ended. Figure 8-29: Output metrics for the PIT restore. 287 288 Chapter 8: Database Backup and Restore with SQL Backup Pro Rerun our data verification query, from Listing 8-18 and you should see that we now have the 42 rows restored to MessageTable2. Restore to standby using a SQL Backup script Before we move on, it's worth taking a more detailed look at the SQL Backup T-SQL script that we'd use to perform the same point-in-time restore operation. EXECUTE master..sqlbackup '-SQL "RESTORE DATABASE [DatabaseForSQLBackups_Standby] FROM DISK = ''C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Full_BASE2.sqb'' WITH NORECOVERY, MOVE ''DatabaseForSQLBackups'' TO ''C:\SQLData\DatabaseForSQLBackups_Standby.mdf'', MOVE ''DatabaseForSQLBackups_log'' TO ''C:\SQLData\DatabaseForSQLBackups_Standby_log.ldf''"' EXECUTE master..sqlbackup '-SQL "RESTORE LOG [DatabaseForSQLBackups_Standby] FROM DISK = ''C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Log_3.sqb'' WITH STANDBY = ''C:\SQLBackups\Undo_DatabaseForSQLBackups_Standby.dat'', STOPAT = '' T10:42:46'', ORPHAN_CHECK"' Listing 8-19: Restore to standby SQL Backup script. The first command restores the base backup file to a new database, using the MOVE argument to copy the existing data and log files to the newly designated files. We specify NORECOVERY so that the database remains in a restoring state, to receive further backup files. The second command applies the log backup file to this new database. Notice the use of the WITH STANDBY clause, which indicates the restored state of the new database, and associates it with the correct undo file. Also, we use the STOPAT clause, with which you should be familiar from Chapter 4, to specify the exact point in time to which we wish to roll forward. Any transactions that were uncommitted at the time will be rolled back during the restore. 288 289 Chapter 8: Database Backup and Restore with SQL Backup Pro This is the first of our restore operations that didn't end with the RECOVERY keyword. The STANDBY is one of three ways (RECOVERY, NORECOVERY, STANDBY) to finalize a restore, and one of the two ways to finalize a restore and leave the data in an accessible state. It's important to know which finalization technique to use in which situations, and to remember they don't all do the same thing. Alternatives to restore with standby In a real-world restore, our next step, which we have not yet tackled here, would be to transfer the lost table back into the production database (DatabaseForSQLBackups). This, however, is not always an easy thing to do. If we do have to bring back data this way, we may run into referential integrity issues with data in related tables. If the data in other tables contains references to the lost table, but the database doesn't have the proper constraints in place, then we could have a bit of a mess to clean up when we import that data back into the production database. Also, one of the problems with this restore to standby approach is that you might also find yourself in a position where you have a VLDB that would require a great deal of time and space to restore just to get back one table, as in our example. In this type of situation, if your VLDB wasn't designed with multiple data files and filegroups, you might be able turn to an object-level restore solution. These tools will restore, from a database backup, just a single table or other object without having to restore the entire database. Restore metrics: native vs. SQL Backup Pro In order to get some comparison between the performances of native restores versus restores from compressed backups, via SQL Backup, we'll first simply gather metrics for a SQL backup restore of our latest base backup of DatabaseForSQBackups (_Full_ BASE2.sqb), shown in Listing 290 Chapter 8: Database Backup and Restore with SQL Backup Pro USE master go --Restore the base full backup EXECUTE master..sqlbackup '-SQL "RESTORE DATABASE [DatabaseForSQLBackups] FROM DISK = ''C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Full_BASE2.sqb'' WITH RECOVERY, DISCONNECT_EXISTING, REPLACE"' Restoring DatabaseForSQLBackups (database) from: C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Full_BASE2). Listing 8-20: Metrics for SQL restore of full database backup. Then, we'll take a native, compressed full backup of the newly restored database, and then a native restore from that backup. USE [master] BACKUP DATABASE DatabaseForSQLBackups TO DISK = N'C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Full_Native.bak' WITH COMPRESSION, INIT, NAME = N'DatabaseForSQLBackups-Full Database Backup' RESTORE DATABASE [DatabaseForSQLBackups] FROM DISK = N'C:\SQLBackups\Chapter8\DatabaseForSQLBackups_Full_Native.bak' WITH FILE = 1, STATS = 25, REPLACE 25 percent processed. 50 percent processed. 75 percent processed. 100 percent processed.). Listing 8-21: Code and metrics for native restore of full database backup. 290 291 Chapter 8: Database Backup and Restore with SQL Backup Pro As a final test, we can rerun Listing 8-21, but performing a native, non-compressed backup, and then restoring from that. In my tests, the restore times for native compressed and SQL Backup compressed backups were roughly comparable, with the native compressed restores performing slightly faster. Native non-compressed restores were somewhat slower, running in around 21 seconds in my tests. Verifying Backups As discussed in Chapter 2, the only truly reliable way of ensuring that your various backup files really can be used to restore a database is to perform regular test restores. However, there are a few other things you can do to minimize the risk that, for some reason, one of your backups will be unusable. SQL Backup backups, like native backups can, to some extent, be checked for validity using both BACKUP...WITH CHECKSUM and RESTORE VERIFYONLY. If both options are configured for the backup process (see Figure 8-5b) then SQL Backup will verify that the backup is complete and readable and then recalculate the checksum on the data pages contained in the backup file and compare it against the checksum values generated during the backup. Listing 8-22 shows the script. EXECUTE master..sqlbackup '-SQL "BACKUP DATABASE [DatabaseForSQLBackups] TO DISK = ''D:\SQLBackups\Chapter8\DatabaseForSQLBackups_FULL.sqb'' WITH CHECKSUM, DISKRETRYINTERVAL = 30, DISKRETRYCOUNT = 10, THREADCOUNT = 2, VERIFY"' Listing 8-22: BACKUP WITH CHECKSUM and RESTORE VERIFYONLY with SQL Backup. Alternatively, we can run either of the validity checks separately. As discussed in Chapter 2, BACKUP WITH CHECKSUM verifies only that each page of data written to the backup file is error free in relation to how it was read from disk. It does not validate that the backup data is valid, only that what was being written, was written correctly. It can cause a lot of overhead and slow down backup operations significantly, so evaluate its use carefully, based on available CPU capacity. 291 292 Chapter 8: Database Backup and Restore with SQL Backup Pro Nevertheless, these validity checks do provide some degree of reassurance, without the need to perform full test restores. Remember that we also need to be performing DBCC CHECKDB routines on our databases at least weekly, to make sure they are in good health and that our backups will be restorable. There are two ways to do this: we can run DBCC CHECKDB before the backup, as a T-SQL statement, in front of the extended stored procedure that calls SQL Backup Pro or, with version 7 of the tool, we can also enable the integrity check via the Schedule Restore Jobs wizard, as shown in Figure Figure 8-30: Configuring DBCC CHECKDB options as part of a restore job. Backup Optimization We discussed many ways to optimize backup storage and scheduling back in Chapter 2, so here, we'll focus just on a few optimization features that are supported by SQL Backup. The first is the ability to back up to multiple backup files on multiple devices. This is one of the best ways to increase throughput in backup operations, since we can write to several backup files simultaneously. This only applies when each disk is physically separate hardware; if we have one physical disk that is partitioned into two or more logical drives, we will not see a performance increase since the backup data can only be written to one of those logical drives at a time. 292 293 Chapter 8: Database Backup and Restore with SQL Backup Pro Listing 8-23 shows the SQL Backup command to back up a database to multiple backup files, on separate disks. The listing will also show how to restore from these multiple files, which requires the addition of extra file locations. EXECUTE master..sqlbackup '-SQL "BACKUP DATABASE [DatabaseForSQLBackups] TO DISK = ''C:\SQLBackups\Chapter8\DatabaseForSQLBackups_FULL_1.sqb'', DISK = ''D\SQLBackups\Chapter8\DatabaseForSQLBackups_FULL_2.sqb'', WITH DISKRETRYINTERVAL = 30, DISKRETRYCOUNT = 10, COMPRESSION = 3"' EXECUTE master..sqlbackup '-SQL "RESTORE DATABASE [DatabaseForSQLBackups] FROM DISK = ''C:\SQLBackups\Chapter8\DatabaseForSQLBackups_FULL_1.sqb'', DISK = ''D:\SQLBackups\Chapter8\DatabaseForSQLBackups_FULL_2.sqb'', WITH RECOVERY"' Listing 8-23: Backing up a database to multiple files with SQL Backup. This is useful not only for backup throughput/performance; it is also a useful way to cut down on the size of a single backup, for transfer to other systems. Nothing is more infuriating than trying to copy a huge file to another system only to see it fail after 90% of the copy is complete. With this technique, we can break down that large file and copy the pieces separately. Note that backup to multiple files is also supported in native T-SQL and for native backups, as shown in Listing BACKUP DATABASE [DatabaseForSQLBackups] TO DISK = 'C:\SQLBackups\Chapter8\DatabaseForSQLBackups_FULL_Native_1.bak', DISK = 'C:\SQLBackups\Chapter8\DatabaseForSQLBackups_FULL_Native_2.bak' Listing 8-24: Native backup to multiple files. Having covered how to split backups to multiple locations, let's now see how to back up a single file, but have it stored in multiple locations, as shown in Listing This is useful when we want to back up to a separate location, such as a network share, when taking the original backup. This is only an integrated option when using the SQL Backup tool. 293 294 Chapter 8: Database Backup and Restore with SQL Backup Pro EXECUTE master..sqlbackup '-SQL "BACKUP DATABASE [DatabaseForSQLBackups] TO DISK = ''C:\SQLBackups\Chatper8\DatabaseForSQLBackups_FULL.sqb'' WITH COMPRESSION = 3, COPYTO = ''\\NETWORKMACHINE\SHARENAME\'', THREADCOUNT = 2"' Listing 8-25: Back up a database with a copy to a separate location. This will cause the backup process to run a bit longer, since it has to back up the database as well as copy it to another location. Just remember that network latency can be a major time factor in the completion of the backups, when using this option. Ultimately, to get the most performance out of a backup, we will need to tune each backup routine to match the specific environment. This requires testing the disk subsystem, the throughput of SQL Server, and making adjustments in the backup process to get the best backup performance. There is a useful listing on the Red Gate support site that offers some tips on how to do this using just a few extra parameters in the SQL Backup stored procedure: SBU_OptimizingBackup. Summary All of the same principles that we have discussed when using native SQL Server backup procedures apply when using Red Gate SQL Backup Pro. We want to follow the same best practices, and we can implement the same type of backup strategies if we are using SQL Backup in our environment. Red Gate SQL Backup Pro is not a requirement for our backup strategies, but it is a great tool that can save substantial amounts of time and disk space. Always remember to use the right tool for the right job. 294 295 Chapter 9: File and Filegroup Backup and Restore So far in this book, all of the full and differential backups we've taken have been database backups; in other words our full and differential backups have been capturing the contents of all data files in all filegroups. However, it's also possible to perform these types of backups on individual files or filegroups. Likewise, it's also possible in some cases, and assuming you have a complete set of accompanying transaction log backups, to restore just a subset of a database, such as an individual file or filegroup, rather than the entire database. I'll state upfront that, in my experience, it is relatively rare for a DBA to have too many databases that are subject to either file backups or filed-based restores. Even databases straying into the hundreds of gigabytes range, which may take a few hours to back up, will be managed, generally, using the usual mix of full database backups, supplemented by differential database backups (and, of course, log backups). Likewise, these databases will be restored, as necessary, using the normal database restore techniques we've discussed in previous chapters. However, it's when we start managing databases that run into the terabyte range that we start getting into trouble using these standard database backup and restore techniques, since it may no longer be possible to either back up the database in the required time, or restore the whole database within the limits of acceptable down-time. In such cases, filebased backup and restore becomes a necessity, and in this chapter, we'll discuss: potential advantages of file-based backup and restore common file architectures to support file-based backup and restore performing full and differential file backups using native SSMS and T-SQL, as well as SQL Backup 295 296 Chapter 9: File and Filegroup Backup and Restore performing several different types of file-based restore, namely: complete restores restore right to the point of failure point-in-time restores restore to a specific point in a transaction log backup using the STOPAT parameter restoring just a single data file recovering the database as a whole, by restoring just a single "failed" secondary data file online piecemeal restore, with partial database recovery bringing a database back online quickly after a failure, by restoring just the primary data file, followed later by the other data files. This operation requires SQL Server Enterprise (or Developer) Edition. Advantages of File Backup and Restore In order to exploit the potential benefits of file-based backup and restore, we need to have a database where the filegroup architecture is such that data is split down intelligently across multiple filegroups. We'll discuss some ways to achieve this in the next section but, assuming for now that this is the case, the benefits below can be gained. Easier VLDB backup administration For very large databases (i.e. in the terabyte range) it is often not possible to run a nightly database backup, simply due to time constraints and the fact that such backups have a higher risk of failure because of the very long processing times. In such cases, file backups become a necessity. Restoring a subset of the data files Regardless of whether we take database or file backups, it's possible in some cases to recover a database by restoring only a subset of that database, say, a single filegroup (though it's also possible to restore just a single page), rather than the whole database. Online piecemeal restores In the Enterprise Edition of SQL Server 2005, and later, we can make a database "partially available" by restoring only the PRIMARY filegroup and bringing the database back online, then later restoring other secondary filegroups. 296 297 Chapter 9: File and Filegroup Backup and Restore Improved disk I/O performance Achieved by separating different files and filegroups onto separate disk drives. This assumes that the SAN, DAS, or local storage is set up to take advantage of the files being on separate physical spindles, or SSDs, as opposed to separate logical disks. Piecemeal restores can be a massive advantage for any database, and may be a necessity for VLDBs, where the time taken for a full database restore would fall outside the down-time stipulated in the SLA. In terms of disk I/O performance, it's possible to gain performance advantages by creating multiple data files within a filegroup, and placing each file on a separate drive and, in some case, by separating specific tables and indexes into a filegroup, again on a dedicated drive. It's even possible to partition a single object across multiple filegroups (a topic we won't delve into further in this book, but see library/ms aspx for a general introduction). In general, I would caution against going overboard with the idea of trying to optimize disk I/O by manual placement of files and filegroups on different disk spindles, unless it is a proven necessity from a performance or storage perspective. It's a complex process that requires a lot of prior planning and ongoing maintenance, as data grows. Instead, I think there is much to be said for keeping file architecture as simple as is appropriate for a given database, and then letting your SAN or direct-attached RAID array take care of the disk I/O optimization. If a specific database requires it, then by all means work with the SAN administrators to optimize file and disk placement, but don't feel the need to do this on every database in your environment. As always, it is best to test and see what overhead this would place on the maintenance and administration of the server as opposed to the potential benefits which it provides. With that in mind, let's take a closer, albeit still relatively brief, look at possible filegroup architectures. 297 298 Chapter 9: File and Filegroup Backup and Restore Common Filegroup Architectures A filegroup is simply a logical collection of one or more database files. So far in this book, our database creation statements have been very straightforward, and similar in layout to the one shown in Listing 9-1. CREATE DATABASE [FileBackupsTest] ON PRIMARY ( NAME = N'FileBackupsTest', FILENAME = N'C:\SQLData\FileBackupsTest.mdf' ) LOG ON ( NAME = N'FileBackupsTest_log', FILENAME = N'C:\SQLData\FileBackupsTest_log.ldf' ) Listing 9-1: A simple database file architecture. In other words, a single data file in the PRIMARY filegroup, plus a log file (remember that log files are entirely separate from data files; log files are never members of a filegroup). However, as discussed in Chapter 1, it's common to create more than one data file per filegroup, as shown in Listing 9-2. CREATE DATABASE [FileBackupsTest] ON PRIMARY ( NAME = N'FileBackupsTest', FILENAME = N'C:\SQLData\FileBackupsTest.mdf'), ( NAME = N'FileBackupsTest2', FILENAME = N'D:\SQLData\FileBackupsTest2.ndf') LOG ON ( NAME = N'FileBackupsTest_log', FILENAME = N'E:\SQLData\FileBackupsTest_log.ldf' ) Listing 9-2: Two data files in the PRIMARY filegroup. 298 299 Chapter 9: File and Filegroup Backup and Restore Now we have two data files in the PRIMARY filegroup, plus the log file. SQL Server will utilize all the data files in a given database on a "proportionate fill" basis, making sure that each data file is used equally, in a round-robin fashion. We can also back up each of those files separately, if we wish. We can place each data file on a separate spindle to increase disk I/O performance. However, we have no control over exactly which data gets placed where, so we may end up with most of the data that is very regularly updated written to one file and most of the data that is rarely touched in the second. We'd have one disk working to peak capacity while the other sat largely idle, and we wouldn't achieve the desired performance benefit. The next step is to exert some control over exactly what data gets stored where, and this means creating some secondary filegroups, and dictating which objects store their data where. Take a look at Listing 9-3; in it we create the usual PRIMARY filegroup, holding our mdf file, but also a user-defined filegroup called SECONDARY, in which we create three secondary data files. CREATE DATABASE [FileBackupsTest] ON PRIMARY ( NAME = N'FileBackupsTest', FILENAME = N'E:\SQLData\FileBackupsTest.mdf', SIZE = 51200KB, FILEGROWTH = 10240KB ), FILEGROUP [Secondary] ( NAME = N'FileBackupsTestUserData1', FILENAME = N'G:\SQLData\FileBackupsTestUserData1.ndf', SIZE = KB, FILEGROWTH = KB ), ( NAME = N'FileBackupsTestUserData2', FILENAME = N'H:\SQLData\FileBackupsTestUserData2.ndf', SIZE = KB, FILEGROWTH = KB ), ( NAME = N'FileBackupsTestUserData3', FILENAME = N'I:\SQLData\FileBackupsTestUserData3.ndf', SIZE = KB, FILEGROWTH = KB ) LOG ON ( NAME = N'FileBackupsTest_log', FILENAME = N'F:\SQLData\FileBackupsTest_log.ldf', SIZE = KB, FILEGROWTH = KB ) USE [FileBackupsTest] 299 300 Chapter 9: File and Filegroup Backup and Restore IF NOT EXISTS ( SELECT name FROM sys.filegroups WHERE is_default = 1 AND name = N'Secondary' ) ALTER DATABASE [FileBackupsTest] MODIFY FILEGROUP [Secondary] DEFAULT Listing 9-3: A template for creating a multi-filegroup database. Crucially, we can now dictate, to a greater or less degree, what data gets put in which filegroup. In this example, immediately after creating the database, we have stipulated the SECONDARY filegroup, rather than the PRIMARY filegroup, as the default filegroup for this database. This means that our PRIMARY filegroup will hold only our system objects and data (plus pointers to the secondary data files). By default, any user objects and data will now be inserted into one of the data files in the SECONDARY filegroup, unless this was overridden by specifying a different target filegroup when the object was created. Again, the fact that we have multiple data files means that we can back each file up separately, if the entire database can't be backed up in the allotted nightly window. There are many different ways in which filegroups can be used to dictate, at the file level, where certain objects and data are stored. In this example, we've simply decided that the PRIMARY is for system data, and SECONDARY is for user data, but we can take this further. We might decide to store system data in PRIMARY, plus any other data necessary for the functioning of a customer-facing sales website. The actual sales and order data might be in a separate, dedicated filegroup. This architecture might be especially beneficial when running an Enterprise Edition SQL Server, where we can perform online piecemeal restores. In this case, we could restore the PRIMARY first, and get the database back online and the website back up. Meanwhile we can get to work restoring the other, secondary filegroups. We might also split tables logically into different filegroups, for example: separating rarely-used archive data from current data (e.g. current year's sales data in one filegroup, archive data in others) 300 301 Chapter 9: File and Filegroup Backup and Restore separating out read-only data from read-write data separating out critical reporting data. Another scheme that you may encounter is use of filegroups to separate the non-clustered indexes from the indexed data, although this seems to be a declining practice in cases where online index maintenance is available, with Enterprise Editions of SQL Server, and due to SAN disk systems becoming faster. Remember that the clustered index data is always in the same filegroup as the base table. We can also target specific filegroups at specific types of storage, putting the most frequently used and/or most critical data on faster media, while avoiding eating up highspeed disk space with data that is rarely used. For example, we might use SSDs for critical report data, a slower SAN-attached drive for archive data, and so on. All of these schemes may or may not represent valid uses of filegroups in your environment, but almost all of them will add complexity to your architecture, and to your backup and restore process, assuming you employ file-based backup and restore. As discussed earlier, I only recommend you go down this route if the need is proven, for example for VLDBs where the need is dictated by backup and or restore requirements. For databases of a manageable size, we can continue to use database backups and so gain the benefit of using multiple files/filegroups without the backup and restore complexity. Of course, one possibility is that a database, originally designed with very simple file architecture, grows to the point that it is no longer manageable in this configuration. What is to be done then? Changing the file architecture for a database requires very careful planning, both with regard to immediate changes to the file structure and how this will evolve to accommodate future growth. For the initial redesign, we'll need to consider questions such as the number of filegroups required, how the data is going to be separated out across those filegroups, how many data files are required, where they are going to be stored on disk, and so on. Having done this, we're then faced with the task of planning how to move all the data, and how much time is available each night to get the job done. 301 302 Chapter 9: File and Filegroup Backup and Restore These are all questions we need to take seriously and plan carefully, with the help of our most experienced DBAs; getting this right the first time will save some huge headaches later. Let's consider a simple example, where we need to re-architect the file structure for a database which currently stores all data in a single data file in PRIMARY. We have decided to create an additional secondary filegroup, named UserDataFilegroup, which contains three physical data files, each of which will be backed up during the nightly backup window. This secondary filegroup will become the default filegroup for the database, and the plan is that from now on only system objects and data will be stored in the PRIMARY data file. How are we going to get the data stored in the primary file into this new filegroup? It depends on the table index design, but ideally each table in the database will have a clustered index, in which case the easiest way to move the data is to re-create the clustered index while moving the data currently in the leaf level of that index over to the new filegroup. The code would look something like that shown in Listing 9-4. In Enterprise editions of SQL Server, we can set the ONLINE parameter to ON, so that the index will be moved but still be available. When using Standard edition go ahead and switch this to OFF. CREATE CLUSTERED INDEX [IndexName] ON [dbo].[tablename] ([ColumnName] ASC) WITH (DROP_EXISTING = ON, ONLINE = ON) ON [UserDataFileGroup] Listing 9-4: Rebuilding an index in a new filegroup. If the database doesn't have any clustered indexes, then this was a poor design choice; it should! We can create one for each table, on the most appropriate column or columns, using code similar to Listing 9-4 (omitting the DROP_EXISTING clause, though it won't hurt to include it). Once the clustered index is built, the table will be moved, along with the new filegroup. 302 303 Chapter 9: File and Filegroup Backup and Restore If this new index is not actually required, we can go ahead and drop it, as shown in Listing 9-5, but ideally we'd work hard to create a useful index instead that we want to keep. DROP INDEX [IndexName] ON [dbo].[tablename] WITH ( ONLINE = ON ) Listing 9-5: Dropping the newly created index. Keep in mind that these processes will move the data and clustered indexes over to the new filegroup, but not the non-clustered, or other, indexes. We will still need to move these over manually. Many scripts can be found online that will interrogate the system tables, find all of the non-clustered indexes and move them. Remember, also, that the process of moving indexes and data to a different physical file or set of files can be long, and disk I/O intensive. Plan out time each night, over a certain period, to get everything moved with as little impact to production as possible. This is also not a task to be taken lightly, and it should be planned out with the senior database administration team. File Backup When a database creeps up in size towards the high hundreds of gigabytes, or into the terabyte realm, then database backups start to become problematic. A full database backup of a database of this size could take over half of a day, or even longer, and still be running long into the business day, putting undue strain on the disk and CPU and causing performance issues for end-users. Also, most DBAs have experienced the anguish of seeing such a backup fail at about 80% completion, knowing that starting it over will eat up another 12 hours. 303 304 Chapter 9: File and Filegroup Backup and Restore Hopefully, as discussed in the previous sections, this database has been architected such that the data is spread across multiple data files, in several filegroups, so that we can still back up the whole database bit by bit, by taking a series of file backups, scheduled on separate days. While this is the most common reason for file backups, there are other valid reasons too, as we have discussed; for example if one filegroup is read-only, or modified very rarely, while another holds big tables, subject to frequent modifications, then the latter may be on a different and more frequent backup schedule. A file backup is simply a backup of a single data file, subset of data files or an entire filegroup. Each of the file backups contains only the data from the files or filegroups that we have chosen to be included in that particular backup file. The combination of all of the file backups, along with all log backups taken over the same period of time, is the equivalent of a full database backup. Depending on the size of the database, the number of files, and the backup schedule, this can constitute quite a large number of backups. We can capture both full file backups, capturing the entire contents of the designated file or filegroup, and differential file backups, capturing only the pages in that file or filegroup that have been modified since the last full file backup (there are also partial and partial differential file backups, but we'll get to those in Chapter 10). Is there a difference between file and filegroup backups? The short answer is no. When we take a filegroup backup we are simply specifying that the backup file should contain all of the data files in that filegroup. It is no different than if we took a file backup and explicitly referenced each data file in that group. They are the exact same backup and have no differences. This is why you may hear the term file backup used instead of filegroup backup. We will use the term file backup for the rest of this chapter. Of course, the effectiveness of file backups depends on these large databases being designed so that there is, as best as can be achieved, a distribution of data across the data files and filegroups such that the file backups are manageable and can complete in the required time frame. For example, if we have a database of 900 GB, split across three 304 305 Chapter 9: File and Filegroup Backup and Restore file groups, then ideally each filegroup will be a more manageable portion of the total size. Depending on which tables are stored where, this ideal data distribution may not be possible, but if one of those groups is 800 GB, then we might as well just take full database backups. For reasons that we'll discuss in more detail in relation to file restores, it's essential, when adopting a backup strategy based on file backups, to also take transaction log backups. It's not possible to perform file-based restores unless SQL Server has access to the full set of accompanying transaction logs. The file backups can and will be taken at different times, and SQL Server needs the subsequent transaction log backups in order to guarantee its ability to roll forward each individual file backup to the required point, and so restore the database, as a whole, to a consistent state. File backups and read-only filegroups The only time we don't have to apply a subsequent transaction log backup when restoring a file backup, is when SQL Server knows for a fact that the data file could not have been modified since the backup was taken, because the backup was of a filegroup explicitly designated as READ_ONLY). We'll cover this in more detail in Chapter 10, Partial Backup and Restore. So, for example, if we take a weekly full file backup of a particular file or filegroup, then in the event of a failure of that file, we'd potentially need to restore the file backup plus a week's worth of log files, to get our database back online in a consistent state. As such, it often makes sense to supplement occasional full file backups with more frequent differential file backups. In the same way as differential database backups, these differential file backups can dramatically reduce the number of log files that need processing in a recovery situation. In coming sections, we'll first demonstrate how to take file backups using both the SSMS GUI and native T-SQL scripts. We'll take full file backups via the SSMS GUI, and then differential file backups using T-SQL scripts. We'll then demonstrate how to perform the same actions using the Red Gate SQL Backup tool. 305 306 Chapter 9: File and Filegroup Backup and Restore Note that it is recommended, where possible, to take a full database backup and start the log backups, before taking the first file backup (see: en-us/library/ms aspx). We'll discuss this in more detail shortly, but note that, in order to focus purely on the logistics of file backups, we don't follow this advice in our examples. Preparing for file backups Before we get started taking file backups, we need to do the usual preparatory work, namely choosing an appropriate recovery model for our database, and then creating that database along with some populated sample tables. Since we've been through this process many times now, I'll only comment on those parts of the scripts that are substantially different from what has gone before. Please refer back to Chapters 3 and 5 if you need further explanation of any other aspects of these scripts. Recovery model Since we've established the need to take log backups, we will need to operate the database in FULL recovery model. We can also take log backups in the BULK_LOGGED model but, as discussed in Chapter 1, this model is only suitable for short-term use during bulk operations. For the long-term operation of databases requiring file backups, we should be using the FULL recovery model. Sample database and tables plus initial data load Listing 9-6 shows the script to create a database with both a PRIMARY and a SECONDARY filegroup, and one data file in each filegroup. Again, note that I've used the same drive for each filegroup and the log file, purely as a convenience for this demo; in reality, they would be on three different drives, as demonstrated previously in Listing 307 Chapter 9: File and Filegroup Backup and Restore USE [master] CREATE DATABASE [DatabaseForFileBackups] ON PRIMARY ( NAME = N'DatabaseForFileBackups', FILENAME = N'C:\SQLData\DatabaseForFileBackups.mdf', SIZE = 10240KB, FILEGROWTH = 10240KB ), FILEGROUP [SECONDARY] ( NAME = N'DatabaseForFileBackups_Data2', FILENAME = N'C:\SQLData\DatabaseForFileBackups_Data2.ndf', SIZE = 10240KB, FILEGROWTH = 10240KB ) LOG ON ( NAME = N'DatabaseForFileBackups_log', FILENAME = N'C:\SQLData\DatabaseForFileBackups_log.ldf', SIZE = 10240KB, FILEGROWTH = 10240KB ) ALTER DATABASE [DatabaseForFileBackups] SET RECOVERY FULL Listing 9-6: Multiple data file database creation script. The big difference between this database creation script, and any that have gone before, is that we're creating two data files: a primary (mdf) data file called DatabaseForFile- Backups, in the PRIMARY filegroup, and a secondary (ndf) data file called Database- ForFileBackups_Data2 in a user-defined filegroup called SECONDARY. This name is OK here, since we will be storing generic data in the second filegroup, but if the filegroup was designed to store a particular type of data then it should be named appropriately to reflect that. For example, if creating a secondary filegroup that will group together files used to store configuration information for an application, we could name it CONFIGURATION. Listing 9-7 creates two sample tables in our DatabaseForFileBackups database, with Table_DF1 stored in the PRIMARY filegroup and Table_DF2 stored in the SECONDARY filegroup. We then load a single initial row into each table. 307 308 Chapter 9: File and Filegroup Backup and Restore USE [DatabaseForFileBackups] CREATE TABLE dbo.table_df1 ( Message NVARCHAR(50) NOT NULL ) ON [PRIMARY] CREATE TABLE dbo.table_df2 ( Message NVARCHAR(50) NOT NULL ) ON [SECONDARY] INSERT INTO Table_DF1 VALUES ( 'This is the initial data load for the table' ) INSERT INTO Table_DF2 VALUES ( 'This is the initial data load for the table' ) Listing 9-7: Table creation script and initial data load for file backup configuration. Notice that we specify the filegroup for each table as part of the table creation statement, via the ON keyword. SQL Server will create a table on whichever of the available filegroups is marked as the default group. Unless specified otherwise, the default group will be the PRIMARY filegroup. Therefore, the ON PRIMARY clause, for the first table, is optional, but the ON SECONDARY clause is required. In previous chapters, we've used substantial data loads in order to capture meaningful metrics for backup time and file size. Here, we'll not be gathering these metrics, but rather focusing on the complexities of the backup (and restore) processes, so we're keeping row counts very low. 308 309 Chapter 9: File and Filegroup Backup and Restore SSMS native full file backups We're going to perform full file backups of each of our data files for the Database- ForFileBackups database, via the SSMS GUI. So, open up SSMS, connect to your test server, and bring up the Back Up Database configuration screen. In the Backup component section of the screen, select the Files and filegroups radio button and it will instantly bring up a Select Files and Filegroups window. We want to back up all the files (in this case only one file) in the PRIMARY filegroup, so tick the PRIMARY box, so the screen looks as shown in Figure 9-1, and click OK. Figure 9-1: Selecting the files to include in our file backup operation. 309 310 Chapter 9: File and Filegroup Backup and Restore Following the convention used throughout the book, we're going to store the backup files in C:\SQLBackups\Chapter9, so go ahead and create that subfolder on your database server, and then, in the Backup wizard, Remove the default backup destination, click Add, locate the Chapter9 folder and call the backup file DatabaseForFileBackups_ FG1_Full.bak. Once back on the main configuration page, double-check that everything on the screen looks as expected and if so, we have no further work to do, so we can click OK to start the file backup operation. It should complete in the blink of an eye, and our first file/filegroup backup is complete! We aren't done yet, however. Repeat the whole file backup process exactly as described previously but, this time, pick the SECONDARY filegroup in the Select Files and Filegroups window and, when setting the backup file destination, call the backup file Database- ForFileBackups_FG2_Full.bak. Having done this, check the Chapter9 folder and you should find your two backup files, ready for use later in the chapter. We've completed our file backups, but we're still not quite done here. In order to be able to restore a database from its component file backups, we need to be able to apply transaction log backups so that SQL Server can confirm that it is restoring the database to a consistent state. So, we are going to take one quick log backup file. Go back into the Back Up Database screen a third time, select Transaction Log as the Backup type, and set the backup file destination as C:\SQLBackups\Chapter9\DatabaseForFileBackups_ TLOG.trn. Native T-SQL file differential backup We're now going to perform differential file backups of each of our data files for the DatabaseForFileBackups database, using T-SQL scripts. First, let's load another row of sample data into each of our tables, as shown in Listing 311 Chapter 9: File and Filegroup Backup and Restore USE [DatabaseForFileBackups] INSERT INTO Table_DF1 VALUES ( 'This is the second data load for the table' ) INSERT INTO Table_DF2 VALUES ( 'This is the second data load for the table' ) Listing 9-8: Second data load for DatabaseForFileBackups. Without further ado, the script to perform a differential file backup of our primary data file is shown in Listing 9-9. USE [master] BACKUP DATABASE [DatabaseForFileBackups] FILE = N'DatabaseForFileBackups' TO DISK = N'C:\SQLBackups\Chapter9\DatabaseForFileBackups_FG1_Diff.bak' WITH DIFFERENTIAL, STATS = 10 Listing 9-9: Differential file backup of the primary data file for DatabaseForFileBackups. The only new part of this script is the use of the FILE argument to specify which of the data files to include in the backup. In this case, we've referenced by name our primary data file, which lives in the PRIMARY filegroup. We've also used the DIFFERENTIAL argument to specify a differential backup, as described in Chapter 7. Go ahead and run the script now and you should see output similar that shown in Figure 312 Chapter 9: File and Filegroup Backup and Restore Figure 9-2: File differential backup command results. What we're interested in here are the files that were processed during the execution of this command. You can see that we only get pages processed on the primary data file and the log file. This is exactly what we were expecting, since this is a differential file backup, capturing the changed data in the primary data file, and not a differential database backup. If we had performed a differential (or full) database backup on a database that has multiple data files, then all those files will be processed as part of the BACKUP command and we'd capture all data changed in all of the data files. So, in this case, it would have processed both the data files and the log file. Let's now perform a differential file backup of our secondary data file, as shown in Listing USE [master] BACKUP DATABASE [DatabaseForFileBackups] FILEGROUP = N'SECONDARY' TO DISK = N'C:\SQLBackups\Chapter9\DatabaseForFileBackups_FG2_Diff.bak' WITH DIFFERENTIAL, STATS = 10 Listing 9-10: Differential filegroup backup for DatabaseForFileBackups. 312 313 Chapter 9: File and Filegroup Backup and Restore This time, the script demonstrates the use of the FILEGROUP argument to take a backup of the SECONDARY filegroup as a whole. Of course, in this case there is only a single data file in this filegroup and so the outcome of this command will be exactly the same as if we had specified FILE = N'DatabaseForFileBackups_Data2' instead. However, if the SECONDARY filegroup had contained more than one data file, then all of these files would have been subject to a differential backup. If you look at the message output, after running the command, you'll see that only the N'DatabaseForFileBackups_Data2 data file and the log file are processed. Now we have a complete set of differential file backups that we will use to restore the database a little later. However, we are not quite done. Since we took the differential backups at different times, there is a possible issue with the consistency of the database, so we still need to take another transaction log backup. In Listing 9-11, we first add one more row each to the two tables and capture a date output (we'll need this later in a point-in-time restore demo) and then take another log backup. USE [master] INSERT INTO DatabaseForFileBackups.dbo.Table_DF1 VALUES ( 'Point-in-time data load for Table_DF1' ) INSERT INTO DatabaseForFileBackups.dbo.Table_DF2 VALUES ( 'Point-in-time data load for Table_DF2' ) SELECT GETDATE() -- note the date value. We will need it later. BACKUP LOG [DatabaseForFileBackups] TO DISK = N'C:\SQLBackups\Chapter9\DatabaseForFileBackups_TLOG2.trn' Listing 9-11: Taking our second native transaction log backup. 313 314 Chapter 9: File and Filegroup Backup and Restore SQL Backup file backups Let's take a quick look at how to capture both types of file backup, full and differential, via the Red Gate SQL Backup tool. I assume basic familiarity with the tool, based on the coverage provided in the previous chapter, and so focus only on aspects of the process that are different from what has gone before, with database backups. We're going to take a look at file backups using SQL Backup scripts only, and not via the SQL Backup GUI. There are a couple of reasons for this: the version of SQL Backup (6.4) that was used in this book did not support differential file backups via the GUI assuming that, if you worked through Chapter 8, you are now comfortable using the basic SQL Backup functionality, so you don't need to see both methods. To get started, we'll need a new sample database on which to work. We can simply adapt the database creation script in Listing 9-6 to create a new, identically-structured database, called DatabaseForFileBackup_SB and then use Listing 9-7 to create the tables and insert the initial row. Alternatively, the script to create the database and tables, and insert the initial data, is provided ready-made (DatabaseForFileBackup_SB.sql) in code download for this book, at ShawnMcGehee/SQLServerBackupAndRestore_Code.zip. SQL Backup full file backups Having created the sample database and tables, and loaded some initial data, let's jump straight in and take a look at the script to perform full file backups of both the PRIMARY and SECONDARY data files, as shown in Listing 315 Chapter 9: File and Filegroup Backup and Restore USE [master] --SQL Backup Full file backup of PRIMARY filegroup EXECUTE master..sqlbackup '-SQL "BACKUP DATABASE [DatabaseForFileBackups_SB] FILEGROUP = ''PRIMARY'' TO DISK = ''C:\SQLBackups\Chapter9\DatabaseForFileBackups_SB.sqb'' WITH DISKRETRYINTERVAL = 30, DISKRETRYCOUNT = 10, COMPRESSION = 3, THREADCOUNT = 2"' --SQL Backup Full file backup of secondary data file EXECUTE master..sqlbackup '-SQL "BACKUP DATABASE [DatabaseForFileBackups_SB] FILE = ''DatabaseForFileBackups_SB_Data2'' TO DISK = ''C:\SQLBackups\Chapter9\DatabaseForFileBackups_SB_Data2.sqb'' WITH DISKRETRYINTERVAL = 30, DISKRETRYCOUNT = 10, COMPRESSION = 3, THREADCOUNT = 2"' Listing 9-12: SQL Backup full file backup of primary and secondary data files. Most of the details of this script, with regard to the SQL Backup parameters that control the compression and resiliency options, have been covered in detail in Chapter 8, so I won't repeat them here. We can see that we are using the FILEGROUP parameter here to perform the backup against all files in our PRIMARY filegroup. Since this filegroup includes just our single primary data file, we could just as well have specified the file explicitly, which is the approach we take when backing up the secondary data file. Having completed the full file backups, we are going to need to take a quick log backup of this database, just as we did with the native backups, in order to ensure we can restore the database to a consistent state, from the component file backups. Go ahead and run Listing 9-13 in a new query window to get a log backup of our DatabaseForFile- Backups_SB test database. USE [master] EXECUTE master..sqlbackup '-SQL "BACKUP LOG [DatabaseForFileBackups_SB] TO DISK = ''C:\SQLBackups\Chapter9\DatabaseForFileBackups_SB_TLOG.sqb''"' Listing 9-13: Taking our log backup via SQL Backup script. 315 316 Chapter 9: File and Filegroup Backup and Restore SQL Backup differential file backups The SQL Backup commands for differential file backups are very similar to those for the full file backups, so we'll not dwell long here. First, we need to insert a new row into each of our sample tables, as shown in Listing USE [DatabaseForFileBackups_SB] INSERT INTO Table_DF1 VALUES ( 'This is the second data load for the table' ) INSERT INTO Table_DF2 VALUES ( 'This is the second data load for the table' ) Listing 9-14: Second data load for DatabaseForFileBackups_SB. Next, Listing 9-15 shows the script to perform the differential file backups for both the primary and secondary data files. USE [master] EXECUTE master..sqlbackup '-SQL "BACKUP DATABASE [DatabaseForFileBackups_SB] FILEGROUP = ''PRIMARY'' TO DISK = ''C:\SQLBackups\Chapter9\DatabaseForFileBackups_SB_Diff.sqb'' WITH DIFFERENTIAL, DISKRETRYINTERVAL = 30, DISKRETRYCOUNT = 10, COMPRESSION = 3, THREADCOUNT = 2"' EXECUTE master..sqlbackup '-SQL "BACKUP DATABASE [DatabaseForFileBackups_SB] FILE = ''DatabaseForFileBackups_SB_Data2'' TO DISK = ''C:\SQLBackups\Chapter9\DatabaseForFileBackups_SB_Data2_Diff.sqb'' WITH DIFFERENTIAL, DISKRETRYINTERVAL = 30, DISKRETRYCOUNT = 10, COMPRESSION = 3, THREADCOUNT = 2"' Listing 9-15: SQL Backup differential file backup of primary and secondary data files. 316 317 Chapter 9: File and Filegroup Backup and Restore The only significant difference in this script compared to the one for the full file backups, apart from the different backup file names, is use of the DIFFERENTIAL argument to denote that the backups should only take into account the changes made to each file since the last full file backup was taken. Take a look at the output for this script, shown in truncated form in Figure 9-3; the first of the two SQL Backup operations processes the primary data file (DatabaseForFile- Backups), and the transaction log, and the second processes the secondary data file (DatabaseForFileBackups_Data2) plus the transaction log. Backing up DatabaseForFileBackups_SB (files/filegroups differential) to: C:\SQLBackups\Chapter9\DatabaseForFileBackups_SB_Diff.sqb Backup data size : MB Compressed data size: KB Compression rate : 98.33% Processed 56 pages for database 'DatabaseForFileBackups_SB', file 'DatabaseForFileBackups_SB' on file 1. Processed 2 pages for database 'DatabaseForFileBackups_SB', file 'DatabaseForFileBackups_SB_log' on file 1. BACKUP DATABASE...FILE=<name> WITH DIFFERENTIAL successfully processed 58 pages in seconds ( MB/sec). SQL Backup process ended. Figure 9-3: SQL Backup differential file backup results. Having completed the differential file backups, we do need to take one more backup and I think you can guess what it is. Listing 9-16 takes our final transaction log backup of the chapter. USE [master] EXECUTE master..sqlbackup '-SQL "BACKUP LOG [DatabaseForFileBackups_SB] TO DISK = ''C:\SQLBackups\Chapter9\DatabaseForFileBackups_SB_TLOG2.sqb''"' Listing 9-16: Second SQL Backup transaction log backup. 317 318 Chapter 9: File and Filegroup Backup and Restore File Restore In all previous chapters, when we performed a restore operation, we restored the database as a whole, including all the data in all the files and filegroups, from the full database backup, plus any subsequent differential database backups. If we then wished to roll forward the database, we could do so by applying the full chain of transaction log backups. However, it is also possible to restore a database from a set individual file backups; the big difference is that that we can't restore a database just from the latest set of full (plus differential) file backups. We must also apply the full set of accompanying transaction log backups, up to and including the log backup taken after the final file backup in the set. This is the only way SQL Server can guarantee that it can restore the database to a consistent state. Consider, for example, a simple case of a database comprising three data files, each in a separate filegroup and where FG1_1, FG2_1, FG3_1 are full files backups of each separate filegroup, as shown in Figure 9-4. Figure 9-4: A series of full file and transaction log backups. 318 319 Chapter 9: File and Filegroup Backup and Restore Notice that the three file backups are taken at different times. In order to restore this database, using backups shown, we have to restore the FG1_1, FG2_1 and FG3_1 file backups, and then the chain of log backups 1 5. Generally speaking, we need the chain of log files starting directly after the oldest full file backup in the set, and finishing with the one taken directly after the most recent full file backup. Note that even if we are absolutely certain that in Log5 no further transactions were recorded against any of the three filegroups, SQL Server will not trust us on this and requires this log backup file to be processed in order to guarantee that any changes recorded in Log5 that were made to any of the data files, up to the point the FG3_1 backup completed, are represented in the restore, and so the database has transactional consistency. We can also perform point-in-time restores, to a point within the log file taken after all of the current set of file backups; in Figure 9-4, this would be to some point in time within the Log5 backup. If we wished to restore to a point in time within, say, Log4, we'd need to restore the backup for filegroup 3 taken before the one shown in Figure 9-4 (let's call it FG3_0), followed by FG1_1 and FG2_1, and then the chain of logs, starting with the one taken straight after FG3_0 and ending with Log4. This also explains why Microsoft recommends taking an initial full database backup and starting the log backup chain before taking the first full file backup. If we imagine that FG1_1, FG2_1 and FG3_1 file backups were the first-ever full file backups for this database, and that they were taken on Monday, Wednesday and Friday, then we'd have no restore capability in that first week, till the FG3_1 and Log5 backups were completed. It's possible, in some circumstances, to restore a database by restoring only a single file backup (plus required log backups), rather than the whole set of files that comprise the database. This sort of restore is possible as long as you've got a database composed of several data files or filegroups, regardless of whether you're taking database or file backups; as long as you've also got the required set of log backups, it's possible to restore a single file from a database backup. 319 320 Chapter 9: File and Filegroup Backup and Restore The ability to recover a database by restoring only a subset of the database files can be very beneficial. For example, if a single data file for a VLDB goes offline for some reason, we have the ability to restore from file backup just the damaged file, rather than restoring the entire database. With a combination of the file backup, plus the necessary transaction log backups, we can get that missing data file back to the state it was in as close as possible to the time of failure, and much quicker than might be possible if we needed to restore the whole database from scratch! With Enterprise Edition SQL Server, as discussed earlier, we also have the ability to perform online piecemeal restores, where again we start by restoring just a subset of the data files, in this case the primary filegroup, and then immediately bringing the database online having recovered only this subset of the data. As you've probably gathered, restoring a database from file backups, while potentially very beneficial in reducing down-time, can be quite complex and can involve managing and processing a large number of backup files. The easiest way to get a grasp of how the various types of file restore work is by example. Therefore, over the following sections, we'll walk though some examples of how to perform, with file backups, the same restore processes that we've seem previously in the book, namely a complete restore and a pointin-time restore. We'll then take a look at an example each of recovering from a "single data file failure," as well as online piecemeal restore. We're not going to attempt to run through each type of restore in four different ways (SSMS, T-SQL, SQL Backup GUI, SQL Backup T-SQL), as this would simply get tedious. We'll focus on scripted restores using either native T-SQL or SQL Backup T-SQL, and leave the equivalent restores, via GUI methods, as an exercise for the reader. It's worth noting, though, that whereas for database backups the SQL Backup GUI will automatically detect all required backup files (assuming they are still in their original locations), it will not do so for file backups; each required backup file will need to be located manually. 320 321 Chapter 9: File and Filegroup Backup and Restore Performing a complete restore (native T-SQL) We're going to take a look at an example of performing a complete restore of our DatabaseForFileBackups database. Before we start, let's insert a third data load, as shown in Listing 9-17, just so we have one row in each of the tables in the database that isn't yet captured in any of our backup files. USE [DatabaseForFileBackups] INSERT INTO Table_DF1 VALUES ( 'This is the third data load for the table' ) INSERT INTO Table_DF2 VALUES ( 'This is the third data load for the table' ) Listing 9-17: Third data load for DatabaseForFileBackups. Figure 9-5 depicts the current backups we have in place. We have the first data load captured in full file backups, the second data load captured in the differential file backups, and a third data load that is not in any current backup file, but we'll need to capture it in a tail log backup in order to restore the database to its current state. In a case where we were unable to take a final tail log backup we'd only be able to roll forward to the end of the TLOG2 backup. In this example, we are going to take one last backup, just to get our complete database back intact. 321 322 Chapter 9: File and Filegroup Backup and Restore Figure 9-5: Required backups for our complete restore of DatabaseForFileBackups. The first step is to capture that tail log backup, and prepare for the restore process, as shown in Listing USE master --backup the tail BACKUP LOG [DatabaseForFileBackups] TO DISK = N'C:\SQLBackups\Chapter9\DatabaseForFileBackups_TLOG_TAIL.trn' WITH NORECOVERY Listing 9-18: Tail log backup. Notice the use of the NORECOVERY option in a backup; this lets SQL Server know that we want to back up the transactions in the log file and immediately place the database into a restoring state. This way, no further transactions can slip past us into the log while we are preparing the RESTORE command. We're now ready to start the restore process. The first step is to restore the two full file backups. We're going to restore over the top of the existing database, as shown in Listing 323 Chapter 9: File and Filegroup Backup and Restore Listing 9-19: Restoring the full file backups. Processed 184 pages for database 'DatabaseForFileBackups', file 'DatabaseForFileBackups' on file 1. Processed 6 pages for database 'DatabaseForFileBackups', file 'DatabaseForFileBackups_log' on file 1. The roll forward start point is now at log sequence number (LSN) Additional roll forward past LSN is required to complete the restore sequence. This RESTORE statement successfully performed some actions, but the database could not be brought online because one or more RESTORE steps are needed. Previous messages indicate reasons why recovery cannot occur at this point. RESTORE DATABASE... FILE=<name> successfully processed 190 pages in seconds ( MB/sec). Processed 16 pages for database 'DatabaseForFileBackups', file 'DatabaseForFileBackups_Data2' on file 1. Processed 2 pages for database 'DatabaseForFileBackups', file 'DatabaseForFileBackups_log' on file 1. RESTORE DATABASE... FILE=<name> successfully processed 18 pages in seconds (1.274 MB/sec). Figure 9-6: Output message from restoring the full file backups. Notice that we didn't specify the state to which to return the database after the first RESTORE command. By default this would attempt to bring the database back online, with recovery, but in this case SQL Server knows that there are more files to process, so it 323 324 Chapter 9: File and Filegroup Backup and Restore keeps the database in a restoring state. The first half of the message output from running this command, shown in Figure 9-6, tells us that the roll forward start point is at a specific LSN number but that an additional roll forward is required and so more files will have to be restored to bring the database back online. The second part of the message simply reports that the restore of the backup for the secondary data file was successful. Since we specified that the database should be left in a restoring state after the second restore command, SQL Server doesn't try to recover the database to a usable state (and is unable to do so). If you check your Object Explorer in SSMS, you'll see that Database- ForFileBackups is still in a restoring state. After the full file backups, we took a transaction log backup (_TLOG), but since we're rolling forward past the subsequent differential file backups, where any data changes will be captured for each filegroup, we don't need to restore the first transaction log, on this occasion. So, let's go ahead and restore the two differential file backups, as shown in Listing USE master Listing 9-20: Restore the differential file backups. 324 325 Chapter 9: File and Filegroup Backup and Restore The next step is to restore the second transaction log backup (_TLOG2), as shown in Listing When it comes to restoring the transaction log backup files, we need to specify NORECOVERY on all of them except the last. The last group of log backup files we are restoring (represented by only a single log backup in this example!) may be processing data for all of the data files and, if we do not specify NORECOVERY, we can end up putting the database in a usable state for the user, but unable to apply the last of the log backup files. USE master RESTORE DATABASE [DatabaseForFileBackups] FROM DISK = N'C:\SQLBackups\Chapter9\DatabaseForFileBackups_TLOG2.trn' WITH NORECOVERY Listing 9-21: Restore the second log backup. Finally, we need to apply the tail log backup, where we know our third data load is captured, and recover the database. RESTORE DATABASE [DatabaseForFileBackups] FROM DISK = N'C:\SQLBackups\Chapter9\DatabaseForFileBackups_TLOG_TAIL.trn' WITH RECOVERY Listing 9-22: Restore the tail log backup and recover the database. A simple query of the restored database will confirm that we've restored the database, with all the rows intact. USE [DatabaseForFileBackups] SELECT * FROM Table_DF1 SELECT * FROM Table_DF2 325 326 Chapter 9: File and Filegroup Backup and Restore Message This is the initial data load for the table This is the second data load for the table This is the point-in-time data load for the table This is the third data load for the table (4 row(s) affected) Message This is the initial data load for the table This is the second data load for the table This is the point-in-time data load for the table This is the third data load for the table (4 row(s) affected) Listing 9-23: Verifying the restored data. Restoring to a point in time (native T-SQL) Listing 9-24 shows the script to restore our DatabaseForFileBackups to a point in time either just before, or just after, we inserted the two rows in Listing 326 327 Chapter 9: File and Filegroup Backup and Restore RESTORE DATABASE [DatabaseForFileBackups] FROM DISK = N'C:\SQLBackups\Chapter9\DatabaseForFileBackups_TLOG2.trn' WITH RECOVERY, STOPAT = ' T13:18:00' -- enter your time here Listing 9-24: Filegroup restore to a point in time. Notice that we include the REPLACE keyword in the first restore, since we are trying to replace the database and in this case aren't starting with a tail log backup, and there may be transactions in the log that haven't been backed up yet. We then restore the second full file backup and the two differential file backups, leaving the database in a restoring state each time. Finally, we restore the second transaction log backup, using the STOPAT parameter to indicate the time to which we wish to restore the database. In my example, I set the time for the STOPAT parameter to be about 30 seconds before the two INSERTs were executed, and Listing 9-25 confirms that only the first two data loads are present in the restored database. 327 328 Chapter 9: File and Filegroup Backup and Restore USE DatabaseForFileBackups SELECT * FROM dbo.table_df1 SELECT * FROM dbo.table_df2 Message This is the initial data load for the table This is the second data load for the table (2 row(s) affected) Message This is the initial data load for the table This is the second data load for the table (2 row(s) affected) Listing 9-25: Checking on the point-in-time restore data. Great! We can see that our data is exactly what we expected. We have restored the data to the point in time exactly where we wanted. In the real world, you would be restoring to a point in time before a disaster struck or when data was somehow removed or corrupted. Restoring after loss of a secondary data file One of the major potential benefits of file-based restore, especially for VLDBs, is the ability to restore just a single data file, rather than the whole database, in the event of a disaster. Let's imagine that we have a VLDB residing on one of our most robust servers. Again, this VLDB comprises three data files in separate filegroups that contain completely different database objects and data, with each file located on one of three separate physical hard drives in our SAN attached drives. 328 329 Chapter 9: File and Filegroup Backup and Restore Everything is running smoothly, and we get great performance for this database until our SAN suddenly suffers a catastrophic loss on one of its disk enclosures and we lose the drive holding one of the secondary data files. The database goes offline. We quickly get a new disk attached to our server, but the secondary data file is lost and we are not going to be able to get it back. As this point, all of the tables and data in that data file will be lost but, luckily, we have been performing regular full file, differential file, and transaction log backups of this database, and if we can capture a final tail-of-thelog backup, we can get this database back online using only the backup files for the lost secondary data file, plus the necessary log files, as shown in Figure 9-7. Figure 9-7: Example backups required to recover a secondary data file. In order to get the lost data file back online, with all data up to the point of the disk crash, we would: perform a tail log backup this requires a special form of log backup, which does not truncate the transaction log restore the full file backup for the lost secondary data file restore the differential file backup for the secondary data file, at which point SQL Server would expect to be able to apply log backups 3 and 4 plus the tail log backup recover the database. 329 330 Chapter 9: File and Filegroup Backup and Restore Once you do this, your database will be back online and recovered up to the point of the failure! This is a huge time saver since restoring all of the files could take quite a long time. Having to restore only the data file that was affected by the crash will cut your recovery time down significantly. However, there are a few caveats attached to this technique, which we'll discuss as we walk through a demo. Specifically, we're going to use SQL Backup scripts (these can easily be adapted into native T-SQL scripts) to show how we might restore just a single damaged, or otherwise unusable, secondary data file for our DatabaseForFile- Backups_SB database, without having to restore the primary data file. Note that if the primary data file went down, we'd have to restore the whole database, rather than just the primary data file. However, with Enterprise Edition SQL Server, it would be possible to get the database back up and running by restoring only the primary data file, followed subsequently by the other data files. We'll discuss that in more detail in the next section. This example is going to use our DatabaseForFileBackups_SB database to restore from a single disk / single file failure, using SQL Backup T-SQL scripts. A script demonstrating the same process using native T-SQL is available with the code download for this book. If you recall, for this database we have Table_DF1, stored in the primary data file (DatabaseForFileBackups_SB.mdf) in the PRIMARY filegroup, and Table_DF2, stored in the secondary data file (DatabaseForFileBackups_SB_Data2.ndf) in the SECONDARY filegroup. Our first data load (one row into each table) was captured in full file backups for each filegroup. We then captured a first transaction log backup. Our second data load (an additional row into each table) was captured in differential file backups for each filegroup. Finally, we took a second transaction log backup. Let's perform a third data load, inserting one new row into Table_DF2. 330 331 Chapter 9: File and Filegroup Backup and Restore USE [DatabaseForFileBackups_SB] INSERT INTO Table_DF2 VALUES ( 'This is the third data load for Table_DF2' ) Listing 9-26: Third data load for DatabaseForFileBackups_SB. Now we're going to simulate a problem with our secondary data file which takes it (and our database) offline; in Listing 9-27 we take the database offline. Having done so, navigate to the C:\SQLData\Chapter9 folder and delete the secondary data file! -- Take DatabaseForFileBackups_SB offline USE master ALTER DATABASE [DatabaseForFileBackups_SB] SET OFFLINE; /*Now delete DatabaseForFileBackups_SB_Data2.ndf!*/ Listing 9-27: Take DatabaseForFileBackups_SB offline and delete secondary data file! Scary stuff! Next, let's attempt to bring our database back online. USE master ALTER DATABASE [DatabaseForFileBackups_SB] SET ONLINE; Msg 5120, Level 16, State 5, Line 1 Unable to open the physical file "C:\SQLData\DatabaseForFileBackups_SB_Data2.ndf". Operating system error 2: "2(failed to retrieve text for this error. Reason: 15105)". Msg 945, Level 14, State 2, Line 1 Database 'DatabaseForFileBackups_SB' cannot be opened due to inaccessible files or insufficient memory or disk space. See the SQL Server errorlog for details. Msg 5069, Level 16, State 1, Line 1 ALTER DATABASE statement failed. Listing 9-28: Database cannot come online due to missing secondary data file. 331 332 Chapter 9: File and Filegroup Backup and Restore As you can see, this is unsuccessful, as SQL Server can't open the secondary data file. Although unsuccessful, this attempt to bring the database online is still necessary, as we need the database to attempt to come online, so the log file can be read. We urgently need to get the database back online, in the state it was in when our secondary file failed. Fortunately, the data and log files are on separate drives from the secondary, so these are still available. We know that there is data in the log file that isn't captured in any log backup, so our first task is to back up the log. Unfortunately, a normal log backup operation, such as shown in Listing 9-29 will not succeed. -- a normal tail log backup won't work USE [master] EXECUTE master..sqlbackup '-SQL "BACKUP LOG [DatabaseForFileBackups_SB] TO DISK = ''C:\SQLBackups\Chapter9\DatabaseForFileBackups_SB_TLOG_TAIL.sqb'' WITH NORECOVERY"' Listing 9-29: A standard tail log backup fails. In my tests, this script just hangs and has to be cancelled, which is unfortunate. The equivalent script in native T-SQL results in an error message to the effect that: "Database 'DatabaseForFileBackups_SB' cannot be opened due to inaccessible files or insufficient memory or disk space." SQL Server cannot back up the log this way because the log file is not available and part of the log backup process, even a tail log backup, needs to write some log info into the database header. Since it cannot, we need to use a different form of tail backup to get around this problem. 332 333 Chapter 9: File and Filegroup Backup and Restore What we need to do instead, is a special form of tail log backup that uses the NO_ TRUNCATE option, so that SQL Server can back up the log without access to the data files. In this case the log will not be truncated upon backup, and all log records will remain in the live transaction log. Essentially, this is a special type of log backup and isn't going to remain useful to us after this process is over. When we do get the database back online and completely usable, we want to be able to take a backup of the log file in its original state and not break the log chain. In other words, once the database is back online, we can take another log backup (TLOG3, say) and the log chain will be TLOG2 followed by TLOG3 (not TLOG2, TLOG_TAIL, TLOG3). I would, however, suggest attempting to take some full file backups immediately after a failure, if not a full database backup, if that is at all possible. USE [master] EXECUTE master..sqlbackup '-SQL "BACKUP LOG [DatabaseForFileBackups_SB] TO DISK = ''C:\SQLBackups\Chapter9\DatabaseForFileBackups_SB_TLOG_TAIL.sqb'' WITH NO_TRUNCATE"' Listing 9-30: Performing a tail log backup with NO_TRUNCATE for emergency single file recovery. Note that if we cannot take a transaction log backup before starting this process, we cannot get our database back online without restoring all of our backup files. This process will only work if we lose a single file from a drive that does not also house the transaction log. Now that we have our tail log backup done, we can move on to recovering our lost secondary data file. The entire process is shown in Listing You will notice that there are no backups in this set of RESTORE commands that reference our primary data file. This data would have been left untouched and doesn't need to be restored. Having to restore only the lost file will save us a great deal of time. 333 334 Chapter 9: File and Filegroup Backup and Restore USE [master] -- restore the full file backup for the secondary data file EXECUTE master..sqlbackup '-SQL "RESTORE DATABASE [DatabaseForFileBackups_SB] FILE = ''DatabaseForFileBackups_SB_Data2'' FROM DISK = ''C:\SQLBackups\Chapter9\DatabaseForFileBackups_SB_Data2.sqb'' WITH NORECOVERY"' -- restore the differential file backup for the secondary data file EXECUTE master..sqlbackup '-SQL "RESTORE DATABASE [DatabaseForFileBackups_SB] FILE = ''DatabaseForFileBackups_SB_Data2'' FROM DISK = ''C:\SQLBackups\Chapter9\DatabaseForFileBackups_SB_Data2_Diff.sqb'' WITH NORECOVERY"' -- restore the subsequent transaction log backup EXECUTE master..sqlbackup '-SQL "RESTORE DATABASE [DatabaseForFileBackups_SB] FROM DISK = ''C:\SQLBackups\Chapter9\DatabaseForFileBackups_SB_TLOG2.sqb'' WITH NORECOVERY"' -- restore the tail log backup and recover the database EXECUTE master..sqlbackup '-SQL "RESTORE DATABASE [DatabaseForFileBackups_SB] FROM DISK = ''C:\SQLBackups\Chapter9\DatabaseForFileBackups_SB_TLOG_TAIL.sqb'' WITH RECOVERY"' Listing 9-31: Single file disaster SQL Backup restoration script. What we have done here is restore the full file, the differential file and all of the transaction log file backups that were taken after the differential file backup, including the tail log backup. This has brought our database back online and right up to the point where the tail log backup was taken. Now you may be afraid that you didn't get to it in time and some data may be lost, but don't worry. Any transactions that would have affected the missing data file would not have succeeded after the disaster, even if the database stayed online, and any that didn't use that missing data file would have been picked up by the tail log backup. 334 335 Chapter 9: File and Filegroup Backup and Restore Quick recovery using online piecemeal restore When using SQL Server Enterprise Edition, we have access to a great feature that can save hours of recovery time in the event of a catastrophic database loss. With this edition, SQL Server allows us to perform an online restore. Using the Partial option, we can restore the primary data file of our database and bring it back online without any other data files needing to be restored. In this way, we can bring the database online and in a usable state very quickly, and then apply the rest of the backups at a later time, while still allowing users to access a subset of the data. The tables and data stored in the secondary data files will not be accessible until they are restored. The database will stay online throughout the secondary data file restores, though. This way, we can restore the most important and most used data first, and the least used, archive data for instance, later, once we have all of the other fires put out. Let's take a look at an example; again, this requires an Enterprise (or Developer) Edition of SQL Server. Listing 9-32 creates a new database, with two tables, and inserts a row of data into each of the tables. Note, of course, that in anything other than a simple test example, the primary and secondary files would be on separate disks. USE [master] CREATE DATABASE [DatabaseForPartialRestore] ON PRIMARY ( NAME = N'DatabaseForPartialRestore', FILENAME = N'C:\SQLData\DatabaseForPartialRestore.mdf', SIZE = 5120KB, FILEGROWTH = 5120KB ), FILEGROUP [Secondary] ( NAME = N'DatabaseForPartialRestoreData2', FILENAME = N'C:\SQLData\DatabaseForPartialRestoreData2.ndf', SIZE = 5120KB, FILEGROWTH = 5120KB ) LOG ON ( NAME = N'DatabaseForPartialRestore_log', FILENAME = N'C:\SQLData\DatabaseForPartialRestore_log.ldf', SIZE = 5120KB, FILEGROWTH = 5120KB ) 335 336 Chapter 9: File and Filegroup Backup and Restore USE [DatabaseForPartialRestore] IF NOT EXISTS ( SELECT name FROM sys.filegroups WHERE is_default = 1 AND name = N'Secondary' ) ALTER DATABASE [DatabaseForPartialRestore] MODIFY FILEGROUP [Secondary] DEFAULT USE [master] ALTER DATABASE [DatabaseForPartialRestore] SET RECOVERY FULL WITH NO_WAIT USE [DatabaseForPartialRestore] CREATE TABLE [dbo].[message_primary] ( [Message] [varchar](50) NOT NULL ) ON [Primary] CREATE TABLE [dbo].[message_secondary] ( [Message] [varchar](50) NOT NULL ) ON [Secondary] INSERT INTO Message_Primary VALUES ( 'This is data for the primary filegroup' ) INSERT INTO Message_Secondary VALUES ( 'This is data for the secondary filegroup' ) Listing 9-32: Creating our database and tables for testing. This script is pretty long, but nothing here should be new to you. Our new database contains both a primary and secondary filegroup, and we establish the secondary filegroup as the DEFAULT, so this is where user objects and data will be stored, unless we specify otherwise. We then switch the database to FULL recovery model just to be sure 336 337 Chapter 9: File and Filegroup Backup and Restore that we can take log backups of the database; always validate which recovery model is in use, rather than just relying on the default being the right one. Finally, we create one table in each filegroup, and insert a single row into each table. Listing 9-33 simulates a series of file and log backups on our database; we can imagine that the file backups for each filegroup are taken on successive nights, and that the log backup after each file backup represents the series of log files that would be taken during the working day. Note that, in order to keep focused, we don't start proceedings with a full database backup, as would generally be recommended. USE [master] BACKUP DATABASE [DatabaseForPartialRestore] FILEGROUP = N'PRIMARY' TO DISK = N'C:\SQLBackups\Chapter9\DatabaseForPartialRestore_FG_Primary.bak' WITH INIT BACKUP LOG [DatabaseForPartialRestore] TO DISK = N'C:\SQLBackups\Chapter9\DatabaseForPartialRestore_LOG_1.trn' WITH NOINIT BACKUP DATABASE [DatabaseForPartialRestore] FILEGROUP = N'SECONDARY' TO DISK = N'C:\SQLBackups\Chapter9\DatabaseForPartialRestore_FG_Secondary.bak' WITH INIT BACKUP LOG [DatabaseForPartialRestore] TO DISK = N'C:\SQLBackups\Chapter9\DatabaseForPartialRestore_LOG_2.trn' WITH NOINIT Listing 9-33: Taking our filegroup and log backups. 337 338 Chapter 9: File and Filegroup Backup and Restore With these backups complete, we have all the tools we need to perform a piecemeal restore! Remember, though, that we don't need to be taking file backups in order to perform a partial/piecemeal restore. If the database is still small enough, we can still take full database backups and then restore just a certain filegroup from that backup file, in the manner demonstrated next. Listing 9-34 restores just our primary filegroup, plus subsequent log backups, and then beings the database online without the secondary filegroup! USE [master] RESTORE DATABASE [DatabaseForPartialRestore] FILEGROUP = 'PRIMARY' FROM DISK = 'C:\SQLBackups\Chapter9\DatabaseForPartialRestore_FG_Primary.bak' WITH PARTIAL, NORECOVERY, REPLACE RESTORE LOG [DatabaseForPartialRestore] FROM DISK = 'C:\SQLBackups\Chapter9\DatabaseForPartialRestore_LOG_1.trn' WITH NORECOVERY RESTORE LOG [DatabaseForPartialRestore] FROM DISK = 'C:\SQLBackups\Chapter9\DatabaseForPartialRestore_LOG_2.trn' WITH RECOVERY Listing 9-34: Restoring our primary filegroup via an online piecemeal restore. Notice the use of the PARTIAL keyword to let SQL Server know that we will want to only partially restore the database, i.e. restore only the primary filegroup. We could also restore further filegroups here, but the only one necessary is the primary filegroup. Note the use of the REPLACE keyword, since we are not taking a tail log backup. Even though we recover the database upon restoring the final transaction log, we can still, in this case, restore the other data files later. The query in Listing 9-35 attempts to access data in both the primary and secondary filegroups. 338 339 Chapter 9: File and Filegroup Backup and Restore USE [DatabaseForPartialRestore] SELECT Message FROM Message_Primary SELECT Message FROM Message_Secondary Listing 9-35: Querying the restored database. The first query should return data, but the second one will fail with the following error: Msg 8653, Level 16, State 1, Line 1 The query processor is unable to produce a plan for the table or view 'Message_Secondary' because the table resides in a filegroup which is not online. This is exactly the behavior we expect, since the secondary filegroup is still offline. In a well-designed database we would, at this point, be able to access all of the most critical data, leaving just the least-used data segmented into the filegroups that will be restored later. The real bonus is that we can subsequently restore the other filegroups, while the database is up and functioning! Nevertheless, the online restore is going to be an I/O-intensive process and we would want to affect the users as little as possible, while giving as much of the SQL Server horsepower as we could to the restore. That means that it's best to wait till a time when database access is sparse before restoring the subsequent filegroups, as shown in Listing USE [master] RESTORE DATABASE [DatabaseForPartialRestore] FROM DISK = 'C:\SQLBackups\Chapter9\DatabaseForPartialRestore_FG_SECONDARY.bak' WITH RECOVERY 339 340 Chapter 9: File and Filegroup Backup and Restore RESTORE LOG [DatabaseForPartialRestore] FROM DISK = 'C:\SQLBackups\Chapter9\DatabaseForPartialRestore_LOG_2.trn' WITH RECOVERY Listing 9-36: Restoring the secondary filegroup. We restore the secondary full file backup, followed by all subsequent log backups, so that SQL Server can bring the other filegroup back online while guaranteeing relational integrity. Notice that in this case each restore is using WITH RECOVERY; in an online piecemeal restore, with the Enterprise edition, each restore leaves the database online and accessible to the end-user. The first set of restores, in Listing 9-34, used NORECOVERY, but that was just to get us to the point where the primary filegroup was online and available. All subsequent restore steps use RECOVERY. Rerun Listing 9-35, and all of the data should be fully accessible! Common Issues with File Backup and Restore What's true for any backup scheme we've covered throughout the book, involving the management of numerous backup files of different types, is doubly true for file backups: the biggest danger to the DBA is generally the loss or corruption of one of those files. Once again, the best strategy is to minimize the risk via careful planning and documentation of the backup strategy, careful storage and management of the backup files and regular, random backup verification via test restores (as described in Chapter 2). If a full file backup goes missing, or is corrupt, we'll need to start the restore from the previous good full file backup, in which case we had better have a complete chain of transaction log files in order to roll past the missing full file backup (any differentials that rely on the missing full one will be useless). 340 341 Chapter 9: File and Filegroup Backup and Restore A similar argument applies to missing differential file backups; we'll have to simply rely on the full file backup and the chain of log files. If a log file is lost, the situation is more serious. Transaction log files are the glue that holds together the other two file backup types, and they should be carefully monitored to make sure they are valid and that they are being stored locally as well as on long-term storage. Losing a transaction log backup can be a disaster if we do not have a set of full file and file differential backups that cover the time frame of the missing log backup. If a log file is unavailable or corrupt, and we really need it to complete a restore operation, we are in bad shape. In this situation, we will not be able to restore past that point in time and will have to find a way to deal with the data loss. This is why managing files carefully, and keeping a tape backup offsite is so important for all of our backup files. File Backup and Restore SLA File backup and restore will most likely be a very small part of most recoverability strategies. For most databases, the increased management responsibility of file backups will outweigh the benefits gained by adopting such a backup strategy. As a DBA, you may want to "push back" on a suggestion of this type of backup unless you judge the need to be there. If the database is too large to perform regular (e.g. nightly) full database backups and the acceptable down-time is too short to allow a full database restore, then file backups would be needed, but they should not be the norm for most DBAs. If file backups are a necessity for a given database, then the implications of this, for backup scheduling and database recovery times, need to be made clear in the SLA. Of course, as we've demonstrated, down time could in some circumstances, such as where online piecemeal restore is possible, be much shorter. As with all backup and restore SLAs, once agreed, we need to be sure that we can implement a backup and recovery strategy that will comply with the maximum tolerance to data loss and that will bring a database back online within agreed times in the event of a disaster, such as database failure or corruption. 341 342 Chapter 9: File and Filegroup Backup and Restore Considerations for the SLA agreement, for any databases requiring file backups include those shown below. Scheduling of full file backups I recommend full file backup at least once per week, although I've known cases where we had to push beyond this as it wasn't possible to get a full backup of each of the data files in that period. Scheduling of differential file backups I recommend scheduling differential backups on any day where a full file backup is not being performed. As discussed in Chapter 7, this can dramatically decrease the number of log files to be processed for a restore operation. Scheduling of transaction log backups These should be taken daily, at an interval chosen by yourself and the project manager whose group uses the database. I would suggest taking log backups of a VLDB using file backups at an interval of no more than 1 hour. Of course, if the business requires a more finely-tuned window of recoverability, you will need to shorten that schedule down to 30 or even 15 minutes, as required. Even if the window of data loss is more than 1 hour, I would still suggest taking log backups hourly. For any database, it's important to ensure that all backups are completing successfully, and that all the backup files are stored securely and in their proper location, whether on a local disk or on long-term tape storage. However, in my experience, the DBA needs to be exceptionally vigilant in this regard for databases using file backups. There are many more files involved, and a missing log file can prevent you from being able to restore a database to a consistent state. With a missing log file and in the absence of a full file or differential file backup that covers the same time period, we'd have no choice but to restore to a point in time before the missing log file was taken. These log backups are also your "backup of a backup" in case a differential or full file backup goes missing. I would suggest keeping locally at least the last two full file backups, subsequent differential file backup and all log backups spanning the entire time frame of these file backups, even after they have been written to tape and taken to offsite storage. 342 343 Chapter 9: File and Filegroup Backup and Restore It may seem like a lot of files to keep handy, but since this is one of the most file intensive types of restores, it is better to be more safe than sorry. Waiting for a file from tape storage can cost the business money and time that they don't want to lose. Restore times for any database using file backups can vary greatly, depending on the situation; sometimes we'll need to restore several, large full file backups, plus any differential backups, plus all the necessary log backups. Other times, we will only need to restore a single file or filegroup backup plus the covering transaction log backups. This should be reflected in the SLA, and the business owners and end-users should be prepared for this varying window of recovery time, in the event that a restore is required. If the estimated recovery time is outside acceptable limits for complete restore scenarios, then if the SQL Server database in question is Enterprise Edition, y consider supporting the online piecemeal restore process discussed earlier. If not, then the business owner will need to weigh up the cost of upgrading to Enterprise Edition licenses, against the cost of extended down-time in the event of a disaster. As always, the people who use the database will drive the decisions made and reflected in the SLA. They will know the fine details of how the database is used and what processes are run against the data. Use their knowledge of these details when agreeing on appropriate data loss and recovery time parameters, and on the strategy to achieve them. Forcing Failures for Fun After a number of graceful swan dives throughout this chapter, get ready for a few bellyflops! Listing 9-37 is an innocent-looking script that attempts to take a full file backup of the secondary data file of the DatabaseForFileBackups database. We've performed several such backups successfully before, so try to figure out what the problem is before you execute it. 343 344 Chapter 9: File and Filegroup Backup and Restore USE [master] BACKUP DATABASE [DatabaseForFileBackups] FILE = N'SECONDARY' TO DISK = N'C:\SQLBackups\Chapter9\DatabaseForFileBackups_FG1_Full2.bak' WITH STATS = 10 Listing 9-37: File/filegroup confusion. The error is quite subtle so, if you can't spot it, go ahead and execute the script and take a look at the error message, shown in Figure 9-8. Figure 9-8: The file "SECONDARY" is not part of the database The most revealing part of the error message here states that The file "SECONDARY" is not part of database "DatabaseForFileBackups. However, we know that the SECONDARY filegroup is indeed part of this database. The error we made was with our use of the FILE parameter; SECONDARY is the name of the filegroup, not the secondary data file. We can either change the parameter to FILEGROUP (since we only have one file in this filegroup), or we can use the FILE parameter and reference the name of the secondary data file explicitly (FILE= N'DatabaseForFileBackups_Data2'). Let's now move on to a bit of file restore-based havoc. Consider the script shown in Listing 9-38, the intent of which appears to be to restore our DatabaseForFileBackups database to the state in which it existed when we took the second transaction log backup file. 344 345 Chapter 9: File and Filegroup Backup and Restore USE [Master] RESTORE DATABASE [DatabaseForFileBackups] FILE = N'DatabaseForFileBackups' FROM DISK = N'C:\SQLBackups\Chapter9\DatabaseForFileBackups_FG1_Full.bak' WITH NORECOVERY, REPLACE RESTORE DATABASE [DatabaseForFileBackups] FILE = N'DatabaseForFileBackups_Data2' FROM DISK = N'C:\SQLBackups\Chapter9\DatabaseForFileBackups_FG2_Full.bak' WITH NORECOVERY RESTORE DATABASE [DatabaseForFileBackups] FILE = N'DatabaseForFileBackups' FROM DISK = N'C:\SQLBackups\Chapter9\DatabaseForFileBackups_FG1_Diff.bak' WITH NORECOVERY RESTORE DATABASE [DatabaseForFileBackups] FROM DISK = N'C:\SQLBackups\Chapter9\DatabaseForFileBackups_TLOG2.trn' WITH RECOVERY Listing 9-38: File restore failure. The error in the script is less subtle, and I'm hoping you worked out what the problem is before seeing the error message in Figure 9-8. Listing 9-39: The backup set is too recent 345 346 Chapter 9: File and Filegroup Backup and Restore We can see that the first three RESTORE commands executed successfully but the fourth failed, with a message stating that the LSN contained in the backup was too recent to apply. Whenever you see this sort of message, it means that a file is missing from your restore script. In this case, we forgot to apply the differential file backup for the secondary data file; SQL Server detects the gap in the LSN chain and aborts the RESTORE command, leaving the database in a restoring state. The course of action depends on the exact situation. If the differential backup file is available and you simply forgot to include it, then restore this differential backup, followed by TLOG2, to recover the database. If the differential file backup really is missing or corrupted, then you'll need to process all transaction log backups taken after the full file backup was created. In our simple example this just means TLOG and TLOG2, but in a real-world scenario this could be quite a lot of log backups. Again, hopefully this hammers home the point that it is a good idea to have more than one set of files on hand, or available from offsite storage, which could be used to bring your database back online in the event of a disaster. You never want to be in the situation where you have to lose more data than is necessary, or are not be able to restore at all. Summary In my experience, the need for file backup and restore has tended to be relatively rare, among the databases that I manage. The flipside to that is that the databases that do need them tend to be VLDBs supporting high visibility projects, and all DBAs need to make sure that they are well-versed in taking, as well as restoring databases from, the variety of file backups. File backup and restore adds considerable complexity to our disaster recovery strategy, in terms of both the number and the type of backup file that must be managed. To gain full benefit from file backup and restores, the DBA needs to give considerable thought to the file and filegroup architecture for that database, and plan the backup and restore process 346 347 Chapter 9: File and Filegroup Backup and Restore accordingly. There are an almost infinite number of possible file and filegroup architectures, and each would require a subtly different backup strategy. You'll need to create some test databases, with multiple files and filegroups, work through them, and then document your approach. You can design some test databases to use any number of data files, and then create jobs to take full file, differential file, and transaction log backups that would mimic what you would use in a production environment. Then set yourself the task of responding to the various possible disaster scenarios, and bring your database back online to a certain day, or even a point in time that is represented in one of the transaction log backup files. 347 348 Chapter 10: Partial Backup and Restore Partial the backup footprint for large databases that contain a high proportion of read-only data. After all, why would we back up the same data each night when we know that it cannot have been changed, since it was in a read-only state? We wouldn't, or shouldn't, be backing up that segment of the data on a regular schedule. In this chapter, we will discuss: why and where partial backups may be applicable in a backup and restore scheme how to perform partial and differential partial backups how to restore a database that adopts a partial backup strategy potential problems with partial backups and how to avoid them. 348 349 Chapter 10: Partial Backup and Restore Why Partial Backups? Partial backups allow us to back up, on a regular schedule, only the read-write objects and data in our databases. Any data and objects stored in read-only filegroups will not, by default, be captured in a partial backup. From what we've discussed in Chapter 9, it should be clear that we can achieve the same effect by capturing separate file backups of each of the read-write filegroups. However, suppose we have a database that does not require support for point-in-time restores; transaction log backups are required when performing file-based backups, regardless, so this can represent an unnecessarily complex backup and restore process.. So, in what situations might we want to adopt partial backups on a database in our infrastructure? Let's say we have a SQL Server-backed application for a community center and its public classes. The database holds student information, class information, grades, payment data and other data about the courses. At the end of each quarter, one set of courses completes, and a new set begins. Once all of the information for a current quarter's courses is entered into the system, the data is only lightly manipulated throughout the course lifetime. The instructor may update grades and attendance a few times per week, but the database is not highly active during the day. Once the current set of courses completes, at quarter's end, the information is archived, and kept for historical and auditing purposes, but will not be subject to any further changes. This sort of database is a good candidate for partial backups. The "live" course data will be stored in a read-write filegroup. Every three months, this data can be appended to a 349 350 Chapter 10: Partial Backup and Restore set of archive tables for future reporting and auditing, stored in a read-only filegroup (this filegroup would be switched temporarily to read-write in order to run the archive process). We can perform this archiving in a traditional data-appending manner by moving all of the data from the live tables to the archive tables, or we could streamline this process via the use of partitioning functions. Once the archive process is complete and the new course data has been imported, we can take a full backup of the whole database and store it in a safe location. From then on, we can adopt a schedule of, say, weekly partial backups interspersed with daily differential partial backups. This way we are not wasting any space or time backing up the read-only data. Also, it may well be acceptable to operate this database in SIMPLE recovery model, since we know that once the initial course data is loaded, changes to the live course data are infrequent, so an exposure of one day to potential data loss may be tolerable. In our example, taking a full backup only once every three months may seem a little too infrequent. Instead, we might consider performing a monthly full backup, to provide a little extra insurance, and simplify the restore process. Performing Partial Database Backups In most DBAs' workplaces, partial backups will be the least used of all the backup types so, rather than walk through two separate examples, one for native SQL Server backup commands and one for SQL Backup, we'll only work through an example of partial backup and restore using native T-SQL commands, since partial backups are not supported in either SSMS or in the Maintenance Plan wizard. The equivalent SQL Backup commands will be presented, but outside the context of a full worked example. 350 351 Chapter 10: Partial Backup and Restore Preparing for partial backups Listing 10-1 shows the script to create a DatabaseForPartialBackups database with multiple data files. The primary data file will hold our read-write data, and a secondary data file, in a filegroup called Archive, will hold our read-only data. Having created the database, we immediately alter it to use the SIMPLE recovery model. USE [master] CREATE DATABASE [DatabaseForPartialBackups] ON PRIMARY ( NAME = N'DatabaseForPartialBackups', FILENAME = N'C:\SQLData\DatabaseForPartialBackups.mdf', SIZE = 10240KB, FILEGROWTH = 10240KB ), FILEGROUP [Archive] ( NAME = N'DatabaseForPartialBackups_ReadOnly', FILENAME = N'C:\SQLData\DatabaseForPartialBackups_ReadOnly.ndf', SIZE = 10240KB, FILEGROWTH = 10240KB ) LOG ON ( NAME = N'DatabaseForPartialBackups_log', FILENAME = N'C:\SQLData\DatabaseForPartialBackups_log.ldf', SIZE = 10240KB, FILEGROWTH = 10240KB ) ALTER DATABASE [DatabaseForPartialBackups] SET RECOVERY SIMPLE Listing 10-1: Creating the DatabaseForPartialBackups test database. The script is fairly straightforward and there is nothing here that we haven't discussed in previous scripts for multiple data file databases. The Archive filegroup will eventually be set to read-only, but first we are going to need to create some tables in this filegroup and populate one of them with data, as shown in Listing 352 Chapter 10: Partial Backup and Restore USE [DatabaseForPartialBackups] CREATE TABLE dbo.maindata ( ID INT NOT NULL IDENTITY(1, 1), Message NVARCHAR(50) NOT NULL ) ON [PRIMARY] CREATE TABLE dbo.archivedata ( ID INT NOT NULL, Message NVARCHAR(50) NOT NULL ) ON [Archive] INSERT INTO dbo.maindata VALUES ( 'Data for initial database load: Data 1' ) INSERT INTO dbo.maindata VALUES ( 'Data for initial database load: Data 2' ) INSERT INTO dbo.maindata VALUES ( 'Data for initial database load: Data 3' ) Listing 10-2: Creating the MainData and ArchiveData tables and populating the MainData table. The final preparatory step for our example is to simulate an archiving process, copying data from the MainData table into the ArchiveData table, setting the Archive filegroup as read-only, and then deleting the archived data from MainData, and inserting the next set of "live" data. Before running Listing 10-3, make sure there are no other query windows connected to the DatabaseForPartialBackups database. If there are, the conversion of the secondary file group to READONLY will fail, as we need to have exclusive access on the database before we can change filegroup states. 352 353 Chapter 10: Partial Backup and Restore USE [DatabaseForPartialBackups] INSERT INTO dbo.archivedata SELECT ID, Message FROM MainData ALTER DATABASE [DatabaseForPartialBackups] MODIFY FILEGROUP [Archive] READONLY DELETE FROM dbo.maindata INSERT INTO dbo.maindata VALUES ( 'Data for second database load: Data 4' ) INSERT INTO dbo.maindata VALUES ( 'Data for second database load: Data 5' ) INSERT INTO dbo.maindata VALUES ( 'Data for second database load: Data 6' ) Listing 10-3: Data archiving and secondary data load. Finally, before we take our first partial backup, we want to capture one backup copy of the whole database, including the read-only data, as the basis for any subsequent restore operations. We can take a partial database backup before taking a full one, but we do want to make sure we have a solid restore point for the database, before starting our partial backup routines. Therefore, Listing 10-4 takes a full database backup of our DatabaseForPartialBackups database. Having done so, it also inserts some more data into MainData, so that we have fresh data to capture in our subsequent partial backup. 353 354 Chapter 10: Partial Backup and Restore USE [master] BACKUP DATABASE DatabaseForPartialBackups TO DISK = N'C:\SQLBackups\Chapter10\DatabaseForPartialBackups_FULL.bak' INSERT INTO DatabaseForPartialBackups.dbo.MainData VALUES ( 'Data for third database load: Data 7' ) INSERT INTO DatabaseForPartialBackups.dbo.MainData VALUES ( 'Data for third database load: Data 8' ) INSERT INTO DatabaseForPartialBackups.dbo.MainData VALUES ( 'Data for third database load: Data 9' ) Listing 10-4: Full database backup of DatabaseForPartialBackups, plus third data load. The output from the full database backup is shown in Figure Notice that, as expected, it processes both of our data files, plus the log file.. BACKUP DATABASE successfully processed 194 pages in seconds ( MB/sec). Figure 10-1: Output from the full database backup. Partial database backup using T-SQL We are now ready to perform our first partial database backup, which will capture the data inserted in our third data load, as shown in Listing 355 Chapter 10: Partial Backup and Restore BACKUP DATABASE DatabaseForPartialBackups READ_WRITE_FILEGROUPS TO DISK = N'C:\SQLBackups\Chapter10\DatabaseForPartialBackups_PARTIAL_Full.bak' Listing 10-5: A partial backup of DatabaseForPartialBackups. The only difference between this backup command and the full database backup command shown in Listing 10-4 is the addition of the READ_WRITE_FILEGROUPS option. This option lets SQL Server know that the command is a partial backup and to only process the read-write filegroups contained in the database. The output should be similar to that shown in Figure Notice that this time only the primary data file and the log file are processed. This is exactly what we expected to see: since we are not processing any of the read-only data, we shouldn't see that data file being accessed in the second backup command. Processed 176 pages for database 'DatabaseForPartialBackups', file 'DatabaseForPartialBackups' on file 1. Processed 2 pages for database 'DatabaseForPartialBackups', file 'DatabaseForPartialBackups_log' on file 1. BACKUP DATABASE...FILE=<name> successfully processed 178 pages in seconds ( MB/sec). Figure 10-2: Partial backup results. Differential partial backup using T-SQL Just as we can have differential database backups, which refer to a base full database backup, so we can take differential partial database backups that refer to a base partial database backup, and will capture only the data that changed in the read-write data files, since the base partial backup was taken. 355 356 Chapter 10: Partial Backup and Restore Before we run a differential partial backup, we need some fresh data to process. USE [DatabaseForPartialBackups] INSERT INTO MainData VALUES ( 'Data for fourth database load: Data 10' ) INSERT INTO MainData VALUES ( 'Data for fourth database load: Data 11' ) INSERT INTO MainData VALUES ( 'Data for fourth database load: Data 12' ) Listing 10-6: Fourth data load, in preparation for partial differential backup. Listing 10-7 shows the script to run our partial differential backup. The one significant difference is the inclusion of the WITH DIFFERENTIAL option, which converts the command from a full partial to a differential partial backup. USE [master] BACKUP DATABASE [DatabaseForPartialBackups] READ_WRITE_FILEGROUPS TO DISK = N'C:\SQLBackups\Chapter10\DatabaseForPartialBackups_PARTIAL_Diff.bak' WITH DIFFERENTIAL Listing 10-7: Performing the partial differential backup. Once this command is complete, go ahead and check the output of the command in the messages tab to make sure only the proper data files were processed. We are done taking partial backups for now and can move on to our restore examples. 356 357 Chapter 10: Partial Backup and Restore Performing Partial Database Restores We will be performing two restore examples: one restoring the DatabaseForPartial- Backups database to the state in which it existed after the third data load, using the full database and full partial backup files, and one restoring the database to its state after the fourth data load, using the full database, full partial, and differential partial backup files. Restoring a full partial backup Listing 10-8 show the two simple steps in our restore process. The first step restores our full database backup file, which will restore the data and objects in both our read-write and read-only filegroups. In this step, we include the NORECOVERY option, so that SQL Server leaves the database in a state where we can apply more files. This is important so that we don't wind up with a database that is online and usable before we apply the partial backup. The second step restores our full partial backup file. This will overwrite the read-write files in the existing database with the data from the backup file, which will contain all the data we inserted into the primary data file, up to and including the third data load. We specify that this restore operation be completed with RECOVERY. RECOVERY Listing 10-8: Restoring the partial full database backup. 357 358 Chapter 10: Partial Backup and Restore The output from running this script is shown in Figure We should see all files being processed in the first command, and only the read-write and transaction log file being modified in the second command.. RESTORE DATABASE successfully processed 194 pages in seconds (1.986 MB/sec). Processed 176 pages for database 'DatabaseForPartialBackups', file 'DatabaseForPartialBackups' on file 1. Processed 2 pages for database 'DatabaseForPartialBackups', file 'DatabaseForPartialBackups_log' on file 1. RESTORE DATABASE... FILE=<name> successfully processed 178 pages in seconds ( MB/sec). Figure 10-3: Partial database backup restore output. Everything looks good, and exactly as expected, but let's put on our Paranoid DBA hat once more and check that the restored database contains the right data. USE [DatabaseForPartialBackups] SELECT ID, Message FROM dbo.maindata SELECT ID, Message FROM dbo.archivedata Listing 10-9: Checking out our newly restored data. 358 359 Chapter 10: Partial Backup and Restore Hopefully, we'll see three rows of data in the ArchiveData table and six rows of data in the read-write table, MainData, as confirmed in Figure Figure 10-4: Results of the data check on our newly restored database. Restoring a differential partial backup Our restore operation this time is very similar, except that we'll need to process all three of our backup files, to get the database back to its state after the final data load. You may be wondering why it's necessary to process the full partial backup in this case, rather than just the full backup followed by the differential partial backup. In fact, the full database backup cannot serve as the base for the differential partial backup; only a full partial backup can serve as the base for a differential partial backup, just as only a full database backup can serve as a base for a differential database backup. Each differential partial backup holds all the changes since the base partial backup so, if we had a series of differential partial backups, we would only need to restore the latest one in the series. 359 360 Chapter 10: Partial Backup and Restore Listing shows the script; we restore the full database and full partial backups, leaving the database in a restoring state, then apply the differential partial backup and recover the database. NORECOVERY RESTORE DATABASE [DatabaseForPartialBackups] FROM DISK = N'C:\SQLBackups\Chapter10\DatabaseForPartialBackups_PARTIAL_Diff.bak' WITH RECOVERY Listing 10-10: Restoring the partial differential backup file. Once again, check the output from the script to make sure everything looks as it should, and then rerun Listing 10-9 to verify that there are now three more rows in the MainData table, for a total of nine rows, and still only three rows in the ArchiveData table. Special case partial backup restore Here, we'll take a quick look at a special type of restore operation that we might term a "partial online piecemeal restore," which will bring the database online by restoring only the read-only filegroup in the database (requires Enterprise edition), as shown in Listing This type of restore can be done with both full partial backups as well as full file 360 361 Chapter 10: Partial Backup and Restore backups, provided the full file backup contains the primary filegroup, with the database system information. This is useful if we need to recover a specific table that exists in the read-write filegroups, or we want to view the contents of the backup without restoring the entire database. -- restore the read-write filegroups RESTORE DATABASE [DatabaseForPartialBackups] FROM DISK = N'C:\SQLBackups\Chapter10\DatabaseForPartialBackups_PARTIAL_Full.bak' WITH RECOVERY, PARTIAL Listing 10-11: Performing a partial online restore. Now, we should have a database that is online and ready to use, but with only the read-write filegroup accessible, which we can verify with a few simple queries, shown in Listing USE [DatabaseForPartialBackups] SELECT ID, Message FROM MainData SELECT ID, Message FROM ArchiveData Listing 10-12: Selecting data from our partially restored database. The script attempts to query both tables and the output is shown in Figure 362 Chapter 10: Partial Backup and Restore Figure 10-5: Unable to pull information from the archive table. We can see that we did pull six rows from the MainData table, but when we attempted to pull data from the ArchiveData table, we received an error, because that filegroup was not part of the file we used in our restore operation. We can see the table exists and even see its structure, if so inclined, since all of that information is stored in the system data, which was restored with the primary filegroup. SQL Backup Partial Backup and Restore In this section, without restarting the whole example from scratch, we will take a look at the equivalent full partial and differential partial backup commands in SQL Backup, as shown in Listing USE master -- full partial backup with SQL Backup EXECUTE master..sqlbackup '-SQL "BACKUP DATABASE [DatabaseForPartialBackups] READ_WRITE_FILEGROUPS TO DISK = ''C:\SQLBackups\Chapter10\DatabaseForPartialBackups_Partial_Full.sqb'' WITH DISKRETRYINTERVAL = 30, DISKRETRYCOUNT = 10, COMPRESSION = 3, THREADCOUNT = 2"' 362 363 Chapter 10: Partial Backup and Restore -- differential partial backup with SQL Backup EXECUTE master..sqlbackup '-SQL "BACKUP DATABASE [DatabaseForPartialBackups] READ_WRITE_FILEGROUPS TO DISK = ''C:\SQLBackups\Chapter10\DatabaseForPartialBackups_Partial_Diff.sqb'' WITH DIFFERENTIAL, DISKRETRYINTERVAL = 30, DISKRETRYCOUNT = 10, COMPRESSION = 3, THREADCOUNT = 2"' Listing 10-13: A SQL Backup script for full partial and differential partial backups. The commands are very similar to the native commands, and nearly identical to the SQL Backup commands we have used in previous chapters. The only addition is the same new option we saw in the native commands earlier in this chapter, namely READ_WRITE_FILEGROUPS. Listing shows the equivalent restore commands for partial backups; again, they are very similar to what we have seen before in other restore scripts. We restore the last full database backup leaving the database ready to process more files. This will restore all of the read-only data, and leave the database in a restoring state, ready to apply the partial backup data. We then apply the full partial and differential partial backups, and recover the database. -- full database backup restore EXECUTE master..sqlbackup '-SQL "RESTORE DATABASE [DatabaseForPartialBackups] FROM DISK = ''C:\SQLBackups\Chapter10\DatabaseForPartialBackups_FULL.sqb'' WITH NORECOVERY"' -- full partial backup restore EXECUTE master..sqlbackup '-SQL "RESTORE DATABASE [DatabaseForPartialBackups] FROM DISK = ''C:\SQLBackups\Chapter10\DatabaseForPartialBackups_Partial_Full.sqb'' WITH NORECOVERY"' -- differential partial backup restore EXECUTE master..sqlbackup '-SQL "RESTORE DATABASE [DatabaseForPartialBackups] FROM DISK = ''C:\SQLBackups\Chapter10\DatabaseForPartialBackups_Partial_Diff.sqb'' WITH RECOVERY"' Listing 10-14: A SQL Backup script for full and differential partial restores. 363 364 Chapter 10: Partial Backup and Restore Possible Issues with Partial Backup and Restore The biggest issue when restoring a database using partial backups is the storage and management of the read-only data. This data is captured in a full database backup, directly after the data import, and then not backed up again. As such, it is easy for its existence to slip from a DBA's mind. However, the fact that this portion of the database is backed up less frequently, does not mean it is less important; it is still an integral piece of the recovery strategy, so manage each file in your backup strategy carefully and make sure the full database backup doesn't get lost in the archival jungle. When performing one of the full database backups on a database where the backup strategy includes subsequent partial backups, it's a good idea to perform a checksum on that full database backup (see Chapter 2 for details). This can, and most likely will, slow down the backup speed but if you can take the speed hit, it's nice to have the reassurance that this full backup is valid, since they will be captured infrequently. Of course, performing a test restore with the newly created full backup file is even better! If you do find that your full database backup has not been stored properly or that the file is somehow corrupted, what can you do? Well, not a whole lot. Hopefully you have multiple copies stored in different locations for just this type of situation. Keeping a copy on long-term storage, as well as locally on a robust disk, are other good ideas when dealing with data that is not backed up on a regular basis. Be diligent when you are managing your backup files. Remember that your data is your job! 364 365 Chapter 10: Partial Backup and Restore Partial Backups and Restores in the SLA Like file backup and restore, partial backup and restore will most likely form a very small part of your overall recoverability strategy; partial backups are a very useful and time saving tool in certain instances, but they will not likely be the "go-to" backup type in most situations, largely because most databases simply don't contain a large proportion of read-only data. However, if a strategy involving partial backups seems a good fit for a database then, in the SLA for that database, you'll need to consider such issues as: frequency of refreshing the full database backup frequency of full partial and differential partial backups are transaction log backups still required? As noted earlier, partial backups are designed with SIMPLE recovery model databases in mind. When applied in this way, it means that we can only restore to the last backup that was taken, most likely a full partial or a differential partial backup, and so we do stand to lose some data modifications in the case of, say, a midday failure. That is something you have to weigh against your database restore needs to decide if this type of backup will work for you. Like every other type of backup, weigh up the pros and cons to see which type, or combination of types, is right for your database. Just because this type of backup was designed mainly for SIMPLE recovery model databases, it doesn't mean that we can only use it in such cases. For a FULL recovery model database that has a much smaller window of data loss acceptability, such as an hour, but does contain a large section of read-only data, this backup type can still work to our advantage. We would, however, need to take transaction log backups in addition to the partial full and partial differentials. This will add a little more complexity to the backup and restore processes in the event of emergency, but will enable point-intime restore. 365 366 Chapter 10: Partial Backup and Restore Forcing Failures for Fun Much as I hate to end the chapter, and the book, on a note of failure, that is sometimes the lot of the DBA; deal with failures as and when they occur, learn what to look out for, and enforce measures to ensure the problem does not happen again. With that in mind, let's walk through a doomed partial backup scheme. Take a look at the script in Listing and, one last time, try to work out what the problem is before running it._Diff.bak' WITH RECOVERY Listing 10-15: Forcing a restore error with partial database backup restore. Do you spot the mistake? Figure 10-6 shows the resulting SQL Server error messages. Figure 10-6: Forced failure query results 366 367 Chapter 10: Partial Backup and Restore The first error we get in the execution of our script is the error "File DatabaseForPartial- Backups is not in the correct state to have this differential backup applied to it." This is telling us that the database is not prepared to process our second restore command, using the differential partial backup file. The reason is that we have forgotten to process our partial full backup file. Since the partial full file, not the full database file, acts as the base for the partial differential, we can't process the partial differential without it. This is why our database is not in the correct state to process that differential backup file. Summary You should now be familiar with how to perform both partial full and partial differential backups and be comfortable restoring this type of backup file. With this, I invite you to sit back for a moment and reflect on the fact that you now know how to perform all of the major, necessary types of SQL Server backup and restore operation. Congratulations! The book is over, but the journey is not complete. Backing up databases and performing restores should be something all DBAs do on a very regular basis. This skill is paramount to the DBA and we should keep working on it until the subject matter becomes second nature. Nevertheless, when and if disaster strikes a database, in whatever form, I hope this book, and the carefully documented and tested restore strategy that it helps you generate, will allow you to get that database back online with an acceptable level of data loss, and minimal down-time. Good luck! Shawn McGehee 367 368 Appendix A: SQL Backup Pro Installation and Configuration This appendix serves as a Quick Reference on how to download, install and configure the SQL Backup tool from Red Gate Software, so that you can work through any examples in the book that use this tool. You can download a fully-functional trial version of the software from Red Gate's website, at By navigating to the Support pages for this tool, you can find further and fuller information on how to install, configure and use this tool, including step-by-step tutorials and troubleshooting guides. See, for example, Content/SQL_Backup/help/6.5/SBU_Gettingstarted, and the links therein. With the software package downloaded, there are basically two steps to the installation process, first installing the SQL Backup GUI, and then the SQL Backup services. SQL Backup Pro GUI Installation This section will demonstrate how to install the SQL backup GUI tool, which will enable you to register servers for use, and then execute and manage backups across your servers (having first installed the SQL Backup services on each of these SQL Server machines). The GUI tool will normally be installed on the client workstation, but can also be installed on a SQL Server. Open the SQL Backup zip file, downloaded from the Red Gate website, and navigate to the folder called SQLDBABundle. Several files are available for execution, as shown in Figure A-1. The one you want here, in order to install the SQL Backup GUI is 368 369 Appendix A: SQL Backup Pro Installation and Configuration SQLDBABundle.exe, so double-click the file, or copy the file to an uncompressed folder, in order to begin the installation. Figure A-1: Finding the installation file. There is the option to install several DBA tools from Red Gate, but here you just want to install SQL Backup (current version at time of writing was SQL Backup 6.5), so select that tool, as shown in Figure A-2, and click the Next button to continue. Figure A-2: Installing SQL Backup 370 Appendix A: SQL Backup Pro Installation and Configuration On the next page, you must accept the license agreement. This is a standard EULA and you can proceed with the normal routine of just selecting the "I accept " check box and clicking Next to continue. If you wish to read through the legalese more thoroughly, print a copy for some bedtime reading. On the next screen, select the folder where the SQL Backup GUI and service installers will be stored. Accept the default, or configure a different location, if required, and then click Install. The installation process should only take a few seconds and, once completed, you should see a success message and you can close the installer program. That's all there is to it, and you are now ready to install the SQL Backup services on your SQL Server machine. SQL Backup Pro Services Installation You can now use the SQL Backup GUI tool to connect to a SQL Server and install the SQL Backup services on that machine. Open the SQL Backup GUI and, once past the flash page offering some import/registration tools and demo screens (feel free to peruse these at a later time), you'll arrive at the main SQL Backup screen. Underneath the top menu items (currently grayed out), is a tab that contains a server group named after the current time zone on the machine on which the GUI installed. In the bottom third of the screen are several tables where, ultimately, will be displayed the backup history for a selected server, current processes, log copy queues and job information. Right-click on the server group and select Add SQL Server, as shown in Figure A 371 Appendix A: SQL Backup Pro Installation and Configuration Figure A-3: Starting the server registration process. Once the Add SQL Server screen opens, you can register a new server. Several pieces of information will be required, as shown below. SQL Server: This is the name of the SQL Server to register. Authentication type: Choose to use your Windows account to register or a SQL Server login. User name: SQL Login user name, if using SQL Server authentication. Password: SQL Login password, if using SQL Server authentication. Remember password: Check this option to save the password for a SQL Server login. Native Backup and restore history: Time period over which to import details of native SQL Server backup and restore activity into your local cache. 371 372 Appendix A: SQL Backup Pro Installation and Configuration Install or upgrade server components: Leaving this option checked will automatically start the installation or upgrade of a server's SQL Backup services. Having have filled in the General tab information, you should see a window similar to that shown in Figure A-4. Figure A-4: SQL Server registration information. There is a second tab, Options, which allows you to modify the defaults for the options below. Location: You can choose a different location so the server will be placed in the tab for that location. Group: Select the server group in which to place the server being registered. Alias: An alias to use for display purposes, instead of the server name. 372 373 Appendix A: SQL Backup Pro Installation and Configuration Network protocol: Select the SQL Server communication protocol to use with this server. Network packet size: Change the default packet size for SQL Server communications in SQL Backup GUI. Connection time-out: Change the length of time that the GUI will attempt communication with the server before failing. Execution time-out: Change the length of time that SQL Backup will wait for a command to start before stopping it. Accept all the defaults for the Options page, and go ahead and click Connect. Once the GUI connects to the server, you will need to fill out two more pages of information about the service that is being installed. On the first page, select the account under which the SQL Backup service will run; it will need to be one that has the proper permissions to perform SQL Server backups, and execute the extended stored procedures that it will install in the master database, and it will need to have the sysadmin server role, for the GUI interface use. You can use a built-in system account or a service account from an Active Directory pool of users (recommended, for management across a domain). For this example, use the Local System account. Remember, too, that in SQL Server 2008 and later, the BUILTIN\Administrators group is no longer, by default, a sysadmin on the server, so you will need to add whichever account you are using to the SQL Server to make sure you have the correct permissions set up. Figure A-5 shows an example of the security setup for a typical domain account for the SQL Backup service on a SQL Server. 373 374 Appendix A: SQL Backup Pro Installation and Configuration Figure A-5: Security setup for new server installation. 374 375 Appendix A: SQL Backup Pro Installation and Configuration On the next page, you will see the SQL Server authentication credentials. You can use a different account from the service account, but it is not necessary if the permissions are set up correctly. Stick with the default user it has selected and click Finish to start the installation. Once that begins, the installation files will be copied over and you should, hopefully, see a series of successful installation messages, as shown in Figure A-6. Figure A-6: Successful SQL backup service installation. You have now successfully installed the SQL Backup service on a SQL Server. In the next section, you'll need to configure that service. 375 376 Appendix A: SQL Backup Pro Installation and Configuration SQL Backup Pro Configuration Your newly-registered server should be visible in the default group (the icon to the right of the server name indicates that this is a trial version of the software). Right-click the server name to bring up a list of options, as shown in Figure A-7, some of which we will be using throughout this book. Figure A-7: Getting to the SQL Backup options configuration. Go ahead and select Options to bring up the Server Options window. File management The File Management tab allows you to configure backup file names automatically, preserve historical data and clean up MSDB history on a schedule. 376 377 Appendix A: SQL Backup Pro Installation and Configuration The first option, Backup folder, sets the default location for all backup files generated through the GUI. This should point to the normal backup repository for this server so that any backups that are taken, especially if one is taken off the regular backup schedule, will end up in the right location. The next option, File name format, sets the format of the auto-generated name option that is available with SQL Backup, using either the GUI or T-SQL code. Of course, it is up to you how to configure this setting, but my recommendation is this: <DATABASE>_<DATETIME yyyymmdd_hhnnss>_<type> Using this format, any DBA can very quickly identify the database, what time the backup was taken, and what type of backup it was, and it allows the files to be sorted in alphabetical and chronological order. If you store in a shared folder multiple backups from multiple instances that exist on the same server, which I would not recommend, you can also add the <INSTANCE> tag for differentiation. The next option, Log file folder, tells SQL Backup where on the server to store the log files from SQL Backup operations. Also in this section of the screen, you can configure log backup management options, specifying for how long backups should be retained in the local folder. I would recommend keeping at least 90 days' worth of files, but you could keep them indefinitely if you require a much longer historical view. The final section of the screen is Server backup history, which will clean up the backup history stored in the msdb database; you may be surprised by how much historical data will accumulate over time. The default is to remove this history every 90 days, which I think is a little low. I would keep at least 180 days of history, but that is a choice you will have to make based on your needs and regulations. If the SQL Backup server components are installed on an older machine which has never had its msdb database cleaned out, then the first time SQL Backup runs the msdb "spring clean," it can take quite a long time and cause some blocking on the server. There are no indexes on the backup and restore history tables in msdb, so it's a good idea to add some. 377 378 Appendix A: SQL Backup Pro Installation and Configuration Once you are done configuring these options, the window should look similar, but probably slightly different, to that shown in Figure A-8. Figure A-8: File management configuration. settings The Settings tab will allow you to configure the settings for the s that SQL Backup can send to you, or to a team of people, when a failure occurs in, or warning is raised for, one of your backup or restore operations. It's a very important setting to get configured correctly, and tested. There are just five fields that you need to fill out. SMTP Host: This is the SMTP server that will receive any mail SQL Backup needs to send out. 378 SQL Server Backup and Restore The Red Gate Guide SQL Server Backup and Restore Shawn McGehee ISBN: 978-1-906434-74-8 SQL Server Backup and Restore By Shawn McGehee First published by Simple Talk Publishing April 2012 Copyright AprilMore information Database Maintenance Essentials Database Maintenance Essentials Brad M McGehee Director of DBA Education Red Gate Software What We Are Going to Learn Today 1. Managing MDF Files 2. Managing LDF Files 3. Managing Indexes 4. MaintainingMore information theMore information Nimble Storage Best Practices for Microsoft SQL Server BEST PRACTICES GUIDE: Nimble Storage Best Practices for Microsoft SQL Server Summary Microsoft SQL Server databases provide the data storage back end for mission-critical applications. Therefore, it sMore information databaseMore information Backups and Maintenance Backups and Maintenance Backups and Maintenance Objectives Learn how to create a backup strategy to suit your needs. Learn how to back up a database. Learn how to restore from a backup. Use the DatabaseMore informationMore information:More information Backup and Recovery. What Backup, Recovery, and Disaster Recovery Mean to Your SQL Anywhere Databases Backup and Recovery What Backup, Recovery, and Disaster Recovery Mean to Your SQL Anywhere Databases CONTENTS Introduction 3 Terminology and concepts 3 Database files that make up a database 3 Client-sideMore information Backup and Restore Strategies for SQL Server Database. Nexio Motion. 10-February-2015. Revsion: DRAFT Backup and Restore Strategies for SQL Server Database Nexio Motion v4 10-February-2015 Revsion: DRAFT v4 Publication Information 2015 Imagine Communications Corp. Proprietary and Confidential. ImagineMore information Nexio Motion 4 Database Backup and Restore Nexio Motion 4 Database Backup and Restore 26-March-2014 Revision: A Publication Information 2014 Imagine Communications Corp. Proprietary and Confidential. Imagine Communications considers this documentMore information DBA 101: Best Practices All DBAs Should Follow The World s Largest Community of SQL Server Professionals DBA 101: Best Practices All DBAs Should Follow Brad M. McGehee Microsoft SQL Server MVP Director of DBA Education Red Gate Software information Bulletproof your Database Backup and Recovery Strategy Whitepaper Bulletproof your Database Backup and Recovery Strategy By Shawn McGehee and Tony Davis The most critical task for all DBAs is to have a Backup and Recovery strategy that ensures, every day,More information MOC 20462C: Administering Microsoft SQL Server Databases MOC 20462C: Administering Microsoft SQL Server Databases Course Overview This course provides students with the knowledge and skills to administer Microsoft SQL Server databases. Course Introduction CourseMore information SQL Server Database Administrator s Guide SQL Server Database Administrator s Guide Copyright 2011 Sophos Limited. All rights reserved. No part of this publication may be reproduced, stored in retrieval system, or transmitted, in any form or byMore information:More informationMore information Getting to Know the SQL Server Management Studio HOUR 3 Getting to Know the SQL Server Management Studio The Microsoft SQL Server Management Studio Express is the new interface that Microsoft has provided for management of your SQL Server database. ItMore information Module 07. Log Shipping Module 07 Log Shipping Agenda Log Shipping Overview SQL Server Log Shipping Log Shipping Failover 2 Agenda Log Shipping Overview SQL Server Log Shipping Log Shipping Failover 3 Log Shipping Overview DefinitionMore information aMore information Best Practices Every SQL Server DBA Must Know The World s Largest Community of SQL Server Professionals Best Practices Every SQL Server DBA Must Know Brad M McGehee SQL Server MVP Director of DBA Education Red Gate Software MyMore informationMore information tairways handbook SQL Server Transaction Log Management tairways handbook SQL Server Transaction Log Management By Tony Davis and Gail Shaw SQL Server Transaction Log Management By Tony Davis and Gail Shaw First published by Simple Talk Publishing October 2012More information.More information Database Administrator Certificate Capstone Project Evaluation Checklist Database Administrator Certificate Capstone Project Evaluation Checklist The following checklist will be used by the Capstone Project instructor to evaluate your project. Satisfactory completion of theMore information EMC APPSYNC AND MICROSOFT SQL SERVER A DETAILED REVIEW EMC APPSYNC AND MICROSOFT SQL SERVER A DETAILED REVIEW ABSTRACT This white paper discusses how EMC AppSync integrates with Microsoft SQL Server to provide a solution for continuous availability of criticalMore information This article Includes: Log shipping has been a mechanism for maintaining a warm standby server for years. Though SQL Server supported log shipping with SQL Server 2000 as a part of DB Maintenance Plan, it has become a built-inMore information Administering Microsoft SQL Server Databases Course 20462C: Administering Microsoft SQL Server Databases Page 1 of 7 Administering Microsoft SQL Server Databases Course 20462C: 4 days; Instructor-Led Introduction This four-day instructor-led courseMore information Course Outline: This five-day instructor-led course provides students with the knowledge and skills to maintain a Microsoft SQL Server 2014 database. The course focuses on teaching individuals how to use SQL Server 2014More information Backup and Recovery in MS SQL Server. Andrea Imrichová Backup and Recovery in MS SQL Server Andrea Imrichová Types of Backups copy-only backup database backup differential backup full backup log backup file backup partial backup Copy-Only Backups without affectingMore information SQL Server 2008 Designing, Optimizing, and Maintaining a Database Session 1 SQL Server 2008 Designing, Optimizing, and Maintaining a Database Course The SQL Server 2008 Designing, Optimizing, and Maintaining a Database course will help you prepare for 70-450 exam from Microsoft.More information 20462- Administering Microsoft SQL Server Databases Course Outline 20462- Administering Microsoft SQL Server Databases Duration: 5 days (30 hours) Target Audience: The primary audience for this course is individuals who administer and maintain SQL ServerMore information Chapter 14: Recovery System Chapter 14: Recovery System Chapter 14: Recovery System Failure Classification Storage Structure Recovery and Atomicity Log-Based Recovery Remote Backup Systems Failure Classification Transaction failureMore information Outline. Failure Types Outline Database Management and Tuning Johann Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE Unit 11 1 2 Conclusion Acknowledgements: The slides are provided by Nikolaus AugstenMore information Handling a Full SQL Server Transaction Log Handling a Full SQL Server Transaction Log T he transaction log for a SQL Server database is critical to the operation of the database and the ability to minimize data loss in the event of a disaster.More information ADMINISTERING MICROSOFT SQL SERVER DATABASES Education and Support for SharePoint, Office 365 and Azure COURSE OUTLINE ADMINISTERING MICROSOFT SQL SERVER DATABASES Microsoft Course Code 20462 About this course This five-dayMore information Destiny system backups white paper Destiny system backups white paper Establishing a backup and restore plan for Destiny Overview It is important to establish a backup and restore plan for your Destiny installation. The plan must be validatedMore information DBAMore information Database Maintenance Guide Database Maintenance Guide Medtech Evolution - Document Version 5 Last Modified on: February 26th 2015 (February 2015) This documentation contains important information for all Medtech Evolution usersMore information Administering Microsoft SQL Server Databases Course 20462C: Administering Microsoft SQL Server Databases Module 1: Introduction to SQL Server 2014 Database Administration This module introduces the Microsoft SQL Server 2014 platform. It describesMore information Administering Microsoft SQL Server Databases Course 20462C: Administering Microsoft SQL Server Databases Module 1: Introduction to SQL Server 2014 Database Administration This module introduces the Microsoft SQL Server 2014 platform. It describesMore information Administering Microsoft SQL Server Databases 20462C; 5 days Lincoln Land Community College Capital City Training Center 130 West Mason Springfield, IL 62702 217-782-7436 Administering Microsoft SQL Server Databases 20462C; 5 days Course DescriptionMore information BrightStor ARCserve Backup for Windows BrightStor ARCserve Backup for Windows Agent for Microsoft SQL Server r11.5 D01173-2E This documentation and related computer software program (hereinafter referred to as the "Documentation") is for theMore information Securing Your Microsoft SQL Server Databases in an Enterprise Environment Securing Your Microsoft SQL Server Databases in an Enterprise Environment Contents Introduction...1 Taking Steps Now to Secure Your Data...2 Step 1: Back Up Everything...2 Step 2: Simplify as Much asMore information SQL Backup and Restore using CDP CDP SQL Backup and Restore using CDP Table of Contents Table of Contents... 1 Introduction... 2 Supported Platforms... 2 SQL Server Connection... 2 Figure 1: CDP Interface with the SQL Server... 3 SQLMore information Chapter 15: Recovery System Chapter 15: Recovery System Failure Classification Storage Structure Recovery and Atomicity Log-Based Recovery Shadow Paging Recovery With Concurrent Transactions Buffer Management Failure with Loss ofMore information Course: 20462 Administering Microsoft SQL Server Databases Overview Course length: 5 Days Microsoft SATV Eligible Course: 20462 Administering Microsoft SQL Server Databases Overview About this Course This five-day instructor-led course provides students with the knowledgeMore information Cyber Security: Guidelines for Backing Up Information. A Non-Technical Guide Cyber Security: Guidelines for Backing Up Information A Non-Technical Guide Essential for Executives, Business Managers Administrative & Operations Managers This appendix is a supplement to the Cyber Security:More information SQL Server 2012 Database Administration With AlwaysOn & Clustering Techniques SQL Server 2012 Database Administration With AlwaysOn & Clustering Techniques Module: 1 Module: 2 Module: 3 Module: 4 Module: 5 Module: 6 Module: 7 Architecture &Internals of SQL Server Engine Installing,More information Perforce Backup Strategy & Disaster Recovery at National Instruments Perforce Backup Strategy & Disaster Recovery at National Instruments Steven Lysohir National Instruments Perforce User Conference April 2005-1 - Contents 1. Introduction 2. Development Environment 3. ArchitectureMore informationMore information SQL Server Maintenance Plans SQL Server Maintenance Plans BID2WIN Software, Inc. September 2010 Abstract This document contains information related to SQL Server 2005 and SQL Server 2008 and is a compilation of research from variousMore information 20462 Administering Microsoft SQL Server Databases 20462 Administering Microsoft SQL Server Databases Audience Profile The primary audience for this course is individuals who administer and maintain SQL Server databases. These individuals perform databaseMore information SQL Server 2005 Backing Up & Restoring Databases Institute of Informatics, Silesian University of Technology, Gliwice, Poland SQL Server 2005 Backing Up & Restoring Databases Dariusz Mrozek, PhD Course name: SQL Server DBMS Part 1: Backing Up OverviewMore information Enterprise PDM - Backup and Restore DS SOLIDWORKS CORPORATION Enterprise PDM - Backup and Restore Field Services - Best Practices [Enterprise PDM 2010] [September 2010] [Revision 2] September 2010 Page 1 Contents Brief Overview:... 4 NotesMore information 20462C: Administering Microsoft SQL Server Databases 20462C: Administering Microsoft SQL Server Databases Course Details Course Code: Duration: Notes: 20462C 5 days This course syllabus should be used to determine whether the course is appropriate for theMore information Oracle Database 10g: Backup and Recovery 1-2 Oracle Database 10g: Backup and Recovery 1-2 Oracle Database 10g: Backup and Recovery 1-3 What Is Backup and Recovery? The phrase backup and recovery refers to the strategies and techniques that are employedMore information Making Database Backups in Microsoft Business Solutions Navision Making Database Backups in Microsoft Business Solutions Navision MAKING DATABASE BACKUPS IN MICROSOFT BUSINESS SOLUTIONS NAVISION DISCLAIMER This material is for informational purposes only. MicrosoftMore information Working with SQL Server Agent Jobs Chapter 14 Working with SQL Server Agent Jobs Microsoft SQL Server features a powerful and flexible job-scheduling engine called SQL Server Agent. This chapter explains how you can use SQL Server AgentMore information Mind Q Systems Private Limited MS SQL Server 2012 Database Administration With AlwaysOn & Clustering Techniques Module 1: SQL Server Architecture Introduction to SQL Server 2012 Overview on RDBMS and Beyond Relational Big picture ofMore information Chapter 13 File and Database Systems Chapter 13 File and Database Systems Outline 13.1 Introduction 13.2 Data Hierarchy 13.3 Files 13.4 File Systems 13.4.1 Directories 13.4. Metadata 13.4. Mounting 13.5 File Organization 13.6 File AllocationMore information Chapter 13 File and Database Systems Chapter 13 File and Database Systems Outline 13.1 Introduction 13.2 Data Hierarchy 13.3 Files 13.4 File Systems 13.4.1 Directories 13.4. Metadata 13.4. Mounting 13.5 File Organization 13.6 File AllocationMore information Using Continuous Operations Mode for Proper Backups Using Continuous Operations Mode for Proper Backups A White Paper From Goldstar Software Inc. For more information, see our web site at Using Continuous Operations Mode for Proper Backups Last Updated:More information 20462 - Administering Microsoft SQL Server Databases 20462 - Administering Microsoft SQL Server Databases Duration: 5 Days Course Price: $2,975 Software Assurance Eligible Course Description Note: This course is designed for customers who are interestedMore information Maximum Availability Architecture. Oracle Best Practices For High Availability Preventing, Detecting, and Repairing Block Corruption: Oracle Database 11g Oracle Maximum Availability Architecture White Paper May 2012 Maximum Availability Architecture Oracle Best Practices For HighMore information Redundancy Options. Presented By: Chris Williams Redundancy Options Presented By: Chris Williams Table of Contents Redundancy Overview... 3 Redundancy Benefits... 3 Introduction to Backup and Restore Strategies... 3 Recovery Models... 4 Cold Backup...More information Restore and Recovery Tasks Objectives After completing this lesson, you should be able to: Describe the causes of file loss and determine the appropriate action Describe major recovery operations Back Administering and Managing Log Shipping 26_0672329565_ch20.qxd 9/7/07 8:37 AM Page 721 CHAPTER 20 Administering and Managing Log Shipping Log shipping is one of four SQL Server 2005 high-availability alternatives. Other SQL Server 2005 high-availabilityMore information Support Document: Microsoft SQL Server - LiveVault 7.6X Contents Preparing to create a Microsoft SQL backup policy... 2 Adjusting the SQL max worker threads option... 2 Preparing for Log truncation... 3 Best Practices... 3 Microsoft SQL Server 2005, 2008, orMore information 50238: Introduction to SQL Server 2008 Administration 50238: Introduction to SQL Server 2008 Administration 5 days Course Description This five-day instructor-led course provides students with the knowledge and skills to administer SQL Server 2008. The course VirtualCenter Database Maintenance VirtualCenter 2.0.x and Microsoft SQL Server Technical Note VirtualCenter Database Maintenance VirtualCenter 2.0.x and Microsoft SQL Server This document discusses ways to maintain the VirtualCenter database for increased performance and manageability.More information SQL LiteSpeed 3.0 Best Practices SQL LiteSpeed 3.0 Best Practices Optimize SQL LiteSpeed to gain value time and resources for critical SQL Server Backups September 9, 2003 Written by: Jeremy Kadlec Edgewood Solutions information Chapter 16: Recovery System Chapter 16: Recovery System Failure Classification Failure Classification Transaction failure : Logical errors: transaction cannot complete due to some internal error condition System errors: the databaseMore information Microsoft SQL Server Guide. Best Practices and Backup Procedures Microsoft SQL Server Guide Best Practices and Backup Procedures Constellation HomeBuilder Systems Inc. This document is copyrighted and all rights are reserved. This document may not, in whole or in part,More information Contingency Planning and Disaster Recovery Contingency Planning and Disaster Recovery Best Practices Guide Perceptive Content Version: 7.0.x Written by: Product Knowledge Date: October 2014 2014 Perceptive Software. All rights reserved PerceptiveMore information Local Government Cyber Security: Local Government Cyber Security: Guidelines for Backing Up Information A Non-Technical Guide Essential for Elected Officials Administrative Officials Business Managers Multi-State Information Sharing andMore information theMore information Course 20462C: Administering Microsoft SQL Server Databases Course 20462C: Administering Microsoft SQL Server Databases Duration: 35 hours About this Course The course focuses on teaching individuals how to use SQL Server 2014 product features and tools relatedMore information 10775A Administering Microsoft SQL Server 2012 Databases 10775A Administering Microsoft SQL Server 2012 Databases Five days, instructor-led About this Course This five-day instructor-led course provides students with the knowledge and skills to maintain a MicrosoftMore information Chapter 8 Service Management Microsoft SQL Server 2000 Chapter 8 Service Management SQL Server 2000 Operations Guide Abstract This chapter briefly presents the issues facing the database administrator (DBA) in creating a service levelMore information Backup and Recovery by using SANWatch - Snapshot Backup and Recovery by using SANWatch - Snapshot 2007 Infortrend Technology, Inc. All rights Reserved. Table of Contents Introduction...3 Snapshot Functionality...3 Eliminates the backup window...3 RetrievesMore information SQL Server Transaction Log from A to Z Media Partners SQL Server Transaction Log from A to Z Paweł Potasiński Product Manager Data Insights pawelpo@microsoft.com Why About Transaction Log (Again)? informationMore information Integrating SQL LiteSpeed in Your Existing Backup Infrastructure Integrating SQL LiteSpeed in Your Existing Backup Infrastructure March 11, 2003 Written by: Jeremy Kadlec Edgewood Solutions 888.788.2444 2 Introduction Needless to say, backupsMore information contact@wardyit.com Administering Microsoft SQL Server Databases Administering Microsoft SQL Server Databases This five-day instructor-led course provides students with the knowledge and skills to maintain a Microsoft SQL Server 2014 database. The course focuses onMore information siteMore information SQL SERVER Anti-Forensics. Cesar Cerrudo SQL SERVER Anti-Forensics Cesar Cerrudo Introduction Sophisticated attacks requires leaving as few evidence as possible Anti-Forensics techniques help to make forensics investigations difficult Anti-ForensicsMore information SQL Server Storage: The Terabyte Level. Brent Ozar, Microsoft Certified Master, MVP Consultant & Trainer, SQLskills.com SQL Server Storage: The Terabyte Level Brent Ozar, Microsoft Certified Master, MVP Consultant & Trainer, SQLskills.com BrentOzar.com/go/san Race Facts 333 miles 375 boats invited 33 DNFs Typical TerabyteMore information More information Administering Microsoft SQL Server Databases CÔNG TY CỔ PHẦN TRƯỜNG CNTT TÂN ĐỨC TAN DUC INFORMATION TECHNOLOGY SCHOOL JSC LEARN MORE WITH LESS! Course 20462 Administering Microsoft SQL Server Databases Length: 5 Days Audience: IT Professionals Level:More information sql server best practice sql server best practice 1 MB file growth SQL Server comes with a standard configuration which autogrows data files in databases in 1 MB increments. By incrementing in such small chunks, you risk endingMore informationMore informationMore information theMore information ! Volatile storage: ! Nonvolatile storage: Chapter 17: Recovery System Failure Classification! Failure Classification! Storage Structure! Recovery and Atomicity! Log-Based Recovery! Shadow Paging! Recovery With Concurrent Transactions! Buffer Management!More information 10775 Administering Microsoft SQL Server Databases 10775 Administering Microsoft SQL Server Databases Course Number: 10775 Category: Microsoft SQL Server 2012 Duration: 5 days Certification: Exam 70-462 Administering Microsoft SQL Server 2012 DatabasesMore information
http://docplayer.net/1206021-Sql-server-backup-and-restore.html
CC-MAIN-2017-30
refinedweb
96,344
54.66
On 11Aug2015 14:09, Chris Angelico <rosuav at gmail.com> wrote: >On Tue, Aug 11, 2015 at 1:40 PM, Cameron Simpson <cs at zip.com.au> wrote: >> I also thought the stdlib had some kind of "namespace" class with this kind >> of API, but I can't find it now:-( > >It does - types.SimpleNamespace(). It accepts keyword arguments, and >will let you create more attributes on the fly (unlike a namedtuple). Yes, that's it. Thanks! Cheers, Cameron Simpson <cs at zip.com.au> Ed Campbell's <ed at Tekelex.Com> pointers for long trips: 6. *NEVER* trust anyone in a cage, if they weren't nuts they'd be on a bike like everyone else.
https://mail.python.org/pipermail/python-list/2015-August/695277.html
CC-MAIN-2019-35
refinedweb
117
85.28
In this tutorial, you’ll learn how to schedule a Python script using crontab. Don’t worry if you never used crontab before. There are no prerequisites for this tutorial. I’ll walk you through everything you need to know step-by-step with lots of examples along the way. Last thing, any modern version of Python should work. Okay, here we go! Crontab vs Cronjob – What’s the Difference? A crontab is a file which contains the schedule of cronjob entries to be run at specified times. Crontab is short for cron table. You can think of a crontab as a configuration file that specifies shell commands to run periodically on a given schedule. A cronjob is basically instructions to run a command at a prescribed time. Crontab Syntax The crontab syntax is very powerful and flexible. Below is a reference describing the syntax for a cronjob i.e. a single line in the crontab * * * * * command to executeFrom left to right, each of the 5 asterisks represents minute, hour, day of month, month, and day of week. Finally on the very right is the actual command to execute. A Very Simple Cronjob Example To add a cronjob to your crontab, open up a terminal window and type the following. The additional argument -e here means edit. crontab -e Assuming that you have no cronjob entries, you’ll see an empty file. Type the following cronjob into your crontab. This cronjob will redirect the current date and time into a file. Save and close your file when you are done. * * * * * date > /tmp/test.txt If you guessed that this command will be executed once per minute, you’re absolutely right. A series of five asterisks in a cronjob is quite valid and simply means to execute the command every minute of every day of every week of every month. Let’s prove that this is actually working. In another terminal window, let’s use the watch command to periodically cat the contents of the test.txt file to the screen. watch cat /tmp/test.txt If you’re quick enough, you may see a “No such file or directory” error if the cronjob hasn’t been executed yet. Otherwise, you will see the contents of test.txt similar to below. Mon Oct 7 12:21:00 CEST 2018 Wait another minute and you will see the date increment by a minute. Mon Oct 7 12:22:00 CEST 2018 It’s worth pointing out here that cronjobs are by default executed at the top of the minute. More Examples of Cronjobs Now that you have created your very first cronjob, let’s go over some other cronjob examples that will execute at various frequencies. As you can see, the crontab syntax is very flexible. You can pretty much execute any command on any schedule no matter how simple or complicated it may be. Schedule a Python Script with Crontab With a good understanding of crontab and the cronjob syntax under your belt, let’s move on and walk through an example to schedule a Python script using crontab. For simplicity’s sake, let’s write a simple Python program to log the date, time, and a random number between 1 and 100 to the end of a file. Create a file in your home directory called rand.py with the following content. import random from datetime import datetime now = datetime.now() num = random.randint(1, 101) with open('/tmp/rand.txt', 'a') as f: f.write('{} - Your random number is {}\n'.format(now, num)) Let’s test out this program before we add it as a cronjob. Execute the following in a terminal window. python rand.py Check that the program did its job with cat. cat /tmp/rand.txt You should see something similar to below. 2018-10-07 12:33:21.211066 - Your random number is 65 It works! Before we add a cronjob to execute the rand.py program every minute, you must know that it is necessary to use absolute paths for everything in your crontab. This is where most people get hung up with cronjobs. We will need the absolute path of the Python binary and the absolute path of our Python script. - To get the absolute path of the Python binary, execute which python in a terminal window. In my case, the Python binary is at /usr/local/bin/python - To get the absolute path of your Python script, execute the pwd in the same directory as the rand.py program. In my case, my Python script is at /Users/tonyflorida/rand.py Alright. Now that we know where everything resides on our filesystem, let’s schedule our Python script to execute every minute. Open the crontab file like before. crontab -e Add the following line to the bottom of your crontab, substituting the appropriate paths for your filesystem. Save and close your file when you are done. * * * * * /usr/local/bin/python /Users/tonyflorida/rand.py Again, we can use the watch command to monitor the contents of the /tmp/rand.txt file. watch cat /tmp/rand.txt After a few minutes, your rand.txt file will look similar to this. 2018-10-01 13:57:31.158516 - Your random number is 27 2018-10-01 14:01:00.175556 - Your random number is 23 2018-10-01 14:02:00.267484 - Your random number is 81 2018-10-01 14:03:00.386802 - Your random number is 85 2018-10-01 14:04:00.504855 - Your random number is 22 2018-10-01 14:05:00.613324 - Your random number is 94 2018-10-01 14:06:00.706200 - Your random number is 45 Crontab Scheduling Final Thoughts Congratulations! You now know how to schedule a Python script using crontab. I’m sure by now, you realize the endless possibilities of scheduling tasks with crontab. Let’s clear out all of our cronjobs with the following command. crontab -r Any questions about how to schedule a Python script with crontab, let me know in the comments below. For another Python tutorial, check out last week’s post about how to send an email from Python. 3 thoughts on “How to Schedule a Python Script with Crontab” Thank you for that incredibly clear and on point post/page. Much appreciated. So happy you found it useful. Thanks for letting me know! Thank you so much. I found this extremely useful. I also fell victim of “…you must know that it is necessary to use absolute paths for everything in your crontab. This is where most people get hung up with cronjobs.”
https://tonyteaches.tech/schedule-python-script/
CC-MAIN-2021-31
refinedweb
1,107
76.11
The while loop is particularly suitable when the number of iterations is not known or can not be determined in advanced. In this section, another loop that is useful in similar situations, the do … while loop is discussed. In case of a do …while loop, it is a exit-controlled or bottom-tested loop as opposed to the while loop which is entry-controlled or top-tested. The do and while commands are separated by one statement. If it is required to include more statements they should be included between a pair of curly brackets to present them as a single block of statements, otherwise the compiler will send out an error message. In a program, do is placed at the top of the statements and while is placed at the bottom of statements. The test is carried out after the execution of statements in the while expression, i.e., at bottom of loop. The statements are executed from top to bottom. Therefore, even if the while expression evaluates false, at least one computation is carried out. Thus, the statement(s) within a do … while loop will be executed at least once, whereas the statement(s) within a while loop may not be executed at all. The general syntax of the do…while loop is given below. do statement; while ( expr) ; where expr is the loop control expression that may be any valid C expression such as arithmetic, relational or logical and statement is the loop body that is to be executed repeatedly. The body of the do…while loop may comprise a compound or a block statement as shown below. do { statement; statement ; ……… }while ( expr ) ; The flowchart for the do … while loop is given in Fig. When the loop is entered, the statement(s) within the loop are executed and then expression expr is evaluated. If the value of expr is true (non-zero), the body of the loop is executed again; otherwise, control leaves the loop. Thus, the body of the loop is executed until expression expr evaluates as true (non-zero). Note that the statements within the do … while loop loop will be executed at least once. Although the for loop is more suitable in situations where the number of iterations are known or can be determined in advance, we can also use the do … while loop in such situations. This can be done as follows: initial_expr ; do { statement; update_expr ; } while (final_expr ) ; However, remember that this is not equivalent to the for loop given below as the do…while loop is bottom-tested, whereas the for loop is top-tested. for ( initial_expr ; final_expr ; update_expr) statement; Illustrates do-while loop #include <stdio.h> void main() { int i =5, m=0,n=0; clrscr(); printf("i\t m\t n\n"); do { m =i*i; n = i*i*i; printf("%d\t %d\t %d\n", i, m, n ); i--; } while(i<=2 ); } The output given below shows that even though the condition is false, the program has been executed once.
https://ecomputernotes.com/what-is-c/control-structures/do-while-loop-in-c
CC-MAIN-2022-05
refinedweb
502
59.23
If you have been using Windows Workflow Foundation to build web service business logic, you may be using the publish-as-web-service tool that is part of the Visual Studio extensions for Windows Workflow Foundation. How it works is if you have a workflow model defined in a Visual Studio project you can right click on the project and choose "Publish as Web Service" from the menu. The tool will add a new project to your solution which is a web service. This new web service will execute the workflow. Your workflow model must have at least one WebServiceInput activity in it to do this. The thing that many people have been finding is that it uses the default namespace of TEMPURI.ORG and it's not configurable. Well here's how you can change the namespace with a minimum of fuss. We're planning a KB article with a more official description of this. 1) First the web service is generated code which is compiled and you are left with the DLL only. The source is deleted by default. You want to change that. There's a registry key that you can set to keep the source for the web service. Usual disclaimers apply about changing the registry on your machine. Here's the key to set: 2) Next go ahead and publish your web service normally as described above. This will create the source and compile it, but it will not be deleted. Right click on your web service project and choose ASP.NET Folder -> App_Code. Now you need to go and fetch the generated source from your Temp directory. My temp directory on Windows Vista is at C:\Users\pandrew\AppData\Local\Temp. Find the recently generated .CS file there and copy it. My test one here was called 077px_9s.cs. Put this file into the App_Code folder using explorer. Now edit the .ASMX file in your project and add the CodeBehind="~/Filea.cs". See I renamed the file from 077px_9s.cs to Filea.cs. My test WorkflowLibrary1.Workflow1_WebService.asmx file now looks like this: <%@ WebService CodeBehind="~/Filea.cs" Class="WorkflowLibrary1.MyClass" %> 3) The final step is to open your newly added code behind file and add the new namespace into the file. Just add the WebService attribute to the class and specify the namespace in that attribute, something like this: [WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1, EmitConformanceClaims=true)] [WebService(Namespace="")] public class MyClass : WorkflowWebService { Once you've done that you can recompile the project and you should have a web service that is implemented by a workflow model and your chosen namespace. PS: This is my first blog entry written in Word 2007. Useful, but horrible :-) I can't see fishing around in the Temp folder as a part of anyone's development process for anything more than a one-off - are there plans to add a namespace override option for RTM? Hi Kev, Unfortunately we passed the deadline for making changes like that quite some time ago. Regards, Paul Understood, I wasn't making a eature request at this late stage. I was just hoping someone might have thought of it in time. Please create a VS.NET macro or shortcut that does this. This is horrible; can't imagine doing this each time my WF project WS receive changes... Thanks for the article, at least its possible now. Best regards, Christof By default the web service wrapper generated around a workflow use the "tempuri.org" namespace. Not very Some of my collegaues are working on a much better solution than this work around. Hope to see this posted shortly. Cheers, Trademarks | Privacy Statement
http://blogs.msdn.com/pandrew/archive/2006/10/25/extending-the-wf-publish-as-web-service-or-get-rid-of-tempura-org.aspx
crawl-002
refinedweb
608
67.35
a pluggable irc bot framework in python Project description the pluggable python framework for IRC bots and Twitch bots Tutorial Installation $ pip install pinhook Creating an IRC Bot To create the bot, just create a python file with the following: from pinhook.bot import Bot bot = Bot( channels=['#foo', '#bar'], nickname='ph-bot', server='irc.freenode.net' ) bot.start() This will start a basic bot and look for plugins in the ‘plugins’ directory to add functionality. Optional arguments are: - port: choose a custom port to connect to the server (default: 6667) - ops: list of operators who can do things like make the bot join other channels or quit (default: empty list) - plugin_dir: directory where the bot should look for plugins (default: “plugins”) - log_level: string indicating logging level. Logging can be disabled by setting this to “off”. (default: “info”) - ns_pass: this is the password to identify with nickserv - server_pass: password for the server - ssl_required: boolean to turn ssl on or off Creating a Twitch Bot Pinhook has a baked in way to connect directly to a twitch channel from pinhook.bot import TwitchBot bot = TwitchBot( nickname='ph-bot', channel='#channel', token='super-secret-oauth-token' ) bot.start() This function has far less options, as the server, port, and ssl are already handled by twitch. Optional aguments are: - ops - plugin_dir - log_level These options are the same for both IRC and Twitch Creating plugins In your chosen plugins directory (“plugins” by default) make a python file with a function. You can use the @pinhook.plugin.register decorator to tell the bot the command to activate the function. The function will need to be structured as such: import pinhook.plugin @pinhook.plugin.register('!test') def test_plugin(msg): message = '{}: this is a test!'.format(msg.nick) return pinhook.plugin.message(message) The function will need to accept a single argument in order to accept a Message object from the bot. The Message object has the following attributes: - cmd: the command that triggered the function - nick: the user who triggered the command - arg: all the trailing text after the command. This is what you will use to get optional information for the command - channel: the channel where the command was initiated - ops: the list of bot operators - botnick: the nickname of the bot - logger: instance of Bot’s logger The plugin function must return one of the following in order to give a response to the command: - pinhook.plugin.message: basic message in channel where command was triggered - pinhook.plugin.action: CTCP action in the channel where command was triggered (basically like using /me does a thing) Examples There are some basic examples in the examples directory in this repository. For a live and maintained bot running the current version of pinhook see pinhook-tilde. Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/pinhook/
CC-MAIN-2018-51
refinedweb
486
50.77
The programming language many love to hate is experiencing a renaissance. This is not your parents’ PHP. The new PHP is a more mature language with community standards, interoperable components, and a passionate movement toward improved performance. If you bypassed PHP for alternative languages, or if you are a PHP veteran unaware of recent changes, you should absolutely give PHP a second look. Language features PHP 7.0 (the latest stable version as I'm writing this) has made tremendous progress from earlier versions. Recent PHP releases contain powerful new features and helpful developer tools including: - Namespaces; - Traits; - Scalar type hints; - Return type declarations; - Secure psuedo-random number generator; - Password hashing API; - New error and exception handling system; - Built-in web server; - Built-in FastCGI process manager; - Built-in phpdbg debugger; Many of these features have accumulated since PHP 5.4. Perhaps the most notable feature of PHP 7.0, however, is raw performance. PHP 7.0 packages these powerful features into a codebase that is up to twice as fast as PHP 5.6. WordPress, Drupal, Symfony, Laravel, and other PHP frameworks all see tremendous speed increases thanks to PHP 7.0. Interoperable components A few years ago, PHP had only a handful of frameworks (e.g. CakePHP, CodeIgniter, and so on). Each framework was an island and provided its own implementation of features commonly duplicated in other frameworks. Unfortunately, these insular implementations were often incompatible with each other; PHP developers had to lock themselves to a specific framework for a given project. Today the story is different. The new PHP community uses package management and component libraries to mix and match the best available tools. I like to compare the new PHP ecosystem to grocery shopping. If I need to consume a remote API, I’ll visit aisle 3 and pick up Guzzle. Do I need a request router? Symfony, Aura, Slim, and FastRoute are on aisle 4. You get the gist. The new PHP is about interoperable components using their comparative advantage to provide the best combination of ingredients for your project. The easiest way to start using PHP components is to install the Composer package manager and browse the Packagist component repository. Community standards Because the new PHP community is large and diverse with many PHP components, it is important that components adhere to shared interfaces and common code style guidelines. Shared interfaces help PHP developers implement new features without reinventing wheels. Common code style guidelines reduce learning curves and allow different developers to read and contribute to shared code. The PHP Framework Interop Group (PHP-FIG) is an unofficial but authoritative group of PHP framework developers and community representatives whose goal is “to talk about the commonalities between our projects and find ways we can work together. The PHP-FIG has passed several standards so far: - PSR-1 (Basic code style); - PSR-2 (Strict code style); - PSR-3 (Logging interfaces); - PSR-4 (Autoloading); - PSR-7 (HTTP message interfaces); These standards propose file, class, and namespace conventions, code style guidelines, and a set of shared interfaces to encourage component and framework interoperability. The PHP-FIG is by no means the law of the land, but its suggested standards are adopted by many of the most popular PHP frameworks. Its goals are admirable, and it welcomes feedback. I highly encourage you to consider implementing the PHP-FIG standards in your PHP code and to submit feedback on future PHP-FIG proposals. Performance There are also exciting things happening with PHP under the hood, too. The Zend Engine included with PHP 7.0 provides up to twice the performance of PHP 5.6. This is possible thanks to reduced memory usage and optimized heap and stack utilization. In practical terms, most modern PHP frameworks will realize serious performance gains with PHP 7.0, essentially for free. Facebook continues to make great progress on its alternative open-source PHP engine, the HipHop Virtual Machine (HHVM). HHVM uses just-in-time compilation to provide great performance while still allowing the dynamic interpretation to which PHP developers are accustomed. PHP 7.0, however, narrows the performance gap with HHVM. PHP 7.0 and HHVM are leveraging each other's momentum to propel themselves further in terms of performance and features. It truly is an exciting time to be a PHP developer. Resources Here are a few resources to help you get up to speed with PHP 7.0: - - - - - - - - - Find out more about the new PHP. Browse PHP ebooks and videos at shop.oreilly.com
https://www.oreilly.com/ideas/the-new-php
CC-MAIN-2018-13
refinedweb
753
55.64
KTRACE(9) BSD Kernel Manual KTRACE(9) ktrcsw, ktremul, ktrgenio, ktrnamei, ktrpsig, ktrsyscall, ktrsysret, KTRPOINT - process tracing kernel interface #include <sys/param.h> #include <sys/proc.h> #include <sys/ktrace.h> KTRPOINT(struct proc *p, int type); void ktrcsw(struct proc *p, int out, int user); void ktremul(struct proc *p, char *emul); void ktrgenio(struct proc *p, int fd, enum uio_rw rw, struct iovec *iov, int len, int error); void ktrnamei(struct proc *p, char *path); void ktrpsig(struct proc *p, int sig, sig_t action, int mask, int code, siginfo_t *si); void ktrsyscall(struct proc *p, register_t code, size_t argsize, register_t args[]); void ktrsysret(struct proc *p, register_t code, int error, register_t retval); This interface is meant for kernel subsystems and machine dependent code to inform the user about the events occurring to the process should trac- ing of such be enabled using the ktrace(2) system call. Each of the func- tions (except for KTRPOINT) is meant for a particular type of event and is described below. The KTRPOINT() macro should be used before calling any of the other trac- ing functions to verify that tracing for that particular type of events has been enabled. Possible values for the type argument are a mask of the KTRFAC_ values described in ktrace(2). ktrcsw() is called during the context switching. The user argument is a boolean value specifying whether the process has been put into a waiting state (true) or placed onto a running queue (false). Furthermore the user argument indicates whether a voluntary (false) or an involuntary (true) switching has happened. ktremul() should be called every time emulation for the execution en- vironment is changed and thus the name of which is given in the name ar- gument. ktrgenio() should be called for each generic input/output transaction that is described by the fd file descriptor, rw transaction type (consult sys/sys/uio.h for the enum uio_rw definition), iov input/output data vec- tor, len size of the iov vector, and, lastly, error status of the tran- saction. ktrnamei() should be called every time a namei(9) operation is performed over the path name. ktrpsig() should be called for each signal sig posted for the traced pro- cess. The action taken is one of SIG_DFL, SIG_IGN, or SIG_ERR as described in the sigaction(2) document. mask is the current traced pro- cess' signal mask. Signal-specific code and siginfo_t structure as described in <sys/siginfo.h> are given in the code and si arguments respectively. ktrsyscall() should be called for each system call number code executed with arguments in args of total count of argsize. ktrsysret() should be called for a return from each system call number code and error number of error as described in errno(2) and a return value in retval that is syscall dependent. The process tracing facility is implemented in sys/kern/kern_ktrace.c. errno(2), ktrace(2), syscall(2), namei(9), syscall(9) The process tracing facility first appeared in 4.4BSD. The ktrace section manual page appeared in OpenBSD 3.4. MirOS BSD #10-current July 21,.
https://www.mirbsd.org/htman/i386/man9/ktrsysret.htm
CC-MAIN-2016-07
refinedweb
517
60.55
Don't Let Your Java Objects Escape How to use Escape Analysis with your Java projects to create more optimal, useful code. Join the DZone community and get the full member experience.Join For Free Background I am working on the Open Source project Speedment and for us contributors, it is important to use code that people can understand and improve. It is also important that performance is good, otherwise people are likely to use some other solution. Escape Analysis allows us to write performant code at the same time we can use good code style with appropriate abstractions. This is Escape Analysis Escape Analysis (also abbreviated as "EA") allows the Java compiler to optimize our code in many ways. Consider the following simple Point class: public class Point { private final int x, y; public Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { final StringBuilder sb = new StringBuilder() .append("(") .append(x) .append(", ") .append(y) .append(")"); return sb.toString(); } } So, after calling the method a million times, there might be millions of StringBuilder objects lying around? Not so! By employing EA, the compiler can allocate the StringBuilder on the stack instead. So when our method returns, the object is automatically deleted upon return, as the stack pointer is restored to the previous value it had before the method was called. Escape analysis has been available for a relatively long time in Java. In the beginning we had to enable it using command line options, but nowadays it is used by default. Java 8 has improved Escape Analysis compared to previous Java versions. How It Works Based on EA, an object's escape state will take on one of three distinct values: - GlobalEscape: An object may escape the method and/or the thread. Clearly, if an object is returned as the result of a method, its state is GlobalEscape. The same is true for objects that are stored in static fields or in fields of an object that itself is of state GlobalEscape. Also, if we override the finalize() method, the object will always be classified as GlobalEscape and thus, it will be allocated on the heap. This is logical, because eventually the object will be visible to the JVM's finalizer. There are also some other conditions that will render our object's status GlobalEscape. - ArgEscape: An object that is passed as an argument to a method but cannot otherwise be observed outside the method or by other threads. - NoEscape: An object that cannot escape the method or thread at all. can be allocated on the stack or even in CPU registers using EA, with need. A Small Example public class Main { public static void main(String[] args) throws IOException { Point p = new Point(100, 200); sum(p); System.gc(); System.out.println("Press any key to continue"); System.in.read(); long sum = sum(p); System.out.println(sum); System.out.println("Press any key to continue2"); System.in.read(); sum = sum(p); System.out.println(sum); System.out.println("Press any key to exit"); System.in.read(); } private static long sum(Point p) { long sumLen = 0; for (int i = 0; i < 1_000_000; i++) { sumLen += p.toString().length(); } return sumLen; } } The code above will create a single instance of a Point and then it will call that Point's toString(). If we run the program with the following parameters, we will be able to see what is going on within the JVM: And yes, that is a huge pile of parameters but we really want to be able to see what is going on. After the first run, we get the following heap usage (after the System.gc() call cleaned up all our StringBuilders) The two following steps gave: pemi$ jmap -histo 50903 | head num #instances #bytes class name ---------------------------------------------- 1: 2001080 88101152 [C 2: 100 36777992 [I 3: 1001058 24025392 java.lang.String 4: 64513 1548312 java.lang.StringBuilder 5: 485 55272 java.lang.Class 6: 526 25936 [Ljava.lang.Object; 7: 13 25664 [B pemi$ jmap -histo 50903 | head num #instances #bytes class name ---------------------------------------------- 1: 4001081 176101184 [C 2: 2001059 48025416 java.lang.String 3: 105 32152064 [I 4: 64513 1548312 java.lang.StringBuilder 5: 485 55272 java.lang.Class 6: 526 25936 [Ljava.lang.Object; 7: 13 25664 [B As can be seen, EA was eventually able to eliminate the creation of the StringBuilder instances on the heap. There were only 64K created compared to the 2M Stings. A big improvement! Conclusions The advantages of Escape Analysis are nice in theory but they are somewhat difficult to understand and predict. We do not get a guarantee that we will get the optimizations we are expecting in all cases but it seems to work reasonably well under common conditions. Check out open-source Speedment and see if you can spot the places where we rely on Escape Analysis. Hopefully this post contributed to shed some light on EA so that you opt to write good code over "performant" code. I would like to thank Peter Lawery for the tips and suggestions I got from him in connection with writing this post. Published at DZone with permission of Per-Åke Minborg, DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own.
https://dzone.com/articles/do-not-let-your-java-objects-escape
CC-MAIN-2021-04
refinedweb
882
64.51
Github user zuyu commented on a diff in the pull request: --- Diff: cli/LineReaderBuffered.hpp --- @@ _LINE_READER_BUFFERED_HPP_ +#define QUICKSTEP_CLI_LINE_READER_BUFFERED_HPP_ + +#include <string> + +#include "cli/LineReader.hpp" +#include "utility/Macros.hpp" + +namespace quickstep { + +class LineReaderBuffered : public LineReader { + public: + /** + * @brief A line reader which accepts a string buffer. + * Other line readers are meant. + */ + LineReaderBuffered(const std::string &default_prompt, + const std::string &continue_prompt); + + LineReaderBuffered(); + + ~LineReaderBuffered() override {} + + /** + * @brief Replaces the current buffer contents with new contents. + * @param buffer Replacement text. + */ + void setBuffer(std::string buffer) { + leftover_ = buffer; + buffer_empty_ = false; + } + + /** + * @brief This is set to true after getNextCommand is called and runs out of input to process. + * @return True if the buffer has been consumed. + */ + bool bufferEmpty() { --- End diff -- Mark . ---
https://www.mail-archive.com/dev@quickstep.incubator.apache.org/msg02465.html
CC-MAIN-2017-26
refinedweb
113
52.66
I have been working on a program that uses Matplotlib to plot data consisting of around one million points. Sometimes the plots succeed but often I get an exception: OverFlowError: Agg rendering complexity exceeded. I can make this message go away by plotting the data in "chunks" as illustrated in the demo code below. However, the extra code is a chore which I don't think should be necessary - I hope the developers will be able to fix this issue sometime soon. I know that the development version has some modifications to addressing this issue. I wonder if it is expected to make the problem go away? By the way, this plot takes about 30 seconds to render on my I7 2600k. The main program reaches the show() statement quickly and prints "Done plotting?". Then I see that the program reaches 100% usage on one CPU core (4 real, 8 virtual on the 2600k) until the plot is displayed. I wonder if there is any way to persuade Matplotlib to run some of the chunks in parallel so as to use more CPU cores? Plotting something other than random data, the plots run faster and the maximum chunk size is smaller. The maximum chunk size also depends on the plot size - it is smaller for larger plots. I am wondering if I could use this to plot course and fine versions of the plots. The course plot is zoomed in version of the small-sized raster. That would be better than decimation as all the points would at least be there. Thanks in advance, David --------------------------- start code --------------------------------- ## Demo program shows how to "chunk" plots to avoid the exception: ··· ## ## OverflowError: Agg rendering complexity exceeded. ## Consider downsampling or decimating your data. ## ## David Smith December 2011. from pylab import * import numpy as np nPts=600100 x = np.random.rand(nPts) y = np.random.rand(nPts) ## This seems to always succeed if Npts <= 20000, but fails ## for Npts > 30000. For points between, it sometimes succeeds ## and sometimes fails. figure(1) plot (x, y) ## Chunking the plot alway succeeds. figure(2) chunk_size=20000 iStarts=range(x.size/chunk_size) for iStart in iStarts: print "Plotting chunk starting at %d\n" % iStart plot(x[iStart:iStart+chunk_size], y[iStart:iStart+chunk_size], '-b') left_overs = nPts % chunk_size if left_overs > 0: print "Leftovers %d points\n" % left_overs plot(x[-left_overs-1:], y[-left_overs-1:], '-r') print "done plotting?" show() ---------------------------------- end code ------------------------ Please don't reply to this post "It is rediculous to plot 1 million points on screen". I am routinely capturing million-point traces from oscilloscopes and other test equipment and to I need to be able to spot features in the data (glitches if you will) that may not show up plotting decimated data. I can then zoom the plot to inspect these features.
https://discourse.matplotlib.org/t/how-to-do-million-data-point-plots-with-matplotlib/16351
CC-MAIN-2021-49
refinedweb
466
64.2
table of contents other languages NAME¶ lockf - apply, test or remove a POSIX lock on an open file SYNOPSIS¶ #include <sys/file.h> int lockf(int fd, int cmd, off_t len); DESCRIPTION¶ Apply, test or remove a POSIX lock on an open file. The file is specified by fd. This call is just an interface for fcntl(2). Valid operations are given below: - F_LOCK - Set an exclusive lock to the file. Only one process may hold an exclusive lock for a given file at a given time. If the file is already locked it blocks until the previous lock is released. - F_TLOCK - Same as F_LOCK but never blocks and return error instead if the file is already locked. - F_ULOCK - Unlock the file. - F_TEST - Test the lock: return 0 if fd is unlocked or locked by this process; return -1, set errno to EACCES, if another process holds the lock. RETURN VALUE¶ On success, zero is returned. On error, -1 is returned, and errno is set appropriately. ERRORS¶ - EAGAIN - The file is locked and the LOCK_NB flag was selected, or operation is prohibited because the file has been memory-mapped by another process. - EBADF - fd is not an open file descriptor. - EDEADLK - Specified lock operation would cause a deadlock. - EINVAL - An invalid operation was specified in fd. - ENOLCK - Too many segment locks open, lock table is full. CONFORMING TO¶ SYSV SEE ALSO¶ fcntl(2), flock(2). There are also locks.txt and mandatory.txt in /usr/src/linux/Documentation.
https://manpages.debian.org/unstable/manpages-pt-dev/lockf.3.pt.html
CC-MAIN-2022-05
refinedweb
248
68.57
| Join Last post 05-09-2008 4:59 AM by talg. 2 replies. Sort Posts: Oldest to newest Newest to oldest Hello all, I am planing a set project for a web site application, there are two unsolved issues that i would like to share with you and fortunly get clear idea about how to acomplish it. I need to retrive a text box'es text property and deploy it on the web config file,or any other xml file with the above value, I know how to raise the install event on a webapplication but i need it on website, anyway it would be good enoufh if i could save an xml file on the same location of my web site,but web aplication dont seem to "know" the path to the actual iis location I attached my webaplication class ,Please let me know what should i do Great day, tal g. public { add_node( } xml_serializer.Serialize(node To get the physical path, you can use the MapPath function on the page. It would look like this: sw = new FileStream(this.MapPath("../config.xml"), FileMode.CreateNew, FileAccess.Write);xml_serializer = new XmlSerializer(typeof(string)); Hi Thanks for the rapid answer, The problem is that the raised event (installer method) which raise after installation of the project (MSI) could be reched only on a new project i just specificly for this mission created(Web apllication proj) , The web site is my base project and I couldnt figure out how to raise install event on this project. I tryied your solution(On the web application) but the intelisense dont know the mappath method, Is a namespace missing? or that web application cant connect to local host url? - By my common sense the secound option seem to be the corect, Am i right? Maybe there are some other options? Much Thanks Hope I was a little more understood. Advertise on ASP.NET About this Site © 2008 Microsoft Corporation. All Rights Reserved. | Terms of Use | Trademarks | Privacy Statement
http://forums.asp.net/t/1258626.aspx
crawl-001
refinedweb
333
68.5
How to Copy an Array in Java Last modified: May 7, 2017 by baeldung Java If you’re working with Spring, check out "REST With Spring": >> CHECK OUT THE COURSE 1. Overview In this quick article, we’ll discuss different array copying methods in Java. Array copy may seem like a trivial task, but it may cause unexpected results and program behaviors if not done carefully. 2. The System Class Let’s start with the core Java library – System.arrayCopy(); this copies an array from a source array to a destination array, starting the copy action from the source position to the target position till the specified length. The number of elements copied to the target array equals the specified length. It provides an easy way to copy a sub-sequence of an array to another. If any of the array arguments is null, it throws a NullPointerException and if any of the integer arguments is negative or out of range, it throws an IndexOutOfBoundException. Let’s have a look at an example to copy a full array to another using the java.util.System class: int[] array = {23, 43, 55}; int[] copiedArray = new int[3]; System.arraycopy(array, 0, copiedArray, 0, 3); Arguments this method take are; a source array, the starting position to copy from source array, a destination array, the starting position in the destination array, and the number of elements to be copied. Let’s have a look at another example that shows copying a sub-sequence from a source array to a destination: int[] array = {23, 43, 55, 12, 65, 88, 92}; int[] copiedArray = new int[3]; System.arraycopy(array, 2, copiedArray, 0, 3); assertTrue(3 == copiedArray.length); assertTrue(copiedArray[0] == array[2]); assertTrue(copiedArray[1] == array[3]); assertTrue(copiedArray[2] == array[4]); 3. The Arrays Class The Arrays class also offers multiple overloaded methods to copy an array to another. Internally, it uses the same approach provided by System class that we have seen earlier. It mainly provides two methods, copyOf(…) and copyRangeOf(…). Let’s have a look at copyOf first: int[] array = {23, 43, 55, 12}; int newLength = array.length; int[] copiedArray = Arrays.copyOf(array, newLength); It’s important to note that Arrays class uses Math.min(…) for selecting the minimum of the source array length and the value of the new length parameter to determine the size of the resulting array. Arrays.copyOfRange() takes 2 parameters, ‘from’ and ‘to’ in addition to the source array parameter. The resulting array includes the ‘from’ index but the ‘to’ index is excluded. Let’s see an example: int[] array = {23, 43, 55, 12, 65, 88, 92}; int[] copiedArray = Arrays.copyOfRange(array, 1, 4); assertTrue(3 == copiedArray.length); assertTrue(copiedArray[0] == array[1]); assertTrue(copiedArray[1] == array[2]); assertTrue(copiedArray[2] == array[3]); Both of these methods do a shallow copy of objects if applied on an array of non-primitive object types. Let’s see an example test case: Employee[] copiedArray = Arrays.copyOf(employees, employees.length); employees[0].setName(employees[0].getName() + "_Changed"); assertArrayEquals(copiedArray, array); Because the result is a shallow copy – a change in the employee name of an element of the original array caused the change in the copy array. And so – if we want to do a deep copy of non-primitive types – we can go for the other options described in the upcoming sections. 4. Array Copy with Object.clone() Object.clone() is inherited from Object class in an array. Let’s first copy an array of primitive types using clone method: int[] array = {23, 43, 55, 12}; int[] copiedArray = array.clone(); And a proof that it works: assertArrayEquals(copiedArray, array); array[0] = 9; assertTrue(copiedArray[0] != array[0]); The above example shows that have the same content after cloning but they hold different references, so any change in any of them won’t affect the other one. On the other hand, if we clone an array of non-primitive types using the same method, then the results will be different. It creates a shallow copy of the non-primitive type array elements, even if the enclosed object’s class implements the Cloneable interface and overrides the clone() method from the Object class. Let’s have a look at an example: public class Address implements Cloneable { // ... @Override protected Object clone() throws CloneNotSupportedException { super.clone(); Address address = new Address(); address.setCity(this.city); return address; } } We can test our implementation by creating a new array of addresses and invoking our clone() method: Address[] addresses = createAddressArray(); Address[] copiedArray = addresses.clone(); addresses[0].setCity(addresses[0].getCity() + "_Changed"); assertArrayEquals(copiedArray, addresses); This example shows that any change in the original or copied array would cause the change in the other one even when the enclosed objects are Cloneable. 5. Using the Stream API It turns out, we can use the Stream API for copying arrays too. Let’s have a look at an example: String[] strArray = {"orange", "red", "green'"}; String[] copiedArray = Arrays.stream(strArray).toArray(String[]::new); For the non-primitive types, it will also do a shallow copy of objects. To learn more about Java 8 Streams, you can start here. 6. External Libraries Apache Commons 3 offers a utility class called SerializationUtils that provides a clone(…) method. It is very useful if we need to do a deep copy of an array of non-primitive types. It can be downloaded from here and its Maven dependency is: <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.5</version> </dependency> Let’s have a look at a test case: public class Employee implements Serializable { // fields // standard getters and setters } Employee[] employees = createEmployeesArray(); Employee[] copiedArray = SerializationUtils.clone(employees); employees[0].setName(employees[0].getName() + "_Changed"); assertFalse( copiedArray[0].getName().equals(employees[0].getName())); This class requires that each object should implement the Serializable interface. In terms of performance, it is slower than the clone methods written manually for each of the objects in our object graph to copy. 7. Conclusion In this tutorial, we had a look at the various options to copy an array in Java. The method to use is mainly dependent upon the exact scenario. As long as we’re using a primitive type array, we can use any of the methods offered by the System and Arrays classes. There shouldn’t be any difference in performance. For non-primitive types, if we need to do a deep copy of an array we can either use the SerializationUtils or add clone methods to our classes explicitly. And as always, the examples shown in this article are available on over on GitHub. The new Certification Class of "REST With Spring" is finally out: >> CHECK OUT THE COURSE Learning to "Build your API with Spring"? >> Get the eBook
http://www.baeldung.com/java-array-copy
CC-MAIN-2017-26
refinedweb
1,129
54.73
Gary Poster wrote: > > > Checking in the code is an assertion of provenance/license: for > instance, I wouldn't have known about the Plone code, which is > potentially a problem because of GPL vs. ZPL (see below). > Hold-off on checking-in jsmin. The original author of the packer has not decided whether allow us a BSD-ish license or ZPL. > Wanna get commit privileges? :-) It's the easiest way for you to > assert the code's status. > Can't at the moment. My note to Benji explains. Maybe after I see the new contributor agreement... >>> - putting them in a namespace? >> Probably a good idea. If it was only one... well, but I do seem to have >> gotten prolific. :) > > :-) > >> Go for it (on whichever namespace gets decided). These three projects, >> I feel a need to reiterate, need zope.paste and Paste.Deploy (or a >> similar stack), to use with zope3, so deprecating zc.resourcelibrary may >> not be a good idea until more folks are on-board with the wsgi filters >> idea. > > I think the project is on board with wsgi. paste is maybe not as > mainstream in the Zope world yet, so yes, maybe we need to let that > settle out. If there are no issues with the paste-based version, > though, I'd like zc to use it. > No further issues. There is some code from Python Cookbook (Python License, presumably, and presumably acceptable) but the rest is substantially mine. >> gzipper and jsmin really have no particular ties to zope at all, >> except that I used Zope3 for developing them, and they probably work OK >> in Zope3 as a consequence. (PS. er, actually, the packer in jsmin came >> from Plone.) > > eek! GPL can't go in zope.org. Do you know what the license is to > that particular component? > Of course, I went "eek!" first when Balazs wanted to include the packer in jsonserver / concatresource when it was GPL. This will be handled in a most appropriate and satisfactory manner. > With the caveats above, sounds great. :-) > Good. You will find that my code has the very liberal Academic Free License referenced. If you need different, I will be happy to relicense. Advertising -Jim Washington _______________________________________________ Zope3-users mailing list Zope3-users@zope.org
https://www.mail-archive.com/zope3-users@zope.org/msg02884.html
CC-MAIN-2016-50
refinedweb
373
77.84
import Specifies another .idl, .odl, or header file containing definitions you want to reference from your main IDL. Parameters - idl_file The name of an .idl file that you want imported into the type library of the current project. The import C++ attribute causes an #import statement to be placed below the import "docobj.idl" statement in the generated .idl file. The import attribute has the same functionality as the import MIDL attribute. The import attribute only places the specified file into the .idl file that will be generated by your project; the import attribute does not let you call constructs in the specified file from source code in your project. To call constructs in the specified file from source code in your project, either use #import and the embedded_idl attribute or you can include the .h file for the idl_file, if a .h file exists. The following code: produces the following code in the generated .idl file: For more information, see Attribute Contexts.
https://msdn.microsoft.com/en-US/library/w2de1a8a(d=printer,v=vs.80).aspx
CC-MAIN-2015-32
refinedweb
163
68.16
perlmeditation mstone <p><b>Meditations on Programming Theory <br>meditation #3: identification, part 1: variables</b></p> <p>Okay, this is where things get complicated.</p> <p>The concept of identification is only the tip of a tightly-interconnected iceberg. I'm going to start by blasting my way through a bunch of vocabulary so you have some idea of where the major pieces are, then I'll go back and fill in the details.</p> <p><i>(and apologies for slipping schedule by 4 days.. I'll try to be back on track with the next one)</i></p> <readmore> <h1>Vocabulary:</h1> <ul> <li>The first piece of the identification iceberg is the concept of <b>encapsulation.</b> </ul> <p>Encapsulation means <b>putting something in a container.</b> When we encapsulate something, we create a boundary that separates 'things on the inside' from 'things on the outside'. Then we treat that container, and everything in it, as a single, coherent unit. For want of a better term, we call that unit an <b>entity.</b></p> <ul> <li> Encapsulation gives rise to the concept of <b>abstraction.</b> </ul> <p>We treat entities differently depending on whether we're looking at them from the inside or from the outside. From the inside, an entity can have any number of pieces. From the outside, an entity is a single, irreducible thing.</p> <p>The word <b>'abstraction'</b> means <b>'taking something away',</b> and in this case, moving from the inside of an entity to its outside takes away information about the entity's internal structure. We <b>abstract</b> an entity's structure by putting those pieces into a container. The boundary between an entity's inside and outside, which defines the limits of what we can see, is called an <b>abstraction barrier.</b></p> <ul> <li>Abstraction barriers gives rise to a concept called <b>scope.</b> </ul> <p>We can only see the pieces that make up an entity from inside the entity's abstraction barrier. For all intents and purposes, neither the pieces, nor the rules that apply to them, exist outside that barrier. The term <b>scope</b> refers to the region inside the abstraction barrier, where those pieces and rules do exist.</p> <ul> <li>An <b>identifier</b> is a string that represents an entity, as seen from outside the abstraction barrier. </ul> <p>Encapsulation and abstraction are powerful concepts, but we can't actually do much with an entity until we give it a name. The rule that associates a specific name with a specific entity is called a <b>binding,</b> and bindings give us the concept of identification.</p> <p>Identification gives us two further concepts: <b>specification</b> and <b>object permanence.</b> <b>referentially transparent,</b> and I'll discuss that idea in more detail later.</p> <ul> <li> A <b>value</b> is a string that represents an entity, as seen from inside the abstraction barrier. </ul> <p> <b>value.</b></p> <p>A value summarizes an entity's internal structure. Summation is a form of abstraction, which means that a summary can pass through an entity's abstraction barrier. The process of finding a string that serves as an abstract summary for whatever lives inside an entity is called <b>evaluation.</b></p> <ul> <li> The association between an entity's name and its value is called <b>reference.</b> </ul> <p>At this point we have three items to consider: <ol> <li> an entity <li> the name that identifies it <li> and the value that summarizes it </ol> <p>We know that the relationship between the entity and its name is called identification, and that the relationship between the entity and its value is called summation. That still leaves the relationship between the name and the value, though. We call that relationship <b>reference.</b> A name identifies its entity, but we say that it <b>refers to</b> the entity's value. The act of replacing a name with its associated value is called <b>dereferencing.</b></p> <p <i>much</i> more powerful than the "replace this string with that string" kind.</p> <h1>Discussion:</h1> <p>Now that we have all those terms out on the table, entities tend to fall into one of two general categories: <b>variables</b> and <b>functions.</b>.</p> <h2>variables:</h2> <p>I should start by saying that this kind of variable has very little to do with the <tt>'$x'</tt> structures that Perl programmers call 'variables'. When programmers think about variables, they tend to think about addressable blocks of mutable storage. Officially, those are called <b>lvalues</b> because they can appear on the left-hand side of an assignment expression. For the purposes of this discussion, <b>lvalues are not variables.</b> Lvalues can do things that variables can't (i.e: violate the principle of referential transparency), which gives rise to unsolvable problems.</p> <p><digression> <br.</p> <p>As Larry Wall once said, "Perl is a mess because the problem space is a mess," and it's easy enough to use Perl in a referentially transparent way. <br></digression></p> <ul> <li>For the sake of this discussion, <b>a variable is an entity that can have some value, but isn't restricted to any specific value.</b> </ul> <p>Variables represent the concept of picking a single value out of a set of possible values. The set of all values a variable can possibly have is called the variable's <b>type,</b> and I'll talk about types in a minute.</p> <p>We use the term <b>raw variable</b>.</p> <p>Raw variables are useful, because they let us define 'generic' operations that appply to every member of a type. We'll get a lot of mileage out of raw variables when start talking about functions.</p> <h3>variables and type:</h3> <p>As I mentioned before, a type is the set of all values a variable can possibly have. If we take that idea all the way back to the level of human assumptions, <b>a type tells us everything we can safely assume about a variable.</b> A type is an information space, and we can represent that space with an appropriately defined language.</p> <p>Now before anyone tries to make this point for me: Perl <i>does</i>.</p> <p.</p> <p>From a theoretical standpoint, the most interesting part of that whole rant was the statement, "defining a type system is just as hard as writing the program itself." That's true, but it takes a bit of work to show how and why.</p> <p>As I mentioned above, a type is an information space, and we can represent that space with a language. We use formal systems to generate languages, so there must be some kind of connection between types and formal systems.</p> <p>That connection is called a <b>decision problem.</b></p> <p, <b>"is this string a theorem?"</b></p> <p>As we saw in MOPT-02, the process of deriving theorems is called <b>computation.</b></p> <p <i>can</i> be computed, and if one of them matches our candidate, we can stop with an answer of 'yes'. We don't have any way to stop with an answer of 'no', though.</p> <p>Theorem proving belongs to a set of problems that are called <b>partially decidable,</b> or <b>recursively enumerable.</b>.</b></p> <p>We generally do that using raw variables. We start with a bunch of axioms of the form:</p> <code> If we apply operation X to a variable of type Y, we get a variable of type Z. </code> <p>which usually gets collapsed to the form:</p> <code> X(Y) : Z </code> <p>and then we start combining those rules to establish the limits of what's possible. We have to know what the operations are, though, and we have to break them down in sufficient detail to prove that <tt>X(Y)</tt> really does generate <tt>Z.</tt> By the time we've done that, we've built a microscopically-detailed specification for the actual program.</p> <p>Type systems are actually quite useful as design tools. They give us a way to keep track of our assumptions without getting bogged down in the details of implementation. They also give us line-by-line suggestions about testing and error handling procedures.</p> <h3>variables and scope:</h3> <p>So.. we know that types can be cool, and that a variable can adopt any value appropriate to its type. The trick of working with values is keeping track of when and where they're defined.</p> <p>Both the entity that acts as a variable, and the name that acts as that variable's identifier, can be defined within the scope of some other entity (called a <b>parent</b>) (1). If they are, they only have meaning within that parent's abstraction barrier, which means that they're subject to scope limitations.</p> <p><i>(1) - A variable's value, of course, will always be defined in the same scope as its name. We have to replace the one with the other, after all.</i></p> <p>An identifier that lives in a different scope than the entity it's bound to is called a <b>free variable.</b> Free variables aren't bound to any entity at all by the terms of their definition, so it's up to the compiler and runtime environment to work out a binding. The rules the compiler and runtime environment use to establish that binding are called <b>scope rules.</b></p> <p>Perl has four different sets of scope rules:</p> <ul> <li> <b>Global scope rules</b> <li> <b>Local scope rules</b> <li> <b>Lexical scope rules</b> <li> and <b>Package scope rules</b> </ul> <p>which cover most of the options available in any language.</p> <p>Under <b>global scope rules,</b> every occurrence of the same name is bound to the same entity. That entity is defined in the outermost parent, regardless of where the variable is first defined. Global scoping is also called <b>static scoping,</b> because the binding between the identifier and the entity never changes. The compiler can create the entity at compile time, and bind every instance of the identifier it sees to that entity as it works its way through the code.</p> <p>The following code, which demonstrates global binding:</p> <code> $GLOBAL = "static"; $LOCAL = "dynamic"; $LEXICAL = "lexical"; sub show_evaluation_context { printf ( "evaluation context: %s \n", join (',', ($GLOBAL, $LOCAL, $LEXICAL)) ); } sub global_scope { printf ( "global scope: %s \n", join (',', ($GLOBAL, $LOCAL, $LEXICAL)) ); show_evaluation_context(); } global_scope(); </code> <p>produces the following ouput:</p> <code> global scope: static,dynamic,lexical evaluation context: static,dynamic,lexical </code> <p>which is pretty much what we'd expect.</p> <p>Perl's <b>local scope rules</b> create a new entity every time the <tt>local()</tt> keyword is executed. Local scoping is also known as <b>dynamic scoping,</b> because a single identifier can be bound to several different entities during the course of a program's lifetime.</p> <p>The value of a dynamically-scoped variable depends on what's called the variable's <b>evaluation context.</b> <tt>local()</tt> keyword can create a new entity and establish a new binding.</p> <p>If we use the code above with a function that creates a dynamic (i.e.: local) variable:</p> <code> sub local_scope { local ($LOCAL) = "-------"; printf ( "local scope: %s \n", join (',', ($GLOBAL, $LOCAL, $LEXICAL)) ); show_evaluation_context(); } local_scope(); print "\n"; print "but outside local_scope(), we still have:\n"; show_evaluation_context(); </code> <p>we get this output:</p> <code> local scope: static,-------,lexical evaluation context: static,-------,lexical but outside local_scope(), we still have: evaluation context: static,dynamic,lexical </code> <p>which shows two different values for <tt>$LOCAL</tt> when we call it from two different evaluation contexts.</p> <p><b>Lexical scope rules</b> create entities that are only visible in the scope where they're defined. Lexically-scoped entities replace globally (or locally) scoped entities that are defined for the parent, but are not visible to any entity created in, of called from, the same scope.</p> <p>A function that sets a lexical variable:</p> <code> sub lexical_scope { my ($LEXICAL) = "-------"; printf ( "lexical scope: %s \n", join (',', ($GLOBAL, $LOCAL, $LEXICAL)) ); show_evaluation_context(); } sub local_override { local ($LEXICAL) = 'DYNAMICALLY RE-BOUND VALUE'; lexical_scope(); } local_override(); print "\n"; lexical_scope(); </code> <p>gives us this:</p> <code> lexical scope: static,dynamic,------- evaluation context: static,dynamic,DYNAMICALLY RE-BOUND VALUE lexical scope: static,dynamic,------- evaluation context: static,dynamic,lexical </code> <p>which shows that lexicals override both local and global bindings in the scope where they're defined. Unlike global or local bindings, though, lexical bindings don't do anything to the evaluation context <i>outside</i> the scope where they're defined.</p> <p:</p> <ul> <li>All three variables in <tt>show_evaluation_context()</tt> are free variables, and so are the three in <tt>global_scope().</tt> <li><tt>$GLOBAL</tt> and <tt>$LEXICAL</tt> are free in <tt>local_scope(),</tt> while <tt>$LOCAL</tt> is dynamically bound to the entity defined in that scope. <li><tt>$GLOBAL</tt> and <tt>$LOCAL</tt> are free in <tt>lexical_scope(),</tt> while <tt>$LEXICAL</tt> is lexically bound to the entity defined in that scope. </ul> <p>As soon as the new entities went out of scope, the free variables returned to their previous bindings. Re-binding free variables to new entities lets us create code that acts like the entity values are changing, without ever changing the values of the entities themselves.</p> <p>Finally, <b>package scope rules</b> <b>fully-qualified</b> identifier:</p> <code> package Foo; $VAR1 = "VAR1 in package 'Foo'."; package main; $VAR1 = "VAR1 in package 'main'."; $VAR2 = "VAR2 in package 'main'."; print $Foo::VAR1, "\n"; print $VAR1, "\n"; print $VAR2, "\n"; </code> <p>produces the output:</p> <code> VAR1 in package 'Foo'. VAR1 in package 'main'. VAR2 in package 'main'. </code> <h3>variables and referential transparency:</h3> <p><b>The principle of referential transparency</b>.</p> <p>The very idea of referential transparency seems crazy to most programmers who are used to thinking of variables as lvalues. The way they see it, the whole <i>point</i> of a variable is to store intermediate values while the program works its way through a calculation. Even so, for most problems, lvalues are just a convenience. In theoretical terms, we can get the same effect by re-binding a free variable to a series of new entities.</p> <p>In practical terms, lvalues can be one <i>heck</i> of a convenience, and when used with a smattering of discipline, can make code more readable while still observing the general spirit of referential transparency.</p> <p>For example.. the following snippet of code:</p> <code> my $total = 0; for $i (1..10) { $total += $i; } print $total, "\n"; </code> <p>isn't referentially transparent, because we assign a new value to <tt>$total</tt> each time we pass through the loop. The referentially transparent way to do the same job would be:</p> <code> sub sum_of { my ($item, @list) = @_; return ((defined $item) ? $item + sum_of (@list) : 0); } print sum_of (1..10), "\n"; </code> <p>which is mathematically correct, but harder to read.</p> <p.</p> .</p> <p>The problems with lvalues all share a common theme, though: <b>timing.</b></p> <p>When you use referentially transparent variables, the order of evaluation doesn't matter. Every entity will return the same value, so as long as you have all your bindings worked out, everything's fine.</p> <p>Lvalues don't work that way, though. The order of evaluation is very important. You have to keep your evaluations in synch with your <b>mutations</b> (changes to the entity's value), or the whole thing will go blooey. You don't want to want to rearrange the sequence: <p> <ol> <li> make sure X is greater than Y <li> subtract Y from X <li> make sure X is greater than Z <li> subtract Z from X </ol> <p>as:</p> <ol> <li> make sure X is greater than Y <li> make sure X is greater than Z <li> subtract Y from X <li> subtract Z from X </ol> <p>if you want to guarantee that X will always be greater than zero.</p> <p.</p> <p>By the same reasoning, though, the more tightly you focus your work with an lvalue, the better your chances of staying in synch.</p> <p>As a general rule of thumb, it's okay to manipulate an lvalue as long as:</p> <ul> <li> you only do it in the same scope where the lvalue was defined, <li> and you never refer to a previous value after a mutation is complete. </ul> <p>If you do that properly, you should be able to encapsulate that chunk of code, and use it as a referentially transparent function. The little summation loop that uses <tt>$total,</tt> above, obeys both of those rules. I'd personally use that version over the recursive version every time.</p> <p>If you <i>can't</i> encapsulate a chunk of code and create a referentially transparent function, that's a warning sign that should tell you to look for design problems.</p> <h1>Surrender:</h1> <p.</p> <p>Spend some time getting used to the vocabulary, and think about types, scoping, and referential transparency. I'll be back next week to talk about functions.</p>
https://www.perlmonks.org/?displaytype=xml;node_id=222451
CC-MAIN-2020-16
refinedweb
2,965
52.9
Problem statement: You have a list of items that you want to randomize. I’ve found myself in this situation many times. If the language you’re working in has a shuffle or randomize function, you’re set. However, there are plenty of languages that don’t provide built in support for such a function, leaving you on your own. The first time I was faced with this problem, I wrote a shuffle algorithm that looked something like this: The above algorithm swaps every element in the list with another randomly-chosen element in the list. But there are three problems with this algorithm: - It’s biased. - It’s biased. - It’s biased. Ok, so there’s really only one problem, but its a big one! This topic has been covered before, most notably by Jeff Atwood in his The Danger of Naïveté post. I’m writing this post to re-emphasize the importance of this topic, especially since I’ve made the mistake of implementing an incorrect shuffle in the past. How do we know that that above algorithm is biased? On the surface it seems reasonable, and certainly does some shuffling of the items. There are two ways to realize the incorrectness of the above algorithm. The first is theoretical. A list of N items has N factorial ( N!) possible orderings. Consider a list with three elements A, B, and C. There are 3! = 6 ways to order these elements: ABC ACB BAC BCA CAB CBA However, the above incorrect algorithm does not yield N! potential orderings. Each item’s final list index is chosen randomly from 0 to N, resulting in N possible final locations for each item. There are N items in the list, so this implementation results in N^N possible orderings. Since N^N is not evenly divisible by N!, some of the final list orderings must be more common than others. This produces a bias for these orderings (e.g., they’re more common than other orderings). The second way to observe the incorrectness is empirical (e.g., by running some examples). Let’s try to randomize our three element [A,B,C] list with the above biased algorithm, and compare those results to randomizing the list with the Fisher-Yates implementation shown below: If we shuffle our [A,B,C] list 1,000,000 times with each algorithm we end up with the following distribution for each of the six possible list orderings: The results show that the biased shuffle produces certain orderings more often than others. The correct Fisher-Yates algorithm produces each outcome with equal likelihood. We can repeat this experiment for a list with four elements. Here are the results: The numbers 1-24 each represent one of the 24 possible orderings of a list with four elements. The Fisher-Yates shuffle produces each final ordering with equal likelihood. The incorrect algorithm does not. The first time I saw this I was quite surprised. What makes this problem especially interesting is that the difference between the two algorithms is essentially one character. The incorrect algorithm has the line: The Fisher-Yates algorithm uses the following line instead: The Fisher-Yates shuffle algorithm (also called the Knuth shuffle) walks a list of items and swaps each item with another in the list. Each iteration the range of swappable items shrinks. The algorithm starts at index zero (it can also walk the list in reverse), and chooses a item from 0 to N at random. This selection freezes the 0th element in the shuffled list. The next iteration moves to index 1 and chooses an item from the remaining 1 to N indices. This repeats until the entire list is walked. On the surface, using something similar to the incorrect shuffle algorithm might not seem like a big deal. However, the shuffling bias grows as the number of list items grows since N^N grows faster than N!. The Fisher-Yates algorithm is a good one to have in your pocket. It comes in handy more often that you would think. 12 Comments Why didnt you just implement the following algorithm in the first place? It is equivalent to popping a randomly chosen item until the input list is empty. What made you expect that swapping randomly chosen items n times would shuffle the list? Hi Henri, Had I known about Fisher-Yates I would have of course used it over the incorrect algorithm :). I found myself in a situation where I needed to randomize/shuffle a collection, and the naive/incorrect implementation certainly does some shuffling, just in a biased way. What I found so interesting is that it’s not immediately obvious that the incorrect algorithm is biased. Think u have a cut and paste error as both algorithms are the same except for name unless I am hulcinating – which has happened befor There is a difference in the randomIndex line. The incorrect algorithm has randomIndex = random.randint(0, len(items) - 1) and the Fisher-Yates implementation has randomIndex = random.randint(i, len(items) - 1) Yes I noticed right after I hit submit! This is stated in what you’ve written, but the interesting part about this is that you actually achieve better randomization by reducing the number of outcomes. I wonder if the “naive” algorithm is periodically “more-correct”? That is, when N^N == k*n! then the “overflow” in outcomes produced by the naive algo would, itself, distribute evenly over n! outcomes. Actually … The number of outcomes isn’t reduced. There *are* only 720 possible combinations for a 6 card deck (6!). The outcome of the naive version however isn’t 6!, but 6^6. Where do these other combinations come out from? They actually don’t. They just repeat the 6! more often and in an uneven way. Matt actually provided a link to another article on CodingHorror. It’s very well written and explains quite a lot. You migt want to check it out, if you’re still wondering why Fisher-And-Yates is better than the naive version. ;-) the example need to be more in explanation and solve a problem. I don’t get it. I understand the math behind it, I see your graphs, but when I try it myself both shuffles give the same distribution. Run this: def pstats(f, items, n): stats = {} for i in range(n): shuffled = f(items) shuffledStr = ”.join(shuffled) if not shuffledStr in stats: stats[shuffledStr] = 0 stats[shuffledStr] += 1 import pprint pprint.pprint(stats) items = [‘A’,’B’,’C’] pstats(incorrect_shuffle, items, 240000) pstats(fisher_yates_shuffle, items, 240000) sir, i work for a communication industry…and i want to know is there any algorithm to shuffle the data sequence and rearranging it again at the receiver in the correct order without passing the transmitted pattern……. here in this example you are using random function whose value will be different every time i run that statement….therefore we need to transmit the whole pattern to the receiver so that we may arrange the data at receiver in correct order.. actually is there any method of shuffling or you can say rearranging any sequence without using random function……so that we donot need to transmit the whole new pattern to the receiver….. it can be generated at the receiver using the same algorithm we used at the transmitter…….. then we donot need to transmit the new pattern…. it will help in reducing bandwidth required for transmission Thanks for the post! A question regarding your theoretical explanation: you wrote “this implementation results in N^N possible orderings”. how could it create n^n permutations, if n^n>n! and there exist only n! permutations of an n-elements array? You are correct that there are only N! permutations for the array. The N^N possible outcomes means that some result orderings will be duplicates. Since N^N is not divisible by N!, it means the some orderings will be duplicated more than others, resulting in the bias for those orderings.
https://spin.atomicobject.com/2014/08/11/fisher-yates-shuffle-randomization-algorithm/
CC-MAIN-2017-47
refinedweb
1,339
65.42
glob.h - pathname pattern-matching types #include <glob.h> The <glob.h> header defines the structures and symbolic constants used by the glob() function. The structure type contains at least the following members: size_t gl_pathc count of paths matched by pattern char **gl_pathv pointer to a list of matched pathnames size_t gl_offs slots to reserve at the beginning of gl_pathv The following constants are provided as values for the flags argument: - GLOB_APPEND - Append generated pathnames to those previously obtained. - GLOB_DOOFFS - Specify how many null pointers to add to the beginning of - are defined as error return values: - GLOB_ABORTED - The scan was stopped because GLOB_ERR was set or returned non-zero. - GLOB_NOMATCH - The pattern does not match any existing pathname, and GLOB_NOCHECK was not set in flags. - GLOB_NOSPACE - An attempt to allocate memory failed. - GLOB_NOSYS - The implementation does not support this function. The following are declared as functions and may also be declared as macros. Function prototypes must be provided for use with an ISO C compiler. int glob(const char *, int, int (*)(const char *, int), glob_t *); void globfree (glob_t *); The implementation may define additional macros or constants using names beginning with GLOB_. None. None. glob(), the XCU specification.
http://pubs.opengroup.org/onlinepubs/7990989775/xsh/glob.h.html
CC-MAIN-2016-18
refinedweb
198
55.24
On Sep 29, 9:14 am, Paul Boddie <p... at boddie.org.uk> wrote: > On 29 Sep, 05:56, Terry Reedy <tjre... at udel.edu> wrote: > > > > > As I understand it, partly from postings here years ago... > > > Lexical: The namespace scope of 'n' in inner is determined by where > > inner is located in the code -- where is is compiled. This is Python > > (and nearly all modern languages). Even without closures, the global > > scope of a function is the module it is defined in. > > This is how I understand it, too. The confusing part involves the > definition of any inner function and how any "external" names are > bound or defined. As we've seen... > > def f(x): > def g(): > return x > x += 1 # added for illustration > return g > > ...it might look at first glance like the function known as g (within > f) should return the initial value of x (as known within f), since > that was the value x had when g was defined. The following is an > example execution trace based on that mental model: > > fn = f(1) > -> def f(1): > -> def g(): # g defined with x as 1 > -> return x # would be 1 > -> x += 1 # x becomes 2 > -> return g > fn() > -> def g(): > -> return x # would still be 1 > > However, as we know, this isn't the case in real Python since g isn't > initialised with the value of x at the time of its definition - it > instead maintains access to the namespace providing x. We must > therefore revise the example: > > fn = f(1) > -> def f(1): > -> def g(): # g refers to x within f(1) > -> return x # would be the current value of x within f(1) > -> x += 1 # x becomes 2 > -> return g > fn() > -> def g(): # g refers to x within f(1) > -> return x # would be the current value of x within f(1), which is > 2 > > This is the dynamic aspect of closures: values aren't used to > initialise inner functions; names are looked up from their origin. > > > Dynamic: The namespace scope of 'n' in inner, how it is looked up, is > > determined by where inner is called from. This is what you seemed to be > > suggesting -- look up 'n' based on the scope it is *used* in. > > Indeed. Dynamic scoping is confusing in that one has to set up an > appropriate "environment" for the closure to access so that references > to names can be meaningfully satisfied; obviously, this creates all > sorts of encapsulation problems. The confusing aspect of lexical > scoping, however, especially if non-local names can be changed, is > that the effects of closures are potentially distant - one doesn't > always invoke inner functions in the place where they were defined, as > we see above - and such effects may thus happen within "abandoned > namespaces" - that is, namespaces which can no longer be revisited and > used in their original context. So, in the above, once f has been > invoked, the namespace for that invocation effectively lives on, but > that namespace is not a general one for f - if we invoke f again, we > get another namespace as one should reasonably expect. > > A somewhat separate issue is illustrated by the modification of x > within f. Although for most statements, we would expect the value of x > to evolve following from a top-to-bottom traversal of the code within > a unit, function definition statements do not behave like, say, "for", > "if" or "while" statements. Now although this should be obvious at the > module global level, I feel that it can be easy to overlook within a > function where one normally expects to find plain old control-flow > constructs, expressions, assignments and so on. It is pertinent to > note, with respect to the original inquiry, that lambda functions are > subject to the same caveats, and I believe that lexical scoping was > introduced precisely to make lambda functions less cumbersome to > employ, eliminating the need to explicitly initialise them using the > "identity" default parameters trick, but obviously introducing the > consequences and potential misunderstandings described above. > > Paul I'm thinking of a comparison to try to see an example. I tried this which still surprised me at first. >>> g= [0] >>> f= lambda: g >>> del g >>> f() NameError: global name 'g' is not defined It took a little thinking. The namespace in 'f' is the global namespace. They are one in the same dictionary. id( f.namespace ) == id( main.namespace ). f.namespace is main.namespace. When f gets a parameter, its namespace is different by one (or two when two parameters, etc). >>> g=[0] >>> f= lambda h: lambda: h >>> i= f( g ) >>> del g >>> i() [0] The statement 'del g' removes 'g' from the module/global namespace, but it lives on in the namespace of 'f', or more accurately, 'i'. >>> g=[0] >>> f= lambda h: lambda: h >>> i= f( g ) >>> j= f( g ) >>> del g >>> i().append(1) >>> j() [0, 1] Here, the namespaces of 'main', 'i', and 'j', all have references to 'g'. 'i' and 'j' still have them when 'main' loses its. The lambda might be confusing. Take a simpler example of a namespace: >>> g= [0] >>> def h(): ... class A: ... a= g ... return A ... >>> i= h() >>> del g >>> i.a [0] Or even: >>> g=[0] >>> class A: ... a= g ... >>> del g >>> A.a [0] The class is executed immediately so 'A.a' gets a hold of 'g'. Function definitions keep a reference to the -identity-, not value, of the namespace they were defined in, and parameters are part of that namespace. >>> def h( a ): ... #new namespace in here, new on each call ... def i(): ... return a ... return i 'i' is not defined in the global namespace, it's defined in a brand new one that is created on every call of 'h'. 'a' is defined in that, so that's what 'a' when 'i' is called refers to. To be specific, the namespace 'h' defines only includes the names that are different from its enclosing scope. Regardless of what's defined below 'h', 'h' only defines one new variable, 'a'. Its value is passed in at call-time. 'i' needs to know what that namespace is-- that's how closures work-- so it saves a reference. That saved reference is to a namespace, not a variable though, which distinguishes it from the 'class A: a= g' statement that's executes immediately. There, 'a' stores the value of g. By contrast, 'i' stores 'h's entire namespace. In 'class A: a= g', the name 'a' is assigned to the contents of 'g'. In 'def i(): return a', 'a' is the value of a look up in a namespace by its name. >>> def h( a ): ... #new namespace in here ... def i(): ... return a ... return i ... >>> g=[0] >>> j= h(g) >>> hex(id(g)) '0x9ff440' >>> del g >>> hex(id(j())) '0x9ff440' >>> j.func_closure (<cell at 0x009FDF50: list object at 0x009FF440>,) By the time 'g' is deleted, 'j' has already hijacked a reference to it, which lives in the namespace of the 'i' it defined that time through. 'j()', originally 'g', and 'j's namespace all refer to the same object. Variables are keys in a namespace, even if it's an "abandoned namespace", adopting the term.
http://mail.python.org/pipermail/python-list/2008-September/503504.html
CC-MAIN-2013-20
refinedweb
1,196
69.41