Test DTOs for default constructor

Monday, February 20, 2012 16:05:54


Here's a quick test method I put together to save me from myself. If you organize your data transfer objects in a single assembly, and use normal serializable classes, you need to ensure that you always have a default constructor. The compiler won't help you out with this one - you've got to do it yourself. Adding this to your unit test project will ensure that you don't accidentally put in a custom constructor without adding in a default one.

[Test]
public void EnsureAllDTOClassesHaveDefaultConstructor()
{
    foreach (var type in typeof(SomeDTO).Assembly.GetTypes())
    {
        if (!type.IsAbstract && type.GetConstructor(new Type[0]) == null)
        {
            Assert.Fail("Type {0} is missing the default constructor.", type.FullName);
        }
    }
}


Tags: programming

Comments:

Add Comment

One-Click Web Deployment with DubDubDeploy

Tuesday, January 31, 2012 21:36:44


After months of development, DubDubDeploy, my one-click web deployment product, is now available to download at DubDubDeploy.com. The beta period will last through the end of March, and the beta licenses will be good through the end of April. After that, the product will be available for just $299 per year - very affordable for small and medium-sized development shops, and well worth it.

This has been an incredible experience for me. I've spent most nights and weekends working on this product for the past several months, and made huge sacrifices. For example, I missed practically the entire season of Dancing with the Stars. I've had to learn to like coffee after spending several entire weekends in coffee shops. And I was forced to take a nice weekend trip to Payson and work outdoors, where I came dangerously close to experiencing fluorescent light withdrawal.

But it's been worth it. I have a great product, and a list of enhancements that I'll be working on over the next year or so, and the first product for my new software company, J T Enos LLC. Hopefully this is just the first of many to come.



Tags: programming

Comments:


Date: 2012-02-01 07:29:53
Name: Eric

"I think that the good and the great are only separated by the willingness to sacrifice." - Kareem Abdul-Jabbar

Your willingness to go so far as to forego DWTS shows me how serious you are. :-) Good luck!


Date: 2012-02-02 19:23:34
Name: Joe Enos

Thanks Eric. But it's not over yet. I'm expecting to miss a season of the Bachelor while I'm working on version 2.

Add Comment

DubDubDeploy Status Update - December 2011

Thursday, December 29, 2011 22:06:17


Here is the latest status update for DubDubDeploy. I'm about a month away from a working beta, and hoping to have a full product out for release by April 1.

Watch on YouTube

Tags: programming tech

Comments:

Add Comment

jQuery Synchronous AJAX Calls

Saturday, December 10, 2011 19:29:33


Have you ever wanted to make an AJAX call without the asynchronous part? Of course you have, who hasn't?

98 times out of 100, asynchronous is just fine, but on occasion, I'd like to wait for the server response before continuing the process flow.

3 seconds of Googling, and I had my answer - a simple parameter, async, to pass into the ajax function:

jQuery.ajax({
    type: "post",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({/*object goes here*/}),
    url: "SomeUrl",
    success: someSuccessFunction,
    error: someErrorFunction,
    async: false
});



Tags: programming

Comments:

Add Comment

DubDubDeploy - Introduction

Saturday, October 15, 2011 16:03:49


Here is a very short introduction to my new product, DubDubDeploy. More information and videos will be coming in the upcoming weeks and months, and I will also be demoing the new features in live in-person and streaming events (more details to follow).



Tags: programming tech

Comments:


Date: 2011-10-16 12:38:00
Name: Flo M (via Google+)

Nice! Producto! No idea lo que hace pero se ve muy bueno!


Date: 2011-10-16 16:44:16
Name: Joe Enos
Website: http://www.jtenos.com/

Muchas gracias. El producto está hecho para las compañías de usar y me envíen bolsas gigantes llenas de dinero.

Add Comment

Entity Framework Bug - Inheritance and Foreign Keys

Tuesday, August 23, 2011 23:26:40


Today I came across a particularly frustrating issue while working with the Microsoft Entity Framework. The solution I'm working on involves using inheritance within the Entity Framework, which is actually reasonably straightforward, following the example from this video on MSDN.

My database model contains a parent table and a child table - these two tables have the same-named primary key, and the child has foreign keys against the parent, and against one other table, with no other columns. Visual Studio's EDMX designer looks at this relationship and thinks that the child table is actually just a many-to-many intermediary table between the other two, and leaves it out of the model. This is not the behavior I want.

I managed to manually update the conceptual model to match the database, and got everything set up the way I wanted. But when I refreshed the model, Visual Studio put its relationships back in and screwed up the model again.

So time to start troubleshooting. I recreated the scenario, using simple data objects, in a throwaway project. I chose a Vehicle to replace my complex object with VehicleCar as its child, and PaintStyle to represent the additional property of the VehicleCar. I recreated my steps, and could not reproduce the problem. I assumed I did something wrong in my original project, so I tried that again, but got the same result.

After some more troubleshooting, I tried my same simple example, this time with the longer names of the original class. My wild guess was that maybe the length of the entity names had something to do with it - my real project's entities had fairly long names (30+ characters) - I wouldn't expect that to be a problem, but it was worth a try.

What I found was very disturbing. I could build two identical models, one with my "Vehicle" names, and one with my original long names, and the long name gave me my error, while Vehicle did not. But that's not the weird part. I tried again, this time with the word "Phoenix" instead of Vehicle - and it failed just like my long names. I then tried with the word "Vermont", and it behaved the same as "Vehicle".

I tried many times, recreating my steps exactly each time, and the words "Vehicle", "Vermont", and "Victory" all behaved one way, and "Phoenix", "Cartoon", "Payout", and "Mystery" all do something else. Somehow the letter "V" is different from other letters.

At this point I decided that it was time to leave for the day - there had to be some other explanation, and I felt like I was going crazy - this is so ridiculous that there's no way in the world this is possible. I had to be missing something, maybe subconsciously doing something different each time.

But it's very recreatable. I got home and tried it on my home PC using a different version of Visual Studio and SQL Server, and recorded my results - the same as before.

My video is available at YouTube:

YouTube: Entity Framework Bug - Foreign Key Relationships

Tags: programming

Comments:


Date: 2011-08-24 00:04:00
Name: Flo MO (via Facebook)

Wow, brotha, i saw your video and read your bug, sounds crazy, i wish i was more knowlegable about it, just wanted to give you some props on your vid and your examples, i hope you find the solution, or a good explanation of why this is happening. I love the Montgomery Ward Sales Videos!! Take it easy brotha and good luck on this !!


Date: 2011-08-24 08:00:00
Name: Joe Enos

Thanks - this was a really screwed up day, but software is still generally an awesome industry if you ever wanted to get back into it. And I'm having some hardware trouble now, but I'll have the rest of those Monkey Wards videos up hopefully in a few weeks.


Date: 2011-08-24 12:05:28
Name: slowturtle

wow, that is pretty nasty...


Date: 2011-08-24 20:54:00
Name: Flo MO (via Facebook)

Ya know i would love to but I dont feel confident in the stuff that has emerged and continues to emerge. I mean design was not really my strong and i was just a worker, i can do the code and learn the system but not good at testing or debuging. I would also be lost on databases, the only thing i learned how to use was MS Access, but if you need me to sell anything just let me know....


Date: 2011-08-24 20:58:00
Name: Flo MO (via Facebook)

There are so many open positions @ WF dealing with database engineers and/or IT related with experience. and the money is so good makes me wish i should have fisnished my program!!

Add Comment

You might be a programmer - Whitespace

Sunday, June 26, 2011 18:56:49


If you call the empty road between cars "whitespace"...you might be a programmer.

I found myself doing this not too long ago. Driving on the freeway, stuck behind a set of nimrods driving 45 MPH when there's a half mile of empty road in front of them, without thinking, I yelled in frustration "Why are you driving so slow when there's all that whitespace in front of you!?"

For you non-programmers, whitespace is any space, tab, or line break in code. Some programming languages, like my specialty, C#, ignore whitespace completely, while some languages like Python use indentation and whitespace to define code behavior.

Tags: programming

Comments:

Add Comment

Internet Exploder 9

Tuesday, March 22, 2011 21:50:43


Sorry, Micro$oft, you let me down again. I installed Internet Exploder 9 shortly after it was made available, because it's supposed to be the most modern browser there is, supposed to be faster than Chrome and Firefox, and supposed to be up to speed on all of the latest standards.

I knew from the start that it wouldn't be, but I expected it to be better than what I'm seeing. Still, I gave it the chance, and it proved that it's still just a little behind.

My experience is on my home PC, which is a desktop Dell PowerEdge SC440 with a Pentium D 2.8GHz, 4GB RAM (although Windows only sees 3GB), with a NVIDIA GeForce 6200A 256MB PCI video card. It's not the most powerful or modern machine, but it does pretty well. I'm running Windows 7 Ultimate x86.

Installation was kind of interesting. It didn't require a full reboot, which was surprising, but did require that I specifically close nearly all of my open programs, including Windows Explorer, in order to install. Why it needed access to the files used by TweetDeck, Trillian, KeePass, Thunderbird, or Toad, I don't know, but turning off my anti-virus and especially not turning it back on when completed seems a little sketchy to me.

Immediately the first thing I noticed was that it's just not quite as "peppy" as Chrome or Firefox. Scrolling up and down a page using my mouse wheel is how I spend a significant amount of time on the web. In Chrome or Firefox, it's very smooth and consistent. In IE9, it's just a little jumpy. We're talking milliseconds here, but it's enough for me to notice.

Watching Flash videos on YouTube is clearly worse in IE9. Simply moving my mouse around the page, hovering over links, or hovering over the video causes the video to be choppy, even stop completely. This doesn't happen in Firefox - the videos are smooth and consistent.

Javascript is definitely improved from previous versions, but it is not faster than Chrome in the apps I tried. A good test is dragging and dropping on the Netflix queue page. IE8 and previous were basically unusable on this page, because it just took so long for the browser to understand what you were doing, while Chrome worked reasonably well. IE9 handles this page about as well as Chrome does. However, there are scenarios that just aren't up to speed yet. Using jQueryUI for custom animations works perfectly in Chrome, but on my machine, it's still a little choppy and not a smooth animation - it's performing about the same as Firefox 3.6. The example I'm using is my own homepage, jtenos.com, where I have links that pop up a jQueryUI dialog box.

There's still no "Paste and Go" option when pasting text into the URL bar. Chrome and Opera have this feature (Firefox, still waiting...). When I right-click in the URL bar when I have text in my clipboard, 99.99% of the time I'm going to want to navigate to what I'm about to paste in, so that should be a no brainer.

One of the major HTML5 testing sites, html5test.com, gives IE9 a worse score (130) than Firefox 3.6 (155) and significantly worse than Chrome 10 (288). One of the big IE9 selling points was that it was HTML5-ready, but that was apparently all fluff. There are all kinds of conspiracy theories on why some tests crowned IE king, while others show it failing miserably. Unfortunately, as a developer, I'm not using the new fancy HTML5 stuff myself yet, so I can't really make an unbiased judgment on this. I guess we'll find out soon how the various browsers handle the new and upcoming standards.

Oh, and one more thing - it's not available for Windows XP, so the millions of us who are still using XP (we're still on XP at work) will not benefit from IE9. I guess that makes Firefox 4 that much more appealing.


It's not all bad. Here's what I liked:

The color-coded tabs seemed a little silly at first, but I think it's a decent idea, that at worst, doesn't hurt anything. It gives related windows the same color, so if you have two original tabs, and click various links from each of the originals, you'll have two sets of colored tabs and can see which one came from where. I don't think anyone asked for this feature, and it was completely unnecessary, but it's not bad.

Middle-clicking the last open tab closes the browser completely. I've liked this feature about Chrome, and I'm glad IE has implemented it.

Overall application speed is significantly better than before - it opens and closes as fast as Chrome now, and when you consider how integrated IE has been in the operating system for the past 10 years or so, you really start to wonder what took so long.

Hardware acceleration is noticeable. IE9 does outperform Chrome and Firefox in some graphics-intensive tests. Whether those tests are legitimate or optimized for IE is debatable, but in any case, it proves that Microsoft does care about performance.


IE9 is nowhere near good enough to pull me away from Firefox and Chrome, but it's definitely a major step in the right direction. Personally, I'd rather see Microsoft abandon what it's not good at (browsers, source control, etc.) and let the industry specialists take over, leaving Microsoft to do what it does best (operating system, development tools, etc.). But that's never going to happen, so instead, I'll settle for them following accepted standards and providing a web experience that's satisfactory for casual surfers, serious web users, designers, and developers. If IE9 is a step in that direction, then I'll take it.

Tags: review microsoft programming browser tech

Comments:


Date: 2011-03-22 23:38:31
Name: Jon Davis
Website: http://www.jondavis.net/

"it's not available for Windows XP, so the millions of us who are still using XP (we're still on XP at work)" .. oh dear! You poor bastard, still using XP! o.O I remember when in 1999 people were insane to still be using Windows 95 ..


Date: 2011-03-23 07:04:01
Name: Joe Enos

It really doesn't bother me. XP is a good operating system, and aside from a few minor things (like the Start Menu searching or Ctrl-Shift-N), it does everything I need of it.


Date: 2011-03-23 10:23:00
Name: Jason H (via Facebook)

Are you surprised? I'm not.


Date: 2011-03-23 12:40:06
Name: Joe Enos

I was expecting it to be better - I didn't think it would be great, but I figured it would be better than it was.


Date: 2011-03-23 21:36:00
Name: Jason H (via Facebook)

I'vee grown to lower my expectations with Microsoft so if it turns out well you can be pleasantly surprised. For example Vista, what I expected. Windows 7, pleasantly surprised.

Add Comment

March of IDEs

Tuesday, March 15, 2011 06:35:19


You've heard of the Ides of March, the Roman name for March 15th, the day that Bluto killed Caesar in front of his palace.

Well, here's the "March of IDEs".

I composed this tune and recorded it with a 110-piece marching band, and set it to an animation designed using top of the line 3-D rendering software, with the help of several dozen artists, consultants, and hundreds of thousands of dollars worth of specialized equipment.



Tags: programming holiday

Comments:


Date: 2011-03-15 09:01:35
Name: Christopher R (via Facebook)

Wow, Joe, just wow. Well done! Star Wars intro look, a Final Fantasy-esque sound, and all the nerd cred of a Dev Days conference.

Add Comment

New websites

Wednesday, September 29, 2010 04:54:46


My web applications have been rebuilt from scratch, with better technology and coding standards. I've been spending a lot of my free time the last couple of months working on them. The visual design hasn't changed much - I'm not an artist by any stretch of the imagination, so I'm sticking with simplicity.

Blog (http://blog.jtenos.com/)

I started this blog back in May 2008, as a programming exercise. At times I've taken myself a little too seriously, especially during the 2008 election season, when I was a little stubborn and idealistic. But the last year or so, I've mellowed out, and tried to keep my content fun and light. I still don't have anything truly interesting or educational to say, but I'll at least try to keep it fun.

Updates with this version include:
  • Color scheme updated from dark red to gold.
  • Comments are now snappier and cleaner.
  • Paging has been added.
  • Things are just generally a little more consistent.

Personal Website (http://www.jtenos.com/)

This site is just where I've got various pieces of information about myself, like my rèsumè, education history, movie ranking, etc. No real user interaction here.

Updates include:
  • Color scheme updated from dark red to green.
  • Server language changed from C# to VB.NET - not my favorite thing to do, but it's always good to have some experience with different languages.
  • Website is built using ASP.NET MVC instead of traditional web-forms.

JTURL (http://jturl.us/)

This is my URL shortener, just built for the fun of it, like the blog.

Updates include:
  • Data access is now done properly, using SQL Server instead of MS Access (I used Access on the previous version to solve specific issues I had with my hosting database - trust me, I wasn't happy about it).
All three applications have also been updated as follows:
  • All AJAX is done using jQuery instead of ASP.NET AJAX. jQuery is a much better technology.
  • Database access is now handled using the Entity Framework, instead of a combination of LINQ to SQL and my custom data management project.
  • The application has been designed using n-tier architecture, with a real presentation layer, service layer (using ASP.NET web services), business layer, and data layer.

My fourth application, JTodo, is down indefinitely. That was probably my biggest project and would take the longest to re-write. I'll probably pick that one back up again sometime in the future, but I'm not in any hurry.

This was also a good time to change my hosting company. I was with GoDaddy, but unfortunately things haven't always gone well with them - there were some technical limitations with their service, and their customer support was simply awful. I switched over to a smaller company called RxHost, based in the United Kingdom, where I've worked directly with the owner, Chirag Desai, during my setup phase. Things have run reasonably smoothly - not perfectly, but Mr. Desai has been there for me to answer all of my questions and guide me through the process of getting things up and running.

I'm still working out some of the bugs - the site has had a tendency to be a little unresponsive since I've turned the switch on, but I'm working on getting that resolved soon. Please let me know if you experience any problems.

Tags: programming blog

Comments:


Date: 2010-09-29 06:06:00
Name: Dan J (via Facebook)

Vb? you comming to the dark side? ;)


Date: 2010-09-29 06:46:32
Name: Joe Enos

Yeah, I feel kind of dirty after writing all that VB. It's really an awful language.


Date: 2010-09-29 21:06:31
Name: Ricardo S (via Facebook)

Dude?! I am sure the rest of your code has some sort of Digital STD now... Good job! :)

Add Comment

NUnit - That Was My Idea

Wednesday, April 14, 2010 19:10:38


You know the "That was my idea" campaign, where people joke about how they are the ones who thought of one of the big improvements that Microsoft made with Windows 7. Recently I had my own "That was my idea" moment, only this one was real.

Back in December, the popular .NET unit testing framework NUnit released their newest version, 2.5.3. This version contains several enhancements, one of which is:

"Abstract classes may now be marked with TestFixtureAttribute to indicate that derived classes are to be treated as test fixtures. The abstract class is no longer marked as invalid."

A month prior, I posted a question to the NUnit Google Group, on this very topic. After discussion back and forth with Charlie Poole, who is one of the developers on the product and runs the NUnit blog, this issue was apparently given priority, to be resolved a short time later, making it into the next version.

Thanks to Charlie and the NUnit team for taking the time to discuss and resolve the issue. It was very nice to actually work directly with the developer, something I really wasn't expecting.

So even though someone else programmed it, and it probably only affects a handful of people worldwide, I'm still going to take credit for this enhancement, because it makes me sound important.

NUnit: That was my idea.

Tags: programming

Comments:


Date: 2010-04-14 19:35:52
Name: Melissa E (via Facebook)

Now that is awesome! Congrats and good job :)


Date: 2010-04-14 20:18:04
Name: Wendy E (via Facebook)

That's my boy!!

Add Comment

JTWeb 3.0

Saturday, January 09, 2010 16:32:51


I just released a new version of my website and blog. There were a lot of administrative changes that you won't see, but the major changes you will see are as follows:

Color scheme
The color scheme has gone from dark blue to dark red, and the blog entry background gradient is lighter, making the text easier to read. I was working on some fonts, but couldn't find a better set of fonts. I'm not saying that mine are the best choice, just that I am so unartistic that I can't find something better. I was also working on some animations like expanding pseudo-popup-windows, and although they worked very well in Chrome and adequately in Firefox, Safari, and Opera, Internet Exploder runs so slowly that I had to give up - the effects just looked like crap. Maybe I'll try some more ideas later, or maybe Microsoft will actually build a good browser someday that runs javascript fast (yeah, like that will happen).

Blog search
I've added the ability to search blog entries and comments for given text. With close to 150 blog entries, it may be hard to find old entries, even with the tags in place, so I figured it was time to introduce this function.

Comments awaiting moderation
When someone leaves a comment on a blog entry, unless it's coming from a trusted source, I have to approve the comment before it will appear. I added a feature so that if you leave a comment that is awaiting moderation, you'll see the comment yourself with a note telling you that it's awaiting moderation. This is one of many features that are in major blog providers like WordPress, that I'm incorporating into mine. In the future, look for things like OpenID integration, automated Facebook comment integration, and links to link-sharing sites.

Photos
There's a new page for my photos: http://www.jtenos.com/photos.aspx. This page allows me to organize my photos into albums. Right now there are only two albums: one from my vacation last summer, and one when I first got my cats. With this page and database solution, I can easily add more photos quickly without a lot of manual manipulation like I had to in the past.

Tags: programming blog

Comments:


Date: 2010-01-09 23:00:10
Name: Mat C (via Facebook)

One of these days, you'll go open-source CMS...


Date: 2010-01-09 23:05:54
Name: Joe Enos

It would make life a whole lot easier, but the whole reason I built it from scratch is for a programming exercise that grows and develops over the years, like a real application. It's forced me to learn about techniques and technologies that have helped me in real life at work.

Add Comment

Free Software

Sunday, November 29, 2009 19:04:12


I've got a new page on my website, Free Software, listing my favorite free applications for software development, data security, and other utilities. Some are open source, some are freeware, and some are free software, but no shareware or trialware.

http://www.jtenos.com/freesoftware.aspx

Tags: microsoft programming operatingsystem browser tech

Comments:

Add Comment

Custom Flags Enum Using Binary Numbers

Tuesday, November 24, 2009 21:33:01


Tonight I submitted another article to The Code Project entitled Custom Flag "Enum" Using Binary Numbers.

This article describes an incredibly awkward way of replacing flag enums in C# with a class that allows you to define values as binary numbers instead of decimal or hexadecimal.

The code itself is totally worthless, but it demonstrates some concepts that occasionally do come up in real life. Like my previous articles submitted, there's nothing really new here, but just something to think about.

Tags: programming tech

Comments:

Add Comment

ReSharper 4.5

Saturday, November 21, 2009 12:26:41


For the last few months, I've been using ReSharper 4.5 for Visual Studio 2008. Prior to that, I was using version 3 for Visual Studio 2005. Version 4.5 introduces some new features, and improved performance over 3.0. Below are my reactions to the new version, and ReSharper in general - many of these were probably new in 4.0, but since I just from 3.0 to 4.5 directly, I'm not going to try to figure out what was in 4.0 and what's only in 4.5:

ReSharper
ReSharper is a plug-in to Visual Studio that provides code analysis, cleanup, refactoring, templates, and IDE helpers in order to provide a better overall coding experience. It's an excellent addition to Visual Studio, and one that I have found to be extremely useful in day-to-day development. Alternatives such as CodeRush exist, but I haven't had any experience with them, so I can't really comment on how well ReSharper compares to them.

New in 4.5
I believe ReSharper 3.0 was limited to C# 2.0, so the new language features in C# 3.0 and 3.5 are all new in ReSharper 4. C# 3.0 and 3.5 introduced quite a few new coding techniques, designed to improve developer productivity and make code cleaner and more powerful, all while still using the 2.0 CLR. ReSharper helps you to take advantage of many of these new features. This is very nice when you have a 2.0 application and upgrade to 3.5. There are a lot of new features, but some of the ones I find most useful are:

Lambda expressions: ReSharper can replace old style anonymous methods with lambda expressions, so code like:
myList.Find(delegate(Foo foo) { return (foo.Id < 10); })
can be replaced by:
myList.Find(foo => foo < 10)
ReSharper suggests this change for you, and automatically refactors it if you accept the suggestion. Of course, like all suggestions/warnings, you can disable this if you like the old-fashioned style.

Auto-Properties
Auto-Properties are one of the best things to come out of C# 3.0. They allow standard properties to be be defined without defining the underlying fields that hold the data. This makes coding easier, debugging faster, and makes it just nicer to look at. ReSharper can automatically detect old-fashioned properties and fields that can be converted to auto-properties, and make the change for you, turning:
private int _id;
public int Id { get { return _id; } set { _id = value; } }

into:
public int Id { get; set; }
It also can find scenarios where you can convert, but it would change the meaning. It will do this for you if you ask, but it won't recommend it, so you don't accidentally change the meaning of your code. Scenarios like:
private readonly int _id;
public int Id { get { return _id; } }

can be modified to an auto-property with a private setter, but it would slightly change the meaning.

Object Initializers
C# introduced a feature called object initializers (also collection initializers), that allows you to initialize an object and set public property values, all in the same statement, borrowing some of the concepts from VB's With statement. This helps in two ways, first by keeping such initializations clear to avoid confusion in reading and writing, and second by allowing you to use a new one-time-use object as a parameter without declaring it as a separate variable and set the values one at a time. ReSharper can recognize when you have a new variable immediately followed by assignments to public properties, and replace the code with an object initializer (same for collections, but I don't see that as often in code):
Foo foo = new Foo();
foo.Id = 1;
foo.Name = "John Doe";

can be automatically converted to:
Foo foo = new Foo { Id = 1, Name = "John Doe" };

Naming Conventions
Other than the new language features, ReSharper also now can analyze your variable naming convention, and warn you when you've named variables inconsistently. For example, my convention is to name fields with a leading underscore and lowerCamelCase; properties, methods, events, types, and enum values as UpperCamelCase; local variables and parameters as lowerCamelCase; and constants and static readonly fields as UPPER_CASE. ReSharper lets you choose for each of these, defining a prefix, suffix, and casing style; it also allows for multiple possible naming types. So you can have methods as UpperCamelCase, but also define event handlers for GUIs as UpperCamelCase_Click or btnUpperCamelCase_Click, or however your event handlers look based on your conventions.

Solution-wide Analysis
ReSharper now can watch your entire solution looking for code errors in real time. So if you modify a class in one assembly that affects another assembly, ReSharper will tell you immediately, instead of having to wait until the next time you build your solution to find out that you screwed something up.

Performance
This is one area that ReSharper 4.5 is supposed to be a significant improvement over previous versions. Version 3.0 slowed down my system quite a bit, causing it to lock up for as much as 30 seconds fairly often, and ate up a ton of memory. My primary development machine wasn't really all that powerful, so I blame my hardware as much as ReSharper itself. With 4.5, I've noticed some improvement, but I think my hardware is still holding me back considerably. Sometimes it takes 15-20 seconds just to open an .aspx file, which can be frustrating. But once everything's loaded and in memory, performance is generally fine. Memory consumption is still quite high, especially with the solution-wide analysis running - my 25-project solution fully loaded can take 700-800MB of RAM, even with no pages currently open. While this may not be much in a powerful 64-bit machine with a lot of memory and new processor, the 4-year-old machine I'm using with just 2GB RAM doesn't like this too much. I'd expect ReSharper to perform well in a newer machine.

Conclusion
There are also a ton of small features that ReSharper provides, such as showing you your unused variables, using statements, and classes, providing code templates, reformatting your whitespace, and rearranging things like 'if' statements into ? or ?? statements, that just make ReSharper nice to have. There are some features such as integration with NUnit that can make writing test fixtures easier and faster. Many of the abilities of ReSharper are available elsewhere - Visual Studio 2008 added several things from 2005, and from what I've read, VS 2010 will provide a big jump as well (I haven't tried the beta yet, so I can't speak for them personally). FxCop provides many of the same code-analysis features, but it's an external program that doesn't work directly with the code the way ReSharper does.

For such a reasonable price, my opinion is that any development shop should give their developers a ReSharper license. It will keep them happy because they can code more productively and write better code, and will keep the development lead happy by making it easier to follow coding standards and conventions. And keeping developers and their supervisors happy is by far the most important thing for a company to do (from my point of view at least).

Tags: review microsoft programming tech

Comments:

Add Comment

Desert Code Camp November 2009

Saturday, November 07, 2009 20:43:00


Today was the newest Desert Code Camp here in Phoenix. This was the second time I've attended - the last camp was back in June, and was a lot of fun. This time around was also a big success. I attended nine sessions, and my reactions are below.

More Advanced Debugging with Visual Studio
This session, led by Michael Collins, introduced some Visual Studio debugging techniques that may aid in debugging applications, both in development and production. The techniques I was most interested in were DebuggerDisplayAttribute and DebuggerVisualizationAttribute - these two attributes allow you to more easily visualize objects in the debugger windows.

Objective-C for Java and .NET Developers
Objective C has been around for a long time, but I've never taken the time to learn anything about it. All I knew was that it was the language typically used for Macintosh and iPhone applications. This session, also led by Michael Collins, obviously couldn't teach a language in just an hour, but it did introduce some of the basics about Objective C and its syntax and basic use. Looks like a reasonable language that wouldn't be too difficult to learn, but I was suprised at how much it didn't look like C (or C++ or C#). I doubt I'll do any Objective C programming myself anytime in the near future, but I think it was worthwhile to see it in action, even if it was just for an hour.

CSS3: Behind the Website
At the last code camp, I attended Saul Mora's session, subtitled "CSS Sucks", where he discussed a lot of interesting things about CSS. Today was like a continuation, called "CSS Sucks Less", where Saul introduced some new parts of CSS 3 that are currently in the works, but not yet fully implemented in all browsers. The most exciting features I saw were the ability to render objects in 3-D and animate them, using only CSS and little if any javascript. Combined with HTML5, these new design techniques may soon take the spotlight from Adobe Flash and Microsoft Silverlight, two web technologies I'd love to see die.

Creating Your First Proof of Concept in Expression Sketch Flow
Visual design has always been my biggest weakness. I'm not an artist by any stretch of the imagination, and I don't think that will ever change. However, there wasn't anything else in this time slot that interested me, so I figured I'd check it out. Joel Neubeck ran this session, and it was very interesting. It was a short session (30 minutes), so there wasn't a lot he could show, but he did make it through a demo of the Sketch Flow concept, showing how you can quickly put together a "sketch" of your application GUI, and give it enough functionality for a quick demo or proof of concept, while being robust enough to be an actual start to the real project. I doubt I'll ever use Expression or similar products, but I'm glad I got the chance to check out the demo.

Javascript: The Untold Story
Saul Mora also led this session, which focused on some of the intermediate topics of javascript, such as prototypes and closure. It was interesting to see other developers' opinions and questions on this language.

Beginning iPhone Development
This was a fast-paced demonstration of how to build an iPhone application from scratch, using Xcode with Objective C. The techniques are significantly different from what I'm used to with Visual Studio - it seems more complex than necessary, but since iPhone apps are so incredibly popular these days, it must not really be that bad once you really get into it.

Learning Web Security with Web Goat
WebGoat was brand new to me - I've never spent much time on web security, other than ensuring my applications are designed properly to protect against SQL injection, XSS attacks, etc. As the speaker, Andrew Wilson, demonstrated, WebGoat is a great tool for learning about all kinds of potential vulnerabilities inherent in web applications. I'd be interested in learning more about this, as well as related applications like WebScarab.

Intro to jQuery
This was the topic I was most looking forward to - I've been wanting to learn about jQuery for a long time, but just never got around to it. This session was led by Remi, who demonstrated how simple it is to incorporate into a web application and get started. It's an exciting technology, providing the ability to manipulate the DOM, modify styles, and fire off AJAX, much simpler than using straight-up javascript. I'm looking forward to continuing learning about it and incorporating it into my own projects.

Intro to Azure
The last session of the day was about cloud computing with Windows Azure, Microsoft's version of cloud computing. Andrew Wilson also presented this session, and provided a good explanation of the concepts, advantages, and disadvantages of this new technology. Azure will probably play a huge role in technology over the next several years, so this is something I'm going to have to keep an eye on.

Of the nine sessions, the two that I got the most out of were Saul Mora's CSS3 presentation and Remi's jQuery sesssion. All of the sessions were interesting and educational, but I think these two technologies will most directly affect me in the short-term.

I'd like to thank Joseph Guadagno for putting this together, as well as all of the presenters and others involved in making this a success. I had a great time and look forward to the next one.

Tags: programming phoenix social tech

Comments:


Date: 2009-11-07 23:22:05
Name: Saul Mora
Website: blog.codedemora.com

Hi! Thanks for the write up! The tough part about presenting is missing other super awesome sessions. I'm glad you got something out of my talks today. It was a good time, even if I was pretty exhausted at the end of the day...


Date: 2009-11-08 01:00:00
Name: Christopher R (via Facebook)

jQuery makes client-side scripting fun and worth your while. And if you're really motivated, jQuery makes it much easier to make your pages dynamic without resorting to Update Panels. I can't imagine writing JavaScript without it.

Why do you want to see Flash and Silverlight die? What better solution exists for lightweight client-side applications that are easy to deploy and cross-platform?


Date: 2009-11-08 02:00:00
Name: Florencio M (via Facebook)

I wished i would have continued to code after ASU, the stuff you talk about sounds real interesting. Was the camp expensive?


Date: 2009-11-08 09:14:47
Name: Joe Enos
Website: http://blog.jtenos.com/

Chris:
My biggest beef with Silverlight right now is that it doesn't work for any OS other than Windows or Mac (there's Moonlight for Linux, but it really doesn't work). In my opinion, the web is the web is the web, regardless of what browser, OS, or hardware you're using.

Adobe is just plain evil - their stuff is bloated, not open, and not free. A big chunk of the evilness is in the implementation, so some of the problems like un-searchengine-friendly content, ludicrous ads, or badly-implemented video are developers' fault, not necessarily Adobe, but still, with HTML5, CSS3, and javascript working together, maybe we can start to see more consistency, and transparency in development.

But of course this is the real world, so I'm sure it will still get worse before it gets any better.


Date: 2009-11-08 09:16:06
Name: Joe Enos
Website: http://blog.jtenos.com/

Florencio:
It's kind of a fun career path - and it's not too late to get back into it if you want - there are plenty of free tutorials, free APIs and SDKs, and networking opportunities to get back into it - shouldn't take more than a couple years if you really wanted to.

Code camp is totally free. They're very developer-friendly - some of their core values are that they only hold them on weekends, it's always free, including food, and it's always by the community, for the community, so anyone can present, and anyone can attend.

Add Comment

JTURL

Thursday, September 17, 2009 23:22:01


My newest reinvention of the wheel, named JTURL, has been released for beta testing. This application is a link-shortener, similar to bit.ly, TinyURL, and a few dozen others out there in the web. The goal is to take long URLs and shorten them into something considerably smaller, for a variety of uses, most notably services like Twitter.

This project has been an interesting experience for me, which is really what my goal was from the start. I don't want to compete with the big players out there, and don't want to make any money on this. Instead, like my other projects, most notably this blog, I'm doing it for the fun, and to gain experience doing things I haven't done before. For JTURL, I've had to learn a little bit about URL rewriting (using UrlRewriter.NET), and also some charting (using Google Charts).

I was incredibly impressed with how easy Google Charts is to work with. Obviously more advanced needs would benefit from a full reporting solution like Dundas or Microsoft Chart Controls. But Google's simple API allows you to define data, formatting, style, etc., all in a single URL, and it returns an image instantly. This met my current needs of a couple of simple bar charts, and if I add more charts in the future, I'm sure I'll be able to make it work with Google.

I ran into a few bumps in the road while working on this project. My hosting provider, GoDaddy, has a limit of just 200MB for SQL Server databases, which is ridiculously small, especially considering the fact that I have 150GB (750 times more) disk space for my website. I ran out of space with my other applications, so I had to find a different solution. After trying unsuccessfully to run SQLite and SQL Server Express from the website (GoDaddy claims it's possible, but won't offer any help, and I couldn't get any help from the community), I had to settle on {cough, hack} Microsoft Access. I'm not happy about it, but it's a simple database, and I think I can get away with it.

The second problem I had was with charting. GoDaddy only allows the web apps to run in Medium Trust, which unfortunately means that the two third-party solutions I started working with, Microsoft Chart Controls and WebChart both failed for security reasons. This was incredibly frustrating, but it did lead me to learn about Google Charts, which I'm very happy with.

The application itself is very simple - you plug in a URL, and it returns a short URL. You can define your own custom code if you want, otherwise you'll get the next four-character (case-sensitive) value from the queue. You can easily retrieve information about a link, which includes the long URL, total number of clicks, and charts of clicks in the last 30 days and 12 months, as well as the ability to download raw data of all clicks for your own analysis. The "About" page contains links that you can bookmark, so you can create short URLs on the fly simply by clicking a button on your bookmarks toolbar.

I'm hoping to add more features to this in the near future, including a user schema, which would allow you to log in and track the links that you created. In addition, I'd like to incorporate some of the security features found in the major services, such as checking links against blacklists.

Feel free to use this application, but I offer no guarantee of uptime, or that your data will be 100% permanent. I don't anticipate any problems, and don't plan on any outages lasting longer than a few minutes during production releases, but you probably shouldn't use this for official documents that require a permanent link or 100% stability. You should be just fine if you want to use this for personal Twitter-type links.

If you experience any problems of any kind, please take a minute to let me know. I'm considering this a beta release, so it's entirely possible that there may be some outstanding bugs to work out.

http://jturl.us/

Tags: programming social

Comments:

Add Comment

JTBinCompare

Monday, July 20, 2009 07:12:36


I recently submitted my fourth article to The Code Project. It's a pretty straightforward piece of code - nothing new or exciting, but it's a utility that I found useful recently.

This application will accept two binary files as input, and simply determine if they are identical - something any file comparer can do, but this runs fast, with hardly any CPU or memory footprint.

http://www.codeproject.com/KB/cs/JTBinCompare.aspx

Tags: programming tech

Comments:

Add Comment

Desert Code Camp 2009

Sunday, June 14, 2009 15:20:43


Yesterday I attended Desert Code Camp here in Phoenix. This was a full-day event, taking place at DeVry University.

This was a great event, targeting programmers from all environments and languages, in a "by the community, for the community" format. The speakers are real-life experts in their field, and are there to teach, demo, and provide insight into their particular technology. Classes ranged from the basics, like intro to OO, to specific sessions like the new FILESTREAM feature in SQL Server 2008. Technologies ranged from specifics like Microsoft.NET or Ruby, to general techniques like table-less CSS web design.

I attended seven sessions: On-Site Optimization, Tableless Layout with CSS, Aspect Oriented Programming in .NET, ASP.NET MVC 101, ASP.NET MVC Advanced, New Features of C# 4.0, and Optimization Patterns: Reducing Memory Footprint in .NET.

Of these sessions, I was especially interested in aspect oriented programming, led by Andrew Wilson, and ASP.NET MVC, led by Scott Williams. Aspect oriented programming has always been somewhat of a mystery for me - I've worked with attributes, and even built my own on occasion, but never really understood how some of the popular frameworks like PostSharp worked - this session helped me to understand what is actually going on behind the scenes with these attributes. ASP.NET MVC seems to be an up-and-coming technology that potentially has a bright future in the .NET world - it still seems a little strange to me, coming from a WebForms background, but I think I'll give it a shot - it could be fun. The two hours of live demos and Q&A beats out reading half a dozen tutorials online.

Code Camp is always free to the community, sponsored by outside companies - I really didn't see any advertising anywhere, so these companies apparently are anonymous to the community. DeVry of course was a big part of the success, providing their campus and several classrooms for the event. Lunch was free - there were probably close to 100 large pizzas from Domino's, and dozens of Subway sandwiches, and there were muffins and danishes for breakfast.

I don't know when the next camp is coming, but I will definitely be attending. I highly recommend it to anyone in the software development industry, whether you are interested in hearing about new technologies or techniques, or if you just want to meet up with your peers throughout the valley.

Tags: programming phoenix social tech

Comments:

Add Comment

NDepend Review

Saturday, March 14, 2009 05:39:05


I've been trying out a product called NDepend (version 2.11), a .NET code analysis tool, for the past few weeks. NDepend was written by a Microsoft MVP named Patrick Smacchia, a software developer and author from France. NDepend provides dozens of useful features for reviewing and analyzing your .NET assemblies.

NDepend uses CQL (Code Query Language) as the backbone for its analysis. CQL is a query language based loosely on the SQL standard syntax, and is fairly easy to read and write, especially due to the similarities to SQL (SELECT, WHERE, ORDER BY, etc.).

Some samples of the CQL code:

SELECT TOP 10 METHODS WHERE NbLinesOfCode > 30 ORDER BY NbLinesOfCode DESC

SELECT TOP 10 METHODS
WHERE MethodCa == 0
AND !IsPublic
AND !IsEntryPoint
AND !IsExplicitInterfaceImpl
AND !IsClassConstructor
AND !IsFinalizer


Out of the box, NDepend provides a significant number of useful queries, such as identifying unused members, improperly encapsulated objects, and code quality features like types or methods that are too big or complex. These queries are all customizable - for example, you can change the "Methods with too many parameters" query so that it only returns methods with more than 8 parameters, instead of the 5 that comes by default - or exclude the query altogether. Adding queries to the analysis is just as easy - just write a CQL query and add it to the project.

In addition to the CQL query results, NDepend provides a few visual representations of the projects. The dependency graph is a diagram that shows each of the assemblies in your project, along with their relationship to one another. The size of the boxes and thickness of the edges represent properties of each assembly, such as number of lines of code, or code complexity.

NDepend Dependency

The metrics chart is a little more difficult to make sense of. It displays fields, methods, types, or namespaces as little boxes inside assemblies, with the sizes representing one of several metrics, like number of IL instructions or number of members. When dealing with large projects, the sheer number of types makes this collection difficult to look at. However, if there are any significantly large methods, types, etc. in your project, that may tend to jump out at you and give you the opportunity to review your code architecture.

NDepend Metrics

Once your NDepend project is ready (or you select a quick project and go with the defaults), you can fire it up, and it takes all of your CQL queries and graphs, and writes them to an HTML report, complete with query results, warnings, and summary information. This report is a great starting point for improving your project and customizing your queries.

There are plenty of options out there when looking for a code analysis and verification tool. In my opinion, what makes NDepend unique is how truly customizable it is, based on the CQL specification. Other code analyzers may allow you to build your own rules, but they typically are all based on what the tool wants you to be able to check. With CQL inside of NDepend, you, as an architect, can decide what's important to you, and query for it, regardless of whether anyone else thinks it's important.

I would definitely recommend NDepend for anyone interested in analyzing and improving their codebase.

Tags: review programming tech

Comments:

Add Comment

Convert Base Type to Derived Type

Friday, March 13, 2009 07:06:52


Last night I wrote another article for the Code Project, my third contribution to the site. This one describes a method to convert an object into a child type, a concept not normally used in object-oriented programming. It's definitely got a limited audience, but I feel that it's got some value.

The article can be found at:

http://www.codeproject.com/KB/cs/JTConvert.aspx

Tags: programming tech

Comments:

Add Comment

Trictionary

Wednesday, March 11, 2009 07:33:18


I just published my second article to The Code Project, one of the top resources on the web for software developers. My first article was published in January, and provided alternate methods for sorting a collection. This time, I am publishing the code for a "Trictionary", which is like a Dictionary, except with two values for a given key instead of just one.

This was an interesting project, and can be a useful technique.

The article can be found at:

http://www.codeproject.com/KB/cs/Trictionary.aspx

Tags: programming tech

Comments:

Add Comment

CollectionSorter

Saturday, January 31, 2009 11:50:55


This morning I published an article to The Code Project, a development site devoted to sharing code techniques and utilities. My article covers my JTCollections project that I built several months ago. JTCollections contains a class called CollectionSorter that provides alternate methods for sorting a generic List. Specifically, it can be useful for sorting a collection of objects by more than one property (the example I gave was sorting a list of Person objects by Age, then LastName). This type of sort is possible using standard framework techniques, but my method makes it easier for the developer to write and read code that accomplishes the sort.

The article can be found at:

http://www.codeproject.com/KB/cs/JTCollections.aspx

Tags: programming tech

Comments:

Add Comment

Evolution Of .NET Delegates

Friday, January 30, 2009 21:36:01


.NET delegates (also known in other languages as function pointers) have evolved significantly since the initial release several years ago. Mike Taulty recently posted a blog entry that does a very nice job explaining how things have changed over the years, providing excellent examples starting with old-fashioned delegates, moving on to anonymous methods, and finally lambda expressions.

This is a great place to start if you're trying to get up to speed on lambda expressions.

http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2009/01/28/anonymous-methods-lambdas-confusion.aspx

Tags: programming tech

Comments:

Add Comment

X Sharp

Thursday, January 22, 2009 21:18:07


There's a new programming language out there, called X# (X-Sharp). It's a programming language made up almost entirely of XML. Normally I'm a huge fan of XML - it is a single format for describing data, markup, configuration, and any of a dozen other purposes. But to use XML as a full programming language? That's a little absurd.

Here's a sample of what you can do with X#:
<xsp:pi xmlns:xsp="http://www.xsharp.org/2008/xxxml">
 <xsp:variable name="lang" type="string" select="'russian'"/>
 <library>
  <xsp:switch>
   <xsp:case test="$lang = 'english'">
    <book name="English dictionary" price="45.50"/>
   </xsp:case>
   <xsp:case test="$lang = 'spanish'">
    <book name="Aprenda Espanol en 1 manana" price="40.29"/>
   </xsp:case>
   <xsp:case test="$lang = 'russian'">
    <book name="OANH R3BLK HEAOCTATOHHO" price="37.45"/>
   </xsp:case>
  </xsp:switch>
 </library>
</xsp:pi>


I don't know about you, but I find real languages much easier to read - I couldn't imagine trying to write this nonsense.

Of course, X# is nowhere near the craziest progamming language out there. There are dozens of languages that people built for the sole purpose of being worthless and crazy languages. Some examples are:
  • Whitespace: My personal favorite: A language composed entirely of whitespace (space, tab, newline).
  • Java2K: A language whose functions only have a certain probability of doing what you intend it to.
  • brainf*** (Reader discretion advised): A programming langauge made up entirely of punctuation.
  • LOLCode: Written by an expert at the ridiculous "language" known as LOLSpeak.
  • Var'aq: A Klingon programming language.


Tags: programming tech

Comments:

Add Comment

Windows Communication Foundation

Saturday, December 06, 2008 13:28:06


This week I attended a 3-day training class from Interface Technical Training on Windows Communication Foundation (WCF). It was an excellent training class, led by Dan Wahlin, following Microsoft's official training modules, starting from the beginning, and including all major aspects of the technology, including basic setup, configuration, usage, debugging, security, transactions, and more.

If you're unfamiliar with WCF, it's a .NET technology that is designed to basically replace .NET remoting and web services. It uses a consistent API to build and consume services that can be exposed through TCP or HTTP, over an intranet, an extranet, or the public internet, or even over the same machine using named pipes. The services are defined in the code one time, and can be exposed using these different techniques simply by modifying the endpoints in the application configuration file. The services can easily be hosted in IIS or with a Windows service, and can be consumed very easily by using Visual Studio 2008, or with a little extra work using .NET command line commands.

The technology is very interesting, and looks like it will soon be the Microsoft standard for communication. Included out-of-the-box are features like encryption, detailed logging, and Reliable Messaging. WCF can also be backward-compatible with standard web services, with a simple configuration setting - of course, some of the more advanced features like decryption are unavailable using this technique, but it's a major part of what makes WCF such an exciting technology.

Tags: programming tech

Comments:

Add Comment

Javascript getElementById Behavior In Browsers

Sunday, October 19, 2008 17:05:14


I came across an issue not too long ago that caught my attention - using javascript to access elements behaves differently in IE and Firefox/Safari/Chrome. IE accepts casing differences - Firefox, Safari, and Chrome (let's call them the "good browsers") do not.

For example:

<span id="span1"></span>
<input type="button" onclick="clk();" value="clickme" />
<script type="text/javascript">
function clk() {
    document.getElementById("Span1").innerHTML = "Text";
}
</script>


Clicking the button in IE populates the span - in the good browsers, it does not, because it does not find an element with that ID.

In my opinion, the good browsers are "right" - elements should be properly cased. Your opinion may vary - please tell me if you disagree - I'd be happy to hear an argument in IE's favor.

In any case, this is just another reason to test in at least Firefox in addition to IE. A few extra minutes of testing can greatly reduce headaches in the future.

Tags: programming browser tech

Comments:


Date: 2008-10-20 06:45:11
Name: frank
Website: http://webbugtrack.blogspot.com/2007/09/bug-154-getelementbyid-is-not-case.html

yeah this is bug 154 in IE.

http://webbugtrack.blogspot.com/2007/09/bug-154-getelementbyid-is-not-case.html

it is actually much worse because not only does it fail on the case check, but it also returns elements that don't even have an ID! because it will match on the name attribute too.

The good news is that in IE8 they've fixed it.


Date: 2008-10-20 06:51:13
Name: Joe Enos
Website: http://blog.jtenos.com/

@Frank: Thanks for the link. Looks like IE8 is going to be worth looking into. Maybe I'll put it back into the 'good browser' list, if it really delivers all it promises.

Add Comment

.NET is a failure?

Monday, September 01, 2008 03:01:23


Some blockhead at PC Magazine wrote an article called 21 Great Technologies That Failed. It gives 10 Microsoft and 11 Apple examples of "failures". Most of the stuff is reasonable, like WebTV and Mac G4 Cube - but they somehow slipped .NET into the list, saying everyone went to Java, and that .NET "has nowhere near the scope that MS had envisioned back in 2002". What an incredibly stupid thing to say!

.NET not only caught up with Java, it surpassed it years ago as the dominant development technology. While there is still plenty of debate as to which is "better" (.NET gets my vote for most, but not necessarily all, situations), there is absolutely no doubt that .NET is nothing short of a tremendous success. Jeremy A. Kaplan and Sascha Segan (the writers of the article), and the PC Magazine editors who allowed this nonsense to be published, should all be fired immediately.

Tags: rant programming tech

Comments:

Add Comment

C# Extension Methods

Sunday, August 17, 2008 14:01:27


I apologize for not posting anything for a couple of weeks - I've been incredibly busy with work, and with a personal project which I hope to release within the next couple of weeks. I'm designing an "RSS feeder", which will allow users to view their favorite RSS feeds (blogs, news articles, etc.) in one centralized location. Once it's ready for initial beta release, I'll post an entry with more details on that product.

For now, I'd like to follow up on one of the new C# 3.0 features, Extension Methods. Basically, extension methods allow you to add methods to existing classes, even classes inside the .NET framework, by using a special syntax inside of a static class. A simple example follows:

// The following adds a method to System.String, which allows you to count the number of a particular character in that string.
public static class ExtensionMethods
{
    public static int CountChars(this string s, char c)
    {
        int counter = 0;
        foreach (char currentChar in s)
        {
            if (currentChar == c)
            {
                counter++;
            }
        }
        return counter;
    }
}

// You can call this code by simply using the dot notation on a string:
string textLine = "This is my string.";
int numberOfIs = textLine.CountChars('i');


Of course, you can do this the old fashioned way by calling:
int numberOfIs = ExtensionMethods.CountChars(textLine, 'i');

But the new way has a syntax like regular string methods, which makes it nicer to read, and more clear what you are accomplishing. In addition, with Visual Studio, the Intelli-Sense picks up this method when you type the dot after the string, so you don't have to think about where that method lives - all you need to do is find it in the Intelli-Sense list.

In ASP.NET web applications, I've found an additional use that is pretty nice. With most web apps, it's a given that you'll be using Session variables, Application variables, cookies, and other state variables. Extension methods can be very helpful in this aspect, allowing you to call individual variables with compiled code, instead of forcing the developer to handle proper casting and calling appropriate keys inside page logic. For example:

// Old way:
// In Global:
public const string APP_USER_KEY = "APP_USER_KEY";

// In page code:
AppUser currentUser = (AppUser)Session[Global.APP_USER_KEY];
// or
AppUser currentUser = {fill in the blank};
Session[Global.APP_USER_KEY] = currentUser;

// New way:
// In ExtensionMethods.cs (or any static class):
private const string APP_USER_KEY = "APP_USER_KEY";

public AppUser GetCurrentUser(this HttpSessionState Session)
{
    return Session[APP_USER_KEY] as AppUser;
}
public void SetCurrentUser(this HttpSessionState Session, AppUser appUser)
{
    Session[APP_USER_KEY] = appUser;
}

// In page code:
AppUser currentUser = Session.GetCurrentUser();
// or
AppUser currentUser = {fill in the blank};
Session.SetCurrentUser(currentUser);


There is a little more code involved when you do it this way, but it is much safer. You control the type of variable getting assigned to the session variable. You can define custom exceptions when setting or getting this variable - for example, if you get a session variable the old fasioned way, and it's null, your page code just gets a null, and you have to handle it in your page. Using extension methods, you can throw a custom NoUserLoggedInException if it's null, and let it get handled by shared code. Also, you can assign events to the Get or Set methods, so that your application can track when those variables are assigned or read. Or any other number of custom logic you can think of. The same technique can be used for Application or Cache variables, and also with cookies, by working with the Request or Response objects.

I've started incorporating this technique in my web applications, and it's worked really well so far. The only downside to this technique is that you need two methods, a getter and a setter - this is the "Java" way of accessing variables. With normal variables, I'd use properties with a get and a set section to accomplish the same thing. It wouldn't surprise me if C# 4.0 introduced something like this, but I haven't heard anything about that.

Tags: programming tech

Comments:


Date: 2008-08-17 14:13:23
Name: Joe Enos
Website: http://www.jtenos.com/

I've never understood why StringBuilder comes with AppendLine and AppendFormat, but not one combining both. How about:

public static void AppendLineFormat(this StringBuilder sb, string format, params string[] args)
{
sb.AppendLine(string.Format(format, args));
}


Date: 2008-08-17 14:16:19
Name: Joe Enos
Website: http://www.jtenos.com/

How about one for TryParse without using "out" variables:

public static int TryParseInt(this string str, int defaultValue)
{
int i;
try
{
i = int.Parse(str);
}
catch
{
i = defaultValue;
}
return i;
}


Date: 2008-08-17 14:22:30
Name: Joe Enos
Website: http://www.jtenos.com/

How about this one, to take a 2-d string array and convert it to CSV (implementation not included):
public static string ToCsv(this string[,] lines)
{
// Convert to CSV and return it
}


Date: 2008-08-17 14:24:00
Name: Joe Enos
Website: http://www.jtenos.com/

One more - to bind a web control to a collection of objects in one step:
public static void BindToControl(this ICollection coll, DataBoundControl dataBoundControl)
{
dataBoundControl.DataSource = coll;
dataBoundControl.DataBind();
}


Date: 2008-08-24 10:28:04
Name: Joe Enos
Website: http://blog.jtenos.com

I just realized that I had a boneheaded mistake in one of the samples in the entry (CountChars). This has been corrected. Maybe I should start actually compiling and testing code samples before posting them...

In any case, it's a trivial example, and wouldn't actually be used in real life. I'd probably be more likely to use something like the following (using lambda expressions):

return (s ?? string.Empty).ToCharArray().Count(currentChar => currentChar == c);

Add Comment

JTCollections 1.1

Monday, July 21, 2008 20:37:19


I just added a new version of JTCollections, version 1.1, to my downloads page. This contains a new method in the CollectionSorter class, utilizing a params array of generic Comparison delegates.

This will allow easy sorting by multiple properties, without the need for reflection (Version 1.0 was all reflection - those methods are still here, but a new one is added). This will significantly increase speed while sorting, with an easy to use syntax.

The fastest way to use this function is by using lambda expressions, as a shorthand syntax for defining Comparison delegates. An example follows, that will sort a list of strings first by length, then alphabetically.

CollectionSorter.SortList(myStrings,
    (s1, s2) => s1.Length.CompareTo(s2.Length),
    (s1, s2) => string.Compare(s1, s2)
);


Using the standard framework sort routines, you would have to put more effort into this. If you define a custom Comparison delegate or a Comparer object, you would have to run the first comparison (length), then check if that was nonzero, then if necessary, run the second comparison (alpha), and return the result. The more levels of sort, the more complex your code becomes. However, with the new technique in JTCollections, each additional layer is just one extra lambda expression, since you don't have to deal with the nonzero checks.

The CollectionSorter code is not complex at all, but it can save a significant amount of coding, without sacrificing performance.

Tags: programming tech

Comments:

Add Comment

.NET 3.0/3.5

Saturday, July 12, 2008 21:24:52


There are a million and one articles and blog entries out there devoted to .NET 3.0 and/or 3.5. But I'm running out of interesting topics, so I'll put my two cents in. I realize I'm a little late, but I recently started using Visual Studio 2008 and the .NET 3.5 Framework. So far, it's very impressive. I will discuss the features I have personally used and appreciate. Since I jumped directly from 2.0 to 3.5, I am not sure which of these came with 3.0 and which with 3.5.

LINQ
Probably the most talked about feature of the new framework is LINQ, Language INtegrated Query. This technology allows you to access data consistently, regardless of the source of that data. That source may be a SQL Server database, Oracle database, text file, XML file, or anything else you can think of. Once the data source is connected, the actual code to retrieve, update, or delete that data is the same. You don't need to write custom SQL statements, stored procedures, or complicated data management routines to access the data - all of that is handled for you.

I began using LINQ in my own applications a few months ago. Originally, my JTodo application used my own personal data management solution, JTDataManagement, which allowed retrieval and update of data in a standardized format. However, it required you to write your own get, save, and update stored procedures in a SQL or Oracle database. It worked very well, and made programming my applications much easier, but it wasn't perfect. I and created a new version of JTDataManagement that works with LINQ, by replacing my stored proc calls with LINQ calls, and replaced my database parameters with lambda expressions.

Anonymous Types
The first time I saw the keyword "var" in C#, I was worried that maybe it would be used improperly by lazy programmers who don't want to give variables strong types. That possibility exists, but as long as you use it for good, instead of evil, this technique can be very beneficial. So far, I have used it to generate data for display on a grid - you can create an anonymous type that defines a datarow without having to define a class to represent that object. That can save significant time when you just want to bind simple data.

AutoProperties
This is the most time and space saving feature I've seen with these releases. Traditional object-oriented .NET programming uses fields and properties (or methods) to access those fields. For simple objects, such as those that represent data tables, a class may contain a private field and a public property, something like:
private int _id;
public int Id { get { return _id; } set { _id = value; } }


This is necessary for every field in the class. The technique is common, and is the same as defining a public field - however, proper procedure dictates that fields are never public, so this was the only other way. With AutoProperties, there's a new way:
public int Id { get; set; }
is now equivalent to the previous code. At compile-time, this code is converted into something similar to the original - a private field and public property are generated, so the end result is the same. In the end, this can save a lot of work and a lot of code.

Type Initializers
This is kind of handy. It allows you to set the values of public members of a class at the same time as you create it. I haven't used it much, but it is an interesting concept, and has the potential for saving some time and code.

Person p = new Person() { FirstName = "John", LastName = "Doe" };

Extension Methods
This is incredibly cool. It allows you to add new methods to existing classes, even classes inside the Framework. If you need functions added to the String class, you can do it. In the past, you would have to utilize utility classes with static methods that accept these objects as a parameter. I haven't used it yet, but I am definitely looking forward to it.


I'm hoping to stay up to date with new technologies as they come out. I'm currently learning all I can about the ASP.NET AJAX standards, and I'd like to get to know Silverlight better over the next year or so. Hopefully, when the next version of the framework is released, I'll be up to date, and ready to start using it right away. Maybe then, I'll be in the first wave of bloggers.

Tags: microsoft programming tech

Comments:

Add Comment

NULL in Subquery

Thursday, June 19, 2008 22:00:03


I've come across an interesting phenomenon with regard to database queries. It's not a bug or flaw, but rather just an unexpected behavior (at least to me). If you have a query that filters records by a "WHERE ... NOT IN ()" clause, your query will return zero records if any of those results are null. For example:
SELECT 'TRUE' WHERE 'A' NOT IN ('X','Y','Z')
returns one record with the word 'TRUE', but:
SELECT 'TRUE' WHERE 'A' NOT IN ('X','Y','Z',NULL)
returns zero records. I would have expected it to be the same as the first, since 'A' is not null, and not one of X, Y, or Z. However, due to the way databases treat null values (or more accurately, lack of values), a match is not found. Adding to the confusion is the fact that calling "IN" instead of "NOT IN" works just fine when you thrown in a null. For example:
SELECT 'TRUE' WHERE 'A' IN ('A','B','C')
SELECT 'TRUE' WHERE 'A' IN ('A','B','C',NULL)

both return one record.

This behavior can be explained, and actually makes sense once you read why it occurs. However, until I discovered this, it caused me some confusion while debugging a complex query. A simple example follows - suppose you have a BOOKS and AUTHORS table, and want to find all authors who do not have any books attached to them, and not all books have authors. The following query:
SELECT * FROM AUTHORS WHERE AUTHOR NOT IN (SELECT AUTHOR FROM BOOKS)
returns zero records. There are several alternatives, such as:
SELECT * FROM AUTHORS A WHERE A.AUTHOR NOT IN (SELECT B.AUTHOR FROM BOOKS B WHERE AUTHOR IS NOT NULL)
SELECT * FROM AUTHORS A WHERE NOT EXISTS (SELECT B.AUTHOR FROM BOOKS B WHERE B.AUTHOR = A.AUTHOR)
SELECT A.* FROM AUTHORS A LEFT JOIN BOOKS B ON A.AUTHOR = B.AUTHOR WHERE B.AUTHOR IS NULL

The first of the three is probably the best, and the third is definitely the worst. But there are probably a dozen other ways of accomplishing the same thing.

These behaviors hold true for both SQL Server and Oracle, so my guess is that it's the same for all other major databases. For more information on why this happens, you can read the following, or just google it.

SQL Server: http://technet.microsoft.com/en-us/library/ms177682.aspx
Oracle: http://articles.techrepublic.com.com/5100-22_11-5319615.html

Tags: programming tech

Comments:

Add Comment

ASP.NET Compilation Options

Friday, May 30, 2008 12:29:03


There are two very distinct ways to build ASP.NET web applications in Visual Studio 2005 or 2008: Web Application projects, and WebSites. There are advantages and disadvantages to each type - I will discuss my personal experience with both of them - there are more differences, but these are what I have come across.

Option 1: WebSite
This is the new way of building a web application beginning with Visual Studio 2005. A page consists of an .aspx file and a single .cs/vb file. You never see the designer file. The compiler builds a designer file at compile-time, and includes that in the DLLs that it creates.

Advantages:
  • You can work on projects locally, over FTP, or even over HTTP with the appropriate setup.
  • You have fewer code files - you don't have to worry about the .designer file.
  • You can work on a website that's not even related to ASP.NET - using the IDE, you just select a folder, call it a website, and it gives you the Visual Studio experience for the files inside that folder.

Disadvantages:
  • You get multiple, randomly-named DLLs - as many as one per page. You have to either publish all of these DLLs, or combine them manually prior to publishing.
  • Your .aspx files are modified by Visual Studio to point to these randomly named DLLs, so what you have in source code is slightly different from what's actually published.
  • Debugging will occasionally throw you for a loop - there are various bugs that occur sometimes, because ASP.NET is handling your DLLs internally in temp folders rather than just using what you have.


Option 2: Web Application Project
This is the "classic" way of building a web application in Visual Studio - it is a "real" .NET project, where all of your .cs/.vb files get compiled into a single DLL, containing a class for each page, and any additional classes you include in your project are combined in the same DLL.

Advantages:
  • You end up with a single consistent DLL name.
  • Your .aspx files that are published are identical to what's in source control.
  • Visual Studio still does all of the grunt work (declaring control variables, attaching events, etc.).

Disadvantages:
  • You have twice as many code files (one .cs/.vb file and one .designer file for each page).
  • With Visual Studio, since it is treated as a regular project, you have to work on it locally and compile and publish yourself.


Given the major disadvantages of the WebSite type, I definitely recommend using the old-fashioned Web Application project. There are ways to convert the randomly-named DLLs into a single, consistent DLL, but it still isn't enough to make the process worthwhile.

Please feel free to disagree with me - I'd be interested in hearing any comments from people who prefer the WebSite style, and how they compile and publish their site.

FYI: If you're interested, here's the NAnt function I have used that merge DLL's together:
<exec program="${dotnet}/aspnet_compiler.exe" commandline="-p ${source} -v / ${target} -fixednames -u -f" />
<exec program="${webdeploy}/aspnet_merge.exe" commandline="${target} -o ${dllname}" />
aspnet_merge is available as part of the Visual Studio Web Deployment Projects, which you can download from Microsoft for free.

Tags: programming tech

Comments:

Add Comment

ReSharper Review

Sunday, May 25, 2008 11:19:49


I've been using a product called ReSharper, from JetBrains, for several months. The product is a plug-in to Visual Studio, and is designed to help refactor code, provide additional shortcuts, formatting, and other code maintenance services. I use several of the functions on a regular basis, and have experimented a little with the rest of the features.

My review follows:

The good:
  • As a plug-in to Visual Studio, all of the hints and shortcuts are right at your fingertips, as opposed to tools like FxCop, which checks your assembly and forces you to go find your problems before you can deal with them.
  • ReSharper informs you if you have any unused local variables or private members. It also tells you if a value assigned to a variable is not used in any execution path. This allows you to cut out unnecessary parts of your code, with no worries about breaking anything else.
  • It auto-generates your "using" statements at the top of your codefile, so you don't have to remember or look up namespaces that you don't use frequently.
    For example, if you add the following line of code:
    FileInfo fi;
    It will add a "using System.IO;" line to the top of your codefile, after confirming with you that this is the namespace you want to add - if there are multiple possibilities (for example, if you have a different FileInfo class in another referenced assembly), it will display both, and let you select which one you want to add to your codefile. In addition, if you have "using" statements that are not referenced in your code, it will tell you, giving you the opportunity to clean that up without any trial and error.
  • It tells you if a method can be made static, which gives you the opportunity to reduce the instance-level members of your class.
  • It provides a testing interface for use with nUnit, so you can run or debug tests directly from the IDE instead of a separate application.


The bad:
  • Ever since I've started using this, performance inside Visual Studio has been inconsistent - definitely worse than normal, sometimes much worse. It takes extra time to load projects, and occasionally locks up the IDE for 5-10 seconds for no apparent reason.
  • One of the default code refactorings it suggests is eliminating redundant "ToString()" calls. While this is fine in most cases, it sometimes is not appropriate. The idea behind the refactoring is to provide EXACTLY the same output with the same or better performance. Here's the classic example:
    int i = 4;
    string s = string.Format("I ate {0} pizzas", i.ToString());
    ReSharper will tell you to remove the ".ToString()" - which will provide the exact same result, since string.Format by default calls the .ToString() method on all objects. However, if you call ToString() yourself before passing to the method, you're passing a reference to a string. If you pass the int, it will box it to an object, pass that object in, and will unbox it back to an int before it can call ToString(), which is additional processing. Granted, it's a tiny amount, but anything that changes the flow of the program should not be done during refactoring.
  • While ReSharper provides very good support for basic nUnit cases, it does not handle certain situations. If you have two classes within the same namespace, where one is the SetUpFixture, and the other is the TestFixture, nUnit will run the SetUpFixture once prior to starting the testing process. ReSharper ignores the SetUpFixture, so those tests will not run properly, and must be run directly from nUnit.
  • It doesn't appear to function quite right for ASP.NET. VS2005 provides several ways to build a web application - you can build a "WebSite", or a Web Application project, which allows you to either work with partial classes much like Windows apps, or the old fashioned way, where all of your server controls and events are declared on a single codefile. ReSharper gets confused sometimes, depending on which model you are using.
  • One of the features is auto-generating parenthesis, braces, brackets, etc. While some people may find this handy, I don't, and I've turned this feature off. However, in some situations, they still come up without my approval, and usually just slow me down, since I have to correct them.
Overall opinion
I believe ReSharper has some great features, most notably the nUnit integration and the code optimization. However, for the amount of additional overhead it brings (processing time, money, and "undocumented features"), I don't believe it's worth it. I'd like to see a "light" version of ReSharper, or an open-source alternative, but that doesn't seem likely anytime soon. My only alternative is to build one of my own - keep an eye out on my downloads page over the next year or so, and I may just have something.

Tags: review programming tech

Comments:


Date: 2009-08-20 01:33:37
Name: David Ridgway
Website: http://web2asp.net

You can win your own personal ReSharper 4.5 license in the Cool Snippets Code-Off see here for details:

http://web2asp.net/2009/08/win-resharper-personal-licenses-in-cool.html

Alternatively get an extended 60 day trial and 10% discount coupon here:

http://web2asp.net/2009/01/resharper-extended-trial-period-and.html


Date: 2009-09-04 13:57:01
Name: Joe Enos
Website: http://blog.jtenos.com/

This was based on ReSharper 3.0. I'm currently using ReSharper 4.5 on VS2008, and I'm significantly happier with 4.5 than I was with 3.0. I may write something about 4.5 one of these days coming up, after I've had a little more experience with this version.

Add Comment

About.Me Facebook Twitter Google+ Stack Overflow LinkedIn FormSpring YouTube Yelp