Showing posts with label coding. Show all posts
Showing posts with label coding. Show all posts

Thursday, September 08, 2011

Use WinMerge in Visual Studio 2010 and TFS

Shamelessly stolen from Sebastien Lambla:

Go to Tools, Options, Source Control, Visual Studio Team Foundation Server, Configure User Tools...

Add a Compare pointing to WinMergeU.exe and using:

    /e /x /s /wl /dl %6 /dr %7 %1 %2

as a command-line argument.

Repeat the operation for Merge, this time using:

    /e /s /x /ub /dl %6 /dr %7 %1 %2 %4

WinMerge is usually found in:

    C:\Program Files (x86)\WinMerge\WinMergeU.exe

Friday, October 15, 2010

How to stop automatic newline in ASP.NET code blocks

I want to keep my one liner code blocks in my ASP.NET MVC views as:

  1. <% Html.BeginForm(); %> 

Unfortunately, a not so helpful feature recognize the C# code and reformats to the following:

  1. <%  
  2.    Html.BeginForm(); %> 

Thanks to Erv Walter for solving the problem.

In short, to remove this feature we have to:

  • Go to Tools – Options – Text Editor – HTML – Formatting
  • Select Tag Specific Options…
  • Under Client HTML Tags, add three tags: “%”, “%:”, and “%=”

The %-tag should have line breaks before and after, and no closing tag.

The %: and %= tags should have no closing tag, and no line breaks.

For ReSharper-users, also remember to disable Auto-formatting on semicolon, and on closing brace. Otherwise, ReSharper will interfere and reformat.

Tuesday, September 21, 2010

Blank page in ASP.NET MVC, IIS and Windows 7

You decide to move your web application from the internal web server to IIS under Windows 7, but observe nothing but a blank page.

Seems like it’s not enough to just add IIS from within Programs And Features – Turn Windows features on or off, but some additional tricks are required.

When activating World Wide Web Services within Turn Windows features on or off, remember to include:

  • HTTP Errors
  • HTTP Redirection

Even if ASP.NET is already selected, the following command line must be executed. Remember to run cmd as Administrator:

  1. %windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe –ir   

Resources:

Thursday, September 16, 2010

Online code syntax highlighter

I never get around to find out how to modify my blog template to include javascript for syntax highlighting.

So I use this online service: http://www.thecomplex.plus.com/highlighter.html

Use Mercurial to remove TFS friction

TFS, unfortunately, does some things wrong by default. If the client is anything except Visual Studio, the user experience is abysmal when it comes to commit file changes.

These days I created wireframes in Mockups for all my screens. But checking in those files were so difficult that I routinely procrastinated the task. I have installed TFS Power Tools with its shell extension, but that UI suffers from the same usability issues.

One possible workaround is to use TortoiseHg, which is pretty frictionless. Eric Hexter at LosTechies has an excellent recipe on how to set up Mercurial as a local repository for TFS. He didn’t, however, provide the source code for the Power Shell scripts. I typed them up here with minor adjustments.

Pull.ps1


  1. $projectName = "your-project"  
  2. $tf = "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\tf.exe"  
  3.  
  4. function pull{  
  5.     cd "\your\tfs\folder"  
  6.     &$tf get  
  7.     hg commit -A -m "from tfs"  
  8.     cd "your\working\hg\folder"  
  9.     hg pull --rebase  
  10. }  
  11.  
  12. pull 

