Exporting Objects from the Visual Studio Debugger

I had been searching for a way to export objects from my debugging windows (ex. locals, autos, watch) to their C# object initialization code for creating unit tests. There have been a few cases where there are some complex objects that I load through a database which would make great unit tests. Unfortunately i was not able to find anything like that, so I decided to create it myself. Enter Object Exporter.

https://visualstudiogallery.msdn.microsoft.com/c6a21c68-f815-4895-999f-cd0885d8774f

Object Exporter is accessed through the tools menu and is only visible when you are debugging.

Export Objects (Tool Menu)

Once selected a dialog is shown with settings for the Object Export.

Export Objects (Select Objects)

The Output Format details which format you want your exported objects to be in. Maximum Object Depth refers to the maximum depth the Serializer will generate text for, this is important as some objects can have an infinite depth. Once you select a debugging window from the drop down, it’s objects will be loaded onto the screen and you may check the objects you wish to export.

The objects which can be selected correspond to the objects that exist within the various windows:

Export Objects (Locals)

Once the objects are selected and the “Export” button is selected, another dialog with the generated texts appear:

Xml:
Export Objects (Xml Generated)

Json:
Export Objects (Json Generated)

CSharp:
Export Objects (CSharp Generated)

You can copy the text in the currently selected tab by selecting “Copy To Clipboard” or you can save all the objects to a folder by selecting the “Save All to Folder” button, a file per tab will be generated.

That’s pretty much it.

Enjoy

Automatically generating Repository and Unit Of Work classes

In my projects I usually access all my data through a repository. The utilization of the repository pattern provides a number of benefits for your code:

  1. Reduces duplicate data access code.
  2. Data access code can be isolated/faked for Unit Testing.
  3. Allows you to swap other ORMs, databases or data access code without affecting other parts of the system.

The only draw back to using a repository pattern is that it can be cumbersome to implement (especially if you have a lot of models), to help with that I’ve created a NuGet package which will generate Repository and Unit of Work classes with basic Get, Get All, Delete, Update code implemented in an abstract Generic Repository (so they can be freely overridden).

The NuGet package is available here:

DotNet
https://www.nuget.org/packages/RepositoryGenerator/

 

The NuGet package will add a RepositoryGenerator.tt which will generate the following classes:

Repository.cs: An abstract class with basic implementation of Get, GetAll, Delete and Update

IRepository.cs: An interface for the abstract class

UnitOfWork: A unit of work class for committing all changes at once.

IUnitOfWork: The interface for the unit of work.

In addition to these classes, a repository and interface will be generated for each one of your entities allowing you to extend beyond the basic functionality provided by the generic repository.

With the Repository Generator NuGet package you should be up and running with a repository within a just few seconds!

Enjoy

Generating C# Classes from Excel

A while back I was tasked with converting and migrating data from an existing accounting system to a new one, (un)fortunately this was not the first time I was asked to do a data conversion. A year prior I had to migrate data from a 20 year old legacy system to a new software solution.

While the systems were completely different I was able to reuse a lot of the patterns and helper libraries which I had used before. During the first data conversion I felt a large portion of my time was wasted creating classes for the corresponding excel input and output files. I thought if I could generate classes with properties corresponding to the excel columns and their types, that it might save some unnecessary typing to create those classes.

So i created ExcelToClasses, a NuGet package which will open an .xls file and convert each worksheet to a class and each column to a property within that class.

The NuGet package can be found here:

https://www.nuget.org/packages/ExcelToClasses/

The package will add some T4 templates to your project, all that’s needed is to open the DataConversion.tt file and supply one or many paths to the excel file(s) and save the DataConversion.tt file.

A .cs file will be generated per worksheet, each property will have an attribute with the name and position of the corresponding excel column. This will be very useful if you are generating classes for the output schema (the format of the new system) and you wish to rename the properties or change their position in the class without affecting the output file to be generated.

Github:

https://github.com/OmarElabd/ExcelToClasses

Enjoy

ASP.NET MVC 4 using the MySQL Simple Membership Provider (errno: 150)

I’ve been using the fairly new Simple Membership Provider (that ships with versions of the MySQL Connector/Net 6.9.0 and greater) for use with a new ASP.NET MVC 4 project.  However when following the tutorial for getting up and running from the MySql site ( https://dev.mysql.com/doc/connector-net/en/connector-net-simple-membership-tutorial-creating.html ). I ran into an issue when generating the webpages_* tables.

The specific error i received is: Can’t create table ‘.webpages_membership’ (errno: 150)

MySql Foreign Key Error

I have tried this multiple times using different configurations of visual studio and MySql server and the issue only seems to be with the MySql server version being too low, however the requirements never mention a specific minimum MySql server version number. Requirements can be found here ( https://dev.mysql.com/doc/connector-net/en/connector-net-simple-membership-tutorial-requirements.html )

However if you are using an older version of MySql server you can run the following script to generate the tables:

CREATE TABLE `webpages_membership` (
  `UserId` int(11) NOT NULL,
  `CreateDate` datetime DEFAULT NULL,
  `ConfirmationToken` varchar(128) DEFAULT NULL,
  `IsConfirmed` tinyint(1) DEFAULT '0',
  `LastPasswordFailureDate` datetime DEFAULT NULL,
  `PasswordFailuresSinceLastSuccess` int(11) NOT NULL DEFAULT '0',
  `Password` varchar(128) NOT NULL,
  `PasswordChangedDate` datetime DEFAULT NULL,
  `PasswordSalt` varchar(128) NOT NULL,
  `PasswordVerificationToken` varchar(128) DEFAULT NULL,
  `PasswordVerificationTokenExpirationDate` datetime DEFAULT NULL,
  PRIMARY KEY (`UserId`),
  CONSTRAINT `fk_User_Membership` FOREIGN KEY (`UserId`) REFERENCES `userprofile` (`UserId`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `webpages_oauthmembership` (
  `Provider` varchar(30) NOT NULL,
  `ProviderUserId` varchar(100) NOT NULL,
  `UserId` int(11) NOT NULL,
  PRIMARY KEY (`Provider`,`ProviderUserId`),
  KEY `fk_UserId_OAuth_idx` (`UserId`),
  CONSTRAINT `fk_UserId_OAuth` FOREIGN KEY (`UserId`) REFERENCES `userprofile` (`UserId`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `webpages_roles` (
  `RoleId` int(11) NOT NULL AUTO_INCREMENT,
  `RoleName` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`RoleId`),
  UNIQUE KEY `RoleName_UNIQUE` (`RoleName`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

CREATE TABLE `webpages_usersinroles` (
  `UserId` int(11) NOT NULL,
  `RoleId` int(11) NOT NULL,
  PRIMARY KEY (`UserId`,`RoleId`),
  KEY `fk_Role_idx` (`RoleId`),
  CONSTRAINT `fk_User` FOREIGN KEY (`UserId`) REFERENCES `userprofile` (`UserId`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_Role` FOREIGN KEY (`RoleId`) REFERENCES `webpages_roles` (`RoleId`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `userprofile` (
  `UserId` int(11) NOT NULL AUTO_INCREMENT,
  `UserName` varchar(250) NOT NULL,
  PRIMARY KEY (`UserId`),
  UNIQUE KEY `UserName` (`UserName`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

 

Hope that helps.

Kinect v2 Initial Thoughts and Resources

I recently acquired the Kinect v2 that was released on July 15th 2014.

 

Kinect v2

After going through the SDK samples i was thoroughly impressed with the capabilities of the Kinect v2 sensor. The projects sampled many of the Kinect v2 features such as Directional Audio, Infrared, Body (Skeletal) Tracking and Depth Sensing.

 

Kinect SDK Samples

 

However, the one thing missing from the SDK is KinectFusion. Kinect Fusion is used for creating 3D models (which you could potentially make a 3d print out of the models you’ve taken from the Kinect). You can request access for the KinectFusion preview by visiting the Kinect Forums.

 

 

Information and Specs:

The Kinect v2 is currently only available on Windows 8 and Windows 8.1 Devices. It is recommended to use a USB 3.0 connection as there is a lot of data to transfer

You can find more information on the Kinect Features here.

 

For programming the Kinect sensor a great resource is the Microsoft Virtual Academy class by Ben Lower and Rob Relyea. The class should be available by the first of August, but if you can’t wait you can  find the slides here.

 

Links:

You can download the SDK here.

You can purchase the Kinect v2 here. (You can get 10$ off the price by applying a 5% Microsoft discount which you can trivially acquire through the Bing Rewards Program)

You can find the Programming Guide here.

ZumoMotors for Netduino

I had purchased a Netduino 2 a few weeks back and wanted to try and make it work with my Zumo chassis for Arduino. Unfortuatenly I couldn’t find an existing ZumoMotors library for the Netduino, after a while for searching i finally gave up and decided to write my own.

The code is availabe on GitHub:

https://github.com/OmarElabd/ZumoNetduino

 

Example Usage:

ZumoMotors zmotors = new ZumoMotors();

//Set Left and Right Motors to go forward with 100% Speed
zmotors.SetSpeeds(100,100); 
Thread.Sleep(1000);
//Stop the Motors
zmotors.SetSpeed(0,0); 
Thread.Sleep(1000);
//Set Left and Right Motors to go in reverse with 100% Speed
zmotors.SetSpeed(-100,-100); 
Thread.Sleep(1000);
//Set Left Motor to 100% forward and Right Motor 50% forward
zmotors.SetSpeed(100,50);

 

If you’re interested in purchasing your own Netduino or Zumo chassis you can find them here on Amazon:

 

 

*Note: While this code should work on the Netduino 2 Plus the ethernet port for it will get in the way of it connecting to the male header pins of the Zumo Chasis, you would need to build an extender to lift it up.

*Note: It might be worthwhile to wait until blackfriday as Pololu will usually put deep discounts on their Zumos and give some away as doorbusters.

MessageBoxes in Windows Phone 8.1

If you want to use MessageBoxes with your Windows Phone 8.1 Applications instead of using MessageBox you’ll need to use MessageDialog.

Make sure to include the following using statement:

using Windows.UI.Popups;

The code to launch a message box is as follows:

MessageDialog msgDialog = new MessageDialog("Works in Windows Phone 8.1");
//launch the dialog
await dialog.ShowAsync();

Hope that helps.

Opening Settings in Windows Phone 8.1 Runtime XAML

I've been frustrated to find that as a result of Microsoft.Phone (and more importantly Microsoft.Phone.Tasks) not being supported in Windows Phone 8.1 XAML launching a specific phone setting from your application has changed. It is however supported in Windows Phone Silverlight 8 and 8.1.

Previously the code for opening a settings page (in this example the Bluetooth Settings Page) would have followed:

ConnectionSettingsTask connectionSettingsTask = new ConnectionSettingsTask();
connectionSettingsTask.ConnectionSettingsType = ConnectionSettingsType.Bluetooth; 
connectionSettingsTask.Show();

or alternatively:

Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth"));

 

The new syntax for opening a settings page (again in this example Bluetooth) in Windows 8.1 Phone XAML is as follows:

Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:///"));

*Notice the addition of the :/// (makes all the difference in the world)

 

Hopefully that saves you some time searching because it took me a while before i found anything remotely useful for Windows Phone 8.1.