SteelePrice.Net

Thinking outside the Box - Thought provoking insights on the Bleeding Edge

VB Requires Certain Keywords to be surrounded with Square Brackets

clock January 9, 2010 06:56 by author Steele

I was working on a conversion of a Visitor Pattern and this was not giving me much information to go on to resolve the problem:

See:  http://msdn.microsoft.com/en-us/library/bb534318.aspx

.NET Framework Class Library

Expression.New Method(ConstructorInfo, IEnumerable(Expression), MemberInfo[])

Creates a NewExpression that represents calling the specified constructor with the specified arguments. The members that access the constructor initialized fields are specified as an array.

The usage sample for VB:

returnValue = Expression.New(constructor, arguments, members)

 

This will not Compile, you will get the following error:
    Constructor call is valid only as the first statement in an instance constructor.

This is an erroneous error since that is not actually what we are trying to do.  We are trying to call a method that just happens to be the same name as a Constructor in VB.

To work around this, surround the New keyword with brackets:

returnValue = Expression.[New](constructor, arguments, members)

 

You will not be prompted to do this, nor will intellisense change it for you, it can be rather frustrating when you are not sure what the problem is. 
You will find this also happens when trying to use System.Enum at various times, this one however is not consistent it depends on what namespaces you have Imported.
This same problem occurs in different variations for other Methods or Properties with names that are special keywords, surrounding them with brackets is the solution.



I'm A VB (imavb.net campaign)

clock June 29, 2009 00:59 by author Steele

Who is the “typical VB.NET developer”? Is there one? There are millions of VB.NET developers in the world, and they each have their own unique story.

Here’s mine:

· How long have you been using VB?

Since V1. In 1992, I was looking for a replacement to QBasic when developing a Point of Sale Application for Windows.

· What industry do you work in?

Software Development. We are very diversified in our client base, touching Medical Records, Financial Services, Home Automation, Factory Floor Control, Online Gaming, Media and Training.

· How big is your development team?

We are a small shop in terms of size. We leverage Code Generation heavily to compensate for not having code monkeys to type in all the repetitive code that goes along most applications.

· What kind of apps do you most commonly build?

Line of Business Web Applications.

· What’s the most interesting app you’ve ever built?

That's Top Secret. :-) I am doing my most interesting app development right now! Think Silverlight, Home Automation and Green Technology. Details will come out soon.

· Please tell us about an app that you’re working on at the moment.

Currently one of my applications is a system for helping Non-Profit Organization raise funds and advertise. We built the Proof of Concept in Silverlight 1.1 and are currently re-engineering for release in Silverlight 3.

· What other technologies do you most commonly use?

Code Generation, this is a pretty broad definition... I use many technologies depending on the needs of my client. Some of those include: Silverlight, WCF, ASP.Net, ASP.Net MVC, MEF and nHibernate.

· What are some of your favorite VB features?

XML Literals, Background compiler, Linq syntax in VB, Case Insensitivity.

· What do you like most about VB as a programming language?

I like VB because I can use it everywhere I work (asp, silverlight, office) and still retain a sense of familiarity with my syntax. VB code is much easier for me to read and review than other more cryptic languages. Also pretty much EVERYONE can read and understand my code... even the perl developers. I can't really say that about any other language.

For other interviews in this series, please visit http://imavb.net.



Send a NameValueCollection ToXElement

clock June 23, 2009 07:12 by author Steele

I do lots of work with collections and one thing I tend to frequently is log all the information I can about a certain Request under certain conditions.

I found myself needing to serialize or save all the Request.ServerVariables.

Now, we could walk through the items, blah, blah, blah, this ends up being much easier with an Extension Method:

Public Module NameValueCollectionExtension
    <Runtime.CompilerServices.Extension()> _
    Public Function ToXElement(ByVal self As NameValueCollection, ByVal RootElementName As String) As XElement
        With self
            If RootElementName = Nothing Then
                RootElementName = .GetType().Name
            End If

            Dim xel As New XElement(RootElementName)
            If .HasKeys Then
                For i As Integer = 0 To .Count - 1
                    xel.Add(New XElement(.Keys(i), .Item(.Keys(i))))
                Next
            End If
            Return xel
        End With
    End Function

    <Runtime.CompilerServices.Extension()> _
    Public Function ToXElement(ByVal self As NameValueCollection) As XElement
        Return self.ToXElement(String.Empty)
    End Function
