mostlylucid

scott galloway's personal blog...
posts - 916, comments - 758, trackbacks - 11

My Links

News

Archives

Post Categories

Misc. Coding

Monday, January 24, 2011

In a new world, my new job and coming to terms with ExtJs

After over a year away from them, I'm busy at my new job in Glasgow with Dell (you know, they make the big black computers) as a Senior Dev Lead (I think, titles are still a bit mixed up). Loving being back working with a team; though I've spent most of my time sniping from the sidelines...the beginnings of my influencing the future direction our application takes. This is a bit of a departure for me, I'm used to developing very high scale and performance apps for internet use, but this one has a more limited audience (so far!) . The app I'm working on is the one used by the Dell factory and corporate customers for defining the 'images' written on to machines at the factory...and new machines in IT departments. So before you ask...no I don't write the crapware, but our app is used to write it to the machines (sorry!).

Anyway, the app I'm working on is pretty interesting, very MS based, uses an SOA architecture and ExtJS as a front end. Kind of uses MVC 2 (just a very thin layer used to provide JSON through ExtJs.Direct.MVC).
ExtJs is an interesting beast...essentially and entirely client side UI framework which bumps all it's templates and code down to the browser in one big file (we use script combining and compression). From then on, you app UI is instantiated entirely on the client...for an old jQuery / Server-side coder like me this is a bit shocking. I understand the theory behind it...in essence all you require from the server after the first load is the JSON which represents the data each 'page' requires (though really each 'operation').
My biggest issue with this approach is: Javascript is a sucky language to build UI with. There, I've said it! Now don't get me wrong, I love Javascript, books like those I recommend below really have over the past year or two really rekindled my love of Javascript (along of course with the superlative jQuery).

My main issue with ExtJS is that is defines the templates it uses entirely in code...and any customization to those templates (size, contents etc...) is also performed using Client-Side code. Looking at the codebase of a reasonably large application like our, I can see well over 200 individual JS files which typically map to operations. Frankly, it's a bit of a pain to read this stuff and update it. Validation logic, text strings containing content etc...are all encapsulated in these files along with operation -> operation flow information.

Anyway, unfortunately I've joined the team when we're just about to do our first release...so it's WAY too late to change (and frankly we have a huge investment in this). My preference is to write UI using server side code to generate HTML (with Razor pages of course!) and load initial data in to the UI using this server side code (whether through partial views and jQuery or just direct rendering to the browser). AJAX is awesome and when used properly can give a very responsive UI...for example, when saving data from a page back to the server, I would always use AJAX these days and give validation feedback direct to the page. Well anyway, enough of the rant. There's lots of places where I *can* make improvements...and hey, it's a good job right!

Sometimes, no matter how much you want to change stuff you just have to live with it!

posted @ Monday, January 24, 2011 1:57 AM | Feedback (0) | Filed Under [ .NET ASP.NET JQuery ]

Tuesday, January 18, 2011

Best Practices for .NET developers

This is something I'm doing for my team at work...thought you may like a look / comment etc...

Know the SOLID principles...

See http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod (the first 5). These are fundamental principles for good OO software design, know them...love them!

If you don't need it...delete it!

As for Code Comments below, never check in an Excluded Class to the source control system. It adds noise and is a great way to have hard to trace exceptions if they're accidentally re-included.

Code comments

I know it's in the policy document but to be honest no-one uses generated docs when tests are a better alternative for learning code.

Code comments should only be used to clarify complex algorithms, apart from that they just add cruft to code and make it harder to read. Method / parameter names should be descriptive (I frankly don't care how long they are, that's what intellisense is for!). If you can't work out what a method does from its name...rename it. Or if a method does more stuff than you can reasonably fit in a name, you need to refactor the method.

Keep classes compact

No hard and fast rule here but if you're >200 lines in a single class think seriously whether you need to refactor. If you follow rule 1 of SOLID (Single Responsibility Principle) then this should rarely happen.

Keep names meaningful

There are, no prizes for being terse...the more readable your code, the easier it is for you and others to find bugs.

Use 'var' instead of the type name where appropriate.

In general it's both neater and increases code readability to replace an often lengthy type name with the 'var' keyword. The main counterpoint to this is when the return type of an operation is not obvious from the name of the method / context.

Instead of:

StringBuilder sb = new StringBuilder(256);
UTF8Encoding e = new UTF8Encoding();
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

We'd end up with this

var sb = new StringBuilder(256);
var e = new UTF8Encoding();
var md5 = new MD5CryptoServiceProvider();

Use the 'as' operator when casting reference types

The 'as' operator avoids runtime exceptions (e.g., (string)foo["bar"] could well throw an exception), in addition it is far more performant that doing an 'is' followed by an explcit cast.

Prefer enums over bools when they are used as return types from methods.

Enumerators make your code more readable (e.g. returning the value Car.Red from is CarColor rather returning true from the method IsCarRed) , they also make it far easier to extend code later on (true and false being rather limiting...)

Exceptions should only be used to indicate Technical Errors

Exceptions in .NET are valuable and when used well are a great feature. However, they should never be used as a tool in normal programmatic flow, only when an object does not perform an operation according to its specification / interface should an exception be returned.

Never catch an exception you can't do something with

Unless you actually do something with an exception, let it bubble up to somewhere which can do something (even if just reporting it to the user)

Use nullable types sparingly

Nullable types encourage optional parameters...optional parameters encourage branching within methods and reduce testability. Avoid them.

Never call the GC manually

It's smarter than you (oh, EXCEPT if you're using unmanaged objects)

Always use generic collection types over their non-generic ancestors

The generic collections are faster, avoid boxing and are basically cooler

The same applies to the new Concurrent collections when multithreading in 4.

Use the TPL

In .NET 4 when using concurrency prefer the new TPL http://msdn.microsoft.com/en-us/library/dd460717.aspx functions over managing threads 'by hand'

Prefer simplicity over more complex language features

Keeping your code simple to follow is critical to making changes easy and relatively low risk, one of the simplest ways to achieve this is to keep your code as transparent and simple to follow as you can.

Write, Test, Refactor, Test

Well factored code is easier to read, easier to change and easier to debug...A great test for well factored code is the 'Single Responsibility Principal', each method should really only perform a single operation on an object (for example, a single method should never both update and delete, or compress and save to disk).

· Avoid branching within methods
· Where you can avoid recursive methods

Avoid Regions

If you can't navigate through a single class file without collapsing sections of the code then your class is almost certainly in need of refactoring.

Regions add noise and make it harder to read code.

Only place they can be valuable is with long test classes...

Avoid Singletons

They mostly avoid concurrency issues at the expense of performance...there's almost always a better way.

Use Conditional Statements and Conditional Directives

When used properly, Conditional Debug Statements and conditional directives such as those below can be extremely useful in adding extra information to help you debug apps:

#if DEBUG
...
#endif

and

[Conditional("DEBUG")]

The main advantage of this method of adding additional debug information is that they are not output when the code is compiled in release mode.

If you DO use nullable types NEVER cast directly to the non nullable form

Again, this is a potential source of runtime exceptions. Instead, always use the .GetValueOrDefault() method and test for the default value (if necessary) before trying to use the value.

Avoid using the 'this.' Keyword

If your naming scheme is correct, you should never have to use 'this.' to specify that an object is local to your class.

posted @ Tuesday, January 18, 2011 5:46 AM | Feedback (19) | Filed Under [ .NET ]

Saturday, October 30, 2010

Essential Books For Pretty Good .NET Developers (IN DEVELOPMENT, SUGGEST MORE!)

Ok, so it will have a strong web programming bias! This list is different to most others, I'm going to assume you basically know how to code in .NET enough to get a senior developer job in most companies. From a very rough poll I'm also going to assume a fair number of you don't have strong University / College CS / Software Engineering backgrounds (I don't). These are the books that over the years I've found useful in filling in / updating bits of my development brain.

NOTE: When it comes down to it, this is MY list...I realize there's some books you just can't believe aren't in the list. This is either because I just don't think  they make the cut (too dated like Code Complete / Rapid Development) or too 'daily textbook' like the JavaScript Bible / Programming C#. Feel free to argue / post mini-reviews of books you feel strongly about in the comments (I JUST won't know some of them and that's good too!).

Design / General Practice

  1. Algorithms in a Nutshell
  2. Applying Domain Driven Design and Patterns - with examples in C#
  3. Agile Principles and Practices in C#
  4. Patterns of Enterprise Application Architecture
  5. Working Effectively With Legacy Code
  6. Domain-Driven Design: Tackling Complexity in the Heart of Software

