Phil posted on November 28, 2009 20:32

Just a quick recent thought. As I am watching the PDC09 videos made available free online by Microsoft, I got me thinking more about the recent changes/improvements in VB. A new feature for VB 9 in 2008 was XML Literals. You know, writing/pasting plain old XML into your source code.  Like this simple example:

dim myXML =  <custs>
<cust ID="5" Name="Oscar" />
<cust ID="9" Name="Ernie" />
</custs>

My thoughts went like this:

  • hey, cool! you don’t have to wrap it in strings, thank goodness.
  • hmm, why would you be hardcoding XML anyway?
  • that belongs in a resource file somewhere, really.

I basically have written off this feature as demoware, really, until I saw the video of Lucian Wischik’s session “Code Like the Wind with Microsoft Visual Basic 2010”. There was one really intriguing feature in his demo of a VB Silverlight component.

The key task that lured me in was a fairly simple demo dealing with HTML replacement. Great application of the technology! If you’re being careful to write your HTML as XHTML, then this is a great way to use VB’s XML Literals feature. Here’s the simple use case from the demo:

  • clicking an input button
  • replacing the innerHTML of a div

 Lucian-InnerHTML

The great thing I like about this that you don’t necessarily have to mess around with string.Format() or string.Concat() and all those other small speedbumps. i.e.

myDiv.innerHTML = string.Format("<p><i>Hello {0}</i><hr/><b>Hello everyone, welcome to VB XML Literals</b></p>",customerName)

Perhaps take it a step further and externalize those snippets if you like. My first thought on that snippet was: “document.getElement? WHAT? Get some jQuery in there! Doh - it’s code-behind!” Interesting how it’s declared as an Object while being assigned Browser.HtmlPage.Document. Likely it’s a quick/dirty demo artifact.

Useful in the Real World?

There’s always the balance of demoware vs. actual best practices vs. your development standards. I am leery of hardcoding markup in your compiled app. It’ll take an application redeploy to change that markup to something different.

Of course, in the real world, you’d probably be loading something user-specific here, like a customer’s name, shopping cart, etc. where you’d be wanting to string.Format() all those details anyway. Heck, you’d even want to iterate through your invoices, tweets, or whatever collection you’d want to start building a simple <ul> with your collection of business data in <li>.

Even if it was a simple replacement of XML, with some business logic around which snippet to insert, consider if you'd had externalized those snippet into an XML resource file(s), you could refer to them easily, although not as simple as strongly typed XML literals compiled in a resource file. There’s that balance again – ease of coding vs. maintainability in production.

I always like discovering new personalities at Microsoft. I’ll be RSS’ing Lucian’s blog, looking forward to seeing any great content he might share.

Real World Production Examples?

Do you know of any examples in the real world of VB and XML Literals in a production app? If/when I find some, I’ll post a link here!


Posted in: visual basic  Tags:
Actions: E-mail | Permalink | Comments (0) |

cruft_folder_2Usually when jumping into a new OS, I largely disregard the built in programs. My typical thought is that they’re for newbies, grandmas, and otherwise lack the features that other 3rd party programs offer. (think MSPaint, Getting Started, Fax/Scanner Wizard, Welcome to XP videos, etc). It got so annoying that I actually go out of my way on new installs to make a new folder on the Start Menu to bury those shortcuts.

Windows 7 Snipping Tool Special-K  brought the new Windows 7 Snipping Tool to my attention, and it’s most definitely a productivity enhancer. My snap judgement was “really, a built-in Windows tool?”, but after 10 seconds of using this tool, I knew I’d be using it immediately in place of my current screenshotting process.

Screenshotting

Here’s my typical OLD style of creating a screenshot. Typical use case here is to send a cropped & marked-up screenshot by email, or perhaps for insert into Windows Live Writer.