End Module

To use this in your code, save the above as a Module.

Then in your ASPX Code Behind or elsewhere applicable (like Silverlight), simply use this:

 

Dim data = Request.ServerVariables.ToXElement()

Or This:

 

Dim data = Request.ServerVariables.ToXElement("ServerVariables")

I took the consideration of allowing you to set a ROOT Element if you don’t want to use the Variable’s Type Name by providing an Override that accepts a String for the Name.

Et, voila! You have a perfectly good XML Snapshot of all the Request’s Server Variables:

<HttpServerVarsCollection>
    <ALL_HTTP>HTTP_CACHE_CONTROL:no-cache
              HTTP_CONNECTION: Keep(-Alive)
              HTTP_CONTENT_LENGTH:7654
              HTTP_CONTENT_TYPE:application/x-www-form-urlencoded
              HTTP_ACCEPT:image/gif, image/jpeg, image/pjpeg, application/x-ms-application, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*
              HTTP_ACCEPT_ENCODING: gzip, deflate
              HTTP_ACCEPT_LANGUAGE: en(-us)
              HTTP_COOKIE: ASP.NET_SessionId = *********************
              HTTP_HOST:localhost:22318
              HTTP_REFERER:http://localhost:22318/Public/MyPage.aspx
              HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618; OfficeLiveConnector.1.3; OfficeLivePatch.0.0; MS-RTC LM 8; .NET CLR 4.0.20506)
    </ALL_HTTP>
    <ALL_RAW>Cache-Control: no-cache
             Connection: Keep(-Alive)
             Content-Length: 7654
             Content-Type: application/x-www-form-urlencoded
             Accept: image/gif, image/jpeg, image/pjpeg, application/x-ms-application, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*
                     Accept(-Encoding) : gzip, deflate
                     Accept(-Language) : en(-us)
             Cookie: ASP.NET_SessionId = *****************
             Host: localhost:22318
             Referer: http://localhost:22318/Public/MyPage.aspx
             User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618; OfficeLiveConnector.1.3; OfficeLivePatch.0.0; MS-RTC LM 8; .NET CLR 4.0.20506)
    </ALL_RAW>
    <APPL_MD_PATH/>
    <APPL_PHYSICAL_PATH>C:\SourceCode\SomeProject\trunk\MyApp\</APPL_PHYSICAL_PATH>
    <AUTH_TYPE/>
    <AUTH_USER/>
    <AUTH_PASSWORD/>
    <LOGON_USER>DREAMSHOP\steele</LOGON_USER>
    <REMOTE_USER/>
    <CERT_COOKIE/>
    <CERT_FLAGS/>
    <CERT_ISSUER/>
    <CERT_KEYSIZE/>
    <CERT_SECRETKEYSIZE/>
    <CERT_SERIALNUMBER/>
    <CERT_SERVER_ISSUER/>
    <CERT_SERVER_SUBJECT/>
    <CERT_SUBJECT/>
    <CONTENT_LENGTH>7654</CONTENT_LENGTH>
    <CONTENT_TYPE>application/x-www-form-urlencoded</CONTENT_TYPE>
    <GATEWAY_INTERFACE/>
    <HTTPS/>
    <HTTPS_KEYSIZE/>
    <HTTPS_SECRETKEYSIZE/>
    <HTTPS_SERVER_ISSUER/>
    <HTTPS_SERVER_SUBJECT/>
    <INSTANCE_ID/>
    <INSTANCE_META_PATH/>
    <LOCAL_ADDR>127.0.0.1</LOCAL_ADDR>
    <PATH_INFO>/Public/MyPage.aspx</PATH_INFO>
    <PATH_TRANSLATED>C:\SourceCode\SomeProject\trunk\MyApp\Public\MyPage.aspx</PATH_TRANSLATED>
    <QUERY_STRING/>
    <REMOTE_ADDR>127.0.0.1</REMOTE_ADDR>
    <REMOTE_HOST>127.0.0.1</REMOTE_HOST>
    <REMOTE_PORT/>
    <REQUEST_METHOD>POST</REQUEST_METHOD>
    <SCRIPT_NAME>/Public/MyPage.aspx</SCRIPT_NAME>
    <SERVER_NAME>localhost</SERVER_NAME>
    <SERVER_PORT>22318</SERVER_PORT>
    <SERVER_PORT_SECURE>0</SERVER_PORT_SECURE>
    <SERVER_PROTOCOL>HTTP/1.1</SERVER_PROTOCOL>
    <SERVER_SOFTWARE/>
    <URL>/Public/MyPage.aspx</URL>
    <HTTP_CACHE_CONTROL>no-cache</HTTP_CACHE_CONTROL>
    <HTTP_CONNECTION>Keep-Alive</HTTP_CONNECTION>
    <HTTP_CONTENT_LENGTH>7654</HTTP_CONTENT_LENGTH>
    <HTTP_CONTENT_TYPE>application/x-www-form-urlencoded</HTTP_CONTENT_TYPE>
    <HTTP_ACCEPT>image/gif, image/jpeg, image/pjpeg, application/x-ms-application, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*</HTTP_ACCEPT>
    <HTTP_ACCEPT_ENCODING>gzip, deflate</HTTP_ACCEPT_ENCODING>
    <HTTP_ACCEPT_LANGUAGE>en-us</HTTP_ACCEPT_LANGUAGE>
    <HTTP_COOKIE>ASP.NET_SessionId=**********</HTTP_COOKIE>
    <HTTP_HOST>localhost:22318</HTTP_HOST>
    <HTTP_REFERER>http://localhost:22318/Public/MyPage.aspx</HTTP_REFERER>
    <HTTP_USER_AGENT>Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618; OfficeLiveConnector.1.3; OfficeLivePatch.0.0; MS-RTC LM 8; .NET CLR 4.0.20506)</HTTP_USER_AGENT>
