DotNet Support Blog

Specification Pattern and Lambdas

Posted In: , , . By Sothy Mom

While working on my current project I decided that I had a need to use the Specification Pattern . After finding a clean implementation by Jeff Perrin I set to work creating the specifications that I needed. I quickly realized that we were going to end up having a ton of specifications and sometimes they would only apply to very special cases. Other times they would be very broad cases and they needed to be even more composable than even the fluid interface implemented in Jeff’s implementation wasn’t going to be enough. It after all still required me to create a concrete implementation for each specification, no matter how minuscule it might be.

This is the part where I thought to my self that since i was really only creating implementations for a single method that I could just write a LambdaSpecification and be able to use this for all the special cases I had.

Below is the LambdaSpecification Code:


using System;
using System.Linq.Expressions;

namespace Specification
{
    public class LambdaSpecification<T> : Specification<T>
    {
        private Func<T,bool> _expression;

        public LambdaSpecification(Func<T,bool> expression)
        {
             if(expression ==null) throw new ArgumentNullException(”expression”);
              _expression = expression;
        }

        public override bool IsSatisfiedBy(T obj)
        {
            return _expression(obj);
        }
    }
}

And the Tests:


[Test]
public void LambdaSpecification_CanExecuteSimpleLambda()
{
    var p = new Person() {Name = “Eric”};
    var spec = new LambdaSpecification<Person>(x => x.Name == “Eric”);

        Assert.IsTrue(spec.IsSatisfiedBy(p));
}

[Test]
public void LambdaSpecification_CanExecuteComplexLambda()
{
    var p = new Person() {Name = “Eric”, Age = 28};
    var spec = new LambdaSpecification<Person>(x => x.Name == “Eric” &&
                                                                        new IsLegalDrinkingAgeSpecification().IsSatisfiedBy(x));

    Assert.IsTrue(spec.IsSatisfiedBy(p));
}

//Might Not be needed but I wanted to be sure
[Test]
public void LambdaSpecification_CanExecuteLambda_AndUseAndSpecification()
{
    var p = new Person() {Name = “Eric”, Age = 28};
    var spec = new LambdaSpecification<Person>(x => x.Name == “Eric” );

    Assert.IsTrue(spec.And(new IsLegalDrinkingAgeSpecification()).IsSatisfiedBy(p));
}

Comments are welcome and encouraged, especially if you see a reason why I shouldn’t be doing this. Or, if you have any ways to make this better, I would love to hear them. This is the first time I have ever used a lambda as a parameter in my own code and so far i am liking it.

Thanks to Jeff Perrin again for his post on creating a clean implementation of the specification pattern.

 

Just like its predecessor, SQL Server 2008 is taking its sweet time to actually ship.  However, unlike its predecessor, it won't just be a "worthwhile upgrade".  It will kick ass.

Here are the top 10 reasons why.

10.  Plug-in model for SSMS.   SSMS 2005 also had a plug-in model, but it was not published, so the few developers that braved that environment were flying blind.  Apparently for 2008, the plug-in model will be published and a thousand add-ins will bloom. 

9.  Inline variable assignment.  I often wondered why, as a language, SQL languishes behind the times.  I mean, it has barely any modern syntactic sugar.  Well, in this version, they are at least scratching the the tip of the iceberg. 

Instead of:

DECLARE @myVar int
SET @myVar = 5

you can do it in one line:

DECLARE @myVar int = 5

Sweet.

8.  C like math syntax.  SET @i += 5.  Enough said.  They finally let a C# developer on the SQL team. 

7.  Auditing.  It's a 10 dollar word for storing changes to your data for later review, debugging or in response to regulatory laws.  It's a thankless and a mundane task and no one is ever excited by the prospect of writing triggers to handle it.  SQL Server 2008 introduces automatic auditing, so we can now check one thing off our to do list.

6.  Compression.  You may think that this feature is a waste of time, but it's not what it sounds like.  The release will offer row-level and page-level compression.  The compression mostly takes place on the metadata.  For instance, page compression will store common data for affected rows in a single place. 

The metadata storage for variable length fields is going to be completely crazy: they are pushing things into bits (instead of bytes).  For instance, length of the varchar will be stored in 3 bits. 

Anyway, I don't really care about space savings - storage is cheap.  What I do care about is that the feature promised (key word here "promises") to reduce I/O and RAM utilization, while increasing CPU utilization.  Every single performance problem I ever dealt with had to do with I/O overloading.  Will see how this plays out.  I am skeptical until I see some real world production benchmarks.

5.  Filtered Indexes.  This is another feature that sounds great - will have to see how it plays out.  Anyway, it allows you to create an index while specifying what rows are not to be in the index.  For example, index all rows where Status != null.  Theoretically, it'll get rid of all the dead weight in the index, allowing for faster queries. 