paint_net Total Clicks/Buttons = up to 15

  • Alt-PrtScn
  • Open Paint.NET
  • Ctrl-V
  • Start cropping
  • Change the color selector to red or yellow or something to make your selection stand out
  • Select the Oval or Rectangle tool to highlight what you need. When Oval doesn’t line up the way you want, Ctrl-Z, and try again x3.
  • Either: a) Select All –> Ctrl V into a new email or b) Save As –> enter a filename, save to desktop. Open email client (Gmail or Outlook), and attach to email as attachment.

Stop the Insanity with Win7’s Snipping Tool

 

Windows 7 Snipping Tool Total Clicks = max 5

  • Keyboard Start key
  • Type sn as if you were typing snipping tool. Hit Enter.
  • Start cropping
  • Highlight, markup, erase, recrop to your heart’s content.
  • Click the Email button to generate a new email message with the image embedded. Launches the default mail client. Works well with Outlook and Gmail.
snip_types

Being the artsy type, you’ll probably want to screenshot in different ways. I think the typical use-case would be the rectangle, whereby you click-drag a rectangle to highlight the parts of your screen that you want. Otherwise, you have the ability to screenshot:

  • a window you choose (it outlines the window when you hover over it, Win7 style)
  • free-form, lasso-style!
  • the entire screen

 

Caveats (or not!)

  • doesn’t work well when you’re trying to capture something from your Start menu!
  • not a caveat – it’s super easy to snip/screenshot your entire toolbar. Select Window Snip, and click your toolbar. The tool captures just your toolbar, from Start button to minimize button. Awesome!
  • not a caveat – saves as .png by default. Yes, Paint.NET does this as well.
  • not a caveat – turns out the .exe isn’t named winsnip.exe (which I would have loved), but rather c:\Windows\System32\SnippingTool.exe

snipping_tool_windows_7_markup_msdn


Posted in: windows 7 , shortcuts , microsoft  Tags:
Actions: E-mail | Permalink | Comments (0) |
Phil posted on November 5, 2009 05:07

Perhaps you’ve got a collection of objects that you want ordered/sorted. I recently did. Perhaps you want them displayed in a non-deterministic manner or sorted randomly each time you write to an HTML view or otherwise consume that collection. Indeed, I did. (OK, lame shtick over…)

Randomize()

So imagine we’re working with a List of Customers.

data

Problem being, we don’t really have anything non-deterministic to work with. We could do this in SQL Server:

SELECT *
        ,(sin(Cust.ID * rand())) AS R
FROM Cust
ORDER BY R

This though, puts your presentation logic in your data tier. Maybe you don’t care, maybe it’s not a big price to pay. I wanted to take it up to the presentation tier and do this sorting right before binding or writing these objects to the page.

Taking the lead from Bruno Silva, I immediately realized this was the seed of the algorithm that I was looking for. Here’s my modification of Bruno’s algorithm:

   Random r = new Random(); 
   myCusts.OrderBy(x=>(r.Next())); //bind this, or use in a foreach

The call to r.Next() is obviously the key. Each object as it is evaluated in the OrderBy() will get a new random number associated with it. Celebrate good times!

Turn It Into an Extension Method

I haven’t written much here about how much I love extension methods in the .NET CLR 3.0. I can’t count the number of times that I’ve created a static ‘utility’ method that did something like this:

  • take in an object of some kind.
  • modify it.
  • return it back to the caller.
  • caller reassigns the return back into the object that it calls.

Rather than the above, I’ve created an extension method that I’ll be able to call whenever for any collection that implements IEnumerable. It’s trivial then to write the extension method for IQueryable.

ExtensionMethod I’ve submitted my Randomize() extension method over at ExtensionMethod.net. What a great site, by the way, kudos to those guys for taking user submissions and helping grow the use of this feature in .NET.

 

http://extensionmethod.net/Details.aspx?ID=236

public static IEnumerable<t> Randomize<t>(this IEnumerable<t> target)
   {
       Random r = new Random();
       return target.OrderBy(x=>(r.Next()));
   }