</HttpServerVarsCollection>

 

Remember, this is NOT limited to HttpServerVariables, it works with ANY NameValueCollection.

This can be a huge amount of data depending on what you are doing.  You can always use Linq to get a subset of the Collection, or .Remove() some known XElements, like ALL_HTTP, ALL_RAW or All the empty nodes before persisting or displaying this.

Extension Methods offer a great solution to common problems when you don’t have access to write a Method for the Class.  They are also great for making shortcuts to common scenarios for work you do with Collections or Conversions.

Click here for another useful extension for NameValueCollection by Tony Cavaliere from which I derived this idea, Thanks for sharing Tony!



Misfit Geek Podcast - Does VB have a Future? &hellip; Absolutely.

clock June 19, 2009 03:30 by author Steele

Lisa Feigenbaum from the .NET Managed Languages Group about Visual Basic .NET. Does VB.NET have a future ? Does Microsoft love C# more than VB.NET? Listen and find out.

Of course it does… As Lisa says, it’s not in Microsoft’s best interest to stop moving VB.NET forward.

Yes, there is a bias about VB in general, but 99.9% of this comes from VB perception and not VB.NET.  VB.NET is completely different and people do not realize it’s only related by SOME (not nearly all) syntax.  The underlying IL is not really any different from C# when compiled.  This is a marked difference in the way VB works internally.

Overall, I think this is a good refresher for people who (quite wrongly) think VB is going nowhere.  VB is here for the long haul, bashers need to just get over it… You will see VB.Net development continue for the rest of most of our careers.  That makes me a very happy developer. 

Anyone still bashing VB is A) ignorant of what VB.Net really is and B) no different from being a racist, beating a drum that is stupid and irrelevant.

Misfit Geek Podcast



VB Extension Methods for Repeating Strings

clock June 15, 2009 07:23 by author Steele

I was looking for a way to create some Repeating Strings easily and I got tired of typing.

You may notice that the String() constructor will allow you to create single repeating characters, but it does not let you create repeating Strings.

For example, creating this is simple:

Dim zeros As New String("0", 10)

which results in a String of ten zeros or “0000000000”.

This is a great way to make String with a single repeating character.  So how to I repeat whole strings?

The first technique would be to use StringBuilder.Append, which is pretty efficient and apparently what most people use.

Then I saw this fairly old (2005) post from Eddie Garmon.

As a result, here is my VB version of String.Repeat()

