Friday 6 August 2010

Script Data in MS SQL Server 2008 Database Tables using Generate SQL Server Script Wizard

Open the Generate Scripts SubMenu Item from Task Menu

First of all, open the Microsoft SQL Server Management Studio which is installed from the Client Tools of a MS SQL Server 2008 installation package.

Connect to a MS SQL Server 2008 database instance using the Server Explorer or using the Connect screen.

Then open the Object Explorer window and expand the Databases node.

Here I connected to the local SQL Server 2008 instance and clicked over the Databases node and a list of existing sql server databases are visible in the object explorer window now. Later, I clicked the sql database MyWorks which owns the tables that I want to script data, rows/records of the database.

Continue by right clicking on the database name and open the context menu, chooes Tasks menu and open submenu. Select Generate Script submenu item from the displated list.



Generate SQL Server Script Wizards

When you select the Generate Scripts sub menu item the Generate SQL Server Scripts Wizard starts. SQL administrators and sql programmers can use the Script Wizard to generate t-sql scripts as a t-sql scripter to create scripts for any object (tables, views, schemas, etc). You can work in detail on the Script Wizard and find useful hint that you can benefit in your sql developments.


Select Database to Script

The first step in the Script Wizard is detemining the database to work on. You can choose a sql database among the listed all sql databases existing on the sql server instance.



Choose Script Options

Here is the screen where sql developers can configure the script details, and where developers can shape the automatic generated script according to the applications needs and requirements.

For our case, since we want to script table data which exists in the database that I have selected in the previous steps, we should set the Script Data option to True. You can see that the Script Data option is listed in the Table/View Options sections on the Choose Script Options screen. Since default Script Data option is set to false by default, we should alter this option in order to get an Insert statement for each row in the database table.

Note : Set Script Data option to True



Choose Object Types

This option in the Script Wizard is for the types of the objects we want the script generator to build scripts for. Since we deal with database tables, we will select Tables among the listed options such as Schema and User-defined table types.



Choose Tables

Since we selected Tables in the previous step, the wizard now displays all the tables that exists in the selected sql database. Here as a developer, I make a list of tables that I want to generate table data scripts for. For our sample case, I only select one table.


Output Option

Output Option screen in the Generate Script Wizard is the screen where a sql administrator or a programmer can make a selection among the existing output options. The script generator can create the desired scripts in the forms of a file, also can split the automatic generated script per object basis, or define the file as a unicode file or in ANSI text. A database developer can also select the file name and the output file folder for the script engine to create and place the script file.

Other output options are script to clipboard, just like a Copy-Paste operation and the last option is displaying the generated script on a new query window in the Microsoft SQL Server Management Studio.

I selected the New Query Window option in order to display the generated script by the MS SQL Server 2008.



Script Wizard Summary

Here is the last stop before proceeding to the script generation where database programmers can see which options they have selected and can go back to previous screen and make re-selections in the options for a desired script.


Generate Script Progress

Generate Script Progress screen displays the status of the scripting operation. If an error occurs sql developers and administrators can find the error details on this screen. If everything runs without any error and does not fail, you will see Success status for each scripting action on the progress screen



Data Script on the Query Window

Since as the output option for the scripting, the New Query Window is selected, the final script is displayed on the SQL Server Management Studio Query Editor window as shown below.

This script is formed of a CREATE TABLE script for the source table and following that, INSERT statements for each row in the selected source table.

As you see, any sql developer or any database administrator can use the below script to create a copy of any sql database tables with their data on another sql database or an other sql server instance



So as a summary, I want to say that if you frequently need to move tables from one sql database to an other with its data like me, you can use the Script Data option of the Generate SQL Server Scripts wizard. The Script Data option is a new enhancement in SQL Server Management Studio with the latest version, Microsoft SQL Server 2008. So you should have installed the Client Tools for MS SQL Server 2008 before using this option. SQL programmers can export data as sql script by using one of the existing SQL Server tools, SQL Server Generate Script Wizard.

Three methods to transfer a mysql database

This is a list of methods alog with a description and howto for each method as well as advices about when to use each method.
1. phpMyAdmin. For this example I used php phpMyAdmin 2.9.1. Older versions may be a little different.

