VB.NET - there are times when you have to keep an open mind

I suddenly found myself needing to write a very simple upload method in our MVC controller.  The uploaded file is in CSV format.

The question that immediately jumps to mind is, where do I find a CSV parser?

  • Do I write my own - it may sound simple, but as soon as you start to think about all the various permutations of splitting a line of text, with all the escape characters as well as error handling, actually, it is NOT simple at all
    1. How do you handle the case where the user actually wants to use comma (,) in a field
    2. Do you include or exclude header row
    3. How do you handle line numbers and parse error
    4. What do you do with extra spaces or tabs
    5. How do you handle line breaks
    6. What about lines that didn't have matching number of fields
  • Do I then, just re-use someone else's example
  • Or do I use the one that's supplied and supported by Microsoft, and already installed on your machine as part of the .NET Framework since .NET 2.0?

The answer is blindingly obvious - use Microsoft's one - move on, next problem.

  • Well, it's in Microsoft.VisualBasic.FileIO

Hmm, let me think about this again…

 

This is where I find many C# developers suffer, we would rather build our own untested, unsupported code to do CSV parsing, either with String.Split(',') or with clever Regex.  We're convinced that our own code is better somehow than the Microsoft supplied library.  We're so convinced, we'll run off and spend 30minutes building our own parser, we'll follow by spending 2 hours on testing our parser and making sure it's bulletproof.

So I took a good look at myself and stopped.  I said to myself. 

No, I'll be pragmatic.

 

The Microsoft VB.NET CSV parser is part of the TextFieldParser class.  Documented here:

http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.aspx

 

Through the Common Language Runtime (CLR) we can include Microsoft.VisualBasic library easily in our C# project.  Here they are, happily (may be) next to each other, and doing work for me.

image

 

The actual code is extremely simple:

using (TextFieldParser reader = new TextFieldParser(fileUpload.InputStream))
{
    reader.TextFieldType = FieldType.Delimited;
    reader.Delimiters = new[] { "," };

    while (!reader.EndOfData)
    {
        string[] parts = reader.ReadFields();

        if (parts.Length != 5)
        {
            // problem.
            continue;
        }
        string customerCode = parts[0];
        string customerName = parts[1];
        string contact = parts[2];
        string phone = parts[3];
        string information = parts[4];

        var customer = customers.FirstOrDefault(c => c.CustomerCode == customerCode);
        if (customer == null)
        {
            // new
            customer = new Customer()
            {
                CustomerCode = customerCode,
            };
            Entities.Customers.AddObject(customer);
        }

        customer.CustomerName = customerName;
        customer.CustomerPhone = phone;
        customer.CustomerContact = contact;
        customer.Information = information;
    }
    Entities.SaveChanges();
}

TIP - Silverlight - InitParams and ApplicationLifeTimeService(s)

I have this love-hate relationship with InitParams

Like

  • Pre-download values to Silverlight, so it's available to the client before Silverlight even starts rendering
  • Don't have to worry about whether Silverlight can talk to any data source - if you can't see the webpage then the problem is elsewhere

Dislike

  • Well it's on the web page…  anyone could see it, and probably tweak it via DOM manipulation
  • If you bind to this data, you can't really "update" it if the data changes on the server.  If say the user settings has changed, you'll need a F5 refresh to force the Silverlight client to reload.  In a sense this is often treated like read-only data.

One thing we can fix

  • A really large App.Current with lots of different values sucked out from the initParams during App_Start

 

Using ApplicationLifeTimeServices

1. Write a Lifetime Service

    public class CompanyApplicationLifeTimeService : IApplicationService
    {
        static CompanyApplicationLifeTimeService _current = null;

        public static CompanyApplicationLifeTimeService Current
        {
            get
            {
                return _current;
            }
        }

        #region IApplicationService Members

        public void StartService(ApplicationServiceContext context)
        {            
            _current = this;
            var parseThisStuff = context.ApplicationInitParams;
        }

        public void StopService()
        {
            _current = null;
        }

        #endregion
    }