.NET - go deep!

  1. The CLR via C# (3rd Edition)
  2. Advanced .NET Debugging (NOT READ THIS YET, PLEASE REVIEW FOR ME!)

TDD, learn, master!

  1. Test Driven Development By Example
  2. The Art Of Unit Testing
  3. xUnit Test Patterns : Refactoring Test Code

The Javascript Triumvirate...you know the syntax, but want to get yourself to godlike status Smile

  1. Pro Javascript Techniques
  2. Javascript: The Good Parts
  3. Pro Javascript Design Patterns
  4. Even Faster Web Sites: Performance Best Practices for Web Developers (previous book is in the next section...this one focuses on JS perf / techniques)
  5.  

CSS / HTML

  1. Pro CSS and HTML Design Patterns
  2. CSS: The Missing Manual
  3. High Performance Web Sites: Essential Knowledge for Front-End Engineers

posted @ Saturday, October 30, 2010 2:34 AM | Feedback (14) |

Thursday, October 07, 2010

Updated Resume link…

If you want my CV / Resume..here it is....here.

posted @ Thursday, October 07, 2010 6:20 AM | Feedback (0) |

LOOKING FOR WORK!

Yup, looking for work again...quick summary of work experience below...

 

01/2010 - 10/2010 - cozwecan.com
Developer
Was tasked to build several products for this small startup ranging from a WPF image management client through to a jQuery, FubuMVC, RavenDB based website (all bleeding edge technologies).

10/2009 - 12/2009 - Chunk, Glasgow, Scotland
Development Lead
Led a small development team of ASP.NET and Flash developers building sites for high profile clients. Lasted a short time as the company wasn't really a match to my skillset.

· 01/2007-10/2009 - Microsoft Corporation, Redmond, WA
Program Manager, ASP.NET Team / Project Server Team

I was responsible for the design of Product features; these included the design of all WebForms features in ASP.NET 4 and potential future releases. I was also responsible for managing the release process of a wide range of products includingASP.NET MVC.

· 06/2005-01/2007 - Microsoft Limited, Reading, UK
Application Development Consultant
As an ADC I advised a number of businesses on the improvement of both application design and architecture as well as improving development practices. I specialized in ASP.NET and Sharepoint as well as in the performance and scalability of enterprise web applications.

· 02/2003-06/2005 - Storm ID Ltd, Edinburgh, UK
Senior Software Architect
At StormId I was involved in the full lifecycle development of a number of customer facing Web Sites. These sites were both ASP.NET as well as classic ASP and SQL Server based.

· 03/2002-02/2003 - VisitScotland.com, Edinburgh, UK
Technical Architect (management responsibilities)
Whilst at VisitScotland.com I oversaw the migration of a Java based Corba architecture to a J2EE / JSP and patterns based system. Additionally I mentored a team of classic ASP developers in the building of a number of high scalability customer facing websites.

· 06/2000-03/2002 - GlobalFarmers.com, Edinburgh, UK
Internet Development Manager(management responsibilities)
Globalfarmers.com was the largest internet startup in Scottish history. I was brought in to bring development back on track with a third party supplier. The system was built using J2EE and an OODMBS, I also developed a subsidiary PHP based system.

· 02/1999-06/2000 - BlackID, Glasgow, UK
Web Developer
At BlackID I worked on the server side elements of web sites for huge customers such as Burger King.

posted @ Thursday, October 07, 2010 2:57 AM | Feedback (0) |

Monday, August 30, 2010

HTTP Optimization the easy way: Part 1, how do I know?

Modern websites necessarily make a lot of requests for resources back to the server.  Through books like those by Steve Souders we've become increasingly aware that each of these requests causes a delay in whatever it is your user has requested being downloaded and displayed. If you don't have both of Steve's books, get them...and spend an hour or two going through his site...it's awesome stuff. The term commonly used for the various efforts to reduce the number of requests made to a server is HTTP Optimization.