Export your database: Go in phpMyAdmin, select your database and go to Export tab. You should see a set of options, by default both data and structure should be checked so your export will contain the database structure and the actual data in the database. You can also pick the format of your export ( sql, csv, pdf, xml ...etc). For transferring the database you should use the SQL format. At the bottom of the page there should be a for that will let you specify the file name, and compression. If you select "none" the export will be dumped in your browser, this is not recommended because you would have to copy that sql and then paste it in phpMyAdmin on the new server and if the dump is large it may not work.

Import the database on the new server: Click on the SQL button in the left sidebar in phpMyAdmin. In the pop up window that just showed up go to "Import files" tab. In there you will be able to import the sql file you get from your first server.The problem with the phpMyAdmin approach is that most web server configurations limit the maximum size of files you upload or the maximum execution time of a php script or the maximum memory that a PHP script can use. So unless you have small dumps ( 1-10 mb ) this method is not recommended.

2. command line mysql client tools: if you have shell access to any of the servers ( ssh or telnet ) you can use the command line mysql client to either export (dump ) or import a mysql database .
To dump the database use mysqldump:


mysqldump -u "your_username" -p --lock-tables \\
"your_database" > your_database_dump.sql

I added --lock-tables there so that it puts a read lock on all tables while running the dump process to make sure that no one can modify the databases and create inconsistencies in the dump.
If you have more then one database that needs to be exported you can use the --databases option like this:


mysqldump -u "your_username" -p --lock-tables \\
--databases DB1 [DB2 DB3...] > your_database_dump.sql

If you want to export all of your databases you can just replace --databases DB1 [DB2 DB3...] with --all-databases
To import the databases on the new server you can try the phpMyAdmin method or if you have shell access (preferable ) you can use the mysql client. If you're going to use the mysql client you will have to transfer the dump file to the server ( use ftp or sftp/scp ).You might want to compress the file before transferring it


bzip2 your_database_dump.sql
scp your_database_dump.sql.bz2 user@newserver:~

and after the transfer finished, run this on the new server:


mysql -u "your username" -p "your_database" < database_dump.sql

or if your dump includes a "CREATE DATABASE" statement ( usually when a file contains the dump of more then one database or if you exported you databases using --all-databases or --databases options ) then you can just do:


mysql -u "your_username" -p < your_database_dump.sql

This method works with very large databases.

3. other tools:
The MySQL server stores database structure and data in regular files on disk. This means that if you can login on the server with privileges to access the folder where the databases are stored ( usually /var/lib/mysql ) then you can just copy or transfer then to another server using tools like ftp, scp, sftp, rsync. Before you use any of those tools you have to make sure no one is writing to the databases that you want to transfer so you should put a read lock on them. If you want to lock a table you will have to use the MySQL client to login to your MySQL server and then just type in :


LOCK TABLE table_name READ[, table_name2 READ, ...]

or if you want to lock all tables on the server:


FLUSH TABLES WITH READ LOCK

leave the mysql client running and then copy or transfer transfer the files. After the transfer finished, exit the mysql client or type:


UNLOCK TABLES

to release the read lock.
This method also works with large databases, and it is faster then the previous method in this case MySQL server does not have to parse and process queries or recreate indexes because the whole data including indexes is transferred from the old server.

Debugging Stored Procedures in SQL Server 2005

Pre-requisites


1. Find the .exe file under the directory, C:\Program Files\Microsoft SQL Server\90\Shared\1033\rdbgsetup.exe or similar path where the SQL Server was installed. The file rdbgsetup.exe stands for 'RemoteDeBuGsetup'. Look for the emphasis on letters. The filename reads rdbgsetup because, we are going to debug a stored procedures of a database available in some remote physical server. Either we need to sit at the server and debug them or we should be in a position to debug the stored procedure remotely. This action should be performed on the physical server where SQL Server 2005 was installed.

2. The user who debugs the stored procedure should be a member of SQL Server's fixed Server role, SysAdmin.

As a DBA, I may need to grant this privilege to the user who is in need of debugging a stored procedure. When I do that, I should trust the user so that he/she will not mess-up anything on the Server. Ok, I believe my users are trust worthy and I issue the following T-SQL command to assigning a fixer server role, SysAdmin.

The command to do so is as follows


EXEC master..sp_addsrvrolemember @loginame = N'&amp;amp;amp;lt;YourLoginName either SQL Server Authentication or Windows Authentication&amp;amp;amp;gt;', @rolename = N'sysadmin'

This can however be accomplished with SQL Server Management Studio's IDE. Perhaps, I prefer using T-SQL commands.

