Unit testing with SqlServerMigrationGenerator

October 27, 2015 Leave a comment

You may have noticed that all of the Generate(…) methods that you would be overriding in a custom Migration class are marked as protected, not public. This means you can’t directly test them in your unit tests.

Luckily we can take advantage of the way the Migration class is built and use the Generate(IEnumerable, string) method for our testing. IT does result in the creation of some extra objects, like a DbConnection (although it is never actually connected to a database). The second parameter takes a SQL version number.

Inside of this method, Microsoft initializes DbProvider things, and then runs through the collection of MigrationOperation and returns a collection of IEnumerable. So your unit test can simply check the first result the return value and pull the SQL from there. While this does make your test a little brittle (since you’re comparing strings that can be somewhat long), a little extra care and some code to clean up extra whitespace goes a long way.

[TestMethod]
public void GetAddColumnSql_DateCreated_ReturnsCorrectScript() {
    //arrange
    var columnName = "DateCreated";
    var columnType = "datetime2";
    var tableInfo = new DatabaseTable("Dbo.Test");
    var columnInfo = new ColumnModel(PrimitiveTypeKind.DateTime) {
        Name = columnName,
        StoreType = columnType
    };

    var addOperation = new AddColumnOperation("Dbo.Test", columnInfo);

    //act
    var result = (new StandardSqlServerSqlGenerator().Generate(new List {addOperation }, "2008")).First().Sql;

    //assert
    Assert.AreEqual("ALTER TABLE [Dbo].[Test] ADD [DateCreated] [datetime2](7) CONSTRAINT DF_Dbo_Test_DateCreated DEFAULT GETDATE()", result);
}

Custom Sorting with Kendo Grid in ASP.NET MVC

September 16, 2015 Leave a comment

So we ran into a problem at work when using Telerik’s Kendo MVC UI package. It turns out that there is no way to server-sort on columns if the column names don’t match the actual data model property names.

In our case, the names didn’t match because we’re using ViewModels for the grid, and this particular viewmodel wrapped two properties in one.

It turns out that the DataSourceRequest object that Kendo sends to the controller has a Sorts collection, and this collection can be modified. So it was simply a matter of modifying and adding to that collection, and the ToDataSourceResult() method performed the sorts as intended.

But how to make this generic so we could apply it to any view model? Attributes to the rescue!

public class SortedAttribute : Attribute {
    public SortedAttribute(params string[] dataPropertyNames) {
        DataPropertyNames = dataPropertyNames;
    }
    public IEnumerable<string> DataPropertyNames { get; set; }
}

Here’s a viewmodel using our new attribute.

    public class MyViewModel {
        int Id { get; set; }
        
        string Description { get; set; }
        
        [Sorted("Customer.Id", "Customer.Name")]
        string Customer { get; set; }
        
        [Sorted("Location.Id", "Location.Description")]
        string Location { get; set; }
    }

Then we just need to modify our request’s Sorts collection using the values in the attribute. I made this an extension method to make it easy to call from the controller method.

public static void UpdateSort<T>(this DataSourceRequest request) {
    //get properties that have a Filtered attribute
    var propertiesToChange = typeof(T).GetProperties()
        .Where(p => request.Sorts.Select(s => s.Member).Contains(p.Name) && p.GetCustomAttributes(typeof(SortedAttribute), false).Length > 0);

    foreach (var sortProperty in propertiesToChange) {
        //get filtered attribute (indexing is okay because we're only looping through ones we know have one)
        var sortedAttribute = (SortedAttribute)sortProperty.GetCustomAttributes(typeof(SortedAttribute), false)[0];

        //get the current Kendo sort descriptor
        var currentSort = request.Sorts.Single(s => s.Member == sortProperty.Name);
        //update the name to be the first data property name
        currentSort.Member = sortedAttribute.DataPropertyNames.FirstOrDefault() ?? sortProperty.Name;

        //if there are other data property names, add them to the sort, using the same sort direction
        foreach (var dataPropertyName in sortedAttribute.DataPropertyNames.Skip(1)) {
            request.Sorts.Insert(request.Sorts.IndexOf(currentSort) + 1, new SortDescriptor(dataPropertyName, currentSort.SortDirection));
        }
    }
}

Now we can just call it like this:

public ActionResult Get([DataSourceRequest] DataSourceRequest request) {
    var data = Context.MyData;

    request.UpdateSort<MyViewModel>();

    var results = data.ToDataSourceResult(request, ModelState, e => new MyViewModel {
        Id = e.Id,
        Description = e.Description,
        Customer = String.Format("{0} - {1}", e.Customer.Id, e.Customer.Name),
        Location = String.Format("{0:000} - {1}", e.Location.Id, e.Location.Description)
    });

    return Json(results, JsonRequestBehavior.AllowGet);
}

Why Telerik hasn’t built similar functionality into their product is beyond me. Microsoft had custom sort properties in their WebForms grid 10 years ago. Anyway, I hope this helps someone!

Gear List – PCT 2014

March 25, 2014 4 comments

A hiking buddy of mine is tackling the PCT this year. I have to admit that I’m a bit envious.

Bone of Contention

Hi Folks! It has been awhile. I hope you are well. Aww thanks, me too! How is the family? The kids? Great, great, good to hear.

Holtwood Dam 3/22 Holtwood Dam 3/22

I have been super duper ultra busy the past few months getting ready for this hike – working on the plans, buying the last minute gear, figuring out my resupply strategy and buying food, packing boxes, testing gear and replacing a few items, and doing my real job, and working with my favorite volunteer group Lancaster Young Professionals. I have been the acting event chair for a gubernatorial debate to be held this October and had many tasks to finish up as well as finding and briefing/training my replacement. Work at RAI has exploded with opportunities, which is good, but the timing is problematic. My dad and I have gamed out as many scenarios as we can, done lots of…

View original post 1,066 more words

Categories: Uncategorized

Future of Microsoft

February 18, 2014 Leave a comment

So here we are in 2014. Windows 8 is by pretty much every measure a failure. Paul Thurrott is writing about how Sinofsky may have killed the Windows product and how Microsoft is making sure it’s dead by bending over backwards to please everyone with 8.1 Update 1 (another stellar name from MS).

Being a professional Microsoft developer, I have a different perspective of things and see the best parts of MS (the .NET Framework and Visual Studio are the best development products out there, bar none). It puzzles me how they can be so great on some sides and so horrible on others.

Still, I see hope for MS. I also see some evidence that they see the solution as well. The answer is to get back to their roots and make simply make great software. Stop focusing so much on controlling the end-to-end experience, and just do what you’re best at.

They’ve already started doing this by making iOS and Android versions of Office, as well as making Skydrive/Onedrive available on all OSes.

Continue down this path, leave Windows to the desktops and servers, and become the best selling software maker on the iPad. Windows wasn’t the beginning of Microsoft, and if they make the right decisions, it won’t be the end.

PDFSharp Bug Workaround

October 23, 2012 Leave a comment

So I’m using PDFSharp to insert page numbers into some PDF files at work. The problem was that somehow the page width was being truncated on save,s o any landscape pages would get cut off.

The solution is to make a new PDFDocument and add the pages from the existing PDFDocument to it, and then overwrite the original document (since for whatever reason, the save method on the new instance of the document doesn’t affect the page widths).

PDFSharp makes PDF operations super easy, but man is it a buggy library.

Thoughts on Windows 8

August 9, 2012 8 comments

I’ve been using Windows 8 for a while, and since everyone else is focusing on the UI changes, I figured I’d list some of the improvements that have been made outside of the Start Screen that I enjoy. There are many others as well, even though most of the press has focused on the new UI.

  • hardware-accelerated graphics everywhere, even for things like decoding JPEG files. This makes Windows much faster all-around. Even text rendering is now done with DirectX, leaving the CPU free to do more important things.
  • built-in “file history” feature that replaces need for backup by storing copies of files in your libraries on a secondary location.
  • much better multi-monitor support, with ability to have taskbar on both screens
  • improvements in NTFS including ability to fix errors on the fly without rebooting to run chkdsk.
  • roaming settings/files with Microsoft ID (any Windows 8 device I log into will have my settings and customizations)
  • better support for high DPI (metro apps get this support automatically, which makes my 120dpi screen happy)
  • pausable file copying with a much better estimate of time to completion.
  • improved task manager showing per-app cpu, memory, disk, and network usage – comes in handy when I want to know which app is making my hard disk churn
  • storage spaces – lets you define a virtual disk out of several existing drives and add new drives to it without any formatting or partitioning. Also includes RAID-like features (RAID 0, RAID 1, RAID 5) without the hassle of rebuilding arrays or making sure disk sizes match.
  • reset/refresh button – takes Windows back to its factory-default state without/with personal files and settings with the click of a mouse. I haven’t had to reinstall Windows in a while, but this would be convenient rather than having to dig out the disc and product key again.
  • fast boots (apparently sub 5 seconds with an SSD and a UEFI motherboard, but still a lot faster than windows 7 boots)
  • pervasive search and share – any app can tell windows it supports searching and/or sharing and is included in the search and share charms. This took some getting used to, but is definitely a better approach than having every app implement its own solution. The app doing the sharing has no knowledge of the share destination.
  • built-in anti-virus program, no need to install Security Essentials since it’s already there.<
  • native support for ISO files – no need to burn them to a disc first, or get a third-party ISO reading app.
  • improved Open File dialogs that support grabbing files from Skydrive, Facebook, Photobucket and more, right alongside local folders.

And of course, there is the huge developer improvement of WinRT, which massively updates the Win32 API and makes programming native apps feel like programming .NET or Java apps with none of the performance penalties that happen when running on the Java Virtual Machine/Common Language Runtime. They’ve also added lots of features for tablets, like cellular data support with airplane mode and metering, much improved power saving, support for all of the gyroscopes and GPS gadgets that are in tablets, and multiple touch points (in fact, tablets must have at least five to get the Windows 8 sticker).

It’s definitely a risk, and if it flops, MS will lose a ton of money. I’ve been using it for months and have no complaints. It did take me a while to figure some things out. There are things I disagree with, like putting printing inside of the Devices charm (that one l would have never found on my own). I think lots of power users will gripe about it but eventually switch over. And in 2-3 years, no one will remember how much they hated it. The same thing happened with XP as many things were moved around from where they were in Win98. I wasn’t old enough, but I’m sure there were similar complaints when Windows first came out and the old DOS users had to start using a mouse and adjusting to the new desktop paradigm.

And remember, Win+C, Win+I, Win+F.

Comcast’s Digital Switchover

April 13, 2012 1 comment

I wrote this as a response to a discussion on LinkedIn, but thought I’d post it here too, in case anyone was interested.

———————————-

Because of the switchover to all digital for over-the-air broadcasts back in June of 2009, all TVs made since 2008 had to have digital (ATSC) tuners built-in.

Most of these digital tuners also support tuning “clear” (unencrypted) QAM signals, which is what most digital cable providers use. Comcast has to send local channels unencrypted, so you will never need a cable box to view those channels as long as your TV has an ATSC/QAM tuner. If your TV doesn’t have this tuner, you will need to get a box from Comcast to continue receiving channels.

Some channels send a virtual channel number with their signals. WGAL does this so that their channel shows as 8.1 on your TV, even though it’s broadcast on channel 58.1. Other channels don’t do this, so without the Comcast box to translate the numbers, they will show up on odd channels. I believe that WGN, for example, is currently on channel 17.5. Since Comcast moves around their channels fairly often, it’s a good idea to do regular rescans if you’re plugging directly into the TV. The Comcast box will continue using the channel numbers that you’re used to (5 for WGAL, 20 for WGN, etc.).

For the encrypted channels (right now this is everything above 24, but Comcast has told me that it will soon be everything but the locals), you’ll need to either rent a cable box from Comcast, or rent a CableCard from Comcast and plug it into a CableCard-supported TV.

Comcast is moving to all-digital because digital channels take up much less bandwidth than analog channels do. This will let them carry more HD channels, more channels with 5.1 surround sound, and even provide faster internet service. It also makes it much easier for them to control access to the channels (and I believe this is the real reason for the switch). For analog cable, a tech would have to go out to the box in your neighborhood and physically install/remove a “trap” to block the signals. With everything digital, it’s the cable box itself (or CableCard) that gives/removes access to certain channels, so they can do it all from their office with the click of a mouse.

Neat document from ALM Rangers

September 9, 2011 Leave a comment

Interesting (but long) read on requirements management written by MS and some sample document templates.

A lot of it is capturing way more information than Lancaster Labs is, but it’s still nice to see another company’s process. I thought the section on traceability was good and liked their definitions for the various requirement types. They also provide detail on how Team Foundation Server lets them store all of this information electronically, so you don’t need to wade through stacks of paper to find the info you’re looking for.

Nice comparison of requirements, use cases, and user stories

July 29, 2011 Leave a comment

I found this on Scrum Alliance. It makes a sometimes difficult topic very clear.

http://www.scrumalliance.org/articles/169-new-to-user-stories

Neat use of HTML5

July 28, 2011 Leave a comment