Public Module StringExtensions
    ''' <summary>
    ''' Maximum performance for Initializing a repeating String
    ''' </summary>
    ''' <remarks></remarks>
    <Runtime.CompilerServices.Extension()> _
    Public Function Repeat(ByVal input As String, ByVal count As Integer) As String
        If input Is Nothing Then
            Return Nothing
        ElseIf (input = String.Empty) OrElse (count < 1) Then
            Return String.Empty
        End If
        Return String.Join(input, New String(count) {})
    End Function
End Module

NOTE: in VB, don’t forget the {} Initializer or String uses the wrong Constructor and you get a compile error.

Now I have a really simple way to create repeated strings:

Dim repeated = "<col/>".Repeat(5)

or this:

Dim repeatThis = "<td></td>"
Dim repeated = repeatThis.Repeat(5)

which is easier to type than:

Dim repeated = String.Join(input, New String(5) {})

In addition, it’s going to handle the basic Error Trapping so I don’t have to repeat that every time too.



More intuitive way to page Linq queries.

clock April 9, 2009 03:05 by author Steele

I found this today from Paul Welter… Easier way to page Linq queries.

Here is the Proper VB Equivalent Snippet:

Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Public Module PageQuery
    ''' <summary>
    ''' Easily get Pages for an IQueryable(Of T)
    ''' </summary>
    ''' <typeparam name="T">any IQueryable supported Type</typeparam>
    ''' <param name="query">The Query we are Paginating</param>
    ''' <param name="page">Page Number (starts at 1)</param>
    ''' <param name="pageSize">Number of Items per Page</param>
    ''' <returns>Reduced query with a single page of information</returns>
    ''' <remarks></remarks>
    <Runtime.CompilerServices.Extension()> _
    Public Function Paginate(Of T)(ByVal query As IQueryable(Of T), _
                                   Optional ByVal page As Integer = 1, _
                                   Optional ByVal pageSize As Integer = 10) As IQueryable(Of T)
        If query Is Nothing Then Return query
        Dim skip = Math.Max(pageSize * (page - 1), 0)
        Return query.Skip(skip).Take(pageSize)
    End Function
End Module

I found this to be more intuitive for doing this:

Dim query = From row In db.Invoices _
            Order By row.InvoiceID Descending _
            Select row
Return query.Paginate(page, pageSize).ToList()

Instead of this:

Return query.Skip(skipRows).Take(takeRows).ToList()

Notes: VB doesn’t like the Namespace in the C# Sample code and it’s not needed for us.  Also remember you should always use an Order By when Paging.

I also added a trap so that if the Query is Nothing it doesn’t throw a NullReferenceException.



XML Literals, WCF and LINQ

clock March 30, 2009 15:39 by author Steele

My most recent article is up at Visual Studio Magazine Online.

I choose to pick the tools that apply directly to a problem I need to solve and use those new capabilities to enhance my productivity. Even more power and flexibility comes when we can take several of these capabilities and combine them for a unique solution to a problem.

We're going to look specifically at three pieces of the framework that can be combined to provide a new technique. This technique helps in writing more responsive ASP.NET pages, while at the same time making the code more readable. The three technologies are: XML literals, Windows Communication Foundation (WCF) Factory Services and LINQ. XML literals and LINQ are new in Visual Basic 9 (VB9). LINQ gives us a common syntax for querying just about any data, be it SQL, XML or objects. Even though WCF has been here for a while, the out-of-the-box readiness for building factory services is little-known. Here we'll show you how to create WCF services without changes to config files for endpoints, behaviors and bindings.

Visual Studio Magazine Online | On VB: XML Literals, WCF and LINQ

I look forward to presenting more of these in the future. I will also be talking about this these techniques for a while, hopefully at the next Desert Code Camp.

Code samples for this article: Templating with XML Literals



Visual Basic QuickStarts and How-to Topics for the Composite Application Guidance for WPF and Silverlight - February 2009

clock March 25, 2009 04:43 by author Steele

 

The Composite Application Guidance for WPF and Silverlight is designed to help you more easily build enterprise-level Windows Presentation Foundation (WPF) and Silverlight client applications. It will help you design and build enterprise-level composite WPF client applications—composite applications use loosely coupled, independently evolvable pieces that work together in the overall application.

This is a great set of guidelines for building WPF, Silverlight Applications and shows you how to build a common framework between the two.



EntityDB: The next great Microsoft tool (if they would just make it)

clock May 20, 2008 08:38 by author Steele

Reading in the Industry blogs, official samples and documentation provided with MS SQL Server 2005+, Visual Studio 2008 and Linq to Sql and the Entity Framework, you will get the impression that we have a tremendous ability to efficiently decipher how to interact with a Database.  Additionally, Industry leaders have led us down a path of Code Generators, Designers and the separation of UI Design from functional Object code; read "Astoria" and/or "MVC" here...

Didn't CASE do this sort of thing for us years ago?  Didn't it also fail?  There is huge amount of traffic about the topic of "Falling down when you hit a threshold" and insistence that all things should be built ultra-scalable.  OK, that's great if you love to write plumbing.  I for one, don't. What if that could be done for you, with the most efficient options always at your disposal; of course with the opportunity to tweak and extend to meet a specific need.

While there are many great arguments to be had over what is exactly ultra-efficient and those who think they have a better method must be able to override and extend the selected generation of code that is offered by not only being able to write that code, but also to inject it into the Generated Code (or at the least allowed to edit the templates) produced by Visual Studio.

If you don't already know why this is so important, we need to first look at the massive shift in Business Software Development and where we are going to be running most business applications.  We used to run all our apps on our own hardware, inside our own network and everything was under our tight control.  While this model still applies to much corporate development, I believe it will become less and less used as a cost effective alternative to a HOSTED solution.  Pricing of hosted solutions have plummeted in recent years, in fact I am almost willing to bet that the cost of electricity alone using hardware just a few years old would cover the cost of a hosted solution.  And what happens when I DO need to scale, How do I add 20 servers to the Web Farm overnight?  Staffing requirements and maintenance of hardware start to become totally offset when we look at this model. I CANNOT BUILD A SERVER CHEAPER THAN I CAN HOST ONE!  That is the real bottom line.

I would wager that MOST applications would run just fine on a hosted solution with one machine doing all the work, at least in the beginning, or at least with a hoster that gives you Web on one machine and your DB on another.  Are we talking about every solution here?  No, but I think we are talking about a gigantic sector of the market that is currently all but ignored by the provided tools we have at our disposal.

Don't get me wrong here, we have GREAT tools available and more coming, do they target what is really needed?

First lets look at the three new primary tools given to us by Microsoft.  WCF, Linq to Sql and the Entity Framework.  WCF provides a great pipeline to pass data between our UI, Business Objects and Database, but it just plumbing.  Linq to Sql and EF provide a great way to interact with a Database IF and ONLY If you have a proper database in place first.

What does this mean to most data-driven development projects?  It means they either need a DBA, or they need to hire one for the portion of the application that defines the database.  This is one reason Migrations for Ruby on Rails has gained so much popularity, it hides this chore.  Most of us don't care about the DB, it's just a place that holds data.  Some of you can go on and on all day about the subtleties of databases but that is completely outside the scope of what I am talking about here. Not only will Migrations create a DB and Schema around what your App needs, it will also keep it up to date with changes made by any developer that can be easily stored in Version Control software like SVN or TFS.

This is what the Designers for Linq to Sql and/or Entity Framework need to do for us.  I really don't mind changing my Linq to SQL Apps over to Entity Framework if it will allow us to focus on one great technology.  It's great that they can operate against a currently created database, but they should also create one (IN AN OPTIMIZED WAY) when one does not exist.  It should create Stored Procedures if I tell it to... Even if we are migrating a legacy application, I would still like to see what a tool spits out for me.  I just might use the new techniques.  There are tons of ways to move data from one schema to another, again, outside the scope of this article.  So back to the scope...  EF Does a great job of creating an interaction between Database and Business Objects, but it doesn't help us rapidly create a NEW model without an existing database and I think this is important in two ways, first and foremost, I don't want to write any plumbing code to do this.  The tools are smart enough already to do almost all the work for us, it can go just a little bit further and create the expected interaction that solves most of the interaction of the database work for us.  I can create a Model with the EF Designer by adding Properties and Associations, but it won't go and create a database around that model.

I should not have to know about how the interaction happens, just that it does and that it does so in a fairly efficient manner.  If I lose a certain percentage of performance due to layers, then so be it if I can create my application 10 times faster.  If the tool developers choose to implement change tracking in a DataContext or Object Context that is great, do so in a way that makes sense for the CODE developers to use, not require me to go hire Database professionals to argue about the proper plumbing or storage techniques.  Linq ALREADY knows how to create efficient SQL, if it did so in code generation vs. dynamically at runtime who cares?

We can host a solution out in the cloud so should we need to be worried about the optimization of how our application persists its data?  Certainly there is is need to cover legacy applications and all the DBAs running around out there, that is well covered right now.  What we seem to be missing is the ability for competent application developers to create Rich Internet Applications (read Silverlight and Ajax) and have the data persisted without a bunch of plumbing and tweaking.

What is NOT covered is the ability to rapidly envision, design, develop and deploy solutions destined to live on a Hosted Solution -- even if it is "hosted" internally.  This solution will most likely have a distinct separation between UI, Business Objects and Database, but do I really need to see those distinctions in my code?  Not really.  Do I really need to spend the time to wire up all the Databinding when the MetaData already knows what I need to do?  No Way, a tool can create that for us.  It can already look into our metadata and see what we need to do to hook up a DataGridView to a table.

I would venture to say that the tools are already here, they just don't work the way we need them to so we can build these applications quickly.  I spend MOST of my time Creating a Database, then working on plumbing and interactions between the Database and the UI, I should not have to do this any more.  Microsoft did a fabulous job of giving us a database that can scale with us as our application grows.  We have SQL CE, SQL Server Express and SQL Server Enterprise to grow with us, we can use SQL CE for Mobile Apps and offline stuff, wouldn't it be wonderful if I did not have to architect that portion of the solution any more?  I am talking about the people who do not have the luxury of a full time DBA.

Of course, the solution is there, staring us right in the face, the answer is the Designer for Entity Framework.  If this Designer could be used to build out the Database, and track the Schema changes, then it would take down part of the battle, just a little more work and it could completely remove the NEED (we should always have the option to extend and modify though) for us to write anything between the Business Objects and the Database.

We should not need to write Serializers for Silverlight, WCF or anything else, the tools already KNOW how to do that, they just don't.  The MetaData is there, let's use it.  Rob Conery's Subsonic and ActiveRecord shows there is interest in such a tool, but I say this tool needs to come from Microsoft and it needs to be built into the current generation of tools we are using or are being pushed to use (aka Linq).  With Rob and Phil working AT Microsoft why can't they contribute some of that knowledge over to the ADO team and get this into the EF Tools we need.  Pablo, Mike, Dinesh and the rest of the ADO Team are doing a great job so far, but they are only touching on what we really need.  The newest version of EF finally gets a way to do disconnected graphs which is a step towards the goal thanks to Danny Simmons.

These tools need to work seamlessly with Linq and allow me as a developer to write applications with little or no concern for how my data is persisting.  I want to create Controls that I can offer to my UI which work seamlessly with Ajax or Silverlight and not require me to write a ton of plumbing just to move things back and forth from one layer to another.

This is the challenge for the new world of development.  We have already moved to a hosted world and our tools need to move there with us. But what do I know, I am a VB developer first and foremost... This is what I know, my customers are asking me to create these applications and to create them really fast.  I can choose to use the tools I know best or I can branch out and find something new.  The problem here is that I have already invested years of time to learn the tools I am using and they are simply not doing what I need them to do to make my job truly easier. 

My Invoice Object doesn't really need to know what DataContext my Customer Object lives in and I as a developer should not have to be concerned about that in the slightest.  I should be able to freely take a Customer I loaded from Invoice "A" and assign it to be used for Invoice "B" without worrying what context it came from, Invoice "B" just needs to know its a valid Customer or that it is a new one I just created without me forcing something into the plumbing to test it.  It should know how to roll itself back when I cancel changes, etc.

With Generics and XML Literals, VB is a Top Notch Code Generator.  Kathleen has proven that here and Karl talks about Metadata and what we can do with it over here... We don't need Yet Another Code Generator.  We need something that works with the existing modelers and designers and just makes our life as developers easier.  It needs to be INSIDE Visual Studio and we need to be able to work with the templates.  I should not need LLBLGen or MyGeneration or CodeSmith or SubSonic to do something Visual Studio pretty much already knows HOW to do, it just doesn't.  I don't need another designer that works with an existing database, I need the CURRENT Designers to Make the Database AND the plumbing.

I personally think this should be the direction for the next revision of Visual Basic.  VB IS the glue that puts the framework together, sure you could also do it in C# (if they added XML Literals...) but VB is already geared for it so why not enhance it's productivity even further by giving us a way to be far more productive than we are today.  This does not require any great shift in the tools we already have, it just requires Microsoft to use them smarter and provide us the keys we need to open the door.



DebuggerWriter for Linq to SQL

clock May 1, 2008 06:12 by author Steele

I needed to find out exactly what was being submitted by DataContext.SubmitChanges and didn't want to use SQL Profiler.

I ran across this post by Kris Vandermotten and have converted the code to VB for anyone else who may need it.

This is now always in my Utility.vb file that gets attached to most of my projects.

 

    
Imports System.Diagnostics
Imports System.Globalization
Imports System.IO
Imports System.Text

''' <summary> ''' Implements a <see cref="TextWriter"/> for writing information to the debugger log. ''' </summary> ''' <seealso cref="Debugger.Log"/> Public Class DebuggerWriter Inherits TextWriter Private _isOpen As Boolean Private Shared _encoding As UnicodeEncoding Private ReadOnly _level As Integer Private ReadOnly _category As String ''' <summary> ''' Initializes a new instance of the <see cref="DebuggerWriter"/> class. ''' </summary> Public Sub New() Me.New(0, Debugger.DefaultCategory) End Sub ''' <summary> ''' Initializes a new instance of the <see cref="DebuggerWriter"/> class with the specified level and category. ''' </summary> ''' <param name="level">A description of the importance of the messages.</param> ''' <param name="category">The category of the messages.</param> Public Sub New(ByVal level As Integer, ByVal category As String) Me.New(level, category, CultureInfo.CurrentCulture) End Sub ''' <summary> ''' Initializes a new instance of the <see cref="DebuggerWriter"/> class with the specified level, category and format provider. ''' </summary> ''' <param name="level">A description of the importance of the messages.</param> ''' <param name="category">The category of the messages.</param> ''' <param name="formatProvider">An <see cref="IFormatProvider"/> object that controls formatting.</param> Public Sub New(ByVal level As Integer, ByVal category As String, ByVal formatProvider As IFormatProvider) MyBase.New(formatProvider) Me._level = level Me._category = category Me._isOpen = True End Sub Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) _isOpen = False MyBase.Dispose(disposing) End Sub Public Overloads Overrides Sub Write(ByVal value As Char) If Not _isOpen Then Throw New ObjectDisposedException(Nothing) End If Debugger.Log(level, category, value.ToString()) End Sub Public Overloads Overrides Sub Write(ByVal value As String) If Not _isOpen Then Throw New ObjectDisposedException(Nothing) End If If value <> Nothing Then Debugger.Log(level, category, value) End If End Sub Public Overloads Overrides Sub Write(ByVal buffer As Char(), ByVal index As Integer, ByVal count As Integer) If Not _isOpen Then Throw New ObjectDisposedException(Nothing) End If If buffer = Nothing OrElse index < 0 OrElse count < 0 OrElse buffer.Length - index < count Then ' delegate throw exception to base class MyBase.Write(buffer, index, count) End If Debugger.Log(level, category, New String(buffer, index, count)) End Sub Public Overloads Overrides ReadOnly Property Encoding() As Encoding Get If _encoding Is Nothing Then _encoding = New UnicodeEncoding(False, False) End If Return _encoding End Get End Property Public ReadOnly Property Level() As Integer Get Return Level End Get End Property Public ReadOnly Property Category() As String Get Return _category End Get End Property End Class

 

To use this for troubleshooting DataContext issues simply set the DataContext.Log = New DebuggerWriter such as this:

 

Dim tran As New Transactions.TransactionScope
Using tran
    db.Log = New DebuggerWriter
    db.SubmitChanges(ConflictMode.ContinueOnConflict)
    'rollback by disposing without complete
    tran.Dispose()
End Using

 

This will submit the changes, spit out all the SQL code to the Debugger Window and roll everything back.



News

no news is good news?

Posts by Date

<<  March 2010  >>
MoTuWeThFrSaSu
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar

Disclaimer

Copyright ©2003-2009
H. Steele Price, IV

All opinions are my own, not necessarily those of my employer, your mother, or any government agency.

Sign in