This is a topic I've been investigating / playing with for quite a while (e.g., CSS Combiner / Minifier ASP.NET Control) and in fact one of the projects I worked on shortly before leaving the ASP.NET team morphed into the Sprite and Image Optimization Framework recently released as a preview by the ASP.NET team. What I wanted to do with this post wasn't to go over these techniques in any great detail...rather it's to cover some of the stuff I currently do when developing sites.

In short there's x techniques you can realistically use to reduce / improve the performance of a web page loading:

1. Make the server code run REALLY fast...either by buying big servers, writing really slick code or by caching everything so it basically works like a static (plain HTML) site...

2. Make your web page really plain...no CSS / JS / Images...just plain old HTML; single request is always quickest - this is of course not usually acceptable!

3. Radically reduce the number of requests made to the server.

4. Make each request deliver more content for less bandwidth.

Of these I'm going to take a closer look at the last two in more detail.

The very first thing you need to do when trying to work out how to fix page loading issues is to actually identify those issues!

I tend to use Firefox when I'm looking at these issues; mainly because it has an amazingly powerful tool in Firebug for debugging and investigating pretty much anything a web site does on the client.

One of the most useful tabs in Firebug is the Net tab...in the image below you can see the result when I ran it with the home page of the ASP.NET site with caching disabled. I'll use this page to point out some of the optimizations they've (recently!) made to improve loading times for the home page of the site.

 FirebugInitial

