2005 2006 2007 2008 2009 2010 2011 2015 2016 2017 2018 aspnet azure csharp debugging docker elasticsearch exceptions firefox javascriptajax linux llblgen mongodb powershell projects python security services silverlight training videos wcf wpf xag xhtmlcss

Firefox for ASP.NET 2.0 Developers Video Series



In September I recorded a video series I entitled the Firefox Web Developer Series. I've since renamed it to the Firefox for ASP.NET 2.0 Developers Video Series (clearly because the original title wasn't long enough). I put the project on hold because of the .NET 2.0 course I was teaching, which took almost all my time, but now I'm ready to take the time to get back into videos.

This series is for ASP.NET 2.0 developers who want to enhance their ECMAScript (JavaScript) skills and see how the powerful web development suite known as Firefox as simplify their lives as much as .NET 2.0 Framework does. In the series I use Beta 2 of Visual Web Developer 2005 and Firefox 1.0, but everything should be good for the final version of VWD2005 and for Firefox 1.5.

I will be releasing videos from this series over the next few weeks. For now, here is my introduction.

You can download the first video from the video below. You can download Visual Web Developer 2005 Express and Firefox 1.5 below as well.

Gosh I hate SPs/SQL (a.k.a. LLBLGen Rocks!)



…well at least in my C# code. That stuff belongs in the world of reporting, integration services, and other places which are NOT IN CODE. You couldn't get me to use ADO.NET anymore; it's such a pain for large projects. I love it for mass importing and when I do extremely dynamics such as report generation and a few other things, but for a static data access teir it's PATHETIC.

Not only is everything you type not strongly typed and therefore prone to error and has no color syntax; SQL (including SP calls) is just abrupt. You are doing this beautiful array of C# 2.0 greatness. Generic collections all over and BAM you see "select * from Person where..." Yuck!

Long live LLBLGen! If you don't know what LLBLGen is, you are completely missing out. I've been using it for months on all my projects and it's just downright awesome. It's basically LINQ...NOW. It allows you to use strongly typed .NET code to access your data WITHOUT writing any data tier code yourself. Not only that, the full blown enterprise edition is only $300. There is NO reason to ever write any data access layer yourself. It will pay for itself in about a DAY. I recommending getting a copy of LLBLGen even for your HOME projects!

All you have to do is point the LLBLGen app to the database, select the tables (and other entities) you want, and hit generate. It automatically creates a Visual Studio 2005 (or 2003 if you HAVE to use that icky thing) project for you. You can either include that project into your solution or compile the assembly and just us the compiled files. You only need to use LLBLGen again when you schema changes, which, as every architect knows...shouldn't be happening that often.

This rant is brought to you by the following sponsor...

DataSet dataSet1 = new DataSet( );
SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter( );


SqlConn1 = new SqlConnection(connString);
SqlConn1.Open( );


SqlCommData = new SqlCommand("GetDraftBox", SqlConn1);
SqlCommData.CommandType = CommandType.StoredProcedure;


sqlDataAdapter1.SelectCommand = SqlCommData;
sqlDataAdapter1.Fill(dataSet1, "MailList");


return dataSet1;

I was porting this old app from .NET 1.x to .NET 2.0 and I kept seeing stupid garbage like this. I got SO sick of it I decided to disconnect the logic tier and connect it to the LLBLGen access layer. Here's what I have now…

DraftMailCollection draftMailBox = new DraftMailCollection( );
draftMailBox.GetMulti(null);
return draftMailBox;

THAT'S IT!!! Short, sweet, strongly-typed, intellisense LOVES it, it's pretty (you gotta LOVE the VS2005 color scheme), and it's VERY easy to extend.

As another quick example here's how you would translate the following code into LLBLGEN code. First, the SQL code...

select *
from Person
where
PersonUserName = username and
PersonPassword = password;

Now the LLBLGen code...

   
PersonCollection people = new PersonCollection( );
IPredicateExpression filter = new PredicateExpression( );
filter.Add(PredicateFactory.CompareValue(PersonFieldIndex.PersonUserName, ComparisonOperator.Equal, username));
filter.AddWithAnd(PredicateFactory.CompareValue(PersonFieldIndex.PersonPassword, ComparisonOperator.Equal, password));
people.GetMulti(filter);

Yes, joining is also BEYOND easy and, yes, it databinds to GridViews with no extra work. I use it all the time in my ObjectDataSources.

OK one last example... well two. This one should be the straw that breaks...something. Look at this ADO.NET code (I'll leave some of it out though)

sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "insert into Customers (CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax )values(@CompanyName, @ContactName, @ContactTitle, @Address, @City, @Region, @PostalCode, @Country, @Phone, @Fax)";
sqlCommand.Parameters.AddWithValue("@CompanyName", companyName);
sqlCommand.Parameters.AddWithValue("@ContactName", contactName);
sqlCommand.Parameters.AddWithValue("@ContactTitle", contactTitle);
sqlCommand.Parameters.AddWithValue("@Address", address);
sqlCommand.Parameters.AddWithValue("@City", city);
sqlCommand.Parameters.AddWithValue("@Region", region);
sqlCommand.Parameters.AddWithValue("@PostalCode", postalCode);
sqlCommand.Parameters.AddWithValue("@Country", country);
sqlCommand.Parameters.AddWithValue("@Phone", phone);
sqlCommand.Parameters.AddWithValue("@Fax", fax);


sqlConnection.Open();


string id = (string)sqlCommand.ExecuteScalar();


sqlConnection.Close();

Some would say that it would not look so bad if the insert was in an SP. Um, ok...so you want to code in more than one place? No thank you. Also, what happens if there is no id to return? I've noticed that .NET 2.0 doesn't like that too much.

Now heres the LLBLGen code...

CustomersEntity customer = CustomersEntity( );
customer.CompanyName = companyName;
customer.ContactName = contactName;
customer.ContactTitle = contactTitle;
customer.Address = address;
customer.City = city;
customer.Region = region;
customer.PostalCode = postalCode;
customer.Country = country;
customer.Phone = phone;
customer.Fax = fax;
customer.Save( );


string id = customer.CustomerId;

Yeah...wow. Not only that, but in the SQL code you also have to do all that ADO.NET stuff. Not with LLBLGen, it's all in one!

I've been using LLBLGen for almost a year now and I have to say that my productivity has SOARED because of it. LLBLGen + .NET 2.0 + Firefox is a smart, er..., GENIUS match that should not be ignored, but rather ran towards!

To get a 30-day trial copy of LLBLGen follow the below link. I'm sure you will love it and for only $300, your manager will as well.

MSDN Nuggets WCF Mania!



I just did my weekly check of the MSDN nuggets page and found that Mike Taulty has been hard at work. He just released 6 more WCF videos.

  • Message Encoding
  • Message Patterns
  • Sessions
  • Instancing
  • Concurrency
  • Exceptions

Given the great quantity and quality of videos out there on WinFX technologies there is absolutely no reason people can't learn these new technologies. You don't need to read books, study whitepapers, or listen to those Geneva-convention-violating boring webcasts, all you have to do it click and pay attention. It's as if osmosis truely is a viable way of learning!

You can access these videos at the below link.

MSDN Nuggets

trycatch in .NET 2.0 - Note



Here is a comment Joe made about my previous post.

... One additional facet that will probably go (mostly) unnoticed is that you can throw exceptions across assembly boundaries, and the wrapping will occur based on the assembly-level attribute on the assembly whose catch block is being evaluated. This makes interoperability with code that isn't on the wrapping plan, e.g. COBOL or Eiffel, work seamlessly as you would expect.

...

This comment is rather hidden in how I have my page designed, but I thought it worthy of it's own posting anyhow.

trycatch in .NET 2.0 - Part 2



As I pointed out in a previous entry, try{}catch{} works differently in .NET 2.0 as it does in .NET 1.x. In 2.0, non-exception "throwables" are wrapped in a RuntimeWrappedException which can be caught by try{}catch(Exception ex){}, while, to catch then in .NET 1.x, you were required to use try{}catch{}. This led me to wonder 1) how does this work? and 2) is there even a purpose for try{}catch{} anymore?

So I started my research by… well, passing the buck, or going to the source, depending on your view on things. The first thing I did was ask Brad Abrams if he had some insights about this. He then forwarded me to Jonathan Keljo who I guess then forwarded me to Joe Duffy…sheesh what a line up! The best of the best of the best right there! Goodness, I feel like an ant…

Anyhow… here's the thing. Joe affirmed that there are at least two purposes for try{}catch{} in .NET 2.0

Here are his exact words…

(1) If your assembly doesn't have "wrapping" turned on;

(2) If you don't care to access the exception information via a variable. This can help to reduce the temptation to accidentally do a catch(Exception e){ //; throw e; } when you meant to do catch { // throw; }.

OK cool, now what about the mechanics? Joe explains that the wrapping of RuntimeWrapperException around non-exception throwables is due to the fact that C# and VB auto opt-in all assemblies to what they call "the wrapping plan". This means there is a RuntimeCompatibilityAttribute(…) on the assembly where, in this case, WrapNonExceptionThrows=true is set. When this is the case all non-System.Exception "exceptions" get wrapped into a RuntimeWrappedException, which, as Joe points out of course does inherit from System.Exception. Conversely, if WrapNonExceptionThrows=false is set, then there is no magical wrapping.

Let's see this all in action. But before we do, last time I wrote about this I forgot to what mention happens when you compile the below code (this is the same code from the previous blog entry about this topic)

// ThrowerHarness.cs
namespace ThrowerExample
{
    class ThrowerHarness
    {
        static void Main(string[] args) {
            try {
                Thrower.ThrowException( );
            }
            catch (System.Exception ex) {
                System.Console.WriteLine("System.Exception error: " + ex.Message);
            }
            catch {
                System.Console.WriteLine("Non System.Exception based error.");
            }

        <span style="color: rgb(0,0,255)">try</span> {
            Thrower.ThrowString( );
        }
        <span style="color: rgb(0,0,255)">catch</span> (System.<span style="color: rgb(43,145,175)">Exception</span> ex) {
            System.<span style="color: rgb(43,145,175)">Console</span>.WriteLine(<span style="color: rgb(163,21,21)">"System.Exception error: "</span> + ex.Message);
        }
        <span style="color: rgb(0,0,255)">catch</span> {
            System.<span style="color: rgb(43,145,175)">Console</span>.WriteLine(<span style="color: rgb(163,21,21)">"Non System.Exception based error."</span>);
        }
    }
}

}

Compiling this code actually gives the following warnings...

throwerlib.cs(16,7): warning CS1058: A previous catch clause already catches all
        exceptions. All non-exceptions thrown will be wrapped in a
        System.Runtime.CompilerServices.RuntimeWrappedException
throwerlib.cs(29,7): warning CS1058: A previous catch clause already catches all
        exceptions. All non-exceptions thrown will be wrapped in a
        System.Runtime.CompilerServices.RuntimeWrappedException

As you can see, we know at compile that try{}catch(Exception ex){} will grab the exceptions.

Here's the IL we are using, which contains the Thrower class and is referenced by the C# application.

// ThrowerLib.il
.assembly ThrowerLib { }


.class public Thrower {
    .method static public void ThrowException( ) {
        ldstr "ThrowException exception from the IL world!"
        newobj instance void [mscorlib]System.Exception::.ctor(string)
        throw
        ret
    }
.method <span style="color: rgb(0,0,255)">static</span> <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">void</span> ThrowString( ) {
    ldstr <span style="color: rgb(163,21,21)">"Weird exception!"
throw ret } }

Of course, there's our command syntax...

ilasm /t:dll ThrowerLib.il
csc Thrower.cs /r:ThrowerLib.dll

After a successful assembly and compilation, running this application gives the following output...

System.Exception error: ThrowException exception from the IL world!
System.Exception error: An object that does not derive from System.Exception has been wrapped in a RuntimeWrappedException.

Now, what about what Joe was saying about the RuntimeCompatibilityAttribute? Well, if we were to tack the following onto our existing class, we would get absolutely no warnings. Pretty cool...

using System.Runtime.CompilerServices;
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = false)]

Not only that, but here's the output as we would expect.

System.Exception error: ThrowException exception from the IL world!
Non System.Exception based error.

As you can see it did not wrap the exception. So, now, the picture of how things work and how to modify them is a bit more complete.

You can download the code for this entry by the link below.

Joe Duffy also has an explanation of this, although his is from the Beta 2 era (I only see one change -- WrapNonClsExceptions -> WrapNonExceptionThrows; but there may be more). Here is his article.

Video 1 (FWD) - "Setting up your Firefox Development Environment"



Finally! Here's the long awaited part 1 of my Firefox for ASP.NET 2.0 Developers Video Series. I will be releasing more parts to the series over the next few weeks.

This video is titled "Setting up your Firefox Development Environment" and contains valuable information on setting up your web development environment for maximizing efficiency. More setup information relating to this video will be mentioned in future videos as the utilities used in future videos of course also require setup.

Furthermore, this video is valuable not only to the professional web developer (as well as the non-professionals who still use tables for layout), but it's also valuable for anyone interested in maximizing their web experience.

Below is the link to part 1 of the Firefox for ASP.NET 2.0 Developers video series. You can download Visual Web Developer 2005 Express and Firefox 1.5 below as well.

New Blog Separation

Alright! So I decided to separate my professional information from my personal by creating a few separate blogs instead of having them all crammed into my website. From here on out, my website at davidbetz.net will be for my own stuff and this one here in particular will be for WinFX.

In the next few weeks I plan on putting up a lot of new information and hopefully I'll keep up a nice flow of blogging…

Constrainted try with retry mechanism for .NET 2.0



Lately I've been working on building a framework of abstractions and features that I feel are rather missing from my daily life. One of these features is a try/retry. In the past I used gotos and a ton of code to do this…but such extra coding was the nature of .NET 1.x. This is the world of .NET 2.0 and therefore I can take it to the next level! My new ExceptionFramework includes a few items to help me with exceptions and I figured I would share the following bit with the world.

using System;

public static class ExceptionManager { public static void TryWithRetryConstraints( Int32 retryCount, Int32 sleepTime, ExceptionConstraintCollection constraints, ExceptionTryBlock tryBlock, ExceptionCatchBlock catchBlock) { Int32 n = 0; retry: try { tryBlock.DynamicInvoke( ); } catch (Exception ex) { if (++n < retryCount) { foreach (Object constraint in constraints) { if (constraint is Type) { Boolean isException = false; if (((Type)constraint).Name == "Exception") { isException = true; }

                    <span style="color: rgb(43,145,175)">Type</span> parent = ((<span style="color: rgb(43,145,175)">Type</span>)constraint).BaseType;
                    <span style="color: rgb(0,0,255)">while</span> (!isException &amp;&amp; parent.Name != <span style="color: rgb(163,21,21)">"Object"</span>) {
                        <span style="color: rgb(0,0,255)">if</span> (parent.Name == <span style="color: rgb(163,21,21)">"Exception"</span>) {
                            isException = <span style="color: rgb(0,0,255)">true</span>;
                        }
                        parent = parent.BaseType;
                    }
                    <span style="color: rgb(0,0,255)">if</span> (isException) {
                        <span style="color: rgb(43,145,175)">Exception</span> thrownException = ex;
                        <span style="color: rgb(0,0,255)">while</span> (thrownException != <span style="color: rgb(0,0,255)">null</span>) {
                            <span style="color: rgb(0,0,255)">if</span> (thrownException.GetType( ).ToString( ) == constraint.ToString( )) {
                                Thread.Sleep(sleepTime);
                                <span style="color: rgb(0,0,255)">goto</span> retry;
                            }


                            thrownException = thrownException.InnerException;
                        }
                    }
                }
                <span style="color: rgb(0,0,255)">else</span> <span style="color: rgb(0,0,255)">if</span> (constraint <span style="color: rgb(0,0,255)">is</span> <span style="color: rgb(43,145,175)">String</span>) {
                    <span style="color: rgb(0,0,255)">if</span> (ex.Message.Contains((<span style="color: rgb(43,145,175)">String</span>)constraint)) {
                        Thread.Sleep(sleepTime);
                        <span style="color: rgb(0,0,255)">goto</span> retry;
                    }
                }
                catchBlock.DynamicInvoke(ex);
                <span style="color: rgb(0,0,255)">return</span>;
            }
        }
        <span style="color: rgb(0,0,255)">else</span> {
            catchBlock.DynamicInvoke(ex);
        }
    }
}

}

Here are some of the support items...

public delegate void ExceptionTryBlock( );
public delegate void ExceptionCatchBlock(Exception ex);


public class ExceptionConstraintCollection : Collection<object>
{
    public ExceptionConstraintCollection( ) {
        // Always declare default constructors!
    }
<span style="color: rgb(0,0,255)">public</span> ExceptionConstraintCollection(<span style="color: rgb(0,0,255)">params</span> <span style="color: rgb(0,0,255)">object</span>[] constraintSet) {
    <span style="color: rgb(0,0,255)">for</span> (<span style="color: rgb(0,0,255)">int</span> n = 0; n &lt; constraintSet.Length; n++) {
        <span style="color: rgb(0,0,255)">this</span>.Add(constraintSet[n]);
    }
}
}

This version allows me to retry only for certain types of failures. There is a simplified version which doesn't take the constraints, but this is one is a bit more useful for my scenarios (I actually think it's a good idea to always constrain it!) I found that the times I wanted to retry involved cases where I either wanted to retry based on a certain type of exception type or based on some text in the string.

Here's is how I use this version of the try/retry in one of my WPF applications. This is my little way of testing my laptop's RAM speed (as well as the CLR speed). I would grab 1GB of ram, free it, and quickly try to get it again (won't work). The below try/retry helps me get a feel or how fast .NET 2.0 can free up the memory and get it again (sometimes it CAN get the 1GB back).

First, I set up the constraints collection which holds the types and strings to which retries will be constrained to. This could of course be inline with the primary call.

ExceptionConstraintCollection constraints = new ExceptionConstraintCollection(
        typeof(OutOfMemoryException),
        "invocation");

Here is the actual call to the try/retry. I tell the try/retry manager how many times to retry (6), how many milliseconds to wait between each try (1000), what constraints to put on the try/retry (the above constraints collection), the logic to run as the try block (a delegate; anonymous in this case), and the code to run as the catch block (also a delegate; also anonymous in this case) and then let it do all the work for me.

ExceptionManager.TryWithRetryConstraints(6, 1000, constraints,
    delegate {
        group = new MemoryGroup();
        MessageBox.Show("Success");
    },
    delegate(Exception ex) {
        ExceptionManager.Report("Unable to allocate memory group.", ex);
    });

Now there are some obvious issues with this. The first: speed. Well, that's the nature of abstraction. You get ease of use and simplicity to life, but it costs a bit. The second is...this just seem weird, doesn't it? It just seems like there's a whole new bag of issues associated with this. Actually, this doesn't really bother me either. I'm keeping my code small enough so that I don't break the Ritcher anonymous delegate rule (never more than 3 lines of code in an anonymous block including comments) and I'm keeping in my mind that top level exceptions will really have the text of "Exception has been thrown by the target of an invocation." (which is, of course, true, but this means I better not be doing this stuff straight with COM interop!) As long as I keep that last one in mind I should be fine.

In any case, this has really been helping me out and have been proving to be a very powerful solution to the lack of a try/retry in the CLR.

Update



Here's a quick update on a few things…

First off the primary feed for this site is now at the below link:

Please change all your references to point to the new link. I'll be removing the old one in a few months.

Secondly, since someone had an aneurysm and decided it would be a great idea to confuse the entire planet, WinFX is now called .NET 3.0. Ergo, I'm changing the name of this blog to NetFX Harmonics for the time being.

Thirdly, I'll probably be posting much more content in the near future. Recently I was at an MSDN event and I was amazed at how little everyone (including the presenter) knew about new technologies. There were people who actually asked what SOA event was. I assumed everyone in the Microsoft technical community would be at least somewhat up to date with WinFX (Uhhhh duhhh .NET 3.0) information. Clearly I was wrong. I guess I should start publishing again!

New Design/New Name



For all you getting this via Atom/RSS (btw, thanks for subscribing), come on by and check out the new blog design. This time I went for a darker design giving a bit of a Vista-ish feel. Also, you will see I finally formally changed the name to NetFX Harmonics to agree with the INSANE decision to rename WinFX to .NET 3.0.

Finally, if you haven't done so already please start using the new feed at http://feeds.feedburner.com/FXHarmonics/ to replace to old one. I will soon be discontinuing the old feed.