To load data or not to load data, that is the question…

•November 12, 2012 • 6 Comments

I wanted to talk about a trend I’ve been seeing as a web developer lately.  And by web developer, I mean strictly in the .NET space, meaning technologies like ASP.NET MVC and to a lesser extent, Web Forms.  So what is this trend?  I’m glad you asked. 

The trend seems to be the move from server-side heavy development to client-side development involving frameworks like jQuery, KnockoutJS, Backbone and others.  It used to be that the bulk of a web developers work would be on the back-end; creating the data layers, the business logic layer, and then throwing all that data to the client where it would get rendered.  The page would be requested, and before sending anything to the browser, you’ve done a database call (or two, or three, etc.), constructed the data as needed to render, then send the entirely processed chunk of HTML to the browser.  You might have some JavaScript on the client side to hide this or that depending on usage, but that was it.  All of the business logic as well as the rendering of HTML happened on the server and was sent to the client.  Even with MVC this was still happening, as views are processed to produce the proper HTML on the server, which is then sent down to the client.

But now, it seems like the back-end has become nothing more than a data repository, and the bulk of the work has been shifted to the client to process data and render it. What I’m seeing more and more (and what I’ve started to do in some of my own work), is when a page is requested, very little HTML is sent to the browser.  I’ve seen some projects where the entire HTML for a given page was generated in JavaScript on the client, and the only HTML sent in the initial response from the server was a wrapper div or two.  Everything else happened client side.  Talk about dynamic.

Even now, you don’t even have to hit the database for any data when a page is requested.  You can essentially send down a skeleton of HTML, and then when the browser gets the response, make an AJAX request to a service endpoint (WCF, old school ASMX, .NET Web API, choose your poison) to get a chunk of JSON, then construct the HTML you need from that.  And I’ve been leaning more and more towards that method of web development.  Why?  Can’t really say for sure, at least not right now.  It just feels right to do it that way.  It makes sense to me.

It has prompted me to ask this question: Is it better to send data with the initial request, or make the request after the page has been loaded by the browser?  That might not make sense, let me clarify a bit.

Let’s say you have an MVC project.  You have a controller with an Index() action.  At this point, you can do one of two things:

  1. You can go to the database to get whatever data you need, create a view model (if necessary), and provide a view name which processes the model to create the final chunk of HTML to send to the browser.
  2. You bypass the database, simply provide a view name which contains a skeleton of HTML, and send that response. When it’s received by the browser, you have JavaScript that makes an AJAX call to get JSON data from a service (or another controller endpoint), and then you process that JSON data to construct your HTML.  Client frameworks like KnockoutJS and Backbone make this exceptionally (and in some cases, magically) easy to do.

So are there benefits to doing one over the other?  I haven’t explored that question much and don’t have any insight/answers at this point in time.  But I thought it would make for good discussion.  I would like to get some feedback.  Feel free to leave a comment with your thoughts.

MVC, Authorization and AJAX – A Sordid Tale

•March 22, 2012 • Leave a Comment

So I was recently notified of a small bug in the application I am developing at work that some functions of the site weren’t responding properly when the user was no longer authorized.  The tester (in this case, my boss), had let his machine go to sleep while he took care of some other things.  By the time he got back, his session had expired but he tried to continue working.  The system obviously didn’t like that, but it didn’t respond properly.

The reason is because the pieces that weren’t functioning were AJAX calls.  While these calls were being authorized (and failing because of the expired session), the content of the response was actually the HTML of the login page.  This was happening because the site was redirecting the request to the login page, as it absolutely should have.  However, I wasn’t handling the situation.

So how do we fix this?  Well, the first thing I did was hit Google, thinking that someone, somewhere had to have encountered this as well and should have a solution already.  Why re-invent the wheel?  The solution I put in place was actually pieced together from a blog post I found on the web and a Stack Overflow article.  The overall concept is this: signify in the AJAX response that the request was denied because the user was no longer logged in, and then respond to that specific response and redirect the user appropriately.

So the first part involves signifying in the response that the request was denied because the user’s session expired.  I found the answer in this blog post.  The idea is simple, if the request is unauthorized and is also an AJAX request (how handy of the HttpContext to provide us with that little nugget of info!), then assembly either a JSON response or a Content response based on the mime type of the request, and assign the return code of 530.  Genius!

So now we’ve signified in our AJAX response that the request was denied, and it was because the user was no longer logged in.  Now we have to appropriately handle this in code.  That’s where this SO article comes into play.  I’m looking at the second response (not the accepted answer), and the “Client Side Code” section specifically.  This was a jQuery function I was not aware of.  Guess you learn something every day.  But the concept is simple; setup all AJAX calls that happen on this page to respond to any 530 status codes with your custom function.  Construct the URL you need to return the user back to and redirect.  Problem solved!

I will come back to this post later and add some actual code samples rather than a wall of text and a couple links. But I hope this has helped someone!

Conditional Breakpoints in Visual Studio 2010

•January 17, 2012 • Leave a Comment

So this is something I’ve known about ever since I started doing ASP.NET development, and I’m sure that many developers know about this, but I thought I’d share this for those that don’t, because it’s such a cool feature.

 

So you’ve got a method that you want to debug for some reason, but let’s say this method gets called quite often and you’re only really interested in debugging the method when a certain parameter contains a certain value.  Happens more often than you might think.  You could throw a breakpoint at the first line of code, but then you have to hit F5 to continue normal processing until you get the specific condition you want to debug.  Or, you can give your breakpoint a condition.  Here’s a quick screen-grab:

 

 

Basically, all you have to do is right-click on your breakpoint to get this menu.  There are, as you can see, several options you can set for your breakpoint, some more advanced than others.  The one we’re going to look at in this blog post is the “Condition…” option.  Clicking this option will give you the following window:

 

 

Now, “fieldName” is one of the arguments to the method that I’m debugging, and as you can see, I’m only interested in hitting this breakpoint if the value of that argument is “SaleStartDate” or “SaleEndDate”.  If the “fieldName” argument does not equal either of those strings, code does not break on that point and continues on its merry way.  This way, I only get a code break when I want it.

 

Again, this is probably nothing new for most of you out there if you’ve been doing development with Visual Studio for any length of time.  But there was a time that I didn’t know about this, and I’m sure there are others that don’t.

 

As always, questions/comments/suggestions are welcome in the comments.

LINQ To Entities and string.Format

•January 13, 2012 • Leave a Comment

So I encountered something interesting today while doing a small bit of refactoring.  Got some new requirements for a grid that was showing some product data, and in determining how to display said data, I found that one of the columns contained a double which I had to convert to a string for display purposes.  So I went on my merry way updating existing code to include these new values.

Now, before I continue, I should mention that my business objects are coming from the Entity Framework, and thus any LINQ queries I execute against collections of these objects will be using LINQ to Entities, not plain LINQ to Objects/LINQ to SQL.  So here’s a snapshot of the existing code (not the exact same code, names have been changed to protect the innocent and/or my job):

// "filteredItems" is an IQueryable<Product> which is returned from an Entity Framework repository
var vms = filteredItems.Take(100).Select(x => new ViewModel
{
    Id = x.Id,
    Description = x.Description,
    Size = string.Format("{0} L", x.SizeValue)
});

Now, after running this code, I started to get this exception: “LINQ to Entities does not recognize the method ‘System.String Format(System.String, System.Object, System.Object)’ method, and this method cannot be translated into a store expression.”  Odd, I thought, I’ve never had a problem calling string.Format() on anything before.  So off to Google I go, which leads me to StackOverflow (of course, can’t pimp SO enough, great developer resource), and I found out what was going on.  As is stated in a comment on this question:

…the problem is with the ELINQ (linq 2 entities), because it translates your code to SQL, and when it comes to an inner ToString request, it doesn’t know how to translate ‘ToString’ to SQL.

Okay, I get that, makes sense I suppose.  So how do I fix it?  Well, that was almost painfully easy to do:

// "filteredItems" is an IQueryable<Product> which is returned from an Entity Framework repository
var vms = filteredItems.Take(100).ToList().Select(x => new ViewModel
{
    Id = x.Id,
    Description = x.Description,
    Size = string.Format("{0} L", x.SizeValue)
});

In case you missed it, after the “Take(100)” call, I call ToList, which iterates through the IQueryable to create the List<T>, which causes EF to execute the SQL to actually return data. After calling “ToList()”, I essentially have a List<T> of POCO objects that I can do whatever I want to, because EF has already executed its SQL.

So, if you are iterating over an IQueryable that came from Entity Framework, if you need to do anything funky with the data for display purposes, make sure you call “ToList” on your collection before doing your funkiness.

Twin Cities Code Camp 12!

•January 11, 2012 • Leave a Comment

So I got the tweet this morning that Twin Cities Code Camp 12 is in the works, and apparently it’s a 2 day event now.  I haven’t been in years and the last time I was there, it was only a 1 day event.

 

Regardless, I am definitely looking forward to attending this year.  It will be held at the U of M Campus on April 14th and 15th.  Follow them on twitter @TCCodeCamp or check out their site http://www.twincitiescodecamp.com.

 

My only question is, will Jason Bock be giving away copies of his VB6 book… again?  Winking smile

Tech Tip: Quantize Values

•January 6, 2012 • 1 Comment

So here’s some tech knowledge to throw out there. I found a need for a current project to take a collection of values (decimals, ints, nothing major), and only show a value if all values were the same. A quick search at stackoverflow got me started, so here’s what I have.
First, I’m using nullable values here because the current problem space requires nullable values. They’re not necessary, just what I had to work with. Here’s some code:

private decimal? QuantizeDecimal(IEnumerable<decimal> values)
{
    if (!values.Any())
    {
        return null;
    }

    decimal firstValue = values.First();
    return (values.Skip(1).All(x => x == firstValue)) ? firstValue : null;
}

So the idea is, if the collection is empty, return null (or whatever value indicates inequality for you). Grab the first value in the collection, then test to see if the rest of the values in the collection match the first one (first skipping the first value, obviously). In my case, a null value defines that there were values that didn’t match, so I don’t show anything. However, if all the values match, then I return that value to display on my form.

Questions, comments, concerns, suggestions for improvement, etc., please comment below!

Blogging Attempt #….

•January 6, 2012 • Leave a Comment

I suck at blogging.  I really do.  I have the best of intentions, but I lose track or it simply doesn’t become the necessary habit to continue.  But here I am, once again, hoping to post more technical tidbits and the like and be somewhat relevant on the web.

In other news, it’s been 6 days since I last had a real cigarette.  Breathing is fun.

 
Follow

Get every new post delivered to your Inbox.

Join 109 other followers