2. Add this to your App.Xaml

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
             x:Class="DispatchKing.Silverlight.App"
             xmlns:common="clr-namespace:DispatchKing.Silverlight.Common"
             >
  <Application.ApplicationLifetimeObjects>
    <common:CompanyApplicationLifeTimeService x:Name="CompanyLifeTimeService" />
  </Application.ApplicationLifetimeObjects>
  <Application.Resources>
    <ResourceDictionary>
   ...

 

3. Now anywhere in your code you have access to the service Singleton

CompanyApplicationlifeTimeService.Current.GiveMeStuff

Silverlight - sharing a common class between Silverlight and .NET

Because Silverlight is compiled against a separate set of Silverlight runtime, we can not reference or share a common library between a Silverlight project and a normal .NET project.

One very common and simple workaround is then to create a common project for .NET, and a common project for Silverlight, and then add the files as existing links from the .NET project to the Silverlight project.  This ensures that the same files are shared by the two sides and we have our matching class definitions.

 

With RIA, there is a new way.

image

In the .NET project, name your extra files with xxx.shared.cs

Compile your .NET project.  This triggers the RIA toolkit to run and generate some files for us:

image

 

So you no longer need to share a file via external link.

Silverlight - the magic of Silverlight RIA Toolkit

 

I checked in some code.  Moments later, my colleague asked me:

"did you check in the service reference for this ServiceReference.DispatchKing.Web.Services.RunboardDuplexService"

I pondered, and answered:

"no need - it was generated for me"

In deed - my Silverlight project started to do something magical for me.  It was creating GeneratedWcfClientCode\ServiceReference.cs

Because this was generated like RIA services, it was not included in the project, and thus - if you didn't have the right tools installed, it appears that your colleague has forgotten to check in files!

 

image

 

Memory Lane

In the old days before RIA services, we rolled out WCF Service and added our own Service Reference via the Silverlight project.  This generated all sorts of service reference proxy classes.

The biggest downside, is that each time we updated the service, we had to regenerate the service reference, otherwise they'd become out of sync and Silverlight will crash and burn.  (or in the case where it didn't crash… we got really scared).

 

In Silverlight 3 we got RIA and the DomainService, having Silverlight project linked to a Web Project meant that Visual Studio automatically started generating all the RIA/DomainService code, as well as the data objects (or entity) required, and making sure everything's available and synchronized between the Web (service) and Silverlight (client).  There was much rejoicing.

What's this magic?

What made this case really special then, is that I'm not using only Domain Services.

image

 

Hmm it doesn't work for my colleague.  We quickly compared out installed Programs and Features, and found out why:

image

 

You can grab this via Web platform installer, or directly from:

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=7b43bab5-a8ff-40ed-9c84-11abb9cda559&displaylang=en

The RIA Services Toolkit enables the following 5 features:

 

1. LinqToSql DomainService
2. Soap endpoint - This enables you to expose a soap endpoint for your DomainService
3. JSON endpoint - This enables you to expose a JSON endpoint for your DomainService
4. ASP.net DomainDataSource - This control will enable you to create an ASP.net application that can talk to your DomainService
5. WCF client proxy auto generation/updating for WCF Core Service – This enables you to get up-to-date WCF proxy and configuration each time you build your solution, when you add Silverlight-enable WCF service in your Silverlight application.

 

The magic, is number 5.

Silverlight - RadScheduler and required field data validation

In my current project I'm having the pleasure of working with the Silverlight RadScheduler control.  While you may read and feel it is a very bloated control, I argue otherwise, it is highly extensible for such a complex control.  I really think the Telerik guys did a very good job.

My particular scenario is interesting.  I need to:

  1. Extend the appointment dialog to support addresses
  2. The addresses aren't always required (so I can't just use RequiredAttribute)
  3. When fields are required, I'd like the validation to kick off and prevent me from saving that appointment