Note: The parameters to the stored procedure, sp_addsrvrolemember are of type, Nvarchar and it stands for (National Variable Character), which usually holds Unicode characters.

Now, we are all set for debugging stored procedures.

Process to Debug a stored procedure


1. Open the Microsoft Visual Studio 2005 IDE.

2. Select Server Explorer option from the View Menu as follows:





3. From the Data Connections node, right click and select, 'Add connection'. Fill in the details to connect to the intended SQL Server and the database using the login who has a fixed server role, SysAdmin. Click on Test connection. Once the connection succeeds, the overall screen should look like the following.



4. Expand the data connection just added, and navigate to the Stored Procedures node.

5. Expand the Stored Procedures node and select the intended SP to be debugged.

6. Right click and select open to view the source code of the selected stored procedure.

7. Place a break point on the intended line of code where debugging needs to be started its usually the way .NET Developers perform.

8. After performing the above steps the screen shot should look like the following.

9. After performing the above steps the screen shot should like the following:



10. Right click on the stored procedure from the 'Server Explorer' and select 'Step-Into Stored Procedure' as shown below.



11. This action brings up the following screen shot.



12. Enter the needful values and click Ok. The next shot will be the following.



13. From here on, its usual .NET debugging stuff. Use Step-Into and Step-Over and Step-out from the shortcuts menu or pressing F11,F10, Shift+F11

Wasn't that very simple. It made the life of DB developers much more comfortable. Had it not been available with SQL Server 2005 and VS 2005 IDE it would have been a nightmare to debug stored procedures remotely/locally.

Happy Development and concentrated debugging.

Saturday 3 July 2010