4.  Resource governor.  All I can say is FINALLY.  Sybase has had it since version 12 (that's last millennium, people).  Basically it allows the DBA to specify how much resources (e.g. CPU/RAM) each user is entitled to.  At the very least, it'll prevent people, with sparse SQL knowledge from shooting off a query with a Cartesian product and bringing down the box.

Actually Sybase is still ahead of MS on this feature.  Its ASE server allows you to prioritize one user over another - a feature that I found immensely useful.

3.  Plan freezing.  This is a solution to my personal pet peeve. Sometimes SQL Server decides to change its plan on you (in response to data changes, etc...).  If you've achieved your optimal query plan, now you can stick with it.  Yeah, I know, hints are evil, but there are situations when you want to take a hammer to SQL Server - well, this is the chill pill.

2.  Processing of delimited strings.   This is awesome and I could have used this feature...well, always.  Currently, we pass in delimited strings in the following manner:

exec sp_MySproc 'murphy,35;galen,31;samuels,27;colton,42'

Then the stored proc needs to parse the string into a usable form - a mindless task.

In 2008, Microsoft introduced Table Value Parameters (TVP). 

CREATE TYPE PeepsType AS TABLE (Name varchar(20), Age int)
DECLARE @myPeeps PeepsType
INSERT @myPeeps SELECT 'murphy', 35
INSERT @myPeeps SELECT 'galen', 31
INSERT @myPeeps SELECT 'samuels', 27
INSERT @myPeeps SELECT 'colton', 42

exec sp_MySproc2 @myPeeps

And the sproc would look like this:

CREATE PROCEDURE sp_MySproc2(@myPeeps PeepsType READONLY) ...

The advantage here is that you can treat the Table Type as a regular table, use it in joins, etc.  Say goodbye to all those string parsing routines.

1. Intellisense in the SQL Server Management Studio (SSMS).  This has been previously possible in SQL Server 2000 and 2005 with Intellisense use of 3rd party add-ins like SQL Prompt ($195).  But these tools are a horrible hack at best (e.g. they hook into the editor window and try to interpret what the application is doing). 

Built-in intellisense is huge - it means new people can easily learn the database schema as they go.

There are a ton of other great features - most of them small, but hugely useful.  There is a lot of polishing all over the place, like server resource monitoring right in SSMS, a la Vista. 

I'd love to finish this entry on a happy note, but I can't, because I just finished perusing Editions of SQL Server 2008 page.  In addition to the Standard, Enterprise, Developer and Express editions, there are now Workgroup, Web, Compact (which has nothing to do with SQL Server) and Express Advanced editions.  Here is the comparison matrix.  And you thought picking a version of Vista was complicated.

 

You have only $50 left and you can buy two DVDs or one SQL book, what do you do? I would buy the book but not every person has the same idea of a fun time. This is the reason why I present you with a bunch of links to articles which will give you very good info. some of this you won’t be able to find in a book anyway.

The curse and blessings of dynamic SQL. How you use dynamic SQL, when you should - and when you should not.

Arrays and Lists in SQL Server. Several methods on how to pass an array of values from a client to SQL Server, and performance data about the methods. Two versions are available, one for SQL 2005 and one for SQL 2000 and earlier.

Implementing Error Handling with Stored Procedures and Error Handling in SQL Server – a Background. Two articles on error handling in SQL Server.

The ultimate guide to the datetime datatypes
The purpose of this article is to explain how the datetime datatypes work in SQL Server, including common pitfalls and general recommendations.

Stored procedure recompiles and SET options
Using stored procedures is generally considered a good thing. One advantage of stored procedures is that they are precompiled. This means that at execution time, SQL Server will fetch the precompiled procedure plan from cache memory (if exists) and execute it. This is generally faster than optimizing and compiling the code for each execution. However, under some circumstances, a procedure needs to be recompiled during execution.

Do You Know How Between Works With Dates?
article explaining why it can be dangerous to use between with datetime data types

How Are Dates Stored Internally In SQL Server?
Article explaining how datetimes are actually stored internally

Three part deadlock troubleshooting post, a must read if you want to understand how to resolve deadlocks.
Deadlock Troubleshooting, Part 1
Deadlock Troubleshooting, Part 2
Deadlock Troubleshooting, Part 3

SQL Server 2005 Whitepapers List
A list of 29 different SQL Server 2005 Whitepapers

Keep a check on your IDENTITY columns in SQL ServerThis article shows you how to keep an eye on your IDENTITY columns and find out before they run out of values, and fail with an arithmetic overflow error.

Character replacements in T-SQL
Quite often SQL programmers are left with the dirty job of working with badly formatted strings mostly generated from external sources. Typical examples are badly structured date values, social security numbers with misplaced hyphens, badly formatted phone numbers etc. When the data set if small, in many cases, one can easily fix by a one time cleanup code snippet, but for larger sets one will need more generalized routines.

 

We’re very excited to announce our 2nd Community Technology Preview (CTP) for Parallel Extensions to the .NET Framework 3.5.  We released the Dec07 CTP on 11/29/2007, and from that we have received a lot of feedback from the community and customers. While you have been using our bits, participating in our forums, sharing your insights and experiences, and following along on our blog, we have been hard at work preparing this CTP, incorporating your feedback into it.

Download the Parallel Extensions June 08 CTP

There are some large changes in there that should provide a lot of benefits.  First off, we have begun to add the third major API component, the Coordination Data Structures, to the technology package.  As we build PLINQ and the Task Parallel Library, we use a lot of components under the covers to handle synchronization, coordination, and scale to contain data reads and writes from multiple procs.  We see these as widely useful, so we’re sharing them here with you.

We incorporated a brand-new user-mode, work-stealing, run-time scheduler (those modifiers essentially mean that it’s light, fast, and flexible) to the system, completely over-hauling the infrastructure.  This is a very important piece of technology for making the most of the resources available on your machines.  This has been in research and incubation for a long time, and it will allow for improved performance and future-proof scalability (e.g. cache consciousness) as we stabilize and improve it.  Expect to hear us talk a lot more about this in the future.  There are still likely to be some growing pains in this release, so please pass along that feedback and expect this to improve.  Additionally, The Task Parallel Library is now built directly on top of this scheduler.  And to add to the excitement, PLINQ is in the first stages of building on top of the Task Parallel Library. 

There are a number of other changes that we have made, some notables include: new ordering implementation for PLINQ, change of Parallel.Do to Parallel.Invoke, continuations in Tasks.  A much more detailed list of updates is coming soon.

Subscribe to the feed or come back to this blog often as we release a flurry of posts regarding the new and exciting work surrounding this CTP.

 

SQL Injection and how to avoid it

Posted In: , . By Sothy Mom

It isn't as big of a deal at the moment, but it is always good to make sure everyone is aware of this and how dangerous it can be.  There is some very good information on it located on MSDN here.  The important part is to remember that anytime you take input from an external source (someone typing on a web page), they don't always have to put in what you expect.

The safest way to keep yourself safe from SQL Injection is to always use stored procedures to accept input from user-input variables.  It is really simple to do this, for example, this is how you don't want to code things:

var Shipcity;
ShipCity = Request.form ("ShipCity");
var sql = "select * from OrdersTable where ShipCity = '" + ShipCity + "'";

This allows someone to use SQL Injection to gain access to your database.  For example, imagine if someone put in the following for the "ShipCity":

Redmond'; drop table OrdersTable-- This would delete the entire table!  If you have seen much on SQL Injection, they have figured out all kinds of ways to get information about your database or server, so don't think they can't find the names of tables, etc.

The correct way to do this would be using a stored procedure as follows:

SqlDataAdapter myCommand = new SqlDataAdapter("AuthorLogin", conn);
myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlParameter parm = myCommand.SelectCommand.Parameters.Add("@au_id",
     SqlDbType.VarChar, 11);
parm.Value = Login.Text;

Then you will be protected.  Be sure to use parameterized stored procedures to keep the stored procedure from having the same problem as before.|

There are other hints and advice on the MSDN article that you can check out, but this is the major piece of advice to know.

There is also some additional information that you can find here.  You can find more information and a video at Explained – SQL Injection and another video about it here.  There are tons of links on the web so feel free to research this more to be sure you are safe from this problem.

 

Recently, a user group held a conference whose subject was Domain-Driven Design with nHibernate. Now, this is a really cool topic of discussion! So, I decided to attend the conference in order to improve my perspective and knowledge on the subject. Little did I know that the speaker was an introverted programmer who greatly lacked in public speaking skills. Many people, including myself, left early, as the presentation became unbearably tedious and awkward.

What follows is a list of tips which I feel to be important when it comes to giving a presentation. This is not an exhaustive list, so I hope you would add your own comments to elaborate on these ideas or to add to the list. [I am also looking to improve my communication and presentation skills, so these rules and principles also apply to me].

Tip #1: Introduce yourself properly

When I was a kid and people asked me what my name was, I used to reply “My name is Brian…don’t you know that?” You see, back then, I thought everybody knew my name: it’s a common name, it’s easy to remember and it’s simple to pronounce. However, in reality, this is not usually the case. Therefore, before beginning a presentation, introduce yourself to your audience. What is your name? What do you do for a living? Why do you want to talk to us about your subject? How can we contact you? Do you have a Web site or a blog?

Tip #2: Make eye contact

Bear in mind that the audience came to see YOU. Therefore, you should be mindful of the fact that we have decided to take time out of OUR day to see YOU, when we could be somewhere else (at home, a friend’s party, a late night dinner, etc.) That being said, PLEASE acknowledge this fact by at least looking at your audience. Don’t stare at the ceiling, the floor or the walls. Don’t stare at your PowerPoint slides either. I think it costs about two calories to move your eyes from one direction to another at variable intervals. In other words: it doesn’t hurt and it doesn’t take a lot of energy to do that. I know some developers are very introverted, and that is in their nature, but would you ask someone out on a date while staring at the wall or the ceiling instead of looking into his/her eyes? This takes practice, but the resulting impact on your audience is well worth the effort!

Tip #3: Talk with a smile

Do you know that the human being is the only living being in Earth that can smile to express different emotions? There are hundreds of muscles and nerves that are being contracted when you smile. Yet it doesn’t hurt. In fact, smiling at an audience changes the atmosphere and the ambience of the room to make it more natural, more humanized and more comfortable. Again, would you ask someone on a date without smiling? I don’t think so.

Tip #4: Move around a little

Just like a shark cannot stay alive without swimming around, so should you be moving and walking around a little on the platform. That platform is yours and you should feel free to walk on it so the whole audience can have a chance to feel your presence and to see you. Don’t stay near the computer just because you want to be there for clicking that button to go to the next slide. The computer is just a tool, not an altar.

Tip #5: Carefully prepare your presentation

Take the necessary time and resources to prepare your material: watch out for grammatical errors which can compromise your credibility, don’t go overboard with the information for a slide. Just like a good class design, your slide should be highly cohesive. What is your intent for a given timeframe? That answer should be reflected on your slide. I personally don’t care much for PowerPoint slides as a participant. What you’re telling me should be enough to understand your intent. I’ll look at your slide to complement your vision or your intent, not to get a second understanding of what you just said. Another thing you can do is to make your PowerPoint presentation available to everyone or by request. That way, the audience can focus on you in a more relaxing manner because they know that your presentation is there for them to look at anytime.

Tip #6: Anticipate obvious questions that could arise and prepare your answers

If your audience is at all interested in your subject, be sure that some people will ask you questions about it. For this, I like to imagine myself as part of the audience and see another projection of myself giving a talk. What kind of question could I ask the speaker right about now? Maybe something I said wasn’t clear or needed an example to better complete the picture. For some abstract or complex subjects, you can try answering some questions related to the 5Ws (Who? What? Where? When? Why? How?). You can also ask a friend what he thinks about your material. Prior feedback is always a good thing!

Tip #7: It’s okay to admit that you don’t know it all (However, do not use this as an excuse to come unprepared!)

This one is simple, but very hard to act on. If you are asked a question which you are unable to answer, just say these three little words: I don’t know. It doesn’t mean that you are completely ignorant. It just means that you don’t know. Even the greatest world leaders don’t have all the answers…no one does! Don’t sacrifice your credibility and your professionalism by risking an incorrect answer or solution. I remember someone once told me “Brian, it is better to remain silent and thought a fool, than to open your mouth and remove all doubt.

Tip #8: Have a plan B in case something goes wrong

Over the years, I have come to realize that Murphy’s Law is true and no one is safe from it. Not even developers. The law states that whatever can go wrong will go wrong. Therefore, prepare a second plan (or more!) in case things don’t go as planned. For example, if you’re modifying code in front of your audience and your system crashes, you shouldn’t take time out of your presentation to fix the problem. You will lose your audience!!! Just scrap the code and use the duplicate that you have as a backup.

There are many (free) resources online about how to improve presentation skills. I strongly suggest you to visit Kathy Sierra’s blog on human usability. It’s really worth it!

 

Over five years ago I posted Tips for a Successful MSFT Presentation. Yesterday I watched the video of my Mix Presentation all the way through. It's always very painful to hear one's own voice but it's even worse to watch yourself. I never listen to my podcast and I avoid watching myself. It's like watching a person in parallel universe and it inspires self-loathing. However, if you are someone who values continuous improvement - and I am - you need to do the uncomfortable.

Here's my five-years-later Updated Tips for a Successful Technical Presentation.

1. Have a Reset Strategy (One-Click)

If you're going to give a talk, you'll probably have to give it more than once. If you have demonstrations of any kind, have a "one-click" way to reset them. This might be a batch file or Powershell script that drops a modified database and reattaches a fresh one, or copies template files over ones you modify during your demo.

Personally, I'm sold on Virtual Machines. I have seven VMs on a small, fast portable USB drive that will let me do roughly 12 different presentations at the drop of a hat. You never know when you'll be called upon to give a demo. With a Virtual Machine I can turn on "Undo Disks" after I've prepared the talk, and my reset strategy is to just turn off the VM and select "Delete Changes." A little up-front preparation means one less thing for you to panic about the day of the talk.

2. Know Your Affectations (Ssssssseriously)

I have a bit of a lisp, it seems. I also hold my shoulders a little higher than is natural which causes my neck to tighten up. I also pick a different word, without realizing it, and overuse it in every talk. This is similar to how Microsoft Employees overuse the word "so" (which is actually Northwestern Americans, not MSFTies) too much.

It's important to know YOUR affectations so you can change them. They may be weakening your talk. Don't try to remember them all, though. Just pick two or three and focus on replacing them with something less detracting. Don't overanalyze or beat yourself up, though. I've spoken hundreds of times over the last 15 years and I'm always taking two-steps forward and one step back. The point is to try, not to succeed absolutely.

3. Know When To Move and When To Not Move (Red light!)

One of the most powerful tips I ever received was this: "When you move, they look at you. When you stop, they look at the screen." Use this to your advantage. Don't pace randomly, idley or unconsciously. Don't rock back and forth on your heels. Also, empty your pockets if you tend to fiddle with lose change or your keys.

4. For the Love of All That Is Holy, FONT SIZE, People (See that?)

It just tears me up. It physically makes me ill. To give a presentation and utter the words "um, you probably won't be able to see this" does everyone in the room a disservice.  Do NOT use the moment of the presentation as your time to do the font resizing.

Lucida Console, 14 to 18pt, Bold.  Consider this my gift to you.  This is the most readable, mono-spaced font out there.  Courier of any flavor or Arial (or any other proportionally spaced font) is NOT appropriate for code demonstrations, period, full stop.  Prepare your machine AHEAD OF TIME.  Nothing disrespects an audience like making them wait while you ask "Can you see this 8 point font? No? Oh, let me change it while you wait."  Setup every program you could possibly use, including all Command Prompt shortcuts, before you begin your presentation.  That includes VS.NET, Notepad, XMLSpy, and any others, including any small utilities.

I've found that the most readable setup for Command Prompts is a Black Background and with the Foreground Text set to Kermit Green (ala "Green Screen."  Yes, I was suspicious and disbelieving also, but believe it or not, it really works.)  I set Command Prompts to Lucida Console, 14 to 18pt, Bold as well, with much success.

Also, set the font size to LARGEST in Internet Explorer and remember that there are accessibility features in IE that allow you to include your own Large Font CSS file for those web pages that force a small font via CSS.

Learn how to use ZoomIt and practice before-hand. It can be an incredibly powerful tool for calling out sections of the screen and making it so even the folks way in the back can see what's going on.

For simplicities' sake, I like to keep a separate user around call "BigFonty" (choose your own name).  He's an Administrator on the local machine and he exists ONLY for the purposes of demonstrations.  All the fonts are large for all programs, large icons, great colors, etc.  It's the easiest way to set all these settings once and always have them easily available.

5. Speak their Language (Know the Audience)

When I was in Malaysia for TechEd, I spent 3 full days exclusively with locals before the talk, I learned snippets of each of the languages, tried to understand their jokes and get an idea about what was important to people in Malaysia.  American analogies, much humor, and certain "U.S. specific" English colloquialisms just didn't make any sense to them.  When it came time to give the presentations, I better understood the Malaysian sense of timing, of tone and timbre, and I began each of my presentations by speaking in Bahasa Malaysia.  I changed aspects of my slides to remove inappropriate content and add specific details that would be important to them.

I've used this same technique in a half-dozen countries with success. While this is an extreme example, the parallels with any audience are clear.  If you're speaking to a room full of IT guys who work in the Automotive field, or the Banking industry, the fact that we are all programmers only gives you a small degree of shared experience.  Remember no matter the technical topic, try to get into the mind of the audience and ask yourself, why are they here and what can I tell them that will not be a waste of their time.  What would YOU want to hear (and HOW would you like to hear it) if you were sitting there?

6. Be Utterly Prepared (No excuses)

Short of an unexpected BSOD (and even then, be ready) you should be prepared for ANYTHING.  You should know EVERY inch of your demos and EXACTLY what can go wrong.  Nothing kills your credibility more than an error that you DON'T understand.  Errors and screw-ups happen ALL the time in Presentations.  They can even INCREASE your credibility if you recover gracefully and EXPLAIN what happened.  "Ah, this is a common mistake that I've made, and here's what you should watch for."  Be prepared with phrases that will turn the unfortunate incident around and provide them useful information.

7. CONTENT, CONTENT, CONTENT (Have some)

Every move, phrase, mistake, anecdote and slide should actually contain content.  It should be meaningful.  Your mistakes should teach them, your demos should teach them; even your shortcut keys, utilities and menu layout should teach them.  A presentation isn't an opportunity to read your slides.  I'll say that again. Don't READ your slides. I can read faster than you can talk.

Remember that most people can read silently to themselves 5 to 10 times faster that you can read to them out loud.  Your job as a presenter is to read in between the lines, and provide them structure.  Your slides should be treated as your outline – they are structure, scaffolding, nothing more.  If you jam your slides full of details and dozens of bullets, you might as well take your content at write an article.  It's difficult to listen to someone talk and read their slides at the same time – remember that when you design your content. YOU are the content, and your slides are your Table of Contents.

8. System Setup (Be unique, but don't be nuts)

When you a presenting, remember that you are looked upon as an authority.  Basically, you are innocent until proven guilty.  It's great to have a personality and to be unique, but don't let your personal choice of editors or crazy color scheme obscure the good information you're presenting.  I appreciate that you may like to use VI or emacs to view text files, but let's just say that sometimes Notepad has a calming effect on the audience. 

I give Microsoft talks, usually, so I tend towards Visual Studio, but 99% of my talks use a limited number of tools. Basically Visual Studio, Notepad, the Command Prompt and a Browser.

Remember that while you may prefer things a certain way while your face is a foot away from the screen, it's very likely the wrong setup when 500 people are more than 100 feet away.

I really like to get Toolbars and things out of the way. I use F11 (Fullscreen) in the Browser a lot, as well as Visual Studio's Shift-Alt-Enter shortcut to FullScreen. Turn off unneeded flair and toolbars. Also, turn on line-numbering so you can refer to lines if you're presenting code.

9. Speaking (Um…)

"Volume and Diction," my High School Drama teacher said to me.  Speak clearly, authoritatively, project your voice to the back of the room.  The best speakers don't even need microphones.  If you have a speaking affectation (I had a lisp growing up) or you tend to say, um, etc, or find yourself overusing a specific phrase ("a priori", "fantastic", "powerful", etc) take it upon yourself to NOTICE this mannerism and avoid it.

Practice multi-tasking.  It seems silly to say, but although we can all multitask to a certain degree, when we hit a real snag in a presentation, many of us tend to freeze.  Silence is deadly.  Remember, since all eyes are on you, complete silence and apparent introspection says "I don't know know what I'm doing."  When you need to get to a particular file, don't make the audience wait for you while you putter through explorer.  Have shortcuts ready (and explain when you use them).  Move fast and efficiently, but annotate your actions.  You should continue to "color-commentate" your actions like a sports announcer.  Don't allow "dead-air," unless it's silence for effect.

10. Advancing Slides (No lasers!)

I always used to hate slide-advancers, you know, those little remotes with forward and backward buttons. Then I tried one and I'm hooked. I use the Microsoft Presenter Mouse 8000 and totally recommend it. It isn't just a great Bluetooth mouse, but flip it over and it's a great Powerpoint slide advancer. 

Take a look at Al Gore's excellent presentation in "An Inconvenient Truth." It's seamless and flows. Now imagine him running over to his laptop to hit the spacebar each time he wanted to advance a slide. My presentations have gotten better as I've started incorporating this technique.

11. Care (deeply)

I really avoid presenting on topics that I don't care about. I avoid it like the Plague and I encourage you to do so as well. There's nothing more important that truly caring about your topic. If you care, it'll show. If you eschew all the other tips, at the very least care.

 

Introduction

In this tutorial we're going to examine the principals and construction of a basic ASP.NET 3.5 AJAX extender control. We'll discover how powerful extender controls can be for the reusability of code and behaviors. For more information on extenders refer to my books ASP.NET 3.5 AJAX Pocket Guide and ASP.NET AJAX Programming Tricks.

As we know, ASP.NET comes packed with a vast number of different controls, all having their own particular uses. However, it may become desirable to extend the behavior of these controls to better suit our needs. In most cases, the extension of these controls would involve building a new custom control, which inherits from the control we wish to extend and the new features coded. For example, consider a TextBox control, you may wish to limit the input of this control, change the background color when focus of the control has been changed, or display a watermark within the content of the control, etc. Building individual controls implementing each of the discussed behaviors, while definitely an option, is perhaps not the best option. What you’ll end up with is several different controls, all of which actually TextBox controls, however, each implementing a slightly different behavior, aside from being a tedious and repetitive task, it’s not the most efficient approach.

Welcome to concept of an extender control. Extender controls represent logical behaviors that can be attached to an existing control. Extender controls are server controls and can be attached to another control simply by identifying the client ID of the control we wish to extend.

Extender controls are standalone server controls, they implement from the Control class, have a Render() method and functions in a manner expected from any other server control. However, extenders offer the ability of injecting client-side code into the pages markup, hence granting the ability of extending the physical behavior of a server control. The controls an extender extends are not changed programmatically and are simply extended via client-side code, for example the addition of JavaScript event handlers to perform specific tasks based on a particular trigger. Extenders are specific to the ASP.NET AJAX Framework, this Framework simplifies the development of extender controls, as it offers a detailed client-side library we may make use of and also offers base classes we should inherit from when developing extender controls.

Extenders usually include a number of client-side objects defining the behavior of the target control. These objects are then written to the output stream by registering themselves with the ScriptManager control included within the page. A ScriptManager control must be present when making use of the ASP.NET AJAX base extender class.

Download all source files

Read more...

 

Often we need to capitalize the first letters of some word or some text (for example when we want to display users name or city name etc).
Since string class does not have a method to do this we could think that there is no built-in solution in C# for this problem...
But a little digging trough MSDN would help us find ToTitleCase method of TextInfo class in System.Globalization namespace that does exactly what we need: capitalizes the first letter of each word in the string.
here is how to use it:

using System.Globalization;

  ...

string capitalized = CultureInfo.CurrentCulture.TextInfo.ToTitleCase("asp.net simply rocks!!!");

After the execution, capitalized string would have this value: "Asp.Net Simply Rocks!!!" which is exactly what we needed, right?
Off course, how will string be capitalized depends on the current culture that is set on your ASP.NET page, but we can easily override this and use the culture we want like this:

TextInfo UsaTextInfo = new CultureInfo("en-US", false).TextInfo;

string capitalized = UsaTextInfo.ToTitleCase("asp.net simply rocks!!!");

 

Wake up ASP.NET developers!

Posted In: . By Sothy Mom

The following contains unfair generalizations about developers, rough language and a bad attitude. Dear reader, this is tough love from yours truly.

You’re participating in the stagnation of the World Wide Web and you hold the human race hostage.

Ouch, that was a bit harsh, but it probably got your attention. That’s important because what I want to address is no laughing matter. There seem to be a huge unwillingness among ASP.NET developers to participate in evolving the web. This is not acceptable and surely not understandable since the web is what brings food on the table for most ASP.NET developers.

The hostage situation

It seems that other developers are much better to push the web forward than our camp is. Python, PHP, RoR and even Perl developers seem to be much more ideological in their approach to web development and makes a bigger effort in evolving it. That might be because these languages are more common in universities. In the meanwhile, ASP.NET devs just sit back and watch it happen without contributing or maybe even caring about it. That is not a flattering attribute by any means.

In case you are wondering, I’m talking about the semantic web or Web 3.0 if you will. Whenever I have written about it, no one really seems to care. Most other .NET bloggers haven’t written about it and the online discussions rarely have ASP.NET devs joining in. As I see it, ASP.NET developers don’t care about the future of the platform they work with every single day and that is a crime.

It’s a crime because you as a developer limit the billions of web users from utilizing all the wonderful possibilities of the semantic web. It’s a crime because you hold them hostage for personal convenience. It’s more convenient to sit back than to learn something new, but this time it’s different. This is not equivalent to learning LINQ or the MVC Framework. This is bigger than you and it’s bigger than the client/company you are working for. This is what will define our online future.

It’s growing

You might think I’m being a bit dramatic about this matter and you are absolutely correct. According to Tim Berners-Lee, the semantic web is growing exponentially these days, but the ASP.NET camp is sleeping through it. The problem is that it will make the growth slower and then we are back at the hostage situation. If we don’t help push native support for these things in the next version of the .NET Framework and Visual Studio, then we become even further alienated and left behind. This matter demands dramatic change in the way we approach web development, so I think it is more than justified to be dramatic.

The semantic web is starting to become useful due to its growth lately, but for it to become truly useful, it has to be widely adopted by big, medium and small websites containing any structured data worth sharing (since it’s on the Internet in the first place, it most likely is worth sharing).

Make a small effort

What puzzles me again and again is that only a fraction of web developers use microformats or any other semantic formats. In the light of how easy and useful it is, it leaves me saddened. It is not a duty to implement semantic mark-up; it is a privilege to help drive the future of the web – and with a minimal effort as an added bonus.

So, if you have a website containing user profiles, calendar events or any other structured data, then please tag them up with the appropriate microformat and XFN tags. If you want to do a little more, then FOAF is a good place to start. Remember, it starts with us, the developers, so wake up! (the lack of the word 'please' is not accidental, although appropriate).

Semantic fun-facts

Did you know that Yahoo has a new search engine in beta that utilizes microformats in a very cool way?
Did you know that Technorati has an hCard microformat parser service?
Did you know that Google has a Social Graph API that takes advantage of microformats and FOAF?
Did you know that LinkedIn is the largest publisher of the hResume microformat?
Did you know that the Operator toolbar for Firefox let’s you utilize microformats on any web page?
Did you know that I've written a guide to implementing microformats in ASP.NET?

 

Do you use database projects in Visual Studio? If not, then now is a good time to start. It is the best way I have found to source control my databases without actually sticking the database file itself in the repository. It is very simple to add to your solution and creates a default directory structure for your create scripts, change scripts and queries. Best of all the project will be recognized by source control and added to the source code repository. This means you can keep versioned scripts for maintainability. It also gives you the option to do the dreaded rollback!

Lets start by creating a database project of our own. To start, we will create a blank Visual Studio solution.

screenshot-2008-05-05_18_56_00

Now click File -> Add -> New Project.

screenshot-2008-05-05_18_57_08

You should get the dialog below. Now we will look in the node of "Other Project Types", click "Database" then select "Database Project". This will give us the opportunity to name our database project. We will call this one by the database we are going to be using, good ol' Northwind.

screenshot-2008-05-05_18_58_44

Next you will be asked to setup a database reference. So here all we have to do is add a new reference to the Northwind database.

screenshot-2008-05-05_18_59_29

My database will be in SQL Server, yours can be in any of the choices shown below.

screenshot-2008-05-05_19_01_31

Now we just set the server name and choose the Northwind database.

screenshot-2008-05-05_19_02_07

You should then test your connection (out of good practice) and see the dialog below upon success.

screenshot-2008-05-05_19_02_15

Now we will see our database reference shown in the original list of references. Just double click on your newly added reference.

screenshot-2008-05-05_19_02_31

Now your project should look something like the shot below.

screenshot-2008-05-05_19_02_51

Once we get this far, we need to start filling our folders with database scripts. You can add new folders if you wish, but I think the default folder structure is good enough. Now then, we can use the database publishing wizard to get our first create script into the "Create Scripts" folder.

Double click the reference to your database in the database references and it should bounce you to the server explorer window with your data connection all setup.

screenshot-2008-05-05_19_05_20

Right click your data connection and click "Publish to provider..." to start the database publishing wizard.

screenshot-2008-05-05_19_05_31

Now we select the database we would like to publish, so again I will choose Northwind.

screenshot-2008-05-05_19_05_52

Now with the "Script to file" option chosen, we will browse to the "Create Scripts" folder in our database project to put the outputted .sql file.

screenshot-2008-05-05_19_06_51

Now we get to choose some options. I am going to set the output for SQL Server 2005 and select to script the database schema only.

screenshot-2008-05-05_19_07_18

Now we can review the summary of what we have configured and click finish.

screenshot-2008-05-05_19_07_26

Upon clicking finish, we will see the progress of the .sql file being scripted to the hard drive.

screenshot-2008-05-05_19_08_07

Ok, for some reason I couldn't find a refresh button in the database project to see the file that was created so we will right click the "Create Scripts" folder and click "Add Existing Item..."

screenshot-2008-05-05_19_10_15

Then browse to our .sql file and click the "Add" button.

screenshot-2008-05-05_19_10_27

Now we should see it in our project and we can also see the contents of the generated script by opening it in the editor.

screenshot-2008-05-05_19_12_20

screenshot-2008-05-05_19_12_31

It really is just that simple. I mean if nothing else you have a designated place to put all your SQL scripts for your database. The big plus is that your scripts will be source controlled. Also, anyone who opens the solution will know exactly which databases are used by the project.

 

LINQ.Flickr 1.3

Posted In: . By Sothy Mom

Just released another version of LINQ.Flickr. The release is out with several bug fixes, code optimization, new feature and overall mocking support. I have used Typemock for the unit test of the product. In coming posts, I will show how powerful mock can be in faking routine like upload photo. But, you can dig it right away, if you go by the release page and download a copy of the product. Truly speaking, testing was never fun for serviced API till mock engine is at my hand.

The release is not all about re-factoring and mocking , but now you can query, add , delete photo comment , query people and popular tags and do more that are mentioned in the release page.

Now, doing complex query is even more fun. lets take this.

var query = from photo in _context.Photos
where photo.Id == photoId && photo.PhotoSize == PhotoSize.Medium
select new FlickrPhoto
{
    Id = photo.Id,
    Description = photo.Description,
    Title = photo.Title,
    Url = photo.Url,
    User = photo.User,
    Comments = ((from comment in _context.Photos.Comments
                 where comment.PhotoId == photoId
                 select new PhotoComment
                 {
                     Author = comment.Author,
                     AuthorName = comment.AuthorName,
                     PermaLink = comment.PermaLink,
                     PhotoId = comment.PhotoId,
                     Text = comment.Text,
                 }).ToList<PhotoComment>()),
    Tags = photo.PhotoTags.Select(tag => tag.Title).ToArray<string>()
};

FlickrPhoto newPhoto = query.Single();

The query is about getting the photo info for a specific photo id and I have now combined it with tags, comments to make it more useful. Also, few posts back, I have mentioned about using a RestToCollecitonBuilder  to build an object on REST response,  it is in action in this release as well.

Finally, don't forget the link and it's www.codeplex.com/linqflickr . In the end, this project is not about querying Flickr and getting photo out of it, but it could be a great learning tool for Mocking, for building custom LINQ provider (with LinqExtender) and other things that you might need to know like, how to define a service endpoint by interface.

 

Unit Testing Events

Posted In: . By Sothy Mom

In this article I will show you how you can unit test your events. I will show you a simple technique that will enable you to test if your events fire exactly as often as you want them to and I will provide you with two implementations. One implementation works well with the .NET Framework 2.0 and the second one uses .NET 3.0 in order to minimize the code necessary.

I am assuming you are familiar with NUnit.

In .NET 2.0 it is useful if you introduce a helper class which looks like this one:

class EventCounter    {
   private int _counter;

   public int Value
   {
      get { return _counter; }
      private set { _counter = value; }
   }

   public void Increment(object o, EventArgs e)
   {
      Value++;
   }
}

The class doesn’t do much. It has only one member (Value) which is increased whenever the Increment method is called.

Well, I must admit that this is one of the most weird classes I ever wrote but it is quite useful in testing code... take that:

[Test]
public void TestIfListChangedEventIsFiredOnceWhenMovingElement()
{
   ResponsiveList<string> collection = new ResponsiveList<string>();
   EventCounter counter = new EventCounter();
   collection.Add(“item 1”);
   collection.Add(“item 2”);
   collection.Add(“item 3”);

   collection.ListChanged += new EventHandler(counter.Increment);
   collection.MoveElement(0, 2); //moves item from index 0 to 2       
   Assert.AreEqual(1, counter.Value);
}

This test checks if the ListChanged event of the class ResponsiveList is fired when elements are moved within the list using the MoveElement method.

Using this class you can not only test if your event fires, you can also test if your event fires exactly as often as you want it to. I found this approach extremely useful and more than once it showed me that some events where fired too often or not at all.

It is a good idea to not only test wether an event fires or not but also test if it fires as often as desired. Firing too many events can result in bad performance and can cause bugs which can be very hard to uncover.

As mentioned before the above code is very old and given the power we have with anonymous methods you don’t even have to use such a weird EventCounter class anymore. Nowadays (.NET 3.0) you could write this unit test like this:

[Test]
public void TestIfListChangedEventIsFiredOnceWhenMovingElement()
{
    ResponsiveList<string> collection = new ResponsiveList<string>();
    collection.Add(“item 1”);
    collection.Add(“item 2”);
    collection.Add(“item 3”);

    int counter=0;
    collection.ListChanged += (sender,e) =>
    {
        counter++;
    });
    collection.MoveElement(0, 2); //moves item from index 0 to 2

    Assert.AreEqual(1, counter);
}

As Niki points out, even in .NET 2.0 you can use a similar approach and spare yourself from using a helper class:

[Test]
public void TestIfListChangedEventIsFiredOnceWhenMovingElement()
{
    ResponsiveList<string> collection = new ResponsiveList<string>();
    collection.Add(“item 1”);
    collection.Add(“item 2”);
    collection.Add(“item 3”);

    int counter=0;
    collection.ListChanged += (delegate)
    {
        counter++;
    });
    collection.MoveElement(0, 2); //moves item from index 0 to 2

    Assert.AreEqual(1, counter);
}

 

  

 