Push.ps1


  1. $projectName = "your-project"  
  2. $tfpt = "C:\Program Files (x86)\Microsoft Team Foundation Server 2010 Power Tools\tfpt.exe"  
  3. $tf = "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\tf.exe"  
  4. hg push  
  5. cd "\your\tfs\folder"  
  6. &$tfpt scorch /noprompt /exclude:.hgignore`,*.ps1`,.hg  
  7. hg update -C -y  
  8. &$tfpt online /adds /exclude:.hgignore`,*.ps1`,.hg`,_ReSharper`,bin`,obj`,*.user`,*.suo  
  9. &$tf checkin  
  10. cd "your\working\hg\folder" 

Wednesday, September 09, 2009

The most important thing nobody told you about model binders

A bold statement, but I stand by it.

I have done numerous searches on how to implement custom model binders in ASP.NET MVC, and all of them are variations of:

public override object GetValue(ControllerContext ctx, string modelName, Type modelType, ModelStateDictionary state)
{
   Customer customer = new Customer();
   customer.FirstName = ctx.HttpContext.Request["FirstName"];
   customer.LastName = ctx.HttpContext.Request["LastName"];
   // ... other properties ...
   return customer;
}


But that’s counter productive, isn’t it? ASP.NET MVC is all about conventions and flexibility. The last thing I want from my model binders are to hardcode expected property names, which would fail anyway. If my type is ReportIdentificator, I certainly don’t want to give all my properties and parameters the very same name. I want my freedom to call them foo and Bar, if that’s what I need.



So I finally went to the source, so to speak. The ASP.NET MVC source code is available, and inside of the DefaultModelBinder, I found the following gem:



    if (!performedFallback) {
        ValueProviderResult vpResult;
        bindingContext.ValueProvider.TryGetValue(bindingContext.ModelName, out vpResult);
        if (vpResult != null) {
            return BindSimpleModel(controllerContext, bindingContext, vpResult);
        }
    }


The getaway here is bindingContext.ModelName. That property is the key to get the proper ValueProviderResult, which contains the posted values for the model. With that information, I am finally able to create the model binder I want.



The usual binder registration:



    ModelBinders.Binders.Add(typeof (ReportIdentifier), new ReportIdentifierBinder());


And my binder:



    public class ReportIdentifierBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var model = (ReportSectionIdentifier)base.BindModel(controllerContext, bindingContext);
            ValueProviderResult serialized;
            if (model == null && bindingContext.ValueProvider.TryGetValue(bindingContext.ModelName, out serialized))
            {
                var values = serialized.AttemptedValue.Split("-".ToCharArray());
                model = new ReportSectionIdentifier
                            {
                                Organization = int.Parse(values[0]),
                                Period = int.Parse(values[1]),
                                Report = int.Parse(values[2]),
                            };
            }
            return model;
        }
    }


I let the base try to create the model first, in those cases where the usual conventions are followed. My implementation deserialize the model from a value on the form “1-2-3”. That code enables me to support drop down lists bound to a report name and its identifier, which posts a value on the form “1-2-3”, or use the identifier in action links, which appends the property values to the querystring according to the conventions.

Thursday, July 09, 2009

Programming IQ test

While the test is purely for fun, I have to comment on my score, which is no better than 75%. I got my bragging rights, though :-)

Many of the questions I got right are just as unimportant than the ones I got wrong.

The worst offender for suckers like me who takes this nonsense very seriously, are:

Question 6: Your local supermarket is all sold out of energy drinks, Jolt Cola, and Mountain Dew. Which beverage will keep you going, packing the most caffeine and sugar into a 12-ounce can?

Correct Answer: Sunkist Orange Soda

Your Answer: Dr. Pepper

Sunkist Orange contains just as much caffeine as runner-up Dr. Pepper but surpasses it in sugar content.

I mean, are programmers only located in the North of America? I live in Norway, which may very well compare to living under a rock. It certainly looks that way on certain government decisions. But that’s a Law of Nature, I guess.

But I digress. WTF is Sunkist Orange Soda? And haven’t people heard of coffee? Need more caffeine? So up the dose! Need sugar? No you don’t, but anyway, what’s stopping us from adding as much sugar as the coffee mug can absorb?

I think I am proud of failing #6.

Then there is, and this is the stupidest, as it contains no correct answer. I failed this one on purpose, because I had to answer something:

Question 12: Which of the following is the best way to write reusable code that is easier to maintain?

Correct Answer: Insert comments throughout your source code files

Your Answer: Use more global variables

Documenting your code is the best way to ensure that another programmer can understand it. All the other choices are recipes for disaster.

People who know me professionally, know I am a test infected kind of guy. Along with Test Driven Development comes Merciless Refactoring, and that is the correct answer. That is, both of them. Code comments are one of the hardest thing to get right, simply because they have to address the code at an abstract level. That is the only way to write comments which will stand the test of time. Most comments simply repeats what the code does, not why. Our variable-, method-, and class-names should do that.

I opted to comment on #16, simply because I hate to be wrong:

Question 16: A client has asked you to write some basic accounting software in C. What data type is best for representing figures in dollars and cents?

Correct Answer: Integer

Your Answer: Double

Integers can be used to implement fixed-precision math. Floating-point numbers, whether single or double precision, aren't accurate enough to keep track of finances.

I flunked this one. Badly. However, the question itself is ill-phrased. The available answers only refer to the type “Integer”, while it should be a set of integers. This is my opinion, though. I can see how one integer can solve the problem: Just look at any financial number and pretend there is always two fractional digits, or four if one need this kind of precision. In financials, we do. Then we pretend that the first two, or four, digits always represents the cents. But then we have greatly reduced the highest value possible to address. Better hope we never have to address Zimbabvian dollars with that software package.

No, the correct answer must be some composite of multiple integers: One for the cents, and one or more for the dollars.

Would I be a better programmer if I knew Kernighan’s best known achievement? Maybe. Or maybe not:

Question 17: For what achievement is Brian Kernighan best known?

Correct Answer: He was co-creator of AWK, a programming language for text processing

Your Answer: He was co-creator of the C programming language

Kernighan is known as the "K" in the K&R C language specification, but he didn't create the language; he just helped Dennis Ritchie document it.

In the same category: I didn’t know what “Turing complete” meant until #18. Who cares? And I don’t know about standard SQL, does that even exist as an implementation? All I know, is that loops are possible in T-SQL. And for PostScript? I thought that was a markup language, like HTML and XML:

Question 18: A programming language is said to be "Turing complete" if it can be used to implement any conceivable algorithm. Which is NOT a Turing-complete language in its standard form?

Correct Answer: SQL

Your Answer: PostScript

Standard SQL can't do loops, although you can get Turing completeness with proprietary extensions to the language from certain vendors.

That said, the questions I got right, by pure chance or otherwise, there are a few that doesn’t tell anything about programming skills:

  • Question 1: What is the relationship between Java and JavaScript?
  • Question 2: Hungarian Notation is a variable-naming convention used by some programmers. How did it get its name?
  • Question 3: Just-in-time (JIT) compilation improves the performance of languages that compile into bytecode. Which language featured the first JIT compiler?
  • Question 4: If I told you a key characteristic of my programming language of choice was that it generated threaded code, which language would I most likely be talking about?
  • Question 5: Once very popular and widely used, Pascal spawned a number of derivative languages. Which is NOT a successor to Pascal?
  • Question 7: What is the best way to preserve type safety in assembly language?
  • Question 8: Which of the following is NOT a central tenet of extreme programming?
  • Question 9: Why are race conditions a problem in modern software development?
  • Question 10: Why do some consider Ruby to be more "purely" object-oriented than other, more popular OOP languages such as Java and C++?
  • Question 15: Is P equal to NP?
  • Question 19: Which group has had the most impact on modern object-oriented programming practices?
  • Question 20: Which of the following is NOT a data structure used in modern programming practice?

There must be something wrong with me: Out of 20 questions, these are the only three I find useful:

  • Question 11: Failure to validate user input is one of the most common sources of software security vulnerabilities. When is it safe to accept user input without validation?
  • Question 13: Of the following, who is NOT the inventor of a programming language in current use?
  • Question 14: To what concept does "the mythical man-month" refer?

Take the test at InfoWorld.

Wednesday, June 10, 2009

ASPNET.MVC Goodies

First of all, the free eBook tutorial. This chapter alone is reason good enough to buy the whole book:

The best practices are already materializing:

Something to simplify the validation code:

Finally, enjoy a simpler MVC experience with:

Update.

Code Camp Server is a very real project done well. And open source:

Wednesday, May 06, 2009

Cool jQuery trick. Or why it pays off to know how things really work

So we have this search against a CRM provider which could have been a lot faster, to say the least. It’s just that we don’t know if this CRM is inherently slow, or us who are inherently incompetent.

Anyways, when we can’t speed things up, we give the user a slightly better experience like an animated dog jumping around, or the more professional spinner.

This being a web application, I dreaded this task. I really didn’t want to change a well functioning search form (except for the lack of speed) into a conglomerate of ajax calls and dom manipulations. Luckily, a coworker volunteered.

Today he asked for a review. Browsing his code, I noted he had begun his journey down that dreaded path. Then we had a moment of insight:

“This is a regular post, right? And the browser will get nothing in return until the search is done, yes?

So all we need is to show that flashy spinner while we wait for the results.

Why not use jQuery to hook up the proper event and make the spinner visible when we post?”

And so we did:

$(“#submitButton”).click( function() { $(“#spinner”).show(); } );




Works like a breeze. At least in Firefox.

Friday, April 17, 2009

My client pays me to develop code

Heard it before?

It’s one of at least five excuses for not unit testing. Although Paul Bourdeaux do a fine job debunking those excuses, this particular has a finer point:

News Flash - Unit tests are code.  They are as integral to the application as any other piece of code you are writing, and should be included in the original estimate and statement of work.  It might also help to mention to the client that unit tests lower both development cost (see previous excuse) as well as maintenance cost.  If you are not writing unit tests, then you are doing your client an injustice by forcing them to incur extra expense.

Our clients don’t really pay us for writing code. They pay us to solve certain problems. It just happens we solve them by writing code. If there was a cheaper, easier way to solve the same problem which did not include code, and your client knew that, would he still pay for your code?

Wednesday, April 08, 2009

A most useful Visual Studio setting for Html/aspx pages

From the blog of Rich Strahl: Unselect “Auto ID elements on paste in Source view”.

Scroll down on his page to find the picture.

Tuesday, March 17, 2009

jQuery event binding blunder

My customer wants a calendar with tricky visual requirements attached, so I thought a good approach would be to:

  • Render a static table with enough room to display any month.
  • Provide all visual data via ajax calls.
  • Create some javascript which decodes the returned json and render the calendar anew.
  • Use jQuery because it’s easy.

Because we need to select a date, and the next or previous months, events are required.

I ended up with the following:

previous.unbind("click").click( function() { current.notifyPrevious();});

The call to unbind() is necessary, I happened to discover. Without it, I bounded an additional, but equivalent event handler for each click.

The next click would trigger all bounded handlers, which would render the calendar and bind new handlers. No wonder my cpu went sky high with that exponential growth.

Thursday, March 12, 2009

ASPNET.MVC Validation UpdateModel() Gotcha

Not only did the Yellow Screen of Death point the error to the incorrect line, the error itself shouldn’t be there according to the tutorial.

While examining the stack trace closer, I could see the offender was HtmlHelper.GetModelStateValue(). How could that be?

A missing call to UpdateModel(), that’s how.

Visual Studio, the ASP.NET compiler and inconsistent file encoding

I have been using Norwegian as my developer language for a while now, and have gotten used to it. The typical non-English characters work just fine in most Visual Studio project types, but not in ASP.NET.

It seems like the ASP.NET compiler process open my files with a different character encoding than what Visual Studio saved it as.

Opening the offending ASPNET.MVC view in Notepad and saving it as UTF-8 removes the compilation / parser error, however, that’s not a working solution. Who knows when Visual Studio decides to save the file as something different than UTF-8?

International characters are not widely supported on the internet, AFAIK, so I guess I am back to English names or some creative naming to avoid the offending characters.

Tuesday, March 10, 2009

Slow internal web server connection on Windows 7

Apparently, I haven’t done much web development on my Windows 7 installation. I downloaded ASPNET.MVC RC2 today, upgraded, and went for a test ride.

Was Visual Studio’s internal web server this slow the last time? It certainly was not on Windows XP.

I tested on Firefox only, and the issue seems to be related to IPv6. Disabling that feature and everything is fast again.

People report that Internet Explorer doesn’t have this issue.

Monday, March 09, 2009

Looking for an open source CMS

I have volunteered to develop the new website for a non-profit organization, and what they need is a Content Management System.

Searching for open source CMS on stackoverflow.com, I found people speaking highly of the N2 CMS. I have to say it looks good, it’s well documented and the programming model is very simple.

The catch, however, is that I checked out the latest version from the trunk, and the Visual Studio projects fail to build due to missing references and coding errors.

When I download a framework and can’t have something running out of the box, preferably without any configuration, I get disappointed. When the source fails to build, I seriously doubt the quality.

My reason to use a framework in the first place is not only to jumpstart my development efforts, but also to ease the maintenance burden for the poor soul who will inherit the project.

These goals are not met by the current state of affairs. And the main developer at codeplex prefers not to be contacted. If I have to do this kind of development, I prefer invest my energy where I am in full control.

Next on my list:

Sunday, March 08, 2009

Monday, February 25, 2008

Making your own MVC - Convention problems

I use the usual naming conventions in my MVC. That is, if I want to see a list of plans, I navigate to /page.ashx/Plan/List.

That will cause my framework to call List on the PlanController. The controller action will then render the view located at /Views/Plan/List.aspx.

The controller action is also used as the default view name.

Problems with the naming conventions:
A view located at the following path, /Views/Plan/List.aspx, will create a List class in the Views.Plan namespace.
  • That causes ReSharper's intellisense to stop at Views.Plan, so it never sees the model class Plan located in the Models namespace.
  • The view List will shadow the generic List class.
  • Sometimes the compiler or ReSharper think I am using the namespace Plan, when I intend to use the Plan class.
Having similar names in namespaces and classes is not good. Nor is it good to have view names similar to other important classes, List being a prime example.

Problems with the default view name:
I guess this works flawlessly in Ruby on Rails, otherwise different conventions would be in use. But it doesn't work that well in .NET.

Default view name works fine when there are no dispatching between controller actions. There are no convenient way to detect the transition from one action to the next. Say we want to have a default action implemented, but also want to change what this should be in the future.

I would do it this way:
public class PlanController
{
public void Index()
{
List();
}

public void List()
{
// stuff data in ViewData
}
}
My intended behavior is to display the List-view. However, when the initial action is Index, then the Index-view is what will be displayed.

I could add a call to RenderView("List"), but I have two problems with that: First, it defeats the purpose of default viewnames, and second, I have to be careful to add a RenderView whenever this scenario arises.

See the problem with that? At some point, I will not discover this is the case and forget to call RenderView(). I am starting to think that a mandatory call to RenderView would be better, as that can't be forgotten.


Another problem I discovered, is the use of default view names. That is, the controller action is used as the viewname unless specified otherwise.

Making your own MVC - Naming problems

Things aren't working out the way I hoped or planned. But then again, when do they?

My migration code is still a spike, and has no tests. The controller-routing part works, and so does my views. They are WebForms, after all. But I have problems with the naming conventions, as ReSharper struggles with them. I don't know if that's a ReSharper bug or an inherent weakness in .NET.

The convention is to locate the view in a path like this: /views/controllername/viewname.aspx.

The problem arise when I have a controller an a model with similar name, like PlanController and Plan, and a view named like an existing class. The view to list plans would have a path like /Views/Plan/List.aspx.

You see how Visual Studio would create a WebForm class named List in a namespace named Views.Plan?

That creates some problems with ReSharper and .NET:
  • The namespace name Plan shadows the model of the same name. ReSharper intellisense stops at the namespace and never suggests to use the model class.
  • The compiler thinks I am using a namespace where a class is expected.
  • The view name List shadows the generic List class. ReSharper intellisense doesn't recognize this, and never suggests to use use List.
Even if the ReSharper intellisense was improved, there are problems with this approach that can't be fixed in an elegant way. The name crach between List.aspx and List will never go away, and suggests a problem with my naming.

The namespace/model crash can be fixed by prefixing the model class, but I don't like to litter my code with Models.Plan or whatever the model-namespace would be.

Thursday, February 21, 2008

Why MonoRail or ASP.NET is not my option today

MonoRail ticks me a little of, because of the numerous dlls I have to reference, and the ASP.NET MVC framework ticks me off because it pushes the newer .NET framework on me. And none of them have database migration the RoR way, as far as I know.

I find the latter quite annoying, actually. I can see why Microsoft wants to use the opportunity to push out new technology, but I find that not very helpful. Many of my customers are still on .NET 1.1 or have just upgraded/ported to .NET 2.0. A move to .NET 3.0/3.5/3.6 will introduce a whole set of new problems, a price I am not willing to pay just to get an MVC framework.

Am I the only one with this mindset?

However, the ASP.NET MVC is still in CTP and I have been down that rat-hole before: Deploying a CTP technology in production is no fun. The next CTP will have breaking changes, and that means lots of rework. I think there are better ways to invest my time. Besides, it's no fun to be responsible for an ever-breaking production environment.