Christopher Green

Now with more Vitamin C!
posts - 41, comments - 30, trackbacks - 1

Tuesday, May 05, 2009

Gone Baby Gone!

After the host of this blog went down for over a week I freaked out that my data might have been lost.  That spurred me on to check out alternative options and have since decided to move my blog to Wordpress.  Please visit me on

www.CodingLifestyle.com

PS: Gone Baby Gone is a great movie, saw it last night, that Affleck may be a knob but he sure can direct!

PPS: Many thanks to developers.ie for hosting this blog for free for the last 4 years.

posted @ Tuesday, May 05, 2009 5:07 PM | Feedback (1) |

Friday, April 24, 2009

Currency TextBox with Javascript

This took me a long time so here it is for prosperity.  I started by looking at Ajax's masked edit field in order to enforce a simply currency field.  This was a waste of time and not up for the job.  I accomplished it with javascript instead.  Very simply, no symbols, just #####.## or ######,## with the cents being optional. 

Here is the script:

        function fnCurrencyOnly(o) {

            var sValue = o.value;

            var sKey = String.fromCharCode(window.event.keyCode);

            if (document.selection.createRange().text == sValue) {

                sValue = sKey;

            } else {

                sValue = sValue + sKey;

            }

            var re = new RegExp("^\\d+(?:\\.\\d{0,2})?$");

            if (!sValue.match(re))

                window.event.returnValue = false;

        }

 

    <div>

        <input type="text" onkeypress="fnCurrencyOnly(this);" />

    </div>

 

Enjoy!

posted @ Friday, April 24, 2009 2:35 PM | Feedback (0) |

Monday, March 09, 2009

Cascading Dropdown Lists with jQuery (parent / child select options)

Recently I was tasked with merging 3 similar screens in to one.  I took stock of the commonalities and decided a Category and Subcategory dropdown list would suffice.   As you’d expect the contents of the Subcategory dropdown depend on the selected Category.  Obviously I wanted to avoid postbacks so I first looked to the Ajax Control Toolkit’s CascadingDropDown extender to link the parent to the child.  In my case, there were only a dozen subcategories so a webservice seemed like overkill.

After attending Tech-Ed 2008 and seeing Microsoft throwing its weight behind jQuery I decided to have a look.  So what follows is my first foray in to jQuery and I’m quite pleased with the results. 

First, we define an enum in the codebehind which can be used for bitwise operations.

public enum Category

{

Invoice     = 1,

Order       = 2,

Shipment    = 4   //Fourth item would be 8, then 16, 32, …

}

Next I wanted to be able to use the enum to specify the Category (only specifying one) and Subcategory items (bitwise OR any combination).

_DropDownCategory.Items.Add(GenerateListItem("Orders", Category.Order, false));

_DropDownCategory.Items.Add(GenerateListItem("Invoices", Category.Invoice, false));

_DropDownCategory.Items.Add(GenerateListItem("Shipments", Category.Shipment, false));

 

_DropDownSubcategory.Items.Add(GenerateListItem("Purchase Orders", Category.Invoice | Category.Order | Category.Shipment, false));

_DropDownSubcategory.Items.Add(GenerateListItem("Quote Number", Category.Order, false));

_DropDownSubcategory.Items.Add(GenerateListItem("Customer Project Number", Category.Shipment, true));

The enum was converted to a number and added as a custom attribute to the new list item in GenerateListItem():

li.Attributes.Add("Category", ((int)eCat).ToString());

 

Enter jQuery, first we’re going to need to keep a copy of all the available Subcategory items.  Each time we change the Category we will be showing a subset of this array which we must keep separate in memory.

var optSubCat = null;

$(function() {

    //Make a copy in memory of all the subcat options

    optSubCat = $("#_DropDownSubcategory").children().clone();

    //Default subcat to "Orders"

    ddSubcategoryUpdate(2);

});

Then we need an event to fire when the Category is changed.

$(function() {

    $("#_DropDownCategory")

    .bind("change", function(event) {

        var eCat = this[this.selectedIndex].attributes("Category").value;

        ddSubcategoryUpdate(eCat);

    });

});

Note how jQuery allows us to wire up DOM events after the fact to our .NET controls.  Here we add an onchange event dynamically rather than injecting this via the codebehind which forces us to put javascript code in the wrong place.  All we’re doing is pulling the value of the enum from the selected Category and then passing it to a function which will update the Subcategory items.

function ddSubcategoryUpdate(eCat) {

    //Remove all items from drop down

    $("#_DropDownSubcategory").children().remove();

    //For each subcat item: test if it belongs in eCat, if so add it

    $(optSubCat).each(function() {

        if (($(this).attr("Category") & eCat) > 0) {

            $("#_DropDownSubcategory").append($(this).clone()[0]);

        }

    });

}

And finally, in the if statement we see we test each Subcategory item previously saved in memory to see if it matches the enum value of the Category.

 

 What we’ve ended up with is a very powerful yet simple mechanism for cascading dropdowns using enums in our codebehind.  It’s easier to wire up than what the Ajax Control Toolkit provides, its all script so the UI looks good, and while this could have been done in straight javascript it demonstrates the power and simplicity of the jQuery library.

posted @ Monday, March 09, 2009 12:54 PM | Feedback (0) |

Monday, November 17, 2008

Tech-ed 2008

Last week I had the opportunity to attend TechEd 2008.  I have compiled a set of notes from the keynote and sessions I attended below.  Most of the information presented at these conferences is not really instructive for addressing today’s problems but talks about future problems and the technologies we will use to address them.  There are some interesting technologies coming down the pipe in the not so distant future and these notes may provide you with enough information to google more information about the topics which interest you.

 

I skipped a lot of older information about the VS2008 release, C# v3.0, and Linq which can all be found here.

 

Keynote

·         Testing Activity Center application

o   Pillar: No more no-repro

o   Generate test cases that tester can click off

o   Bug recording including video, call stack, system information

o   Generate a bug integrated in to Team System

§  Can start up debugger and reproduce tester’s scenario

§  Captures line of code, call stack, everything

·         Code buffering

o   Method shows history of changes (graphically too)

o   Integrates SCC versions in to IDE

·         MVC design pattern

o   Model                   =              data

o   View                     =              web page / UI

o   Controller             =              logic

·         SharePoint Integration

o   Server explorer includes lists, ect

o   Webpart template automatically contains ascx control for design support

o   SharePoint <> LINQ

o   List Event wizard

§  Auto-generate XML for site def??

·         Performance Profiler

o   Pillar: Leverage multi-core systems

o   See which method is taking time and core utilization

§  Graphically shows core usage including drill down

·         Will help with concurrency, deadlock debugging, ect

VS2008 Service Pack 1 Overview

·         ADO.NET Entity Framework release

o   Very similar to Linq To SQL

o   Generate data model

§  conceptual model < mapping > static (actual db) model

o   Data Services

§  Data centric abstraction over web services (WFC)

§  Exposes and takes IQueryable<T> so datasets very easy to work with in a LINQ like way

§  Routing lets URI act like a Linq query

·         http://Root/my.svc/Customers/35/FirstName

o   Dynamic Data

§  Given a data model will create aspx accessibility to defined objects

·         Security: all objects off by default but can dynamically access entire data model

·         Allow CRUD access via ASPX templates applied to all objects

o   CRUD = create, read, update, delete

o   Can create individual page for certain object

o   Can customize template to affect all objects

·         Ajax / other enhancements

o   Ajax

§  History Points

·         Addresses problem that users lose ability to hit back button

§  Script combining

·         To improve performance allows to dynamically combine js libraries

o   Improves javascript intellisense

o   Improves web designer performance (bugs/regressions addressed)

C# v4.0

·         History

o   V1 – Managed Code big emphasis

o   V2 – Generics; finished the language

o   V3 – LINQ

·         Pillars

o   Declarative programming: we are moving from “what?” to “how?”

§  LINQ is an example of this

o   Concurrency: Some of the parallelism extensions we will be getting

o   Co-Evolution: VB and C# will more closely evolve together vs. Features hitting languages at different times

o   Static vs. Dynamic Languages: aren’t necessarily a dichotomy

§  Static: C++, C#, VB – anything compiles

§  Dynamic: IronRuby, IronPython, Javascript

·         New keyword: dynamic

o   Call any method of a dynamic object and the compiler won’t complain

§  No intellisense possible

§  Will call during runtime

§  i.e.

·         dynamic calc = GetCalculator();

·         calc.Add(10,20);   //We know nothing about calc object

§  Lots of power to  be explored here

o   Optional Parameters

§  Like in C++ (and apparently VB)

§  Named parameters

·         Can also skip optional parameters

·         Public StreamReader OpenTextFile(string sFile, bool bReadOnly = true, int nBufferSize = 1024);

·         sr = OpenTextFile(“foo.txt”, buffersize:4096);

o   COM Interoperability

§  No more “ref dummy”!

·         Will get: doc.SaveAs(“Test.docx”);  //Winword saveas

·         Versus:   doc.SaveAs(“Test.docx”, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy);

§  Automatic dynamic mapping so less unnecessary casting

§  Interop type embedding

·         No more bringing in PIA

o   Safe Co and Contra-variance

o   Compiler as a service

§  Compiler black box opened up to be used and extended

§  In example created a command window with C#> prompt

·         Was able to define variables, functions, ect like in IronPython

Ajax v4.0

·         Introduction

o   Web app definition

§  Web site is a static collection of pages (such a BBC news)

§  Web application is something which replaces a traditional windows app

o    Traditional Server-Side ASP.NET vs. AJAX

§  Pros

·         Safe: Guaranteed browser compatibility

·         Powerful: All the power of a .NET language in code-behind

§  Cons

·         Response: User must wait for postback

·         Performance: All page content rendered for each interaction

·         Update Panels: Use Wisely

o   An update panel uses sneaky postbacks so while it looks better it is still as bad as traditional server side asp.net

o   Don’t wrap an entire page in an update panel

§  Wrap the smallest region required

§  Use triggers to set what controls will fire a sneaky postback

o   Turn ViewState OFF

§  Down the line this will not be on by default

§  We often send a lot of unnecessary information over the wire in ViewState

·         Ajax Calls (Services)

o   Consider using an Ajax control to update data as needed

o   Calling a web service from javascript is not considered dangerous or bad practice

o   Example

§  Have a datagrid with postback bound to a dropdown list.  Instead of a postback on ddlist use Ajax call

·         Instead of a datagrid use a straight html table

·         Via script we make a call to the web service

·         Use stringbuilder to format return to build up new rows

§  Kinda horrible!  Too much mixing of mark-up and script

·         Client Side Controls

o   Clean way of separating Ajax related script from the web page

o   Allows you to bind to Ajax calls in a template way

o   Example

§  From above we now separate js in to a client side control which is now cleanly referenced on our web page

·         Declarative Client Side Controls

o   “X” in XML stands for extensible; but not often extended!

o   Use XML to bring in namespaces like System and DataView

o   Can define a datagrid purely in html by adding attributes to the <tbody> tag in a table

·         Fail over

o   Problem with Ajax is not it is not always supported for reasons of accessibility, search engines, or disabled javascript (mobile devices)

o   Does require double implementation of Ajax and traditional solution but it is an option when needed

·         New features in SP1

o   Back button support!

§  As of VS2008 SP1 Ajax now has back button support

§  ScriptManager property EnableHistory=true and onNavigate event

§  AddHistoryPoint(key,value);

§  AddHistoryPoint(key,value,“Text seen in back button history instead of url”)

§  Process

·         Enable history and add event

·         When page event fires store value (index, ect) with AddHistoryPoint() in provided history cache

·         Use history event to set page back up with value retrieved from HistoryEventArgs

o   Example: set a form to display an item from the last selected index

o   Script Combining

§  Combine scripts for better performance

·         Example showed initial 15sec down to 3

§  Must tell ScriptManager all libraries and it will combine/compress them in to one server call

§  Must explicitly tell which scripts to use – even separate AJAX libraries

·         ScriptReferenceProfiler

o   Free webcontrols which will tell you all the libraries a page uses to make the above less painful

·         Factoids

o   Ajax initiative started to address Outlook Web Access (OWA); a good example of a web application

o   Script Manager is just a way to make sure the page includes the Ajax javascript libraries

§  Ajax script commands prefixed with $

·         $get(“my id”) looks to be handy

§  Can dynamically add event handlers in javascript using Ajax js library

·         $addHandler($get(“dropdownlist1”), “change”, myFunc);

·         Cool “must have” tools

o   Fiddler (www.fiddler2.com)

§  Shows response time, requests/responses, statistics

§  Tip: must place a dot in uri for Fiddler to capture localhost

·         http://localhost./default.aspx

o   Firebug – Firefox extension

 

Visual Studio Tips & Tricks

·         Ppt slides: http://code.msdn.microsoft.com/karenliuteched08

·         A lot more keyboard shortcuts: http://blogs.msdn.com/karenliu/

·         MS and partnered with DevExpress which is offering CodeRush Express for free

o   Required for a lot of the shortcuts and refactoring shown

·         Editing

o   Tools>Options>Editors>C#>Formatting>Set Other Spacing Options>Ignore Spaces

o   Keyboard tricks

§  Ctrl M,O               Toggle collapse all

§  Ctrl M,M              Expand region

§  F12                         Go to definition

§  Shift F12              Final all references

§  Ctrl Shift F8        Jump up Go to definition stack

§  Ctrl [ or ]              Jump between brackets

§  Ctrl Alt = or -      Smart Select

§  Ctrl .                      See smart tag (Implement a missing function, add using statements)

§   

o   Snippets

§  Lots of boilerplate goodies are there.  Really need to start using them

·         Ctor

§  Lots more smart HTML snippets coming

·         Debugging

o   Step OVER properties (r-click at breakpoint to check option)

o   Step into Specific – list of all functions down the chain you can jump to step in to

o   Tools

§  Tinyget – mini stress test

§  Adphang – get memory dump of w3wp

§  Windbg – open dump

·         Loadby SOS mscorwks

o   Need sos.dll for windbg to interpret stack

·         Deployment

o   Web.config transform for release, uat, ect

o   Powerful web deployment publishing options

§  Http, ftp, fpse

§  Msdeploypublish

·         New MS protocol for host supporting includes database, iis settings, access control lists (ACL), ect

·         Free test account at http://labs.discountasp.net/msdeploy

·         Other

o   www.VisualStudioGallery.com  – IDE extensions gallery

§  PowerCommands for VS08

o   VS2008 SDK application

§  Samples tab

·         Click to open sample straight in VS ready to go

Silverlight v2 101

·         XAML

o   A subset of WPF

o   Read-only designer view

§  Must edit  XAML by hand

§  Proper designer on the way

o   Can at least drag XAML text templates for many controls

·         Silverlight Controls

o   Greatly extended in Silverlight v2

§  Visit: www.silverlight.net for a demo

§  Most of what you’d expect in ASP.NET is available in Silverlight

o   Of Note

§  StackPanel

·         Previously on Canvas available requiring static x,y position designation

·         Operates like a panel with z-order

·         Security

o   Lives in a sandbox which can’t be extended for security reasons

o   There are ways to safe access local (isolated) storage, have a file dialog, sockets, cross domain access

·         Nifty

o   Can easily stream media content with one line of XAML

o   Can easily spin any element

Parallelism

·         Introduction

o   Sequential performance has plateaued

o   When we have 30 cores this may lead to dumber cores where we have a situation that today’s software runs slower on tomorrow’s hardware

o   Need  to start thinking about parallelism

§  Understand goals vs. usage

§  Measure existing performance.  VS2010 has tools to do this

§  Tuning Performance

·         Typically we start with sequential programming and add parallelism later

·         VS2010 has Profiler tool for tuning performance

§  Identify opportunities for parallelism

§  Use realistic datasets from the outset; not only on site with the customer

§  Parallelize only when necessary, but PLAN for it as it does introduce race conditions, non-determinism, timing issues, and a slew of other potential bugs

§  Once code is written for parallelism it can scale to any size automatically without any code changes

·         New technologies to help

o   Parallel API

§  Task

·         Like a thread but more optimal with a richer API

o   Has a value for threads which must return a value

§  Accessing the value automatically the same as Thread.Join or Task.Wait

§  ThreadPool

·         Just pass a delegate and let Microsoft worry about the hardware and how to best allocate and spawn threads

·         The ideal number of threads = number of cores

§  TimingBlock class makes it easy to test performance

·         No more: (end time – start time) / 1000

§  Decorate code w/ measurement blocks which appear in Profiler

o   Parallel Extensions

§  First class citizen in VS2010 (SDK today?)

§  Parallel.For and Parallel.ForEach

·         Still need to use critical sections around shared resources inside loop

·         Tip: Best practice is to parallelize the outer for loop only

·         Automatically adds measurement blocks to profiler to see results

§  Parallel.Invoke

§  Parallel extended IEnumerable to perform queries much faster

·         var q = from n in arr.AsParallel() where IsPrime(n) select n;

§  Task group

·         i.e.  For a quick sort instead of using a recursive algorithm use task groups to leverage parallelism with little change to code

o   Debugging – Parallel Stacks

§  Richer API to display tasks or threads and view a holistic mapping of their execution

o   Tools

§  Performance Wizard

·         CPU sampling, timing, ect

§  Profiler

·         Thread Blocking Analysis

o   Shows each thread’s parallel execution revealing race conditions affecting performance

§  Displays information about critical sections in tooltip

§  Can show dependencies for resources/locks across threads

jQuery

·         Ships in future VS but available now

·         Will not be changed by Microsoft but will be supported so we can use it with customers requiring support

·         VS intellisense available from jquery.com

·         Selectors

1.       $(“:text”)             tag          Select all text boxes

2.       $(.required)       class      Select any element with this class tag

3.       $(“#name”)        id            Select with this ID

·         Animations

1.       $(...).Show()

2.       $(...).Hide()

3.       $(...).slideDown()

4.       $(...).slideUp()

5.       $(...).fadeIn()

6.       $(...).fadeOut

7.       Massive open source libraries with hundreds more

§  Plugins.jquery.com

MVC 101

·         MVC

o   Controller (input) pushes to model and view

o   View (UI)

o   Model (logic)

·         An alternative, not replacement, to traditional web forms

·         Easier to test

o   No dependencies on request/response or viewstate as this everything is explicit and therefore testable

·         No server side controls (or designer support), postbacks, or events.

o   Think back to classic ASP

o   What is all this by-hand crap?  XAML (WPF and Silverlight) is only notepad as well

·         Action, instead of event, fires not in View but in the Controller. 

o   The View, aka aspx page, has no code behind.

·         In Controller can define a action and use wizard to create it’s view (web page)

·         ViewUserControl is a collection of html and inline asp which is reusable

IIS v7

·         Modules

o   ASP.NET managed HttpModules can be plugged in directly to IIS v7

§  No more unmanaged ISAPI filters

o   Modules can be managed within IIS v7 Manager

o   Configuration for modules can be exposed through manager

§  Customer WinForm configuration can also be exposed

·         Config

o   No more meta-base

§  All settings exists in central applicationHost.config – similar to a web.config

·         C:\windows\system32\inetsrv\config\schema

§  Can share IIS config for farm scenario

o   www.iis.net contains a configuration pack which allows you to show the config file within the IIS manager

Security

·         Concept of Security Development Lifecycle (SDL)

·         Threat Modelling – package available for formalized  security reviews

o   Talks about prioritizing risks

·         Multi-Pass Review Model

o   1 – Run fuzz and code analysis tools

o   2 – Look for ‘patterns’ in riskier code

o   3 – Deep review of riskiest code

·         Golden rule: What does the bad guy control?

o   What if he controls x & j (resources obtained from user, port, pipeline, compromised file system or database)

§  Char [] f = new char[3];

§  f[3] = 0;                                 bug

§  f[x] = 0;                                 can write a null to anywhere in memory

§  f[x] = y;                                 can write anything anywhere in memory

·         Accepted encryption

o   AES and SHAXXX only

o   Everything else is banned!  So long TripleDES

·         Do not use:  try { } catch (Exception ex) { }

o   Hides bugs and security flaws

o   Catch only exceptions we can handle

IE v8

·         Debug tools included out of the box

o   Hit F12

§  Debug javascript

§  Solve style issues

·         Compatibility – new rendering engine following widely-accepted standard

o   Get prepared for our apps look and feel to break

o   www.msdn.com/iecompat

o   Set meta-tag to tell IE8 to continue to render using v7 engine

·         Accelerators

o   Can develop own accelerators which can highlight a name and pass to a website as a parameter.  Employee staff directory, for example.

Cool Stuff

·         Ctrl-,

o   Quick search feature in 2010

·         Ctrl-.

o   Refactoring: infers using statement.  Generate a new method as your developing

·         Web.config

o   Release version compiles debug/standard web.config and turns off debug, hardens security, replaces config and connection strings

o   Part of the installer

Other Stuff

·         Ribbon support in VS2008 Feature Pack

·         Vista Bridge

o   Wrapper to get access to Vista controls and features

o   TaskDialog and CommandLinks

§  Standard now so will be seen in Win v7

§  Backwards compatible, just extra messages to standard native button

o   Restart/Recovery API

§  Get notified of a reboot

§  Register delegate called in separate thread when app crashes/reboots

§  OS will run app with a command line argument you catch to load saved info

o   Power Management

§  Get notified about all power related info, low battery, ect

Biz Stuff

·         StepUp Program

o   Allows customers to upgrade current SKU

§  i.e. VS Pro to Team Foundation Server

§  30% discount until June 2009

 

posted @ Monday, November 17, 2008 2:11 PM | Feedback (1) |

Wednesday, September 17, 2008

Expand a Virtual PC hard drive

Remember the days before 500GB discs were a hundred bucks and you spent all afternoon cleaning out your tiny hard drive to make more room? Well, if you still use virtual machines (VMs) then you probably still have that experience even today. Over the last few years I've been handed VMs with a fixed disk of just 10GB. When these VMs suddenly become important this can become a problem. Sure, you can add a disk but often we need to expand the C: drive. After running in to this problem again I thought surely there is a way around this if I look hard enough and indeed there is! Follow the steps below and you will be able to expand your C: drive or even change it from fixed to dynamic (however, an bigger fixed disk offers better performance).

  1. Create larger vhd file with expander utility
    1. Can also convert fixed to dynamic and vice versa
    2. http://vmtoolkit.com/blogs/announcements/archive/2007/01/17/vhd-expander-available.aspx  
  2. Add new vhd file as an additional disk
  3. From command line use diskpart to extend volume (in example volume 1 becomes 20gb after extend)
  4. diskpart: list disk, select disk, detail disk, select volume, extend
  5. Shut down
  6. Remove old disk, set extended disk to primary channel (0)
    1. Optionally delete old vhd file once satisfied everything is working
  7. Boot up on extended disk

posted @ Wednesday, September 17, 2008 9:42 AM | Feedback (0) |

Tuesday, July 08, 2008

XML Serializing between WebService proxy classes and Entity classes

If you are looking at this page I would suggest you ask yourself the following questions:
  • Is the architecture of my software broken?  Why am a referencing a class on either side of a webservice?
  • Are web services really necessary in this situation?
My answers are yes, it is broken, and yes, there is an egrigious use of web services throughout.  Unfortunately, this product is many years old and I have to do what the customer asks.  So here I have an entity class which is not a simple container for data.  It contains additional methods and logic.  This entity is populated by the database and then forked over by webservices.  However, the UI layer also needs access to the additional methods and logic in the entity.  The WSDL generated proxy class does not contain these methods or logic; just a simple representation of the public properties of the class with straight gets and sets.  
 
The challenge then, is to serialize the web service proxy class back to the entity class.  Once this is done, I will have access to the additional methods and logic I need.  We can do this by using what web services use, XML serialization.  Its a fast way of getting our data from the proxy class back to XML.  Then deserialize the XML back to the entity class.
 
        ///<summary>
        /// Serialize the data from an object of Type_A to a new object of Type_B
        ///</summary>
        ///<param name="oSource">The Type_A object containing the data to serialize</param>
        ///<param name="tDestination">The Type_B to be created and deserialized with the Type_A object</param>
        ///<returns>An object of Type_B</returns>
        static object SerializeObjects(object oSource, Type tDestination)
        {
            XmlNoNamespaceWriter xw = null;
            Object oDestination = null;
 
            try
            {
                //Prepare to convert XML entity to XmlNoNamespaceWriter
                MemoryStream ms = new MemoryStream();
                xw = new XmlNoNamespaceWriter(ms, Encoding.UTF8);
                XmlSerializer xsA = new XmlSerializer((oSource.GetType()));
 
                //Serialize web service xml data to xml stream
                xsA.Serialize(xw, oSource);
 
                //Deserialize stream to entity actual
                XmlSerializer xsB = new XmlSerializer(tDestination);
                xw.BaseStream.Position = 0;
                oDestination = (WSEntityTest.Entity)xsB.Deserialize(xw.BaseStream);
            }
            catch
            { }
            finally
            {
                //Close the stream
                if (xw != null)
                    xw.Close();
            }
 
            return oDestination;
        }
 
So what we are doing is using a memory stream and XmlTextWriter to contain the XML.  The XmlSerializer serializes the proxy class to the stream.  If you wanted to look at the resulting XML, you could use an XmlDocument to load the stream and take a look.  If we do that, we will notice a small problem.  Every child element will contain a namespace attribute (xmlns). This will throw a spanner in the works when deserializing the data to our entity class. Basically what the namespace is telling the XmlSerializer is the data doesn’t belong in our entity class so it will skip it. It’s just doing its job because technically we shouldn’t be serializing data from the class of type A to a class of type B. However, this is exactly what we need to do. To work around this, I looked high and low for a simple way of turning off the namespace (in .NET v2.0).  Nothing simple turned up, hence the use of XmlNoNamespaceWriter which is derived from XmlTextWriter.   The implementation of this class is shown below:
 
    public class XmlNoNamespaceWriter : System.Xml.XmlTextWriter
    {
        bool m_bSkipAttribute = true;
 
        public XmlNoNamespaceWriter(System.IO.Stream writer, System.Text.Encoding encoding) : base(writer, encoding)
        {
        }
 
        public override void WriteStartElement(string sPrefix, string sLocalName, string sNS)
        {
            base.WriteStartElement(null, sLocalName, null);
        }
 
 
        public override void WriteStartAttribute(string sPrefix, string sLocalName, string sNS)
        {
            //If the sPrefix or localname are "xmlns", don't write it.
            if (sPrefix.CompareTo("xmlns") == 0 || sLocalName.CompareTo("xmlns")==0)
            {
                m_bSkipAttribute = true;               
            }
            else
            {
                base.WriteStartAttribute(null, sLocalName, null);
            }
        }
 
        public override void WriteString(string sText)
        {
            //If we are writing an attribute, the sText for the xmlns
            //or xmlns:sPrefix declaration would occur here. Skip
            //it if this is the case.
            if(!m_bSkipAttribute)
            {
                base.WriteString(sText);
            }
        }
 
        public override void WriteEndAttribute()
        {
            //If we skipped the WriteStartAttribute call, we have to
            //skip the WriteEndAttribute call as well or else the XmlWriter
            //will have an invalid state.
            if(!m_bSkipAttribute)
            {
                base.WriteEndAttribute();
            }
            //reset the boolean for the next attribute.
            m_bSkipAttribute = false;
        }
 
 
        public override void WriteQualifiedName(string sLocalName, string sNS)
        {
            //Always write the qualified name using only the
            //localname.
            base.WriteQualifiedName(sLocalName,null);
        }
    }
 
I found this class here, and modified it slightly to use a stream rather than a file. So now we get past our namespace issue and the serializer won’t be confused by the namespaces. Now all we need is a second XmlSerializer created with our entity type.  This will deserialize the stream in to a new instance of our entity class.  The usage of the method is shown below:
 
//Retreive the WebService proxy class
localhost.Service1 svc       = new Client.localhost.Service1();
localhost.Entity xmlEntity   = svc.HelloWorld(); 
 
//Serialize the proxy class to a new entity class
Entity entity = (Entity) Program.SerializeObjects(xmlEntity, typeof(Entity));
 

posted @ Tuesday, July 08, 2008 12:01 PM | Feedback (0) |

Tuesday, December 18, 2007

Visual Studio 2008 JumpStart

Yesterday I attended the Visual Studio 2008 Jumpstart at Microsoft in Dublin.  This was a one-day course, presented by David Ryan, introducing some of the new features in C# 3.0 and VS2008.

 

I approach every release with excitement and trepidation.  There are some fantastic new features like JavaScript debugging, nested MasterPages, improved IDE for both coding and web design, and multi-target runtime support.  With multi-targeting support we can use VS2008 to continue to code or support .NET 2.  If you open a VS2005 project, you will be prompted to upgrade your project even if you continue to use .NET 2.  I asked was there any risk associated with this for those who need to continue to support .NET 2 and was told only the SLN file is changed.  So theoretically, there is no reason to keep VS2005 installed!  Do you believe it??  If only we could get rid of VS2003 as well.

 

Now, the reason I also approach each release with trepidation is because you know there is going to be some big, new, ghastly feature which will be force-feed to us like geese in a pâté factory.  This time that feature in LINQ.  Open wide because there is a big push behind LINQ and you’ll notice a using System.Linq statement in every new class (which is a real pain if you change target framework back to .NET 2).  But first, let’s review some of the changes made to C#:

 

  • Anonymous types
    • var dt = DateTime.Today;
    • Anything can be assigned to a var, but once it’s assigned its strongly typed and that type can’t be changed.  So I can’t reuse local variable dt and assign string “Hello” like I could with object.
  • Automatic Properties
    • This:

      private int m_nID;

         public int ID

         {

             get

             {

                 return m_nID;

             }

             set

             {

                 m_nID = value;

             }

         }

 

    • becomes this:

public int ID { get; set; }

 

    • The problem is in practice I prefer to use the private variables in code leaving properties for external access only.  Many times the get/set is doing something interesting, like reading the value from a cache or performing some complex operation.  We don’t necessarily want/need this code to execute every time it is accessed from within the class so I use the private variable.  Automatic Properties has us using the public property directly everywhere in the class.  So, personally, this will cause inconsistency in my coding style.
    • You can also specify the get as public but keep the set to just be accessible from within the class like this:

public int ID { get; private set; }

 

  • Object initalizers
    • Ever have to instantiate your own class and have to initialize it with a dozen properties?  Do you add 13 lines of code or go overload the constructor?  Now you don’t have to, imagine a simple Person class with 3 properties:

Person person = new Person { FirstName="Chris", LastName="Green", Age=33 };

 

    • Only initialize what you properties you want:

Person person2 = new Person { FirstName = "Chris", LastName = "Green" };

 

  • Collection initalizers

List<Person> people = new List<Person>

         {

new Person { FirstName = "Chris", LastName = "Green", Age = 33 },

new Person { FirstName = "Bill", LastName = "Bob", Age = 46 },

new Person { FirstName = "Foo", LastName = "Bar", Age = 26 }

         };

 

  • Extension methods
    • This is a way of adding new inherent functionality to existing classes.  The objective is to add a new method to the DateTime type called LastDay() which will return the last day of the given date’s month.

public static class DateTimeUtils

{

        public static int LastDay (this DateTime dt)

        {

            return DateTime.DaysInMonth(dt.Year, dt.Month);

        }

}

 

    • Notice the this before the first parameter argument.  This tells the compiler that this is an extension method for the DateTime type.  We can now use this method as if it was built in to the DateTime class:
      • int nLastDay = dt.LastDay();
  • Lambda expressions
    • Too lazy or couldn’t be arsed to write a small 2 line function?  This is for you:

Func<string, bool> CheckName = sName => sName == "Bob";

bool bBob = CheckName(person.FirstName);

Func<int, int> Square = x => x * x;

int nSquare = Square(5);

 

The fact is there’s an ulterior reason var, Lamda expressions, and many of above additions have been added to C# 3.0.  C# had been bent in order to accommodate LINQ.  LINQ allows you to perform queries on objects, DataSets, XML, and databases.  It’s interesting in that it offers an independent layer of abstraction for performing these types of operations.  This has actually occurred to me before when looking at data layers chock full of embedded SQL not being particularly ideal.  LINQ offers a generic and powerful alternative.  Let’s take a look at a simple example based on the people collection from above:

 

var matches = from person in people

              where person.FirstName == "Bob"

              select person;

 

The first thing that caught my attention was the select was last.  One reason they likely did this was to force us to state what we were querying first (the from clause) so that Intellisense could kick-in for the rest of the expression.  Notice person.FirstName was fully supported by Intellisense so the Person class was automatically inferred from the people collection.

 

You can create objects on-the-go from your expression.  For example:

 

var matches = from employee in people

              where employee.FirstName == "Bob"

              select new Person(employee.FirstName, employee.LastName);

 

 

Notice how var is inherently handy here (but bad practice for nearly everything else) as our LINQ expression returns System.Collections.Generic.IEnumerable<Person>.  Lambda expressions as well play a key part in LINQ:

 

var matchesBob = people.Select(CheckName => CheckName.LastName == "Bob");

 

matchesBob.ToArray()

{bool[3]}

    [0]: false

    [1]: true

    [2]: false

 

var matchesInitials = people.Select(ChopName => ChopName.FirstName.Remove(1) + ChopName.LastName.Remove(1));

 

matchesInitials.ToArray()

{string[3]}

    [0]: "CG"

    [1]: "BB"

    [2]: "FB"

 

There is so much more to LINQ that I won’t attempt to cover any more.  Rest assured you will hear much more about LINQ in the months to come (fatten up those livers).  One thing is obvious, C# took a heavy hit in order to support it.  Let’s hope it’s worth it as every release we lean more and more towards VB.  A colleague recently remarked, “C# is all VB under the covers anyhow”.  He might be right.

 

Some other interesting new additions:

  • XElement – for anyone who has programmatically built XML before you will appreciate this quicker alternative
  • ASP.NET ListView – the singular new control this release.  Its basically a Repeater but with design-time support
  • Script Manager Proxy – typically the Ajax ScriptManager will be placed in the MasterPage.  When the content page needs to access the ScriptManager a ScriptManagerProxy can be used to get around the restriction of only one ScriptManager allowed per page.
  • Javascript enhancements – built-in libraries which extend string, add StringBuilder, and a number of other enhancements to make writing JavaScript more .NET-like
  • CLR Add-In Framework: essentially a pattern for loading modules (only from a specified directory) vs. using reflection, iterating classes for a specified type, and using the activator to instantiate the object
  • Transparent Intellisense: In VS2005 Intellisense went in to hyperdrive and our tab keys have never been the same.  However, I often found myself cursing it as it often got in the way.  So when VS is being too helpful and you can’t see what you’re doing press CTRL rather than ESC to turn Intellisense transparent.
  • Right-click the code and you will see an Organize Using menu below Refactor.  Here is a feature I’ve often dreamed of: Remove Unused Usings.  Pinch me!  Also, if you right-click the interface in a class's definition (public class MyClass : Interface) there is an Implement interface option.   Last, if you are coding away and using a class before adding a using statement use ALT-Shift-F10 to automatically resolve the class and add the using statement to your file.
  • Improved support for debugging multithreaded applications
  • SQL Database Publishing Wizard is now integrated in the VS
  • Did I mention JavaScript debugging??!

 

You may notice I’ve omitted a few big topics.  I didn’t mention Ajax because that’s old news now.  However, there are new versions of the Ajax Control Toolkit and web deployment projects for VS2008.

 

I also didn’t mention Silverlight although I may find some interesting applications for it in the future.  For example, if you really hate writing JavaScript you could use Silverlight’s built-in mini CLR to write C# code which executes in the browser.  Oh, I hear it does some UI stuff too.

 

References: ScottGu 19-11-2007, ScottGu 13-03-2007, ScottGu 08-03-2007, C# 3.0 In a Nutshell, Pro ASP.NET 3.5 in C# 2008, and CodeProject.

 

posted @ Tuesday, December 18, 2007 2:21 PM | Feedback (0) |

Friday, September 14, 2007

Using reflection to copy a DataRow to a class

Very often when working with DB tables we serialize a row in to class.  This entity class simply holds the data and hosts a rack of get and set methods.  The data layer serializes this class, the business logic layer manipulated it, and the UI layer ultimately displays it.  Here is a simple example:

 

    class Class1

    {

        private string m_sProp1;

        private int m_nProp2;

 

        public string Prop1

        {

            get

            {

                return m_sProp1;

            }

            set

            {

                m_sProp1 = value;

            }

        }

 

        public int Prop2

        {

            get

            {

                return m_nProp2;

            }

            set

            {

                m_nProp2 = value;

            }

        }

    }

 

Very often somewhere in the UI and/or logic layers you have a large function laboriously copying each value in or out of the entity class.  In my case, I was serializing the entity to a DataSet to be displayed in a Repeater control.  So I thought to myself, “Self, wouldn’t it be cool to use reflection to automatically perform the copy”.  While I didn’t know much about reflection a couple hours ago, it’s remarkably easy to use and, as you probably know, very powerful.  Let’s get started…

 

I need a copy function to copy a DataRow to my entity class and vice versa.  We’ll address the first case. 

 

        public static object SetValuesToObject(Type tClass, DataRow dr)

        {

            try

            {

                Object oClass        = System.Activator.CreateInstance(tClass);

                MemberInfo[] methods = tClass.GetMethods();

                ArrayList aMethods   = new ArrayList();

                object[] aoParam     = new object[1];

 

                //Get simple SET methods

                foreach (MethodInfo method in methods)

                {

                    if (method.DeclaringType == tClass && method.Name.StartsWith("set_"))

                        aMethods.Add(method);

                }

 

                //Invoke each set method with mapped value

                for (int i = 0; i < aMethods.Count; i++)

                {

                    try

                    {

                        MethodInfo mInvoke = (MethodInfo)aMethods[i];

                        //Remove "set_" from method name

                        string sColumn = mInvoke.Name.Remove(0, 4);

                        //If row contains value for method...

                        if (dr.Table.Columns.Contains(sColumn))

                        {

                            //Get the parameter (always one for a set property)

                            ParameterInfo[] api = mInvoke.GetParameters();

                            ParameterInfo   pi  = api[0]; 

 

                            //Convert value to parameter type

                            aoParam[0] = Convert.ChangeType(dr[sColumn], pi.ParameterType);

                           

                            //Invoke the method

                            mInvoke.Invoke(oClass, aoParam);

                        }

                    }

                    catch

                    {

                        System.Diagnostics.Debug.Assert(false, "SetValuesToObject failed to set a value to an object");

                    }

                }

                return oClass;

            }

            catch

            {

                System.Diagnostics.Debug.Assert(false, "SetValuesToObject failed to create an object");

                return null;

            }

        } 


The way this works is I’m going to pass in a Type and a DataRow.  First we look through at all the methods in the entity class and pull out all the set methods.  Then look at the DataRow to see if we have a column which corresponds to the method.  Looking at the example entity class above, I would be hoping to have a column called Prop1 and Prop2*.  We the look to see what type of set method is expecting: string, int, DateTime, ect.  We use this to convert the value from the DataRow and set this in to an object array of length 1.  Finally, invoke the set method passing in the object array.  The end result, a newly instantiated entity class pre-populated with the values from the DataRow.

 

* Although it’s rare to abide by a naming convention in reality, this is new code, so we will keep naming identical from DB to entity to DataTable.  It would be trivial to introduce a mapping of column to property.

 

posted @ Friday, September 14, 2007 10:57 AM | Feedback (0) |

Wednesday, August 22, 2007

Create custom, professional buttons with .Net LinkButton and CSS

Anyone who has played with one of Microsoft’s web starter kits will have noticed the graphic designers who created them use an image for each and every damned button on the site.  Not only that, but they create the same button for each .NET theme.  I don’t know about you, but the prospect of opening Photoshop every time I add a button to a site is too much work.  At the same time, you can’t argue they don't give the site a slick, professional look.

 

What would be really ideal is to have one blank button image and use a standard control and CSS to get the same effect.  After playing with the various button types you see that the standard .NET button doesn’t support background-image, but LinkButton does.  In fact, LinkButton is almost perfect once you set the display: inline-block so it pays attention to the width and height.  Because LinkButton renders as a hyperlink, the text color and text-decoration are ignored until we add the visited, hover, and active elements.  Finally, we get LinkButton to behave consistently.

 

.button, .button:visited, .button:hover, .button:active

 {

       width: 140px;                                    /*Make these the size of the image*/

       height: 18px;

       background-image: url(images/button-blank.gif);  /*Blank button image*/

       background-repeat: no-repeat;

       color: Navy;                                     /*Color of text*/

       display: inline-block;                           /*Required*/

       margin-left: 5px;                                /*Spacing so buttons can...*/

       margin-right: 5px;                               /*simply be side-by-side*/

       text-align: center;                              /*Alignment of text*/

       padding-top:5px;                                 /*Push text down like v-align:center*/

       text-decoration:none;                            /*Do not show link underline*/

}

 

Of course, you could break out this style to have the button look different depending on its state.

 

Now we can simply drop a LinkButton on the page and set the CssClass to button. 

 

Enjoy the ease of creating a professional look with the humble LinkButton control.

posted @ Wednesday, August 22, 2007 10:05 AM | Feedback (1) |

Monday, August 20, 2007

SqlDataSource: Getting @@Identity after Insert

Yesterday I was developing a simple form using a SqlDataSource to INSERT or UPDATE when saving the form.  The form consisted of a few controls and a button.  In the case of a new item, on clicking the save button I am executing SqlDataSource1.Insert().  For an existing item, I’m using an “ID” parameter on the query string which in turn is used by the UPDATE command.  So I need the ID of the row I’ve just inserted to allow the user to update the form.  I should mention my table has a column called “ID” of type int which is specified as the auto-incrementing identity column. 

 

I put together the form in less than 30 minutes and then spent twice that time trying to find the solution you are reading now.  I was sorely tempted to ditch the DataSource as this is straightforward when you’re executing your SQL commands directly in the code-behind.  But I was curious and persevered until I found the answer:

 

Firstly, let me describe how to set up the DataSource to do the insert.  The InsertCommandType is “Text”.  For the InsertQuery click the button to open the Command and Parameter dialog.  Use the query builder, if you like, to create your insert statement.  After the insert statement append “SET @Identity = @@Identity;” so our insert command looks something like this:

 

INSERT INTO TestTable (TestCol) VALUES (@TestValue); SET @Identity = @@Identity;

 

The statement above has 2 parameters.  One is TestValue we’re setting in to TestCol.  The other is Identity which will be the ID of the column we insert.  Click Add Parameter and type “TestValue”, Parameter source is control, and ControlID is a textbox.  Add another parameter called “Identity”.  This time click Show Advanced Properties, set Direction to “Output” and Type to “int” (leaving Parameter source as “None”). 

 

Now the trick is catching the DataSource at the right time so that our output parameter will have a value.  Don’t mistake the DataSource.InputParameters as the place to look as this merely describes the parameters we’ve configured above.  To actually see the parameters after execution you need to catch the OnInserted event.  Here we have SqlDataSourceStatusEventArgs which contains the command and its parameters after the command has executed.

 

    protected void SqlDataSource1_Inserted(object sender, SqlDataSourceStatusEventArgs e)

    {

        //Read the value of the @Identity OUTPUT parameter

        string sID = e.Command.Parameters["@Identity"].Value.ToString();

 

        //Display new ID

        Label1.Text = sID;

    }

 

So with the ID known I can now redirect the user to "page.aspx?ID=" + sID such that they may update the form.

posted @ Monday, August 20, 2007 1:04 PM | Feedback (3) |

Powered by: