17 November 2015

How to fix visual studio 2015 error "The package did not load correctly"

When a visual studio extension is installed, a error can occur that gives the following error:

The 'zebre' package did not load correctly.

The problem may have been caused by a configuration change or by the installation of another extension. You can get more information by examining the file 'C:\Users\[user name]\AppData\Roaming\Microsoft\VisualStudio\14.0\ActivityLog.xml'.

Restarting Visual Studio could help resolve this issue.
Continue to show this error message?


The error can cause intellisense not working or other erratic issues.

A possible fix is to uninstall the extension that is causing the error.

The issued can be fixed executing the following command as an administrator:

devenv.exe /setup

If the previous solution does not work, reset the visual studio preferences by issuing the command (Execute as an administrator):

devenv.exe /resetuserdata

02 October 2015

Dapper: Powerful micro object mapper for .Net

Introduction

Dapper.Net or Dapper is a simple and powerful micro object mapper for .Net, that eases the development of a Data Access Layer (DAL).
Dapper is in production used by Stack Overflow, helpdesk and other companies.
Performance is the major focus in Dapper. It is very fast and the execution time is near equal to a hand coded DAL using the SqlDataReader.
Dapper uses the POCO (Plain Old CLR Object) approach.

Setup

Dapper has several installation options:
1) Download from github
Dapper can be downloaded from the github
After the download the cs class files must be added to your project or class library.

2) Nuget package
Dapper is also available as a Nuget package that can be added to you Visual Studio Project references.

Helpers

Dapper extend the IDbConnection interface with three Helpers:
1) Execute a query and map the results to any strongly type
public static IEnumerable Query(this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null, bool buffered = true)

2) Execute a query and map the results to a Dynamic type
public static IEnumerable Query (this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null, bool buffered = true)

3) Execute a command that returns no results
public static int Execute(this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null)

A simple example is to retrieve user information from a database.
First define the POCO class that represents the user. The names must be equal to the database table names.
public class User
{
     public int UserID { get; set; } 
     public string Name { get; set; }
}
To select a list of all the users:
using (SqlConnection connection = new SqlConnection(myConnectionString))
{
     connection.Open();
     List users = connection.Query("SELECT * FROM [User]").ToList();
     connection.Close();
}
Not that "myConnectionString" must be a connection string accepted by the SqlConnection.
Dapper also works with LINQ to return a list (ToList) or single objects (Single / SingleOrDefault)

Parameterized queries

The parameters of a query are passed as anonymous classes.
The anonymous classes must have the query parameter name and it's value.

Example:
To select a list of all the users that the name ends with "Doe":
using (SqlConnection connection = new SqlConnection(myConnectionString))
{
     connection.Open();
     List users = connection.Query("SELECT * FROM [User] WHERE Name LIKE @name", new {name = "%Doe'"}).ToList();
     connection.Close();
}
In this example the name will be matched with the parameter @name of the query.

Stored Procedures

Dapper has extensive support for stored procedures.

Example:
using (SqlConnection connection = new SqlConnection(myConnectionString))
{
     connection.Open();
     List users = connection.Query("UserSearch", 
                                               new {name = "%Doe"}, 
                                               commandType: CommandType.StoredProcedure).ToList();
     connection.Close();
}
In this example, the stored procedure has a parameter named "name" that will receive the value "%Doe".
The parameters can also be passed using the DynamicParameters class, but the anonymous class approach works fine and is more simple.

Table Value Parameters

Dapper supports Stored Procedures Table Value Parameters (TVP):
System.Data.DataTable countryDataTable = new System.Data.DataTable();
countryDataTable.Columns.Add("Id", typeof(long));

countryDataTable.Rows.Add(1);
countryDataTable.Rows.Add(2);

using (SqlConnection connection = new SqlConnection(myConnectionString))
{
     bool isValid = connection.Query(@"IsValid", 
                                      new {
                                             UserID = 674,
                                             countries = countryDataTable.AsTableValuedParameter("[dbo].[IdList]")
                                           },
                                           commandType: CommandType.StoredProcedure
                      ).Single();
}

Where IdList is the sql server table value type with the column Id of type INT
CREATE TYPE [dbo].[IdList] AS TABLE(
 [Id] [int] NULL
)