Get Method Names using Reflection [C#]

If you want to get method names of a given type in C#, you can use method Type.GetMethods. This method returns array of MethodInfo objects. MethodInfo contains many informations about the method and of course a method name (MethodInfo.Name). To filter returned methods (for example if you want to get only public static methods) use BindingFlags parameter when calling GetMethods method. Required are at least two flags, one from Public/NonPublic and one of Instance/Static flags. Of course you can use all four flags and also DeclaredOnly and FlattenHierarchy. BindingFlags enumeration and MethodInfo class are declared in System.Reflection namespace.

This example gets names of public static methods of MyClass, sorts them by name and writes them to console.
[C#]

using System.Reflection;

// get all public static methods of MyClass type
MethodInfo[] methodInfos = typeof(MyClass).GetMethods(BindingFlags.Public |
BindingFlags.Static);
// sort methods by name
Array.Sort(methodInfos,
delegate(MethodInfo methodInfo1, MethodInfo methodInfo2)
{ return methodInfo1.Name.CompareTo(methodInfo2.Name); });

// write method names
foreach (MethodInfo methodInfo in methodInfos)
{
Console.WriteLine(methodInfo.Name);
}

Database Terms

* Aggregation - Objects that are composed of other objects.
* Concurrency - Databases must ensure that data is checked when concurrent access is allowed. Concurrent access means more than one application or thread may be reading or updating the same data at the same time.
* Database Garbage Collection - Garbage collection is the process of destroying objects that are no longer referenced, and freeing the resources those objects used. In Java there is a background process that performs garbage collection. Requires bi-directional object relationships. Determines if the database performs garbage collection on objects that are no longer referenced by the database. This keeps external programs from having to track the use of object pointers.
* DBMS - Database management system.
* Distributed Architecture - Object are sharing in a distributed environment or the entire database may be replicated on multiple computers.
* DML - Data Manipulation Language separate from programming languages (for RDBMS) and used as a means of getting and storing data in the database.
* Encapsulation - Data with method storage. Not all databases support the methods but rely upon the classes defined in the schema to reconstruct the object with its methods.
* Fault tolerance - Features that provide for fault tolerence in the event of a hardware of software failure. Normally transaction processing provides software fault tolerance. Data replication to other servers on the network supports hardware fault tolerance.
* Heterogeneous environment - Cross Platform support - The database may be able to run on various builds of computers and with various operating systems.
* Inheritance - Objects inherit attributes from parent objects.
* JDBC - An application program interface (API). Calls are used to execute SQL operations.
* normalized - Elimination of redundancy in databases so that all columns depend on a primary key.
* Notification - Notification may be active or passive. A passive system can minimally determine if an object has changed state. An active system may provide for an application to be informed when an object is modified.
* Object relationships - Object relationships define association with other objects, and whether objects can detect each other in one direction or two directions. Two way object relationships may allow for garbage collection.
* ODBMS - Object Database management system.
* OQL - Object Query Language, is a data manipulation language for Object Databases although many object databases do not support it. They rely on object class extensions or interfaces for their support.
* Persistence - Databases provide persistance which for object databases means object can be stored between database runs.
* RDBMS - Relational database management system.
* Schema - The data structure of the database.
* SQL - Structured Query Language is a standard language for communication with a relational database management system (RDBMS). Structured Query Language, is a data manipulation language which is a standard for getting and storing data in an RDBMS.
* SQLJ - Supports structured query language (SQL) calls for Java. It consists of a language allowing SQL statements to be embedded in it, a translator, and a runtime model.
* Transaction processing - Some databases may have some form of transaction processing which may support concurrency. Transaction processing will ensure that the entire transaction is made or none of it is made. Transactions support concurrency and data recovery. A data failure will cause a rollback of data.

Object Oriented Databases

Object oriented databases are also called Object Database Management Systems (ODBMS). Object databases store objects rather than data such as integers, strings or real numbers. Objects are used in object oriented languages such as Smalltalk, C++, Java, and others. Objects basically consist of the following:

* Attributes - Attributes are data which defines the characteristics of an object. This data may be simple such as integers, strings, and real numbers or it may be a reference to a complex object.
* Methods - Methods define the behavior of an object and are what was formally called procedures or functions.

Therefore objects contain both executable code and data. There are other characteristics of objects such as whether methods or data can be accessed from outside the object. We don't consider this here, to keep the definition simple and to apply it to what an object database is. One other term worth mentioning is classes. Classes are used in object oriented programming to define the data and methods the object will contain. The class is like a template to the object. The class does not itself contain data or methods but defines the data and methods contained in the object. The class is used to create (instantiate) the object. Classes may be used in object databases to recreate parts of the object that may not actually be stored in the database. Methods may not be stored in the database and may be recreated by using a class.
Comparison to Relational Databases

Relational databases store data in tables that are two dimensional. The tables have rows and columns. Relational database tables are "normalized" so data is not repeated more often than necessary. All table columns depend on a primary key (a unique value in the column) to identify the column. Once the specific column is identified, data from one or more rows associated with that column may be obtained or changed.

To put objects into relational databases, they must be described in terms of simple string, integer, or real number data. For instance in the case of an airplane. The wing may be placed in one table with rows and columns describing its dimensions and characteristics. The fusalage may be in another table, the propeller in another table, tires, and so on.

Breaking complex information out into simple data takes time and is labor intensive. Code must be written to accomplish this task.
Object Persistence

With traditional databases, data manipulated by the application is transient and data in the database is persisted (Stored on a permanent storage device). In object databases, the application can manipulate both transient and persisted data.
When to Use Object Databases

Object databases should be used when there is complex data and/or complex data relationships. This includes a many to many object relationship. Object databases should not be used when there would be few join tables and there are large volumes of simple transactional data.

Object databases work well with:


* CAS Applications (CASE-computer aided software engineering, CAD-computer aided design, CAM-computer aided manufacture)
* Multimedia Applications
* Object projects that change over time.
* Commerce

Object Database Advantages over RDBMS

* Objects don't require assembly and disassembly saving coding time and execution time to assemble or disassemble objects.
* Reduced paging
* Easier navigation
* Better concurrency control - A hierarchy of objects may be locked.
* Data model is based on the real world.
* Works well for distributed architectures.
* Less code required when applications are object oriented.

Object Database Disadvantages compared to RDBMS

* Lower efficiency when data is simple and relationships are simple.
* Relational tables are simpler.
* Late binding may slow access speed.
* More user tools exist for RDBMS.
* Standards for RDBMS are more stable.
* Support for RDBMS is more certain and change is less likely to be required.

ODBMS Standards

* Object Data Management Group
* Object Database Standard ODM6.2.0
* Object Query Language
* OQL support of SQL92

How Data is Stored

Two basic methods are used to store objects by different database vendors.

* Each object has a unique ID and is defined as a subclass of a base class, using inheritance to determine attributes.
* Virtual memory mapping is used for object storage and management.

Data transfers are either done on a per object basis or on a per page (normally 4K) basis.

Stupid C# tricks: Working with indexers

One of C#'s most interesting features is the class indexer. Simply put, an indexer is a special kind of property that allows you to reference your class like you would an array. Obviously, this ability becomes useful when creating a collection class, but giving a class array-like behavior can be useful in other situations, such as when dealing with a large file or abstracting a set of finite resources. In this article, I'll show you how to set up a class to use an indexer. But first, let's get some necessary background by reviewing the concept of properties.

Properties 101

If you've done any programming in VB6, you'll be familiar with property methods—special class members that allow controlled access to a private class field. In C#, you have two kinds of properties: get, which allows you to return the value of a private field, and set, which allows you to set the value of a private field. As a simple example, consider the code below, which creates a FirstName property to control access to the private class member firstname:

class Person {
private string firstname;
public string FirstName {
get {return firstname;}
set {firstname = value;}
}
}

That property declaration would allow you to write code like this:
Person p = new Person();
p.FirstName = "Lamont";
Console.WriteLine (p.FirstName);

As you can see, a property declaration looks a lot like a field declaration, except that it's declared with two special members, called accessors in Microsoft parlance. The get accessor is called when the property is invoked on the right-hand side of an expression or used as a parameter to another routine. The set accessor is called when the property is invoked on the left-hand side of an expression and sets the value of its associated private field via the implicitly passed value parameter. You'd create a read-only property by omitting the set accessor, which would cause any attempts to set the property to generate compiler errors.

Using indexers for fun and profit
So why did I launch myself on that tangent? Because a class indexer works almost exactly like a property and looks very similar when you examine the code. Here's a sample class with an indexer that returns a string:

class Sample {
public string this [int index] {
get {return "You passed " + index; }
)
}

Notice that the property name is this, which refers back to the current instance of the class, and that the parameter list is enclosed in square brackets instead of parentheses. Also, this is a read-only indexer. To make it read/write, I'd have to add a set accessor. When defining an indexer, you are not limited to a single parameter. Indexer parameters may be of any type, although int usually makes the most sense. It's also possible to have more than one indexer in the same class (overloading)—more on that later.

Having defined Sample in this way, we can use the indexer as a sort of default property, like so:
Sample s = new Sample();
Console.WriteLine(s[55]);

Properties vs. indexers

There are a few differences between properties and indexers. Essentially, they boil down to the following:

* Each property in a class must have a unique name, while each indexer defined in a class must have a unique signature or parameter list. (This allows indexer overloading.)
* Properties can be static, while indexers must always be instance members.
* Accessors defined for an indexer can access parameters passed to the indexer, while property accessors have no parameters.


Advanced tricks: Interfaces

When array-like behavior is desired for an implementer, you can define indexers for interfaces. In fact, the IList and IDictionary collection interfaces both declare an indexer to provide access to the items they're storing.

When declaring an indexer for an interface, remember that the declaration just serves to indicate the existence of the indexer. You need only provide the appropriate accessors and should not include a scope modifier. The following is an example of an indexer declared as part of an interface appropriately named

IImplementMe:
interface IImplementMe {
string this[int index]
{
get;
set;
}


An implementing class would have to provide the implementations for both the get and set accessors for IImplementMe's indexer.

That'll about do it for now. You should have a strong enough understanding of indexers to play with them on your own. Have fun.

Visual Studio: Turn on line numbering

Many development tools—e.g. FxCop—refer to source code line numbers. Visual Studio .NET always shows the current line number, but finding a particular line called out by a tool is simpler if source code line numbering is enabled.
[edit]
Change Visual Studio Options

The grid layout settings are found on the Visual Studio 2005 Options dialog box. To access the Options dialog box, select the Tools / Options… menus. It is the same in the Visual Studio Express Editions.
[edit]
Check Line numbers

* Expand the Text Editor item in the left panel of the Options dialog box.

* Select the C# item.

* Enable source code line numbering by checking the Line numbers checkbox in the Display section of the right panel. Click the OK button and voilá—line numbers!

Visual Studio: Turn off snap lines

Snap lines were introduced with Visual Studio 2005. They are used to faciliate the positioning of elements on Windows Forms. But, snap lines can be disabled if you prefer the snap to grid layout style of Visual Studio 2003.
[edit]
Change Visual Studio Options

The grid layout settings are found on the Visual Studio 2005 Options dialog box. To access the Options dialog box, select the Tools / Options… menus. It is the same in the Visual Studio Express Editions.
[edit]
Check Show all settings

If you do not see the Windows Forms Designer item in the left panel of the Options dialog box—only Environment, Text Editor, and Debugging are viewable—, look for the Show all settings checkbox at the bottom left of the Options dialog. Check it to make the other settings viewable.
[edit]
Select SnapToGrid

* Now, in the left panel, expand the Windows Forms Designer by clicking on the plus (+) sign to expose the General item. Click the General item to display the general options in the right panel.

* If necessary, expand the Layout Settings item by by clicking on the plus (+) sign next to it.

* Select LayoutMode. Then, from the pull down menu, select SnapToGrid. And, click the OK button.

* Finally, exit Visual Studio and restart it for the change to take effect.



Figure: Visual Studio Layout Settings

Visual Studio: Export and import settings

If you work in Visual Studio on multiple computers or if you share Visual Studio with someone else on the same computer, it is very handy to be able to import your personal Visual Studio settings. It is very disconcerting to work without your personal source code markup, custom keyboard shortcuts, and other personal settings. And, it is nice to have a backup, just in case Visual Studio or an update should lose your personal settings.


Contents

  • 1 Export personal settings
  • 2 Import personal settings


Export personal settings

Navigate to the Tools / Import and Export Settings… menus to access the Import and Export Settings Wizard.



Figure 1. Import and Export Settings Wizard


Be sure Export selected environment settings is checked. Then, click the Next button; and, the following screen will be displayed:



Figure 2. Select settings for export


Check off all the settings you wish to export. Then, click the Next button. In the next step, you will provide the name and location for the exported settings.



Figure 3. Enter a name and directory for the exported settings


After entrering the name and location of your settings, click the Finish button. The wizard will export your selected settings. Now, your personal Visual Studio settings are in a file which you can move to another computer and Import.


Import personal settings

Navigate the Tools / Import and Export Settings… menus to the Import and Export Settings Wizard.



Figure 4. Import and Export Settings Wizard


Check Import selected environment settings. Then, click the Next button; and, the following screen will be displayed:



Figure 5. Option to save the current settings


If you wish to save the current Visual Studio settings, check the Yes radio button and enter the name and directory for the settings to be saved. Otherwise, check No. In any case, click the Next button.

Next, you select the settings you wish to import. In this example, the previously exported settings file named Exported-2006-10-23.vssettings is selected.



Figure 6. Select the settings collection to import


Simply, select the individual settings you wish to import from the settings collection on the following screen:



Figure 7. Select indiviudal settings to import


Finally, click the Finish button; and, Visual Studio will import the settings.

Visual Studio: Implementing interfaces

An interface is implemented at class definition level by using the : (colon) operator after the class name but before the interface name. Then, you must provide concrete implementations of the methods of that interface. In Visual Studio, this task is automated for you; so, you do not have to type out all the methods.

Steps:

  1. Type the classname.
  2. Type the colon (:).
  3. Type either Ctrl+Space or begin typing the interface name to bring up the IntelliSense menu. Select the interface name from the menu list.
  4. Right click the interface name and select Implement Interface from the popup menu.


Implementing an interface in Visual Studio
Figure: Implementing an interface in Visual Studio

Visual Studio: Configure automatic backups

The AutoRecover feature was introduced with Visual Studio 2005. AutoRecover allows you to configure Visual Studio to save your projects and solutions automatically. So, your work can be recovered in the event of a crash.
[edit]
Configure AutoRecover

First, navigate through the Tool / Options… menus to the Options dialog box.

Then, select Environment / AutoRecover in the left panel of the Options dialog box.



Figure: Visual Studio Options Dialog Box



Be sure the Save AutoRecover information every: checkbox is checked.

Now, enter the number of minutes between automatic backups. If you enter 10, Visual Studio will automatically create a backup every ten minutes.

Next, enter the number of days you wish to keep previous backups in the Keep AutoRecover information for: control. If you enter 10, Visual Studio will retain previous backups for ten days.

Finally, click the OK button.

If Visual Studio or the system should crash, then the next time you start up Visual Studio it will prompt you to have Visual Studio automatically restore your project or solution.

Anonymous Methods vs Threads

With the release of .NET Framework 2.0, we have gained access to a very powerful feature called Anonymous Methods. I'm sure that almost any .NET developer has used Anonymous Method at least once and most of us use them on a daily basis.

Typically you use Anonymous Methods when you want to declare an event handler inline, without the need of creating a separate, named method (hence the name Anonymous). Other usage areas include delegates of types such As Predicate or Action. Mentioned delegates are most often used in methods found on all types of collection related classes be it Array or List. Typical code for this may look like this:

string[] urls = GetUrls();

string[] urlWithWww;
urlWithWww = Array.FindAll(urls, delegate(string url)
{
return url.StartsWith("www");
});

Nothing unusual here. The usefulness of Anonymous Methods comes from the fact that they allow us to access variables defined in the scope in which the very method is defined. Here as an example of how this feature is usually used:

string pattern = ".com";

string[] urls = GetUrls();
string[] urlWithWww;
urlWithWww = Array.FindAll(urls, delegate(string url)
{
return url.Contains(pattern);
});

Great feature indeed, but there is one gotcha that we have to be aware. The problem most often appears when we start to work with multiple threads. Given the following code:

foreach (string url in urls)

{
DoSomethingAsync(delegate()
{
Debug.WriteLine(url);
});
}

We have to know that the url variable that we pass to a Debug.WriteLine method is "shared" among all Anonymous Methods and because of this, we may (and most probably we will) get results that we do not expect: same url printed few times, than a different url, again printed few times. Confusing, isn't it?

Why is that? Brad Adams explains the mechanism behind this strange behavior here (scroll down to the comments). It's worth mentioning that you could get the same strange behavior without working with multiple threads. It is just far more common to get it while theading.

To make things more "predictable", the code above has to be written in a slightly different way:

for (int i = 0; i < style="color: rgb(0, 0, 255);">string url = urls[i];

DoSomething(delegate()
{
Debug.WriteLine(url);
});
}

Now every Anonymous Method gets its own copy of url and everything works as expected.

Visual Studio 2010 and .NET Framework 4.0 Overview

Check out this SlideShare Presentation:

Visual Studio Code Snippets

There is a feature in Visual Studio 2005 called Code Snippets. Basically what this feature allows you to do is type in a code editor, some special string such as "prop":

And then by pressing the TAB key once (or twice if using the provided intellisense), Visual Studio generates some code for you as on the picture below:

Notice that there are reqions highlited witha green color. You can tab through those regions with a TAB key. On the above example, If you eddit the type of the field, the type of the property is automaticaly updated for you. The same holds true for the field name which is used inside the property.

Visual Studio 2005 comes boundled with a couple of useful code snippets of which I use the "prop" the most. However, If you do mostly ASP.NET applications you know that the standart property with underlying field is not so widely used here. What we need is a property which uses ViewState as a storage medium. Fortunatelly it is very easy to create your own snippets. Just go to the folder where VS is installed - for me it was: "c:\Program Files\Microsoft Visual Studio 8\VC#\Snippets\1033\Visual C#". There you will find all the available snippets. When you look any one of them what you will find is a simple XML defining the snippet behavior. From there it should be no problem to create your own snippets.

Being ASP.NET developer myself I have created few snippets that help me doing my work faster and those are: propv, propvd, props and test. First two generate a property that uses the ViewState, the third one generates a static property and the third one a method that has a Test attribute of an NUnit testing framework. You can download the snippets here: Snippets.zip (2,23 KB). Just put them together with the rest of the snippets.

Hey, Google! There’s Another Programming Language Called Go!


When you’re a huge web company, and you choose a name for something as important as a new programming language, you should take great care to investigate whether the name is already taken.

Apparently, Google (Google) didn’t do that. Frank McCabe, a developer working at San Jose, Calif.-based Starview Technologies, created a programming language and named it Go years ago. In fact, he published a research paper about it in 2004, and devoted an entire book to it, named “Lets Go” in 2007.

In an e-mail to Information Week, McCabe said he doesn’t own a trademark on the language, but he’s not happy about Google choosing the name Go nevertheless. “It takes a lot of effort to produce a reasonably well-designed language. I am concerned that the ‘big guy’ will end up steam-rollering over me. I do not have resources to invest in legal action; but do not intend to let Google keep the name without them being explicit that they are steam-rollering over us,” he says.

If the folks at Google who named the language didn’t know about the other “Go”, they were careless. If they knew about it and decided to name their language “Go” anyway, it sounds like a big company not caring much about the little guy. After all, how many names are taken when it comes to programming languages? Perhaps a couple hundred? Surely Google could have chosen another name.

Google hasn’t given a definitive answer to this problem yet. So far, their spokesman merely said they “recently became aware of the Go! issue and are now looking into the matter further.” But ignoring the issue definitely won’t go well with Google’s oft quoted mantra – “Don’t be evil”.