C#, Code, Tips, Visual Studio

Visual Studio – Paste Special – JSON as Classes

This has been there since 2013 I believe, but I’m just now discovering it….wish I would have found it sooner as it’s an awesome feature.

Take a JSON (or XML as there is a Paste XML as Classes as well) like the following and copy it into the clipboard:

"People" :[{
    "First Name" : "Jason",
    "Last Name" : "Lautzenheiser", 
    "Address" : {
        "Street" : "1122 Main",
        "City" : "BigTown",
        "State" : "OH",
        "Zip" : 66554
    "Phones" : [{
        "PhoneType" : "Home",
        "Number" : "330-555-7777"
        "PhoneType" : "Work",
        "Number" : "330-222-1111"

Then under the Edit->Paste Special menu, there is an option for Paste JSON as Classes which will spit out the following code:

public class Rootobject
 public Person[] People { get; set; }

public class Person
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public Address Address { get; set; }
 public Phone[] Phones { get; set; }

public class Address
 public string Street { get; set; }
 public string City { get; set; }
 public string State { get; set; }
 public int Zip { get; set; }

What a beautiful thing that is. I recently had to import and manipulate some JSON data for a report which was much more complex than this. Within minutes I had my object model setup and the JSON files being read in.

Small feature, but what a time saver.

.NET, Code

String.Contains looking for an empty string

Here’s another one of those little idiosyncrasies that I run across in coding.  In some ways I’m almost embarrassed to say I never knew this as it’s really quite simple and also well documented, but it’s one of those edge cases that just don’t happen that often and may not be that damaging of a bug if it does sneak through.

The construct I’m talking about is the String.Contains() method.   In .NET it simply returns a true/false on whether the string contains the string parameter passed into it.

string s1 = "This is a nice string";
bool b;
b = s1.Contains("nice"); // returns true;
b = s2.Contains("bad"); // returns false;

All nice and simple. The issue I ran into was when the string I was looking for was an empty string.

b = s1.Contains(""); // returns true

In my application, that requirements were that it should return false. However, this returns true. It is well documented, but not something I really had to deal with before.

Something to keep an eye out for as it could give you some false positives if you’re not careful.

Still learning after all these years.

Code, Links

Links to Code By #4

Another episode of my infrequent Links to Code by. My take on things old and new that are interesting to me and perhaps make my coding life easier, more entertaining or purely stretches my cerebral matter. Enjoy!

Giving Clarity to Linq Queries by Extending Expressions – What a great article. This is something I’ve done plenty of times before, but here is a formal write-up.  in this article, Edward talks about using the Pipe and Filter pattern to simplify and give clarity to your linq statements.  Through the judicious use these custom expressions, our linq queries become more concise and readable and the expressions become easily reusable.   Good stuff here.

The Wounded QR Code – Most everyone knows what a QR code is by now.  But do you know how they work?  Do you know how durable they are and how resistant to damage they can be?  Do you also realize how creative you can become with their design while still maintaining a working code?  Well this article is a great introduction (and goes beyond just introducing them) to the great QR code with a special emphasis on damage and reliability.

NAudio 1.7 – I’ve always been fascinated by audio programming from the days on my Commodore 64 doing MIDI programming (good resource here), but I’ve never had a reason to dive into it before…..I still don’t really, so perhaps this is just an empty promise to myself, but I am going to look at this deeper some day.

WebForms URL Routing – I’ve not done a ton of web programming over the last couple years so I’ve not kept up on the new advancements in ASP.net.   Here is a good example of something I just discovered this morning.  New in 4.0 (I think) the routing capabilities adds a new dimension to the whole web forms arena.  I have to do a lot more research and testing before I pronounce judgement on this, but it’s nice to know that it is here.

When I interview potential new developers, one question I usually ask is, “If given unlimited resources and time, what would you do?”  9 out of 10 developers say some form of “Develop games”.  If was asked that years ago, my answer probably would have been the same (it still may be for that matter).  Game development has always fascinated me even though I realize that is probably one of the most demanding forms of development there is.  Well here is a blog from one Jesse Freeman, who is a technology evangelist for Microsoft that focuses on Windows 8 game development.  Good stuff, worth the read.

Well that’s enough to keep you busy for this Saturday….until next time….

.NET, C#, Code, PetaPoco

PetaPoco Needs a Parameterless Constructor

I’ve been using PetaPoco for a few years as my micro-orm of choice.  It’s lightweight, simple to use, yet powerful enough for most of my needs.  Let me share one thing that I tend to forget and it seems to trip me up all the time.

In short, PetaPoco requires a parameterless constructor on the classes it’s trying to integrate with.

  public class Customer 
    public Customer() 

Or if there is no other constructor defined, the compiler will create that default constructor for you essentially and you don’t have to explicitly code it. This is where I usually run into trouble. I’ll depend on the compiler to give me the default constructor and code as follows.

  public class Customer 
    public string Name {get;set;}
    public string Address {get;set;}
    // more properties and methods

With this PetaPoco works flawlessly. No problems here. Now let’s say I create a constructor for one reason or another. For example, we want to pass the customer’s name in the constructor.

  public class Customer 
    public string Name {get;set;}
    public string Address {get;set;}

    public Customer(string _name)
      Name = _name;
    // more properties and methods

Now if we try to read in a list of customers with PetaPoco, we suddenly get a Null argument exception and it comes from deep inside PetaPoco where it’s not at first obvious what is going on. In fact, every time I get this error, I forget that I’ve seen it before and scratch my head for a few minutes…..thus this post…hopefully I’ll remember now.

Anyway, PetaPoco needs that parameterless constructor, which if we have no other constructor defined, will happily get created by the compiler. However, if we do provide a constructor like in the last example above, the compiler does not create that default constructor and we have to define it explicitly.

  public class Customer 
    public string Name {get;set;}
    public string Address {get;set;}

    public Customer() 

    public Customer(string _name)
      Name = _name;
    // more properties and methods

Once we do that, PetaPoco works beautifully once more.

.NET, Code

VB.NET, Inline If statement

I’m much more of a C# guy than VB.net .  I haven’t worked steady in VB.net since 1.1 (around 10 years or so).  However before .NET, I was a VB4-6 guy and spent many hours working in classic VB.  Having originally come from a C background, the switch to C# was natural.  One thing that had always bothered me about VB was the lack of short circuit evaluation.  I won’t explain that here, but if you want to learn more, follow that last link.  C and it’s derivatives offered it, while VB did not. 

Not a huge deal, but it often lead to some nested IF’s if you handled it, or some unsuspecting bugs if you didn’t.  Recently, I’ve been working on a project for a client that has requested the project be done in VB.net.  While working on some code, I ran across an old friend, the IIF function.

IIf(PrinterDevice Is Nothing, “<Device not setup yet>”, PrinterDevice.ToString())

Basically, just want to print “<Device not setup yet>” if the PrinterDevice object is nothing, otherwise printout the results of the ToString() on the PrinterDevice.  The problem is, if PrinterDevice is nothing, then the PrinterDevice.ToString() gives a nullreference exception.  As I was preparing to nest my If statements, I discovered something new was added to .NET 2.0 that I hadn’t run across.  For you VB guys, you’ve probably seen this already, but interestingly enough, I had not.

If(PrinterDevice Is Nothing, “<Device not setup yet>”, PrinterDevice.ToString())

That simple change (notice the IF vs IIF) makes the difference.  The IIF call is a method call, so all parameters are evaluated before the call is made.  In the case of the IF, the IF() is a statement, so it first evaluates the condition (PrinterDevice Is Nothing) and if it’s true, it prints “Device not setup yet” and never evaluates the ToString().  It performs the short circuiting that I’m used to.

Nothing new for you VB guys, but for use C# guys that are stepping into the VB world from time to time, this is a nice change.



.NET, Code, Infragistics, WinGrid

Infragistics WinGrid – Tips and Tricks #1 – Right Click Row Select

I’ve been working with Infragistics tools, specifically the UltraWinGrid for 10 years or more (worked with the Sheridan grid before that, anyone remember those tools?), and outside of the Infragistics forums there seems to be very little in the way of information on this very powerful and complex tool.  Perhaps I can leverage my experiences with these tools into a nice little series of posts on things I’ve discovered over the years.

I came upon a situation where I wanted to right click on a grid, have it select the row under the mouse and bring up a context menu to act on that selected row.  As another requirement I wanted it to only act upon data rows.

I came up with the following extension method.

  1. First get the element under the mouse and determine if it’s a row element.
  2. If it’s a row, is it a datarow?
  3. Make it the active row.
  4. if the row is not already selected, select it and deselect any other row.
  5. if the row is already selected, then do nothing else special with the selection properties.
  6. if we’ve clicked somewhere not a datarow, I clear any selected rows in the grid.
21 public static void RightClickRowSelect(thisUltraGrid grid, Point mouseLocation)  
22 {  
23     UIElement element = grid.DisplayLayout.UIElement.ElementFromPoint(mouseLocation);  
24     var row = element.GetContext(typeof(UltraGridRow)) asUltraGridRow;  
25     if (row != null && row.IsDataRow)  
26     {  
27         grid.ActiveRow = row;  
28         if (!row.Selected)  
29         {  
30            grid.Selected.Rows.Clear();  
31            row.Selected = true;  
32         }  
33     }  
34     else  
35     {   
36        grid.Selected.Rows.Clear();  
37     }  
38  }

Then to use this, I simply call it in the MouseDown event on the grid as follows.

    1     privatevoid grdLabsMouseDown(object sender, MouseEventArgs e)
    2     {
    3       if (e.Button == MouseButtons.Right)
    4       {
    5         grdLabs.RightClickRowSelect(e.Location);
    6       }
    7    }

Pretty basic really, but knowing how to determine what element is under the mouse is a critical tool in your belt when dealing with the WinGrid and opens up the door for a lot of advanced features.

Code, SQL

SQL Server – Fixing Orphaned Users after restore

I was tasked with migrating a SQL 7 box (yes still heavily used) to SQL 2008.  Really wasn’t that difficult, perhaps I’ll make another post about the process and issues I ran into.  But for now let me talk about something real quick. 

When restoring a database to a new server you may not have your security setup properly.  For example, the database will have users that don’t exist on the server.  Or perhaps they do but they are not linked properly.  This is the issue I ran into. 

Sometimes it’s just as easy to delete the users from the database and recreate them on the server to relink.  This is fine if you have simple permissions.  But if you have a complex set of permissions on a large number of tables, this get’s difficult to recreate properly and of course you always have the potential to create errors in multiple applications that may connect as that user.

Then I found sp_change_users_login, this has saved the day.  This allowed me to fix the orphaned users after the restore.


EXEC sp_change_users_login 'Auto_Fix', 'orphaned-user-name'

How do we quickly determine if we have this issue?

EXEC sp_change_users_login 'Report'

This will give us a list of orphaned users.  Very handy indeed.