Posted in: development , c# , linq , extension methods  Tags:
Actions: E-mail | Permalink | Comments (0) |
Phil posted on November 2, 2009 01:10

I recently had the privilege of working on a contract where the main goal of the project was to port/convert the web project and associated assemblies (business and data layers) from one .NET language to another. The other tasks were around fixing a handful of defects, and adding a few bits of functionality. The project was hard-capped at a set quoted number of hours, so there was little room for error.

The solution consisted of three .NET 3.5 projects:

  • ASP.NET web project – this project had roughly 10 pages and a handful of helper classes in the App_Code directory. This project already had VB as its language.
  • Business Layer Assembly – 6 classes brokering access to the data layer. Very much pass-through code with not a lot of business logic in between the web layer and data layer. There were moderate amounts of looping and updating of the business object properties.
  • Data Layer Assembly – the DL included the matching DL classes for each of the 6 classes above. The most challenging (code for the converter here was the Linq-To-Sql code.

Sizing Up the Task

The largest part of the project for me was the conversion task. All told, the conversion/translation involved:

  • 12 .cs files
  • ~55 methods
  • ~500 lines of code

I had previously figured the smartest way to spend my time was not rewriting code by hand. If there’s anything a developer should be good at, it’s evaluating and choosing to use the right tool for the job. That’s a major part of your job as a developer!

Enter the Telerik Batch Converter Tool

A quick Bing search brought me to a few options: online-in-the-browser-cut-and-paste style, or full file upload.

I first noticed that Telerik had a batch converter tool. This allows the user to upload a handful of source code files, and the converter will do its magic on the server. This was right up my alley, as it meant that I didn’t have to laboriously open each code file, copy, paste, and make a new source code file.

Telerik Batch Code Converter Upload

The initial load of the page shows the user 3 input boxes where you can browse to the location of your code file. Obviously for those ASP.NET web projects needing conversion, you don’t need to upload your .aspx files, but rather your code-behind files. This particular project was using code-behind files, rather than inline <script>.

Aside: It’s amazing to me that some developers are using <script> tags to hold their code which belongs in a code behind  Page.aspx.cs or .vb file. Obviously it’s a style or configuration issue, but to me it just feels wrong. I like the separation of .NET code and HTML markup. Perhaps it’s just a side effect of trawling the web for source code, and people are choosing to format their .aspx to include code within, instead of posting separate files.

Back to the task. The process is easy:

  • Browse one-by-one for the files you need converted. Make sure to remember to pickup your Linq-To-Sql’s .designer.vb or .cs class. That’s the file where your SQL Server tables are mapped to POCO [Plain Old CLR Objects ;) ]
  • Upload, Convert and Download a .zip containing the artifacts of the conversion. Included are all the converted files, and a Report.txt file.

Telerik Batch Code Converter Done

Results & Conversion Report

The real answer you’re looking for is right here: the results of the conversion with the Telerik tool, for me, were 100%. Absolutely no problems were had in compiling a new project with these new files added to it. I can’t believe it was so easy. Here’s the report that Telerik included in the .zip (irrelevant or repetitive bits snipped):

Conversion Error Report (Created [datetime])

Every time a possible conversion problem is located, the file name, problem severity , and problem description are recorded. There are three levels of severity:

    Warning    = code will convert and will likely work, but conversion may need manual improvement
    Minor    = code will convert, but it will likely need manual correction to work
    Major    = code will not convert. It must be modified before used with converter

There are also general issues to remember when converting web sites:
    - Events connected with the Handles syntax in VB will not work in C#. Events must be connected in code or in the control markup.

Report Details:
================================================
1: TEST.designer.cs    Minor    Your region may not convert from C# to VB if quotes have not been used to name the region. Make sure       region name is surrounded in quotes before using code.
2: TEST.designer.cs    Minor    Your region may not convert from C# to VB if quotes have not been used to name the region. Make sure       region name is surrounded in quotes before using code.

End Report (11 total matches)

Easy & Accurate Results

I can’t believe it was so easy to convert the code. It really meant that I could spend more time ADDING VALUE to the project by way of adding features and fixing defects than by the drudgery of converting source between languages. The price to pay for the Telerik online batch tool was the included comments at the bottom of each source file. That’s an easy price to pay! Can I say now a BIG THANK YOU to Telerik, NRefactory & SharpDevelop, and Todd Anglin @ Telerik for making this tool free and available for the world at large!

TelerikBatchCodeConverter_Comments

Stitching your Converted Files Back Into a Project & Solution

The tricky work is to then take the output of the converter and create a new project. For each of the assembly projects, I:

  • copied all the reusable non-.NET files from the old solutions - *.xml, *.config, etc.
  • made new .vbproj projects in Visual Studio
  • for the web project, Add Existing Files –> Select all your converted files.

For those converting a web project, just create a new Web Project. For each of your pages, modify your .aspx  to have its Page directive to have the appropriate configurations:

<%@ Page Language="VB" MasterPageFile="~/SomeMaster.master" CodeFile="SomeFile.aspx.vb"

Then do the same Add Existing Files routine for all your converted .aspx.vb or .cs files.

Quick Online .NET VB and C# Converters

In some cases, you’ll find snippets online (yes, the bathroom wall of code) where you actually like the snippet, but rather want it in the language of your choice. I recently searched for and used both these tools when needing to convert a large snippet of VB to C#.

Try DeveloperFusion’s online code conversion tool - http://www.developerfusion.com/tools/convert/vb-to-csharp/

Telerik’s Code Converter is of course, likely to be mostly used for its quick online code converter - http://converter.telerik.com/


Posted in: linq-to-sql , c# , vb , shortcuts , best practices  Tags:
Actions: E-mail | Permalink | Comments (0) |

As developers, we usually have these things (file most of these under ‘duh!’):

  • well powered desktop machines. OK, mostly desktop. Maybe you’ve got a big honkin’ laptop-with-great-specs-but-called-a-desktop-replacement.
  • a need to deploy/test/mess about in another machine. You don’t want the cruft of your development machine to get in the way of the operation of your target environment.
  • the desire to test out a new tool: a beta/RC OS, a new beta of Visual Studio, a new server product (SVN), a community technology preview (CTP), or some other package that you just don’t want to push to your current Dev server. Hands up if you even have a ‘Dev’ server other than your machine?

In the last 4 years, I’ve usually run into something dev-related that I really wanted to get my hands dirty with. Yes, the shiny-object developer syndrome. The old way was to install that piece on your Dev machine. Months would go by, and you’d (theoretically) dirty up your registry, and contribute to the eventual slowdown of your Windows install. The logical solution at that point would be to format and repave your Dev machine. Looking forward, and a bit contrary to the point I was just making, I don’t get the sense that Windows 7 will succumb to the bloat and eventual slowdown. That said, it doesn’t invalidate the need & convenience of virtualization.

Free & Many Options

Enter the full on assault of free options for virtualizing operating environments. We really have an embarrassment of riches. Perhaps I am late to the party, but the freeness of the VM solutions is jolting:

My Fave Virtualization Platforms

Doubtless you know the benefits of running VMs. Lower TCO in terms of number of physical metal boxes, lower cost of electricity to power and cool, etc. For me, it’s the ability to pop (uh, Remote Desktop) into a new machine on the ‘network’ and install/configure/test whatever I am working on. The ability to mount ISOs for OS and app installation is just another kick ass speed benefit. Even better are the instances where you can download a pre-configured VM. Check out ALMWorks’ turnkey Bugzilla and Subversion virtual machines.

Sun VirtualBox

sun_virtualBox Great product here. Easy creation of virtual hard drive disks, mount ISOs, and a nice looking application overall. Its config files are all XML, and messing around with file locations is easy. The one thing about VirtualBox is that it doesn’t run VMs out of a single window, but rather opens a new window in your (in Windows anyway) taskbar. This is different from VMWare, likely due, in part, to VMware being headless.

My big want out of VirtualBox is the ability to run headless. It’s the one big feature that would allow me to adopt it as my one and only VM product on the Developer’s machine. Sun releases this product for Windows, Mac and Linux hosts, and I think they’ve done a great job. The release frequency is stunning! Keep up the good work, Sun! 8/10

VMWare Server

vmware-server I first got into VMWare Server as I was encouraged to run Windows 2003 on the job. Previously I had only used the Microsoft Virtual PC products, which were decent. The killer bit that won me over on VMWare Server was that it is HEADLESS. The machines can startup and shutdown in parallel with your host OS. Excellent feature for those who would expect those services to be up 100% of the time that your dev machine is (Dev or Test SQL Server, Active Directory services, build machine, etc). This is basically gives you the Ron Popeil method of running additional machines: set it, and forget it (curse you, 90’s infomercials).

The kicker for me today is that VMWare does NOT make Windows 7 64-bit signed drivers. Absolute killer for me during the Release Candidate of Windows 7, and still today at Win7’s release. Reading the forums and related searches, it appears there were hacks for Vista 64, but the important part here is that Microsoft REQUIRES signed drivers for 64 bit systems today, starting with windows 7. VMWare, please! Get those signed drivers out!

There’s one thing about the latest releases of VMWare Server that gets me. The 1.x versions all had built in console on the host where you defined/configured/started/stopped your VMs. It was a nice presentation with console UI elements coming in an .exe. The 2.x releases have moved to a web-based console. I much preferred the 1.x presentation.

I’m still using in on the job with Win7 32-bit, and it works well! 9/10

Microsoft Virtual PC

virtual_pc This was my first foray into VM’ing. I think XP was the modern OS at the time, and it was a great introduction to testing out changes or running other apps that I didn’t want on my machine. The kicker again here was that the system was not headless. Today, you’ll run Virtual PC 2007 on XP or Vista hosts, while Win7 has the ‘year’ moniker dropped.

The biggest one was a Toshiba voicemail/PBX management app that ONLY ran on XP machines that were NOT on a domain. What a pile of disappointment. The phone technician who installed the system had to be called out every time the company wanted to adjust the phone system (change a number, a name/label on the phone’s display, or any options on the phone system overall). It turns out he simply was running this web app on IIS on his laptop. He just needed to tweak the IP address in the app to match the customer’s phone system. One day I asked him how to DIY, and he suggested to run this web app on my machine. It was a perfect candidate for virtualization. Thanks MS Virtual PC 2004! 7/10

VMWare Server ESXi

vmware-esxi This is a free hypervisor product. Really it’s the entry-level product within the hypervisor line. It allows you to deploy multiple VMs on a machine and incur just a small performance penalty for the host OS. The licensing cost is zero. It runs a Linux kernel, and its footprint is ~32MB! Hmmm… could you install that to a USB thumbdrive? So the real benefit here is that you don’t have to worry about the license for your host, nor the overhead of the host.

My next project will be to take my 4 virtual machines and deploy them to a machine running ESXi. How cool is it that VMWare makes it free? Your only limitation at this point is the amount of RAM and disk space (hardly a limitation today at 7 cents per GB on a SATA drive). The product is a downloadable ISO. You boot into its setup app, and from then on, you use the console application to communicate with it.

Also-Ran

The new hotness is Virtual XP with Windows 7. It’s not really a multi-machine solution, and as a developer, it doesn’t do much for me. I am surprised that they are doing the ‘Remote App’ thing in Windows 7, and definitely applaud Microsoft for it! XP, however… 2003 called, and it wants its… oh, nevermind!

How have *you* leveraged virtualization as a developer?


Posted in: virtualization , windows 7 , green it , cost savings  Tags:
Actions: E-mail | Permalink | Comments (0) |
Phil posted on October 14, 2009 19:37

Paul Thurrott posted something that I had missed on Channel 9: A documentary on the evolution of Visual Studio. I took the time on a Sunday night to watch both parts (Part 1 and Part 2)

Part One

The first part was a look back at the early-mid 80's: MS-DOS, green-screen, OS/2 + IBM, and the arch of Visual Basic from version 1.0 through 5.0. One thing I did NOT know was that Alan Cooper's prototype of VB was called Tripod, and later Ruby. Cooper talks about the presentation of Tripod to Microsoft reps., "Gates-clones" as he calls them.

cooperRuby-Tripod

It was interesting to me that he scoffed "… like Microsoft would care about something like this."

Some of most interesting bits were around the culture or atmosphere at Microsoft - "pulling more all-nighters at Microsoft than I did at University" was telling. It makes sense - the stakes are much higher, and the environment more professional. It reminded me slightly of Barbarians Led By Bill Gates by Edstrom and Eller. (great read!)

Microsoft was incredibly focused on building a developer community. I feel they've done an amazing job at this, and they really are unparalleled in this respect. I've seen it first-hand at various DevDays.

They traced the evolution of Visual Basic from VB3 to VB5. One interesting part for me was the comment that "you could compile an application as an executable, which was a really big deal at the time." 

Part Two

hotjava   

The second part was a tracing of the genesis or development of C#. The impetus for the new language was due to Java. In 1996/1997, Java was the hot new kid on the block with the promise of 'write once, run anywhere' on other computing platforms.

 csharp

C# was then conceived from the lawsuit and forced failure of Microsoft's implementation of their own Java VM and Visual J++. The fact that Microsoft had the market-leading Java dev toolset at the time, and then extended further with C# is amazing.

 anders

guthrie

C# is inarguably the tool that helped win more developers over to the .NET platform from the Java space. Some great shots of the 2000 PDC with Scott Guthrie presenting. It really highlighted the war with Java in the early 2000s, and how Sun just got crushed. I say: "Thank goodness!" I loved the time-to-market and LOC graphs around Microsoft's copy of the prototypical Java app PetStore.

petstore

 

The video led into some self-criticism about some Visual Studio attributes like performance, the help system, the Ladybug defect/feature website, etc. Lots of talk about how Microsoft wants to connect with its customers, and wants to be more transparent to its customers.

Part 2 then devolved, in my mind, into a sales pitch for VS2010, Team Suite, and Azure. I guess I am not too surprised :)

Some of my favorite lines (Alan Cooper is full of them!):

  • "It (Visual Basic) a very different thing from what I had originally set it out to be. It's like sending your son to college, and he comes back graduating with honors and a sex-change." says Alan Cooper.
  • "I think Basic is a terrible language. Nothing more than FORTRAN with a dress on it. It's a language that should be dragged outside and shot." says Alan Cooper.
  • "C++ - a terrible, terrible language. An awful language… basically un-learnable… not a tool for the masses." says Alan Cooper.
  • "C# - is most of the magic of C++, with a lot of the simplicity of Visual Basic combined" says Dave Mendlen
  • "You don't have to be a genius to be an application developer." - Tim Huckaby

Overall it wasn't as much a "history" of Visual Studio as I had expected. I had expected to hear more fine-grained details about how the product was built/merged. It's definitely a worthwhile watch. Check it out for yourself!

Part 1 and Part 2 of The Visual Studio Documentary at Channel 9.


Posted in: visual studio , microsoft  Tags:
Actions: E-mail | Permalink | Comments (0) |
Phil posted on October 12, 2009 05:43

Damien Guard was nice enough to blog about changes coming to L2S in VS 2010. Rather, the changes are coming in the .NET Framework 4.0.

The whole rumor within the development community/blogs about "Linq To Sql is being unsupported, Entity Framework is the new coolness" was just plain wrong, I believe. Microsoft is too big, and has too many projects on the go. They'll gauge the momentum of both technologies. Have you heard Damien as a guest on Herding Code Episode 50? In this blog post, Damien says that the focus for Microsoft will be on EF, and that's fine. L2S is definitely not dead!

I still believe that if you're needing an ORM, and working with SQL Server, then use Linq To Sql. I've tried EF, and it worked fine. I've ended up with 4 projects using L2S, and haven't found any real need for EF.

Welcome Defect Fixes in coming in .NET 4.0 for Linq-To-Sql

For me, the most interesting changes within Damien's post are:

* Contains() with enums automatically casts to int or string depending on column type

* String.StartsWith(), EndsWith() and Contains() now correctly handles ~ in the search string (regular & compiled queries) - Here's a small defect. I've not needed to search for tildes very much, but I decided to give it a shot just in case! It's true, the behavior is just as described!

tilde-2

tilde 

 

* Now detects multiple active result sets (MARS) better - I am not the heaviest user of L2S, and definitely haven't needed to specify MARS myself. Here's the MultipleActiveResultSets defect as reported on MS Connect. It's a simple issue where the connection string property "MultipleActiveResultSets" is only picked up when CamelCased exactly as shown above. Any deviation will ignore the option!

* DeleteDatabase no longer fails with case-sensitive database servers - Interesting that this functionality even exists. I had to research this method - DataContext.DeleteDatabase(). I can't recall actually seeing it in the Intellisense method list, but indeed it's there! Most blogpost or articles that I read in that 5 minute span were talking about using this method for tear-down during "Unit Testing". I'd call that integration testing, and ill-informed as well. Unit tests should not include databases!

DeleteDatabase

* VarChar(1) now correctly maps to string and not char - This one has bitten me before. The column was called Gender. Of course it was storing M, F, T, or U for unknown. The core of the problem was that some rows were having a blank stored in this field, rather than null. StackOverflow to the rescue! http://stackoverflow.com/questions/1190328/linq-to-sql-exception-string-must-be-exactly-one-character-long. After some thought, I'd agree that storing this value as char(1) would be semantically more correct, more performant, and consume just one byte per tuple.

varchar

len zero 

* Decimal precision and scale are now emitted correctly in the DbType attributes for stored procedures & computed columns - I couldn't reproduce this defect, and perhaps I misunderstood.  I defined a decimal(18,5) attribute on the table, and L2S brought it back without any problems. Then I realized the key to this defect was probably the 'computed' bit. So I went and created a simple decimal return type. I ran the query, and still no defect.

computeddecimalsOK

Then I clued in - the defect was under the Linq To Sql Designer heading. So upon further inspection, here's the defect in the myL2S.designer.cs. The return type is calculated as decimal(0,0). Ouch! :)

  decimalzero

* Foreign key changes will be picked up when bringing tables back into the designer without a restart - This defect has hit me a few times as well. It appears as such:

  • Edit a FK in SQL Server. If you've got an open L2S file, deleting + dragging and dropping those tables back onto the L2S surface DO NOT show your FK changes.
  • Clicking the Refresh button in Server Explorer doesn't help.
  • The only solution is to close your L2S file, and re-open.

* Changing a FK for a table and re-dragging it to the designer surface will show new FK’s - this is very much related to the item above.

* Opening a DBML file no longer causes it to be checked out of source control - this has appeared to me a few times. Simply opening/viewing the L2S file creates a 'check out'. Nothing earth shattering here, and glad to see this is fixed.

* Can edit the return value type of unidentified stored procedure types - This feature is great! It's very helpful when you've got a sproc that shapes data just the exact perfect way that you'd like to show on a custom report. Perhaps you're binding to an asp:GridView or including as part of an MVC FormViewModel. The normal course of action is:

  • Create your sproc to shape your data as you like

    Sproc-To-Custom-Object

  • Drag a sproc onto the Methods section of the L2S designer.
  • Try change its return type to a class you've created solely for the purpose of binding

  • Oops, it's locked!

    locked

    The work around is a bit time-consuming. You have to:

    • open up the myL2S.designer.cs file

    • find your method marked with the attribute containing your sproc name

    • replace the default return type int with ISingleResult<T> - in my simple example here, it's ISingleResult<CustomerReport>

      modify dbml

    The frustrating bit here is that this behavior isn't predictable (to me at least). I CONSTANTLY have to go through this process to properly set the return type of 2 sprocs in one particular project. This defect fix in particular by Microsoft will be welcome!


Posted in: linq-to-sql , c# , microsoft  Tags:
Actions: E-mail | Permalink | Comments (0) |

On two recent projects, I've had the need to write out the properties of multiple custom entities. The example here will be around the venerable Customer class. Let's pretend that a requirement would be to send an email each time a customer makes an order to a support rep in your company. Yes, we'll be logging the order to the database, but the value-add here is that the recipient of the email will receive a link to the order, plus all the details of the customer and order included in the email.

So we need to take an object, iterate through its properties and their values, and put into a string for the body of an email.

The first thought might be: "just loop through each property and write it to the email body". That's fine, but as soon as you add a property in the future, you need to remember to change the emailing code. That's not helpful for the developer needing to maintain this application. Let's look at the Reflection namespace in the .NET framework.

Reflection in .NET

Reflection lets you programmatically find out information about types in your assemblies at runtime. Using classes in the System.Reflection namespace, you can learn details of an class's methods & properties. In the topic at hand, we're interested in the names, values, and datatypes of properties. You could possibly use reflection to get info at runtime about a method's parameters.

Override Customer.ToString()

The Customer class needs its own ToString() method overridden. Here's the class:

 
using System.Reflection; 
using System.Text;
 
public class Customer{
    
    public string Name{ get; set; } 
    public string Email { get; set; }
    public string Address { get; set; } 
    public string City { get; set; } 
    public string State { get; set; } 
    public DateTime JoinDate { get; set; }
        
    public override string ToString() {
    
        StringBuilder personString = new StringBuilder(); 
    
        foreach (PropertyInfo pi in this.GetType().GetProperties()) {
            //get the name of the property and its value. 
            personString.AppendLine(string.Format("{0}: {1}", pi.Name, pi.GetValue(this,null))); 
        } 
 
        return personString.ToString(); 
    }
} 

 

Use It!

 
Customer cust = new Customer{
    Name = "Mike",
    Email = "some@dot.com",
    HomeAddress = "1 Some Street",
    State = "ZZ"};
 
string customerOuput = cust.ToString(); //now put this in your email body!
 
Console.WriteLine(customerOutput);
 
/* Console will show:
Name: Mike
Email: some@dot.com
HomeAddress: 1 Some Street
City: 
State: ZZ
JoinDate: 
*/

 

Consider This…

There are a few things to consider with this implementation:

  • collections aren't handled well.
  • complex datatypes aren't either.
  • consider customizing your implementation to include special formatting for DateTimes.
  • what happens when you want the output to have a well-formatted output for a property like HomeAddress. We'd probably want it to show as "Home Address".
  • consider handling null values better than writing "null".

Wrap Up

I know this will save developers time in two ways:

  1. Not having to iterate manually through X properties to build your string for email. That'll scale depending on the number of properties and your adeptness at Ctrl-C, Ctrl-V.
  2. When you add a new simple property, you will NOT have to adjust anything for it to show in the .toString() method.

How are you using System.Reflection?

Posted in: c# , development , code blowout , .net framework  Tags:
Actions: E-mail | Permalink | Comments (0) |