What you can see in the image above is a bunch of rows containing GET and POST requests (we'll, only one POST to a tracking page). Each of these requests represents a single request back to the server. In fact if I roll my mouse over one of these rows I get more information which provides a legend for what each of the colors means:

popout

I'll come back to this page in more detail later...

Another great tool for identifying issues with page loading is YSlow, in fact if you look at the Firebug page above you'll see that YSlow has it's own tab! What YSlow does is report on issues with your pages in a very direct way:

YSlow1 

As you can see, YSlow gives a grade for a number of specific items which have proven to make a difference in page load time. Rolling over each one will tell you why they're important and give pointers. In fact, it even gives you links to tools which can help resolve these problems!

YSlow3

So, great...we can now see what problems we have...and even have a way to fix them. However, what it you could avoid them happening in the first place?

In part 2 of this post I'll show you what you can do (and what I actually do) to avoid these problems in the first place. I'll focus on using these techniques in Visual Studio and how you can easily incorporate some practices into your own development to get fast, fluid web pages...

posted @ Monday, August 30, 2010 12:24 PM | Feedback (2) | Filed Under [ Http Optimization YSlow! Firebug ]

Friday, August 27, 2010

Back to posting this weekend…

Promising to do this for a while. I only really like to post about new stuff..others can cover old stuff in detail. Right now I'm learning:

  • FubuMVC: a kind of super flexible, advanced version of an ASP.NET MVC framework.  Has proven challenging to learn but really worthwhile.
  • RavenDB: fantastic, document oriented database. Fits in really well with web development but has some unique challenges.
  • JQuery: far from new, but building lovely UIs with it, REALLY improving my general Javascript dev skills (a lot thanks to this book).
  • Spark View Engine:  an alternative view engine (was for ASP.NET MVC but my boss @robertthegrey has written a brilliant FubuMVC engine for it too!).
  • Dotnetopenauth : Open Id authentication library for .NET  (this article was invaluable for simplifying the whole experience for me...)

In all, I feel like the technologies above really hit the sweet spot for me for web development for the next little while. So, I'll write about them all. As usual, not tutorials, more hints, tips and guidelines which may help you avoid some of the learning curve I've had recently...

Until then here's some lovely fish to tide you over (flash so you have to visit the site to see them :)).

posted @ Friday, August 27, 2010 4:26 PM | Feedback (0) | Filed Under [ RavenDB FubuMVC Spark JQuery DotNetOpenAuth ]

Monday, July 12, 2010

Handy indexes for versioning with RavenDB

Mainly for me to remember this but if you're using the excellent Versioning bundle for RavenDB then you'll find you quickly need to work out a way to get the latest version of a document if querying on any field other than ID (I *believe* ID actually only gets the latest one). The little index definitions below do just that (the secome one is just adding another field to the map so I can query by that...useful example)...

documentStore.DatabaseCommands.PutIndex("CurrentVersion",
                                                        new IndexDefinition
                                                            {
                                                                Map = @"from doc in docs
                                                                              where
                                                                                  doc[""@metadata""][
                                                                                      ""Raven-Document-Revision-Status""] !=
                                                                                  null &&
                                                                                  doc[""@metadata""][
                                                                                      ""Raven-Document-Revision-Status""] ==
                                                                                  ""Current""
                                                                              select new {doc};"
                                                          },true);


                documentStore.DatabaseCommands.PutIndex("CurrentImageVersionBySlug",
                                        new IndexDefinition
                                        {
                                            Map = @"from doc in docs
                                                                              where
doc[""@metadata""][""Raven-Entity-Name""] ==""Images""
&& doc[""Slug""]!=null &&
                                                                                  doc[""@metadata""][
                                                                                      ""Raven-Document-Revision-Status""] !=
                                                                                  null &&
                                                                                  doc[""@metadata""][
                                                                                      ""Raven-Document-Revision-Status""] ==
                                                                                  ""Current""
                                                                              select new {Slug=doc[""Slug""]};"
                                        ,  } , true);

posted @ Monday, July 12, 2010 6:59 AM | Feedback (0) | Filed Under [ .NET RavenDB ]

Friday, July 09, 2010

Of the beginning…


So, I'm not dead! Have been busy moving house, getting two new kittens (Tycho and Cozmo) and bascially settling into my new existence.

 

I HAVE also been getting back down to some serious coding. LOVING RavenDB (I seriously think it is THE .NET database of choice now), getting deep an dirty with some awesome HTTP optimization techniques...which I really do have to blog about soon!

My first pointers to HTTP optimization greateness are:

Chirpy: a brilliant little VS add-in (check the Codeplex page for the VS 2010 version) , compresses and combines your CSS and JS files as well as lets you use .less syntax easily inside VS (kinda a programmatic extension to CSS allowing for cleaner, less repetitive style definitions).

LabJS: a bit more complex but really stunning little bit of JS which lets you seriously optimize your JS loading...JS becomes non-blocking and all loads asynchronously (see http://labjs.com/description.php for more details)! Here's how I use this in one of the cozwecan sites (note, I also use LabJS to do a 'load from CDN with fallback' behavior which I have yet to see fully documented) ...

var scriptModifier = "";


$LAB
.setGlobalDefaults({ AllowDuplicates: false });
$LAB
   .script({ src: "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js",
       alt: "/Scripts/jquery.1.4.2.min.js",
       test: "jQuery"
   }).wait()
     .script({ src: "http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js",
         alt: "/Scripts/jquery.validate.min.js",
         test: "jQuery.validate"
     })
     .script("/Scripts/jquery.ba-bbq.min.js")
     .script({ src: "http://cdn.jquerytools.org/1.1.2/tiny/jquery.tools.min.js",
         alt: "/Scripts/jquery.tools.min.js",
         test: "jQuery.tools"
     })
    
    .script("/Scripts/jquery.easing.1.3.min.js")
    .script("/Scripts/jquery.jnotifica.min.js")

    .script("/Scripts/Custom/MainScripts" + scriptModifier + ".js")
    .wait(function () { SetupInitialLoad(); });

 

 

Anyway will get a blog post together eventually covering all that I've been up to...until then...follow me on Twitter @scottgal..late peeps!

posted @ Friday, July 09, 2010 6:30 AM | Feedback (1) |

Saturday, March 20, 2010

Be vewy vewy quiet I’m writing WPF with MVVM

Get Microsoft Silverlight

Ok, not a catchy title but it really is what I've been up to for the past 3 months. As I wrote before, I'm currently working with the awesome @RobertTheGrey on a project called cozwecan, which is a bunch of sites set up with the aim of being an amazing independent ecommerce platform for artists (photographers to start with, in the future, who knows...). Anyway, I've been remiss in blogging about the amazingly cool stuff I've been doing (IMHO :)), using WPF with Reactive Extensions, MongoDB, FluidKit and of course the awesome WPF / SL MVVM framework, Caliburn (the embedded bit aboveis the creator of Caliburn, @EisenbergEffect's presentation on MVVM from MIX). So, just licking my wounds and getting my brain back in one piece after last year's craziness (minor drug problem, clinical depression, car crashes, international moves etc...) and will be back to full communicative me soon enough :)

posted @ Saturday, March 20, 2010 3:43 PM | Feedback (0) |

Powered by: