Suppress Columns in Entity Framework Code-First

I'm not a big fan of what I call "aggressive code-first," where your table design is derived from your object design. And, to tell you the truth, I'm not sure I have a good reason for my skepticism. With the one client I worked for who used this process, everything worked out fine (by which I mean that the table design we ended up with was exactly the one I would have recommended).

One issue I have with deriving my table design from my object model is that my object model frequently includes properties that I don't want to have appear as columns in my database. The most obvious example of this are read-only properties whose values are calculated internally (typically, from other properties on the object). Entity Framework is smart enough that it will skip most of these properties but, every once in a while, EF will want to add a column to a table based on a property that I'd prefer EF ignored.

To get EF to ignore the property, just decorate the property with the NotMapped attribute. In this code, for example:

Public Class Customer
  Public Property Status As String
  Public Property Rating As String
  <NotMapped>
  Public Property CreditRating As String
End Class

the Customer class' Status and Rating properties will generate columns in the Customer table but the CreditRating property will not.

Posted by Peter Vogel on 09/30/20160 comments


Label Your Breakpoints

With more recent versions of Visual Studio, breakpoints you set in your code are saved from one editing session to another. Because you might not always want to stop on those breakpoints, however, you will want to selectively enable and disable them. To facilitate that, from the Debug | Windows menu choice, open the Breakpoints window to view (and manage) all of your breakpoints. From this window you can, for example, double-click on any of the listed breakpoints to be taken to its position in your source code.

The only problem is that, in the Breakpoints window, all breakpoints look very much alike. Fortunately, once you're in that window, you'll also find that you can right-click on any breakpoint and assign it a label that's displayed right beside the breakpoint in the window (you can also right-click on the breakpoint in your source code and assign a label right there). If you're clever about adopting a naming convention you can then sort your breakpoints into groups that you can enable and disable with a single click just by selecting multiple breakpoints in the window. There's no reason, for example, that you can't assign one label to a set of related breakpoints.

There's more you can do in this window. You can assign a condition specifying when the breakpoint should be honored or have the breakpoint write a message to the output window instead of stopping on the breakpoint. You should start thinking of your breakpoints as a resource that lasts the life of your code.

Posted by Peter Vogel on 09/26/20160 comments


Doing Calculations Right with the Math Class

The .NET Framework gives you the Math class, which has a ton of methods and properties that you can use.

The Abs function will convert negative numbers to positive (and leave positive numbers alone), while the Sign method will tell you if a number is positive, negative or zero.

The Truncate, Ceiling, Floor and Round methods will give you four different ways to get the integer portion of a decimal value, depending on what you want.

The DivRem method will return both the result of a division and its remainder (and IEEERemainder has a special result when you divide a smaller number by a larger number).

The Math object's PI property gives you a value of PI to more than 12 decimals -- more accuracy than you'll probably need.

The Sin, Cos and related methods will perform all of those trigonometry functions that I never really got in high school.

There's more functionality here than I can discuss, but I have to mention the BigMul method (which sounds like the name of a Scottish folk hero to me). When you multiply two large integer numbers you might get a result bigger than an integer … which will cause an overflow exception. BigMul, on the other hand, will multiply two 32-bit integers and return a Long, avoiding overflow.

Maybe it is a folk hero.

Posted by Peter Vogel on 09/15/20160 comments


Always Go to Production in Release Mode

I was at a client's site recently and watched them move the new version of their app to production by copying all the DLLs from the "staging" computer to the production computer. I commented on how that was the beauty of the .NET Framework: Once you had the application installed, upgrades could just consist of replacing the EXEs and DLLs. Of course, I added, you have to remember to do one last compile in Release mode before copying the DLLs.

My client said, "Pardon?" I said, "What!?!"

It turns out that, at my client's site, once a developer got their code working, my client just copied that developer's DLLs to the QA testing site. There's nothing wrong with that ... but my client was leaving money on the table as far as performance goes.

When you press F5 to start debugging, Visual Studio saves and compiles your application. However, that compile is a "fast and sloppy" one -- Visual Studio doesn't do any real optimization of your code. There are a couple of reasons for that. First, this "fast and sloppy" compile gets you into debug mode faster (which is good). Second, skipping optimization avoids rearranging, merging or even eliminating lines of your code, which some compiler optimizations can do. When you're stepping through your source code in debug mode, it's helpful if there's a one-to-one relationship between your source code and your compiled code which rearranging/merging/eliminating makes difficult.

However, when you move to production, you want all of those optimizations. I know that I've said elsewhere that the speed of business applications is controlled by their data access ... but for the cost of going up to the toolbar and changing that Solution Configuration's dropdown list setting from Debug to Release you can, potentially, get a significant improvement in your application's performance (my client estimated about a 10 percent reduction in average response time, for example).

You do have to remember to switch back to Debug mode after doing your "production compile." One of the other things that the Debug mode does is generate a .pdb file that supports debugging (among other things, it provides the relationship between your lines of source code and your compiled code). If you don't keep regenerating that file as you make changes to your source code, your debugging sessions will get decidedly weird.

Posted by Peter Vogel on 09/09/20160 comments


Maximize Your Visual Studio Editor Window Space Fast

When I'm writing code, I like to devote as much screen space in Visual Studio to my editor window as possible. I did a tip earlier on how to get into Visual Studio's full screen mode where your entire screen becomes your editor window. However, I understand that full screen mode might not be your cup of tea because getting to the various tool windows -- Solution Explorer, for example -- isn't obvious (you also lose the window's title bar with the standard maximize/minimize/reset buttons).

If you'd like to get the maximum room for your editor's window without giving up the Visual Studio window, then go to the Windows menu and select Auto Hide All. That choice will immediately collapse all of your tool panes -- Solution Explorer, the toolbox, the Properties List and all of their siblings will collapse into the sides of Visual Studio, giving you the maximum editing space inside of Visual Studio. You can, of course, bring back the tool panes you need by clicking on them...but there is no "auto un-hide all" so you have to bring each tool pane back individually.

In Visual Studio 2015, though, you have an alternative to bringing back each tool pane one-by-one: Windows Layouts. To use this, first set up your "preferred" layout of tool panes (probably the one you have in front of you right now). Then assign this Windows layout a name and save it by going to the Window menu and selecting Save Window Layout.

With your preferred layout saved, after using Auto Hide All you can get back to the tool panes you want by selecting Window | Apply Window Layout | <your layout name> from the menu. Saving Windows layouts isn't an option in earlier versions of Visual Studio which only remembered the layouts for four fixed modes: Design, Debug, Full Screen, and File.

Posted by Peter Vogel on 09/01/20160 comments


Make Sure You're Compressing What You Send to the Browser

This is really a tip for IIS 7 (or later) Web site administrators than it is for developers: Make sure that you've looked at how you're using urlCompression your site. urlCompression ensures that, when the browser supports it, your Web pages and static resources (PDF files, for example) are compressed before being sent to the user. This can reduce the amount of bandwidth used on each user request.

There are three compression options and, since IIS 7.5, the most useful one (dynamic compression, which compresses your Web pages) should be turned on by default. Having said that, I had a client running IIS 10 where even that option was turned off. You probably want to ensure that dynamic compression is turned on and, if your users download a lot of files from your site, that the other choices are turned on also.

However, there are a number of options to manage here and the highest compression settings aren't necessarily the best ones (higher compression settings require more processing time and the savings in bandwidth might not compensate for that processing time). In fact, if you're tight on CPU cycles but have lots of network bandwidth to spare you might actually be better off by not using compression. The best discussion that I've found about the various tradeoffs is here (though the post is rather old).

Posted by Peter Vogel on 08/25/20160 comments


Visual Studio Toolbox Shortcuts: Expand, Collapse, and Find

With the rise of ASP.NET MVC, the role of the visual designers that were so much a part of creating UIs have diminished and that's too bad. If you're using one of the UI development technologies that give you a Visual Designer with toolbox, here are three tips you might not know to make working with your toolbox easier. After clicking on the toolbox (or otherwise making it active), if you type

  • An asterisk (*), you'll expand all of the sections
  • A forward slash (/), you'll collapse all of the sections
  • Any alphabetic characters, you'll start a search for widgets with matching names (Even if there isn't a search box at the top of the toolbox)

With the search option, once you find a matching widget, pressing the Tab key will move you to the next matching entry. If your toolbox doesn't have a search box at the top, you can see what you've typed in the status bar at the bottom of the toolbox.

Posted by Peter Vogel on 08/12/20160 comments


Add an Error Handler to Your ASP.NET MVC Controller

There really isn't such a thing as an "unhandled error" -- if your code throws an error outside of a Try...Catch block, then your error bubbles up through various ASP.NET and .NET Framework error handlers. An "unhandled error" is just an error that you aren't handling.

In ASP.NET MVC you can handle more errors by inserting an error handler inside your Controller: Just add an OnException method to your Controller. The code in this method will be invoked each time you have an "unhandled error" in that Controller.

It's easy to add the method: In your Controller, just type Overrides (in Visual Basic) or override (in C#), press the Tab key to get a list of overrideable methods, pick OnException from the list, and press the Tab key again. Visual Studio will write out the skeleton of the method for you.

The Visual Basic version looks like this:

Protected Overrides Sub OnException(filterContext As ExceptionContext)

End Sub

Your method will be passed an ExceptionContext object whose Exception property will give you access to all of the information about what went wrong. Within your OnException method you can do whatever you want about the error that's specific to the Controller (log to some audit file, for example). If you take no further action, the error will continue to bubble up to the ASP.NET error handler.

If, however, you wanted to finish by using the RedirectToRouteResult method built into your Controller to send the user the error page of your choice then you need to stop that bubbling process. You can do with this line:

filterContext.ExceptionHandled = True

which sets the ExceptionContext object's ExceptionHandled property to True.

Posted by Peter Vogel on 08/09/20160 comments


What Version of ASP.NET MVC Are You Using?

Prior to the pause in releases triggered by the latest structural changes to the .NET Framework, it seemed like the ASP.NET MVC team was releasing a new version in any month whose name ended with a letter. As a result, you could easily find yourself supporting multiple applications, each with its own version of ASP.NET MVC. Alternatively, you might have just taken over support for an ASP.NET MVC application and be wondering what version your application is using.

As an independent contractor, often faced with an application I've never seen before, I figure out the version by opening the Web.config file and doing a search on "System.Web.MVC". This is the element I currently find:

<dependentAssembly>
  <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
  <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0"/>
</dependentAssembly>

with the version number in boldface.

Posted by Peter Vogel on 07/29/20160 comments


Including the Location of Your Error in Your Error Message

A user calls you to complain that your code has thrown an exception. You ask the user to read the message to you … and you realize that you have no idea where that error comes from. You would know if you'd included the Exception object's TargetSite property in your error message because that property reports on the method that had the problem.

The TargetSite property returns a MethodBase object (part of .NET's Reflection infrastructure) which has a ton of properties telling you everything you'd ever want to know about the method. However, all you probably want in your error message is the method's full name, including the name of the class. To get that, just call the TargetSite's ToString method:

Try
  ' ... potential exception
Catch ex As Exception
  Throw New Exception("Something has gone horribly wrong at " & ex.TargetSite.ToString)
End Try

One caveat: If you're still embedding class and method names in your ASP.NET MVC routing rules then the class name/method name is information you probably don't want to share with your users (though you still might want to write those names to some log). Fortunately, I discussed how to avoid embedding controller and method names in your UI in my previous tip which makes that problem go away.

Posted by Peter Vogel on 07/22/20160 comments


Write to Visual Studio's Output Window on Your Breakpoints

I can't tell you the number of times I've put a breakpoint inside a loop so that I could stop each time I go through the loop and check the value of some variable or property. Unfortunately, by the third or fourth trip through the loop I've forgotten what the values were on my first trip through the loop.

If that's your life also, your best choice is to use a tracepoint which will write the information you're interested in to the output window. With a tracepoint, you can review the values you're interested in after the loop finishes. You can even just let your code run, rather than stopping on the line you're interested in.

Setting a tracepoint varies from one version of Visual Studio to another. The easiest way is to set a breakpoint and then right click on the dot in the margin that marks your breakpoint. When the popup menu appears, either select the When Hit choice (in earlier versions of Visual Studio) or the Actions choice (in later versions). Those choices will display the dialog that lets you define your tracepoint.

In that dialog you can enter the message you want written to the output window, enclosing any variables you want displayed in curly braces ({ }). Something like "The counter is {i} and the Customer's age is {cust.age}" will work, for example.

If you'd rather not stop on the breakpoint, make sure the Continue Execution checkbox at the bottom of the dialog is checked. You can do a quick visual check to see if you'll be stopping on the line: If you still have a dot in the margin, it's still a breakpoint and you'll stop every time the line is hit; if you have a diamond in the margin, it's a tracepoint and will just write out your message without pausing.

Now run your application and, after it finishes, look in the output window to see how your data changed over time.

Posted by Peter Vogel on 06/23/20160 comments


Save Some Time Deleting Entities in Entity Framework: RemoveRange

When it comes to speeding up your application, your best opportunity is to reduce trips to your database. So, when you see a method like RemoveRange on a DbContext collection, you might think that's an opportunity to delete a bunch of objects in less time than deleting those same objects one by one. You'd be right…but not because you're saving trips to your database.

Here's some sample code that will delete all of the SalesOrderHeaders with a DueDate before the current date:

Dim res = From so In db.SalesOrderHeaders 
          Where so.DueDate < DateTime.Now 
          Select so 
db.SalesOrderHeaders.RemoveRange(res)  
db.SaveChanges

This will run faster than, for example, looping through the res collection and passing each object to the SalesOrderHeaders Remove method before calling SaveChanges. However, either way, you'll still be making one trip to the database, submitting one SQL delete statement for every SalesOrderHeader that's being deleted.

Where you'll save time is in the overhead around removing the objects from the SalesOrderHeaders collection (especially around change tracking which will run once with RemoveRange rather than once for each object with Remove).

Posted by Peter Vogel on 06/21/20160 comments


Subscribe on YouTube