Multiple Result Sets

Dapper has support for multiple result sets in a single query.
In this case use the QueryMultiple extension method:
var sql = @" select * from Users where UserID = @id ";
sql += @" select * from Roles where UserID = @id"

using (var multi = connection.QueryMultiple(sql, new {id = myId }))
{
     var users = multi.Read<User>().Single();
     var roles = multi.Read<Role>().ToList();
} 

CRUD - Create, Read, Update and Delete


Dapper has no native support for Create, Read, Update e Delete (CRUD)
These operations must be manually developed in queries.

There are however third party extensions that easy the implementation of these operations.
One of those is SqlMapperExtensions the can be found on the dapper github on the Dapper.Contrib Folder.
The file must be added to your project or class library.
This extension uses the POCO (Plain Old CLR Object) approach, so you must create a class that has it's properties with the same name and corresponding data type with the database table.
Take some time to read the extension code and verify that it implements the code accordingly to your needs.

The SqlMapperExtension implements the following extension methods:

The entity identifier must have the attribute [Key] to identify it.
Example:
public class User
{
     [Key]
     public int UserID { get; set; } 
     public string Name { get; set; }
}

1) Get
Get returns a single entity by it's Id.
using (SqlConnection connection = new SqlConnection(myConnectionString))
{
     connection.Open();
     User user = connection.Get(200);
     connection.Close();
}

2) Insert
Inserts the entity and returns it's Id.

using (SqlConnection connection = new SqlConnection(myConnectionString))
{
     connection.Open();
     User user = new User();
     user.Name = "John Doe";

     connection.Insert(user);
     connection.Close();
}
3) Update
Updates the entity.

4) Delete
Delete the entity by it's Id.

5) DeleteAll
Deletes all the entities in the table with the same name as the POCO class.
The best documentation for this extension is at the Test cases

12 May 2015

Time testing: How to prevent time syncing

A common task when performing tests on data sets that vary over time is to advance the windows time.
The server or the workstation can however be part of a domain and the time is synced with it.
In this situation after the date/time is changed for the tests, the sync process will update them to the Domain Controllers value.
This will reset the date/time and the test environment is lost.

A question will then arise:
How to prevent time syncing with Domain Controllers?

The best solution that works in my test environment, is to change the registry key Type (REG_SZ value) located at
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Parameters

The Type can have the following values:
Value Description
NoSync No Sync with Domain Controllers
Nt5DS Sync with Domain Controllers

Note that the Nt5DS value is my configuration. Keep your Type value in the registry to restore to it.

The value can be updated with the registry editor (regedit) or by the command line, executing the following command:

reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Parameters /v Type /d NoSync /f

Note that the value NoSync forces the time not being synced with the Domain Controllers. Change the value to you configuration to restore the time sync.

This solution is great, but be aware that if the server/workstation date/time gets out of sync with the Domain Controllers, authentication will fail and you can loose access to them.
While testing, keep the server/workstation logged-in so that you can keep the date/time in sync with the Domain Controllers.

To automated the process of setting the test ambient you can create a cmd file with:

reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Parameters /v Type /d NoSync /f
net start W32Time
sc config "W32Time" start= disabled
net stop W32Time
date 01-04-2090

In this example the date is set as 01-04-2090

To return to the previous environment:
reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Parameters /v Type /d Nt5DS /f
sc config "W32Time" start= auto
net start W32Time

You may also need to set the date, if you computer is not syncing the date with and time server.

03 March 2015

Fix: Property PopulationStatus is not available for FullTextCatalog

After restoring a database with full text search active, on Sql Server 2014, on a staging server I got the following error when opening the Full Text Catalog:

Property PopulationStatus is not available for FullTextCatalog '[SearchDB]'. This property may not exist for this object, or may not be retrievable due to insufficient access rights. (Microsoft.SqlServer.Smo)

The error is not self explanatory, but after some investigation I descovered that Full Text Search Service isn't installed on the staging server.

The easy way to validate if  Full Text Search is installed on a Sql Server is to execute the following T-SQL statement on Management studio:

SELECT FULLTEXTSERVICEPROPERTY ('IsFulltextInstalled')