FOAF parsing and crawling in C#

Posted In: . By Sothy Mom

I’ve been looking deeply into FOAF lately and last week I worked on a parser that could wrap a FOAF document into a strongly typed class for easy consumption by C#. Now I want to share it with anyone interested. It appears there are no FOAF parsers available in C# yet. I wasn’t able to find any.

The parser

The class FoafParser has two public methods, Parse and ParseFriendsAsync, which handles two different approaches in fetching FOAF documents.

The Parse method

This method takes a URL as a parameter which must point to an online FOAF document. It then parses the foaf:Person element which contains fields such as name, birth date, photo, homepage etc. It then looks for people in the FOAF document that are described as someone you know, parses the information available and adds it to a public collection property. The following example parses a FOAF document and binds it to an ASP.NET Repeater.

FoafParser parser = new FoafParser();
parser.Parse(new Uri("
http://example.com/foaf.xml"));
if (parser.IsParsed)
{
  ltOwner.Text = parser.Owner.Name;
  repFriends.DataSource = parser.Friends;
  repFriends.DataBind();
}

The ParseFriendsAsync method

When you list people you know in a FOAF document, it is common to only provide very little information such as the full name. When that is the case it is also common to provide a link to that persons FOAF document using the rdfs:seeAlso tag. We can then use that link to retrieve all your friend's FOAF documents and parse them as well.

It can take a long time to retrieve all those documents one at a time, but if we do it asynchronously then we can speed things up substantially. When you have called the Parse method on the FoafParser class, you can then call ParseFriendsAsync. It loops through all the friends that the Parse method found in search for the rdfs.seeAlso tag. When it finds it, a web request is made to retrieve the FOAF document of that friend and then parse it for information.

When the ParseFriendsAsync method is finished, it triggers an event you can listen to. All the friends with FOAF documents have now been updated in the collection.

private void RetrieveAsync()
{
FoafParser parser = new FoafParser();
  parser.Parse(new Uri("
http://example.com/foaf.xml"));
if (parser.IsParsed)
  {
    parser.FriendParsingComplete += new EventHandler<EventArgs>(parser_FriendParsingComplete);
    parser.ParseFriendsAsync();
  }
}

void parser_FriendParsingComplete(object sender, EventArgs e)
{
// Now the Friends collection has been updated asynchronously.
FoafParser parser = (FoafParser)sender;

  Response.Write(parser.Friends.Count);
}

Download

In the zip file below you’ll find the FoafParser.cs class as well as an example .aspx page and code-behind file.

FoafTester.zip (3,77 kb)

 

Operator~ and BinarySearch

Posted In: . By Sothy Mom


Usually, we use Array.BinarySearch to find a value in a sorted array, we all know that this method returns the index of the searched value in the array, if value is found. It turns out that the return value of BinarySearch is much more interesting and useful. Lets focus on what happens if the value is not found in the array.

Those who claim that if value is not found than a negative number will be returned, are absolutely right. But most of us don’t really know the whole truth about that negative number and how it can be used.

magnifying-glass

To understand its usage, we can see how the Add method in SortedList class is implemented (this operation must keep the list sorted):

1:
2: public virtual void Add(object key, object value)
3: {
4:     if (key == null)
5:     {
6:         throw new ArgumentNullException();
7:     }
8:     int index = Array.BinarySearch(this.keys, 0, this._size, key, this.comparer);
9:     if (index >= 0)
10:     {
11:         throw new ArgumentException();
12:     }
13:     this.Insert(~index, key, value);
14: }

Did you notice the bitwise complement operator~ in line 13? It is applied on the negative result of the binary search to produce an index that is used in the Insert method. The guys in Microsoft who wrote the SortedList.Add method took advantage of the following fact about BinarySearch return value:

If the array does not contain the searched value, the method returns a negative integer so you can apply the bitwise complement operator~ to it and produce an index. If this index is greater than or equal to the size of the array, the searched value is the largest number in the array. Otherwise, it is the index of the first element that is larger than the searched value.

So, the produced index can be used in the Insert method to add the value in the correct place and keep the array sorted. When I introduced this fact to some of my colleagues , they claimed this is very nice and tricky but may be unreadable. What do you say?

 

The single biggest factor for success on any project I have been apart of in the last 10 years at Microsoft is the people.  In a business like ours where intellectual capital is the biggest asset, hiring and growing people is an extremely important task. 

I have gathered some details on a few positions working on the .NET Framework product team, if you are interested  please click on the link and apply... If you know someone who would be just prefect for the job, please send them a link!

A few general tips for folks interested:

  1. Know what you want to do, but be flexible.  We typically hires for a specific role on a specific team.  The system is geared to work that, so if you have some solid ideas on what you'd like to get more information on that helps a lot.  During the interview process, if it becomes clear you'll be a better fit for a different position we will suggest that you. 
  2. Specific knowledge of .NET is not required.  By and large we don't hire for specific skills.  We hire for passion, smarts and the drive to get things done.  If you have those attributes, my feeling is that you can learn the details of .NET.   In fact, I think it is a plus if a candidate as deep experience in related technologies in the industry. 
  3. Follow your passions. The best way to succeed at Microsoft is to do something you are passion about.  That passion could be about the life changing technology you are working hard to bring out to customers, it could be people you get to work with on a day to day biases, it could be about the way we do development.  Whatever your passion is, find the position that best helps you follow it!
  4. A few details...For most jobs, we do consider international candidates, so please go ahead and apply!  For these jobs we do need you to relocate to sunny Redmond, WA.  We aren't looking for contractors or work-for-hire for any of these, we are looking for folks that want to make a career at Microsoft.

Program Manager Jobs

These are job openings on my team.  Read my past few "PM tips".. chances are if they resonate with you you could be a fit.   For both of these are are looking for senior folks...  people with 5+ years of industry experience and of course a passion for these spaces is very important.

Managed Extensibility Framework PM

We are looking for a someone to drive the release and design of the very recently announced Managed Extensibility Framework.  Our high level goal is to evolve the state of the art of component development.  If you know what DI, IoC and TDD\BDD are that is a good first step!  We have some big customers internally and lots of interest already externally.  Please see Krys's blog for more details and apply on line

Core ASP.NET Feature PM

ASP.NET runs a large chunk of the web today and there are some very exciting plans for what we can do to make it even better in the future.  If the day in the life of a ASP.NET PM sounds like your prefect day at work, then apply on line.

Software Development in Test

SDETs on our team are talented application developers and testers.  Our products (ASP.NET, ASP.NET AJAX, Silverlight 2, and Windows Forms) are focused on developer technologies and are first-class frameworks.  SDETs on our team are successful by representing the customer, participating in product design, and innovating in the test space.  SDETs are often the very first people that get to build applications with new technology that comes out.  They thrive on finding design and implementation issues early in the cycle and ensuring the customers have an excellent experience with the product. Apply on line.

Test Manager

For the ASP.NET Test Manager, we’re looking for someone who can manage a strong team of 25+ technical SDET’s to deliver the next generation web application platform.  Successful candidates are those that have experience shipping multiple products and can advance the state of the art of software testing. Apply on line

ASP.NET Developer

As you likely know AJAX development is becoming increasingly important.  We have some great plans for what is coming in the future of the Microsoft Ajax Library (part of ASP.NET AJAX) and we'd love to have your help in making it happen.  Of course you can work on any of the other tons of Ajax libraries out there, but only at Microsoft can you work on the Ajax framework that will be the best tooled, best server integrated, best supported and most used!   Apply on line

Other Positions:

Also, related my good buddy Doug Purdy has some very cool sounding positions open on his team as well:

Emacs.Net
New Languages & Compilers

Please apply on line for any of these positions or drop me an email if you have specific questions. 

 

Source from Brad Abrams

 

A C# Operator I would like to see.

Posted In: . By Sothy Mom

You could argue there are too many operators in C# as it is; however, I feel having an acute knowledge of the available operators is like knowing CTRL + B will bold the selected text in most word processing software.

To put it simply, it hurts no-one, whilst providing shortcuts to advanced users.

Consider the following:

if (MyObject != null)
{
    return MyObject;
}
else
{
    return SomeOtherObject;
}

In C# 2.0, the kind people at Microsoft provided the ?? operator to make this a much more sucinct:

return MyObject ?? SomeOtherObject;

One thing that I find ugly and boring in code is that of checking for nulls in nested object properties, so for a moderately extreme example:

Staff.Manager.PersonalDetails.Address.Location.Postcode

In order for me to be sure that I can access the “Postcode” part of this chain correctly (with the caviet that each of these proerty objects might be null) I’d have to write something like the following:

if (Staff != null && Staff.Manager != null &&
    Staff.Manager.PersonalDetails != null &&
    Staff.Manager.PersonalDetails.Address != null && .....
{

I’m sure you’ll agree the above is pretty ugly, especially if you don’t really care which property is null, just if any of them are.

So, I propose a new operator, the “Is anything in this chain null” operator, to be used something like so:

return ??{Staff.Manager.PersonalDetails.Address.Location.Postcode} : “No Postcode”

The actual syntax of this operator isn’t important, just the functionality.

 

What makes one developer better than another? Shouldn’t we all be performing at the same level? Of course not, we’re not sewing buttons on an assembly line. We’re using every bit of our intelligence to create something that we can only begin to understand.

  • I think logically. Computers don’t care how you feel, and your opinion doesn’t matter. All that matters is if you write your code exactly the way the computer dictates.
  • I constantly look for better ways of doing things. I subscribe to a good number of development blogs. I alone cannot always come up with the best way to solve a problem, but somebody somewhere probably can.
  • I read books. Joel says that most programmers have stopped reading books. What a shame. Blogs are great for snippets, but it’s rare that they cover a topic well from start to finish. Blogs are the ADD version of books.
  • I don’t stop thinking about problems and how to solve them through automation. Sometimes I’ll wake up in the middle of the night, and I can’t get back to sleep until I write some code that I can’t get out of my head.
  • I have side projects that I think are interesting, and give me a chance to try things that I might not want to try on my production code at work. Yes, my side projects distract me at work, but the knowledge I gain pays back the time I lost.
  • I have a tech blog. I suggest all developers start a blog and give back to the community. If you solve a problem, we want to hear about it! At the very least, it will give you an opportunity to formalize your ideas, which will either reinforce them, or make you realize you were wrong. You might also get some great feedback.
  • I try to prove myself wrong (aka objective). Everyone wants to be right. I try to prove myself wrong when appropriate. One of the hardest things in the world for a developer to do is say that the code they just spent a week writing is useless. Maybe it is, don’t fight it, work with it.
  • I keep up with the latest technologies, and force myself to try them.
  • I have a relatively good understanding of how the computer hardware and software works. I’ve met too many developers that barely know how to turn on a computer.
  • I’m great at writing Google queries.
  • I’m not just in it for the money. I actually enjoy what I do. I had a job interview where the guy that would have been my boss told me a story about how he was brought in off the street and thrown into managing their software projects. When the software industry starts getting rough, who do you think is the first person to go?
  • I’m sympathetic to the users pain. If I can share their pain, I’ll want to fix it and prevent it.
  • I realize my code will never be perfect, so I try to make it testable and modular. I set up processes that try to minimize the effect of my human error.
  • I don’t think Microsoft is evil, and I don’t think they’re a saint. They’re a big company. Some of the stuff they write is crap, some is amazing. The same is true for any other company out there.
  • I learn from my mistakes. I try to put at least 2 checks in place to avoid any past mistakes. If one check fails, I’ll have the other.
  • When I’m asked to solve a problem, I think above the problem, and determine if it’s a problem that even needs solved.

 

Microsoft has just released a hotfix for a number of issues that have been plaguing me for some time in Visual Studio 2008. The issues involved have to do with the visual designer and the HTML code editor and a number of different input focus and slow input situations.

You can get the hotfix from here:

Blog Hotfix

You can read the official fix list at the link above, but here are a few issues that it has addressed for me specifically:

Visual Designer Focus issues

In the the Visual Web Forms designer I would often be unable to select controls inside of container controls or DOM elements. Instead of selecting a contained control the control's container would select and only repeated clicking and selecting de-selecting would eventually get the control focused. The fix now gets selection right in most cases. Also multiple selection is no longer so sketchy. I also had a number of issues with cutting and pasting of controls almost consistently crashing VS - which also seems to be gone now.

Visual Designer and Property Sheet Synching

I had major problems with the property sheet not synching with the selected control. In many situations the sync would simply not work at all or require repeated clicks on the Properties context menu. Now controls select much more quickly and the property sheet synchs properly although there's still a second or so delay, which is annoying but acceptable.

Slow Master Page Loading

I had major issues with master pages loading taking forever when the page loaded for the first time. It would often take 20-30 seconds for the first form to come up. Subsequent forms were much faster, but the first load was horrendous. Now in the same project I was blown away to see that the load was maybe 5-10 seconds with subsequent pages loading nearly instantly.

Performance for loading into the Visual Editor in general is much improved.

Keyboard Input lagging in the HTML Source Editor

On occasion I would have situations where the editor would be up and running and there'd be a cursor, but I'd type into the editor and nothing would happen. I'd have to click off and back into the editor to properly get focus and then it would work. In some cases the keyboard buffer was even locked where any additional keys would bring a white overlay on the editor. Now with the hotfix that problem seems to have disappeared. Also the editor seems a lot more snappy in general.

Mysterious View Code Availability

The patch also fixes the View Code context menu option which prior to the patch was extremely hit or miss. Sometimes the menu option would show up - other times it wouldn't. Apparently a lot of the problems fixed by this patch have to do with idle state detection and some hardware configuration apparently never entered the necessary wait states to update certain VS UI features. Other things that can be affected by this are things like Syntax highlighting taking a while to show up or the member list to populate. All of that too is now working as it should.

What's odd is that I *really* didn't notice these problems as acutely until a few weeks ago around the same time Microsoft had put out a pre-release patch. I tried the patch about a week ago and all the above issues disappeared. Some of these fixed issues appear to be side effects of this patch since they're not explicitly mentioned on the fix list, but hey I'm not arguing. This patch has brought some sanity back into my development environment.

The patch has a few additional fixes that you can find on the download page. The fixes will eventually end up in Visual Studio 2008 SP1, but I suspect most people will want to install this hotfix since these issues affect a wide range of the product.

 

Recently I found out this great add-on for Visual Studio 2008 called PowerCommands. PowerCommands Extends the functionality of Visual Studio 2008 by adding some features which we all want built into Visual Studio. PowerCommands provides the following:

1. My favorite: Copy Reference, very useful indeed, and you all know it, just right click on the reference you want copied and select copy reference, now go to the another project and just paste that reference

* you can copy all the references by right clicking on references.

2. Another useful option is Collapse Projects, click on the solution and collapse all the projects at ounce. Very handy if you have a project loaded solution.


3. Email Code Snippet, I don’t know about how useful is it, but its cool :).