Saturday, June 11, 2016

SQL Server Management Studio: Automatically Generating Script for Restoring a Backup File

I was developing an SSIS package and as part of the development process I would test and then restore a clearn version of the database, again and again and again using the Restore Database dialog. Now, I can figure out how to automate the restore process by writing a T=SQL script using RESTORE DATABASE but this is not necessary. The Restore Database dialog contains a Script button (see below) that will write the script for you:


The Script button creates a RESTORE DATABASE script corresponding to the options select on Restore Database dialog. By default clicking on the Script button create a RESTORE DATABASE script as a new query editor window in SQL Manager. Click on the down arrow to the right of the Script button displays the following:


It is possible to not only create a new query editor window but save the script to a file, save the script to the Clipboard or to create a SQL Agent Job that performs the restore.

An example of the RESTORE DATABASE created is as follows:

USE [master]

ALTER DATABASE [Buddy] SET SINGLE_USER WITH ROLLBACK IMMEDIATE

RESTORE DATABASE [Buddy] FROM  DISK = N'C:\temp\Buddy.bak' WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 5

ALTER DATABASE [Buddy] SET MULTI_USER

GO

It took two seconds to create the above script while writing it by handle would have meant a half hour to an hour of diddling.

The Restore Database dialog is displayed from within SQL Manager by right clicking on the database to restore (the database below is Buddy) and selecting Tasks | Restore | Database:


Selecting Tasks | Restore | Database display the Restore Database dialog:


The Restore Database dialog shown already has a backup file selected the will be restored. SQL Manager 2014 remembers the previous backup created and pre-populates the Restore Database dialog with the last backup created. The previous screenshot shows how the Script button added the file path to the RESTORE DATABASE command it generated (see below)

RESTORE DATABASE [Buddy] FROM  DISK = N'C:\temp\Buddy.bak' WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 5

Selecting the Options tab from the Restore Database dialog allows the restore to be configured more precisely. With regards to the script generated the following options were checked:

  • Overwrite the existing database (WITH REPLACE)
  • Close existing connections to destination database


The Options tab of the Restore Database dialog for the previous options is as follows:


The REPLACE option is incorporated into the script as follows (demarcated in boldface):

RESTORE DATABASE [Buddy] FROM  DISK = N'C:\temp\Buddy.bak' WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 5

The "Close existing connections to destination database" options is handled in the script as follows  (demarcated in boldface):

USE [master]

ALTER DATABASE [Buddy] SET SINGLE_USER WITH ROLLBACK IMMEDIATE

RESTORE DATABASE [Buddy] FROM  DISK = N'C:\temp\Buddy.bak' WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 5

ALTER DATABASE [Buddy] SET MULTI_USER

GO

Having used SQL Server since SQL Server 2000, it is pleasant to notice usability enhancements like remembering the last database backup in the Restore Database dialog and obviously, having the Script button available on the Restore Database dialog. A Script button is similarly available on the Backup Database dialog.

Wednesday, May 25, 2016

Visual Studio Unit Tests: Handling Exceptions

In a previous post the development of Unit Tests was presented (Visual Studio: Developing Unit Tests) but in each case the methods under test returned a value and none of the methods under test threw exceptions. This post will present how to test exceptions using ExpectedException attribute from the Microsoft.VisualStudio.TestTools.UnitTesting namespace.

public bool IsItSo(string data)
{
  if (data == null)
  {
    throw new ArgumentNullException();
  }

  if ((data == "A") || (data == "B") || (data == "C"))
  {
    return true;
  }

  else
  {
    return false;
  }
}

The previous post, Visual Studio: Developing Unit Tests, demonstrated how to create unit tests so to test the passing a null value to the IsItSo method, a new test method can be created:

[TestMethod]
public void IsItSoNullException()
{
  Worker worker = new Worker();
  bool result;

  result = worker.IsItSo(null); 
  Assert.IsTrue(result); 
}

This test can be run from Test Explorer displayed using Visual Studio’s Test menu’s Windows | Test Explorer option: Running the test method, IsItSoNullException creates a failed test due to the exception:


The behavior that the IsItSo method will throw an exception is a known behavior. To test this the ExpectedException  attribute is added to the IsItSoNullException  test method:

[ExpectedException(typeof(ArgumentNullException))]
[TestMethod]
public void IsItSoNullException()
{
  Worker worker = new Worker();
  bool result;

  result = worker.IsItSo(null);
  Assert.IsTrue(result);
}

Running the test method, IsItSoNullException, results is a successful test run:



The constructor for the ExpectedException attribute used above is as follows:

public ExpectedExceptionAttribute(
Type exceptionType)

The type passed into the constructor is the type of the exception expected. If a different exception is thrown in the test method then the test will fail:



If no exception is is thrown by the test method adorned with the ExpectedException attribute then the test fails:



The ExpectedExceptionAttribute class exposes a second constructor signature:

public ExpectedExceptionAttribute(
Type exceptionType,
string noExceptionMessage)

The second parameter is supposed to display when the test fails. This behavior does not work in Visual Studio but according the postings on the web, this works when running MSTest or VSTest. So if developers need to convey information to QA with regards to test failure, this is the mechanism that should be used.



Monday, May 23, 2016

Visual Studio: Developing Unit Tests

On a typical software project developers are responsible for writing per-method tests called unit tests. Such tests exercise the code within a method but typically do not exercise end-to-end functionality. For example, units tests would not invoke web services, access a database, etc.

It is unrealistic from a time/cost perspective for developers to write tests that cover every line of code within a project so a goals are set on a project. A common goal is that the tests written by developers achieve fifty percent coverage with respect to the lines of code within the project. Visual Studio provides the tools and infrastructure that the support the development of unit tests and measuring metrics such as code coverage.

To understand this consider the following solution, AnEntireApplication, which contains a single project (a Windows console application), TheCode:



This console application project, The Code, contains a source file, Worker.cs. In order to demonstrate Visual Studio's support for developing unit tests, such tests will be developed to exercise the methods of the Worker.cs source file which contains the Worker class.

The first thing to do when developing tests is to organize their location within the solution. The most straight forward way to do this is to create a folder in the solution called "Tests" and to place each test-related project associated with the solution in the Tests folder. To create this folder right click on the solution name within Solution Explorer and select Add | New Solution Folder:



When prompted create a solution folder named, "Tests":


To add a Unit Test project to the solution right click on the Tests folder and select Add | New Project:


Selecting New Project, displays the New Project dialog. Within this dialog select Installed | Visual C# | Test | Unit Test Project:


The project containing the code to test is TheCode project. The Unit Test Project to be created will be named TheCodeTest. The name is identical to the project to test with the name Test appended.

When the Unit Test project is added to the solution it appears as follows:



TheCodeTest unit test project will be testing the clases of TheCode console project. For this reason a reference should be added to from TheCodeTest to TheCode. This is achieved by right clicking on the References folder and from the contact menu select, Add Reference:



Selecting Add Reference from the Context Menu displays the Reference Manager dialog for the TheCodeTest project:


Prom the Projects tab select TheCode so TheCostTest unit test projects references project containing the code to be tested, TheCode:


As you can see above, the References for TheCodeTest project now contains a reference to TheCode.

The Unit Test project that was crated came pre-seeded with a sample unit test class, UnitTest1:


A clean way to approach testing is to have one test class per-class being tested. For this reason the UnitTest1 class and source file should be renamed WorkerTest as they will be testing the Worker class:


The attributes associated Unity Test project a predicated on common sense. Any class used to test is adorned with the [TesteClass] attribute and any method executing a test will be adorned with a [TestMethod] attribute.

The code associated with the TheCode class is as follows:

public class Worker
{
  public bool IsItSo(string data)
  {
    if ((data == "A") || (data == "B") || (data == "C"))
    {
      return true;
    }

    else
    {
      return false;
    }
  }

  public bool IsThatSo(string data)
  {
    switch (data)
    {
      case "A":
      case "B":
      case "C":
        return true;

      default:
        return false;
    }
  }
}

As the previous code snippet shows, the class to test exposes two methods IsItSo and IsThatSo. Once again the common sense design pattern should be applied when creating test methods. To understand how this consider the following from the WorkerTest class whose responsibility is to test the Worker class:


Notice above that there is a method defined, TestIsItSo, whose purposes is to test the Worker class' IsItSo method. Also notice above that there is a method defined, TestIsThatso whose purpose is to the the Work class's IsThatSo method.

The code associated with the IsItSo method is straightforward. If the parameter data is set to “A” or “B” or “C” then IsItSo returns true otherwise the method returns false. The TestIsItSoMethod should follow some obvious steps:
  1. Create an instance of the Worker class
  2. Invoke the IsItSo method passing in “A” as a value
  3. Verify the return value returned is set to true.
  4. Repeat steps 2 and 3 above by pass in “B” and “C” as a parameter.
  5. Pass in “D” as a parameter
  6. Verify the return value is set to false
At the top of the TestWorker class, a using statement was created where Visual Studio created the source file:
using Microsoft.VisualStudio.TestTools.UnitTesting;

The using Microsoft.VisualStudio.TestTools.UnitTesting; namespace contains a class called, Assert, that is used to test the return values for the methods to be tested. The Assert class exposes static methods such as:

  • IsTrue
  • IsFalse
  • AreEqual
  • AreNotEqual
  • IsNull
  • IsNotNull
Each of the previous methods (and there are a lot more of them within the Assert class) are designed to cause the test to fail if the assertion is false. The test passes if the assertion is true. Given that IsItSo returns a boolean, it makes sense to validate this methods return value using IsTrue and IsFalse. A example of a test case for IsItSo is as follows:

Worker worker = new Worker();
bool result;

result = worker.IsItSo("A");
Assert.IsTrue(result);

In the previous snippet, we expect the “result” parameter to be assigned a value of true when IsItSo is passed a string value of “A”. The Assert class’s IsTrue method tests the value of “results” and insures it is “is true” and hence the test passes passes. If IsItSo had returned false then the test case would have failed.

To be thorough the code for the TestIsItSo is as follows where functionality verifies each code path in the Worker class’ IsItSo method:




The TestIsThatSo method similarly tests the code associated with the Worker class’ IsThatSo method:


At this point, it is possible to run the tests which is done using Test Explorer. To display Test Explorer select the Test | Windows | Test Explorer:


From Text Explorer the tests can be run by clicking on the project and selecting Run Selected Tests:


Since the project was clicked on within Test Explorer all tests for the project are run which displays the following at the bottom of Test Explorer:

The test would pass if the covered one percent of the code or if the covered one hundred percent of the code. To see that actual code coverage invoke Analyze Code Coverage for Selected Tests:


The hierarchy of coverage can be expanded to reveal the following:


Test coverage applies to both the code being tested (TheCode project) and the test code itself (TheCodeTest project). Our target was to test the Worker class' IsItSo and IsThatSo method. The percent coverage for these methods is one hundred percent so it looks like we have done our job.


Sunday, May 8, 2016

SQL Azure: Finding the Server Name for SQL Azure Instance

Overview

Migrating from an on premise version of SQL Server to SQL Azure utilizes standard tools such as SQL Server Management Studio. To access any database whether SQL Azure or on premise SQL Server, a server name is required. The server name is simply the name of the computer on which the database resides. 

For an Azure instance that contains at least one SQL Azure instance, a server name already exists for the SQL Azure Instance. Finding the server name is demonstrated in the section below entitled, "Finding an Existing Server Name." For an Azure instance that has never had a SQL Azure instance created, there is no server name. How create and find the server name associated with SQL Azure is demonstrated in the secton below entitle, "Find the Server Name of a New SQL Azure Instance."

Finding an Existing Server Name

First log into the Azure management portal, https://portal.azure.com/. Once logged in click on the "SQL databases" tab header which displays a list of SQL Azure instances. Click on the instance name for which the server name is needed (see below). An example of the information shown when clicking on a SQL Azure instance is show below:


On the far right blade the server name is show. For instance in the previous screenshot the server name is keysersoeze.database.windows.net.

Find the Server Name of a New SQL Azure Instance

There is no server name associated associated with a SQL Azure if there is no SQL Azure database instance. To create a server and hence a server name, a SQL Azure database must be created. This is achieved by first logging into the Azure management portal, https://portal.azure.com/:


Once logged into the Azure Portal the tab selector for managing SQL Azure instances is found on the left but then again the tab selectors for managing all Azure components (App Services, Virtual Machines, Cloud Services, etc.) are found on the left side of the portal page:


Clicking on "SQL databases" tab selector displays the following (note this is a virgin instance of Azure so there are no SQL Azure instances and no server name associated with the Azure instance):


To create a SQL Azure instance click on the "Add" button from the "SQL Databases" blade. This displays a form that allows a SQL Azure database to be created:


When creating a SQL Azure instance a "Database name" and a "resource group name." The database name is self explanatory. The concept of a resource group is documented here "Azure Resource Manager overview" but simply put a resource group is a way to bind all resources associated with an application. The resource group allows all components of an application to be tracked by the unifying resource group name. The components associated with an application (hence a resource group) include virtual machines, storage, networks, web apps, databases and database servers.

The Configure required settings must be clicked on to complete the creation of the SQL Azure database. Clicking on the aforementioned link shows a blade containing a "Create new Server" button. Recall that this is a new instance of Azure so there are new existing servers to select. Clicking on the "Create new Server"  button displays the "New server" blade:


In order to create a server name both a server name and an administrative user for the server must be specified. With regards to server name and the administrative username, the usual suspects will be specified namely server name, KeyserSoeze, and administrative username, Verbal Kint. A password is also required for the administrative user. Looking  at the previous screenshot it should be clear that the fully qualified server name is keysersoeze.database.windows.net.

Once the required values have been specified for the "New Server" the "Select" button should be created in order to complete the creation of the new server. 

This action closes the "New Server" blade and fills in the server name under "Server" value associated with the SQL Azure database being created (see the following):


Click on "Create" to complete the creation of the SQL Azure instance and its corresponding server name name called keysersoeze.database.windows.net.

Saturday, May 7, 2016

Visual Studio Enterprise with MSDN benefit: Free Azure Credit

Microsoft provides $150 per-month in Azure credit with each Visual Studio Enterprise with MSDN subscription. To active the Azure credit, first login to msdn.microsoft.com using the account associated with the MSDN subscription (the aptly named "Sign in" button):


Once signed into MSDN click on "MSDN subscription" found in the upper right corner:


Clicking on "MSDN Subscriptions" lists the features provided as part of the MSDN subscription including the category "Microsoft Azure." In order to activate the subscription associated with the MSDN subscription click on the "Activate Microsoft Azure" link:


Clicking on the "Activate Microsoft Azure" link navigates to the sign up page (no credit card required) for Microsoft Azure:


Once a user has signed up, the Azure account is not created immediately. It takes several minutes in order for an account to be created. The following screen is displayed (note the spiraling gear indicating a user should wait for the account to be created):


After less than ten minutes an account is created and an email is sent to the email address associated with the MSDN account:


From the email clicking on the "Azure Account Center" link redirects to the URL account.windowsazure.com which displays the following page:


Clicking on "Start managing service" redirects to user to https://portal.azure.com where the Azure subscription can be managed:

An MSDN subscriber can no access their activated Azure subscription.

Monday, February 15, 2016

Windows Forms: Suppressing Control Validation when a Form is closing

Windows Forms developers have too often felt the sting of trying to close a window (a form) by clicking on the X in the form's upper right corner but instead of closing the form triggers the Validating event of a control contained on the form. The form does not close specifically because the focus is presently on a control that requires validation.The Validating event takes place before the FormClosing event so there is no way for the closing event to disable the validating event.

To demonstrate this consider the following form:



The Validating event of the textbox in the previous screenshot is handled as follows to insure the data entered in the textbox is of type integer:

private void textBoxToBeValidated_Validating(
                 object sender, CancelEventArgs e)
{
    int result;

    if (Int32.TryParse(textBoxToBeValidated.Text, out result))
    {
        // success
    }

    else
    {
        MessageBox.Show(
            "Data entered must be of type integer", 
            "Error", MessageBoxButtons.OK, 
            MessageBoxIcon.Error);
    }
}

The most obvious (but doomed to fail) way to allow the form to close when clicking on the X in the upper right corner while suppressing validation is as follows:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    AutoValidate = AutoValidate.Disable;
}

The Form class's AutoValidate property appears to be the solution as during the closing, all validations in the form and its descendant controls can be suppressed. The AutoValidate is of type AutoValidate (an enumeration). Yes, the property, AutoValidate, is the same name as its type, AutoValidate.

From MSDN (AutoValidate Enumeration) the AutoValidate enumeration is defined as follows:



Based on its definition the AutoValidate.Disable prevents the form and its descendants from triggering validations.

Attempting to close the form compiled with the previously shown Form1_FormClosing method results in the following when the TextBox is currently in focus:




What is shows is that handling the form's FormClosing event does not solve the issue because the TextBox's Validating event is raised before the FormClosing event is raised.

When the X in the upper right corner is clicked, windows raises a specific Windows message, WM_CLOSE, where the numeric value of WM_CLOSE is 0x10. To jump the queue of messages and handle WM_CLOSE (FormClosing) before the TextBox's Validating, the method Windows uses to process messages mush be overridden. A base class of the Form class is the Control class. The Control class exposes the method that Windows uses to process messages, WndProc:

The method that handles messages is WndProc defined in the Form class as follows (from MSDN Control.WndProc Method (Message)):




So in the derived class, the Form, it is possible to override the Control bass class' WndProc method. Am example of overriding WndProc is as follows were the code uses the WM_CLOSE (0x10) message number to detecting closing and to disable AutoValidate for the Form:

public const int WM_CLOSE = 0x10;

protected override void WndProc(ref Message m)
{
    if (m.Msg == WM_CLOSE)
    {
        AutoValidate = AutoValidate.Disable;
    }

    base.WndProc(ref m);
}

When the previous code is added it is possible close the form by clicking the upper right corner's X and the form closes as validating is disabled.

Friday, September 11, 2015

WPF/Prism using C# strings in Xaml to name Regions

The MVVM design pattern in WPF is often implemented using Prism. In such an implication Views (UserControls) are mapped to regions within WPF pages. Each region is named and all too often said region name is hard coded -- bad programming style.  An example of such is the following excerpt from Shell.xaml where the Prism region is specified as follows:
prsm:RegionManager.RegionName="MainRegion"

The entire Shell.xaml is as follows with the region control noted in boldface:

<Window x:Class=Desktop.Shell"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc=
   "http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:prsm="http://www.codeplex.com/prism"
        xmlns:local="clr-namespace:Desktop"              
        mc:Ignorable="d"
        Title="Any Title Here" Height="350" Width="525"
        TextBlock.TextAlignment="Center">
    <Grid>
        <ContentControl Name="MainRegion" 
             prsm:RegionManager.RegionName="MainRegion" />
    </Grid>
</Window>

A static resource can be used WPF page's title or the content of a TextBlock so why not in the RegionName of a Prism region? Below is the same Shell.xaml modified to reference a C# namespace/assembly and then using the namespace to access a string constant that specifies the region name:

<Window x:Class=Desktop.Shell"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc=
   "http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:prsm="http://www.codeplex.com/prism"
        xmlns:local="clr-namespace:Desktop" 
        xmlns:infrastructure=
"clr-namespace:ViewModels.Infrastructure;assembly=ViewModels"             mc:Ignorable="d"
        Title="Any Title Here" Height="350" Width="525"
        TextBlock.TextAlignment="Center">
    <Grid>
        <ContentControl Name="MainRegion" 
            prsm:RegionManager.RegionName=
              "{x:Static infrastructure:Regions.MainRegion}" />
    </Grid>
</Window>

The C# variable bound to the RegionName is as follows (in boldface):

namespace ViewModels.Infrastructure
{
    public static class Regions
    {
        public const string MainRegion = "MainRegion";

Just because Xaml is markup language and not C# does not mean we should abandon good programming practices.