Here we go:

Updating the RadScheduler template:

This is pretty simple - find the EditAppointmentTemplate

  <ControlTemplate x:Key="EditAppointmentTemplate" TargetType="telerik:AppointmentDialogWindow">
  1. Customize the control template, we added additional fields
  2. NotifyOnValidationError and ValidatesOnException are important.
..snip

          <input:ValidationSummary x:Name="ValidationSummary" />

          <TextBlock Text="Suburb" Style="{StaticResource FormElementTextBlockStyle}"/>
          <TextBox Text="{Binding Suburb, Mode=TwoWay, NotifyOnValidationError=True, 
ValidatesOnExceptions=True}" />

Extend the Appointment class:

  1. Create a ValidationEnabled property - sometimes you need to "not validate"
  2. Create a ValidateProperty method - this takes a property name and triggers all validate attributes on that property - Validator.ValidateProperty is the method that will trigger all kinds of fun validation exceptions for us.
  3. Set the appropriate validation attributes on the property e.g. Suburb - I'm using a custom validation property that I've created based on the RequiredAttribute
  4. In the setter, call ValidateProperty.
    public class JobAppointment : Appointment
    {
        private string _suburb;

        public ObservableCollection<ValidationError> Errors { get; set; }

        public bool ValidationEnabled
        {
            get;
            set;
        }

        private void ValidateProperty(string propertyName, object value)
        {
            if (ValidationEnabled)
            {
                var context = new ValidationContext(this, null, null);
                context.MemberName = propertyName;

                Validator.ValidateProperty(value, context);
            }
        }

        [ValidationRequired]
        public string Suburb
        {
            get
            {
                return _suburb;
            }
            set
            {
                ValidateProperty("Suburb", value);

                if (_suburb != value)
                {
                    _suburb = value;
                    OnPropertyChanged("Suburb");
                }
            }
        }

Add our own Validation attributes

  1. This Required attribute checks against our settings to see if "Suburb" happens to be a required field.  If not, then skip the validation and just return success.
 public class ValidationRequiredAttribute : RequiredAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (SettingsLifeTimeService.Current != null )
            {
                if (SettingsLifeTimeService.Current.RequiredFields.Contains(validationContext.MemberName))
                {
                    // RequiredAttribute validation
                    return base.IsValid(value, validationContext);
                }
            }
            return ValidationResult.Success;
        }
    }

 

Stop validation on Scheduler's Appointment_Saving event

  1. In the AppointmentSaving event, grab all the children framework elements from the appointment dialog window
  2. Find their binding expression (e.g., for TextBox I want the binding expression for Textbox.Text)
  3. If exists, I want it to push the values back into the datasource (our customized Appointment class) - this triggers the property setter (which triggers our ValidateProperty, which triggers the custom Required attribute)
  4. Finally, check the validation summary to see if we have any binding errors, if we do, cancel the save.
void _scheduler_AppointmentSaving(object sender, AppointmentSavingEventArgs e)
        {
            JobAppointment jobApp = e.Appointment as JobAppointment;
            AppointmentDialogWindow window = e.OriginalSource as AppointmentDialogWindow;
            var children = window.ChildrenOfType<FrameworkElement>();

            if (children != null)
            {
                foreach (var element in children)
                {
                    BindingExpression binding = null;
                    if (element is TextBox)
                    {
                        binding = element.GetBindingExpression(TextBox.TextProperty);
                    }

                    if (binding != null)
                    {
                        // force control to update databound VM.  This triggers the validation.
                        binding.UpdateSource();
                    }
                }
            }

            ValidationSummary summary = window.FindChildByType<ValidationSummary>();

            if (summary != null)
            {
                if (summary.HasErrors)
                {
                    e.Cancel = true;
                    return;
                }
            }
        }

Finished!

 

image