Exception Aspect – a quick but real example

After my previous post, I realised it probably wasn’t hard to actually DO something with the PostSharp aspect library. As it happens, I’ve got a work experimental project I’m playing with that would benefit from exception logging. This saves me bothering with endless Try…Catch blocks. This implementation doesn’t distinguish the exception types as all I want is a running log of the specific messages. The getexceptionmessage routine is a simplistic means of grabbing inner exceptions to a string.

Imports System.ComponentModel
Imports System.IO
Imports System.Text
Imports PostSharp


<Serializable>
Class ExceptionAspect
Inherits PostSharp.Aspects.OnMethodBoundaryAspect

Public Overrides Sub OnException(args As Aspects.MethodExecutionArgs)
    If returnInnerExeception(args.Exception) <> "" Then
        LogWrite(returnInnerExeception(args.Exception))
    Else
        args.FlowBehavior = Aspects.FlowBehavior.Continue
    End If
End Sub

Private Sub LogWrite(errorString As String)
    Dim fileName = "\errorLog.txt"
    Using fs As StreamWriter = File.AppendText(fileName)
        Log(errorString, fs)
    End Using
End Sub

Public Shared Sub Log(logMessage As String, w As TextWriter)
    w.Write(ControlChars.NewLine + "Log Entry : ")
    w.WriteLine("{0} {1}", DateTime.Now.ToShortTimeString(), _
        DateTime.Now.ToLongDateString())
    w.WriteLine("  :{0}", logMessage)
    w.WriteLine("-------------------------------")
End Sub

End Class

'To use it, simply add an annotation above your class as shown. There are similar, simpler variations that are method level annotations but for this piece - a repository - all the methods needed exception handling. `
 <ExceptionAspect>
Public Class Repository 
' Methods etc
End Class
` Thanks again to Mr Groves!

Aspect Orientated Programming – also F# CSV Type Provider

Aspect Oriented Programming – Another morning challenge

I don’t like repeating and copy paste code, its hard to maintain and its way to tempting to do it – “to get it working”. So when Manning offered me a discount on their latest Early Access Book of 50%, I felt it’d be rude not to.

This is a programming concept that very simply allows you to weave consistent code for so called cross cutting concerns throughout your classes.
A cross cutting concern is something that each class may have to be concerned with, yet definitely should NOT be implementing in its own way. For example, error logging, auditing or security is needed through most parts of any modern application.

An aspect is nothing more than code that handles this work for you that is then woven into each class with the assistance of annotations and a framework like PostSharp.

Below is my first attempt at using this, in VB, to inject a very simple method. Note all the aspects setup affect each method defined in the class. Perfect if you’ve a logging system setup.

Next post is doing something more useful with this! Coding time, including playing with references 25 minutes. The book is done in C# so swap [] for <> in your annotations!

To install, in VS2012 use Nuget Package Manager to find PostSharp as an evaluation.

Book: AOP in .Net from Manning


Imports PostSharp
Class MainWindow
'Everything in SimpleAspect is applied to every method in this class.
< SimpleAspect>
Private Sub Button_Click_1()
Textbox1.Text = "This is normal text"
End Sub
End Class


Class SimpleAspect
Inherits PostSharp.Aspects. OnMethodBoundaryAspect

Public Overrides Sub OnEntry(args As Aspects. MethodExecutionArgs )
MessageBox .Show("Aspect injected stuff" )
End Sub

Public Overrides Sub OnExit(args As Aspects. MethodExecutionArgs )
MessageBox .Show("Aspect Exit injected stuff" )
End Sub

End Class

F# and CSV exploration: As part of a slightly larger project I’ve been exploring the use of type providers to talk to a CSV file. Finally, today I got a working console app that does nothing more than spit these out to the console 🙂


open Samples.FSharp.CsvProvider
let surguries = new Samples.FSharp.CsvProvider.MiniCsv< "T201111ADD REXT.csv">()

let surgurylist = surguries.Data |>Seq.iter( fun x -> printfn "%A - %A - %A" x.``201111`` x.A81001 x.``CLEVELAND ``)

A quick note: problems with a reference you KNOW exists in FSharp? Source file order is important! Right click the main file, move down until its last in the list. Like magic, red wriggles go away.

R in F Sharp – Another morning post

In the spirit of expanding my toolbox, todays’ challenge has been to learn what R is, how to do something with it and use it in a .net project. Why?

Any language that can produce a graph straight into a pdf in this few a number of code lines looks vaguely useful right?

pdf("test1.pdf")
hist(rnorm(100))
dev.off()

In the process I learnt that there is a difference between a histogram and a bar chart-roughly speaking, a histogram has x values that are a continuous domain whereas a bar chart can be used to compare apples & oranges. Corrections in comments please.

A second reason is F# Type Providers. These things are fantastic – a prime candidate for unintended Golden Hammer usage. Imagine you can treat massive and varied data sources in a strongly typed, easily accessible manner; as if you’d got a class structure already defined for them.

Turns out you can stick the R language right into F#:

Example

This is a provided example, nothing clever here. However as F# can be compiled and used in C#/VB projects, a more mainstream application could be put together with the facilities that both R and F# provide.

In other words, polyglot programming.

F# Odata and Netflix – Day 3

A third morning before work challenge in a row – I’ll have to watch out, I might get a habit!


Today it was the turn of the Netflix Odata feed. This is a nice API to work with and I was able to produce a reasonable, if rather basic implementation in a very short space of time. It qualifies for the 1 hour in the morning tag I think.

Here’s the F# dll part:

type netflix = ODataService<"http://odata.netflix.com/Catalog/">

let films = netflix.GetDataContext()

let FilmSearch title number =
query {
for film in films.Titles do
where (film.Name.Contains title)
take number

}

Here’s the simplist VB implementation – note the decided lack of Datatemplates. What I should do is bind a template to instances of the movie list. Another day.


Function buildFilmStackPanel(Title As netflix.ServiceTypes.Title)

Dim stack As New StackPanel
Dim Filmtitle As New Label With {.Content = Title.Name, .ClipToBounds = True}
Dim Synopsis As New TextBlock With {.Text = Title.Synopsis, .TextWrapping = TextWrapping.Wrap, .FontSize = 10, .ClipToBounds = True, .MaxWidth = 400}

Dim imageStr As String = Title.BoxArt.MediumUrl
Dim image As New Image() With {.Source = New BitmapImage(New Uri(imageStr)),
.Width = 256,
.HorizontalAlignment = Windows.HorizontalAlignment.Left}

stack.Children.Add(Filmtitle)
stack.Children.Add(Synopsis)
stack.Children.Add(image)
Return stack
End Function

This is probably the end of the series on simple OData access, next steps are either Fsharp R Type providers or something else 🙂

Edit: I’m sorry but I don’t like WordPress so much; it keeps losing Code tags!

Ebay Odata – 2nd Morning

Last post I had a few deals showing from Ebay but nothing like a real search of their items. Today, thanks to assistance with my syntax from Robert Jeppeson @ StackOverFlow, this is now done. Forgive my lack of designer coolness!

My XAML work leaves some styling to be desired!


Private Sub search_Copy_Click() Handles search_Copy.Click
DealResults.Items.Clear()
If title.Text <> "" Then
For Each item In ItemSearch(title.Text, resultNumber.Text)
DealResults.Items.Add(buildStackPanel(item))
Next
End If

End Sub

Function buildStackPanel(ebayItem As Catalog.ServiceTypes.Item)
Dim stack As New StackPanel
Dim title As New Label With {.Content = ebayItem.Title}
Dim imageStr As String = ebayItem.GalleryUrl
Dim image As New Image() With {.Source = New BitmapImage(New Uri(imageStr)),
.Width = 256,
.HorizontalAlignment = Windows.HorizontalAlignment.Left}
stack.Children.Add(title)
stack.Children.Add(image)
Return stack
End Function

A note on the white spacing (#light directive) in F#. It seems a bind that F# uses whitespace to determine when a structure ends, instead of End class/function etc or }. However, it does make for neat code. Also, it’s easy to get used to tab counting as a quick way to line up code blocks.

OData, F# and VB

Each morning before work I do an hour of trying something new with programming technology. Today its the turn of OData, F# and TypeProviders. And VB because I didn’t have time to work out WPF in F# – instead I learnt how to use an F# Dll within VB.

First, ugly rushed form in VB:

Next, F Sharp Type provider as a simple DLL. This is missing Take 10, but the syntax to make this work eluded me in the time allotted.


namespace ODataSearch

open Microsoft.FSharp.Data.TypeProviders

module SimpleSearch =

type stackData =
ODataService<"http://data.stackexchange.com/stackoverflow/atom">

let context = stackData.GetDataContext()

let siteSearch title body = query {
for post in context.Posts do
where (post.Tags.Contains(title) && post.Body.Contains(body))
count
}

let search title body = siteSearch title body

let resultsList title body = query {
for post in context.Posts do
where (post.Tags.Contains(title) && post.Body.Contains(body))
select post
}

Next the VB where I cheat and add the Take(10) here.


Private Sub search_Click(sender As Object, e As RoutedEventArgs) Handles search.Click
If title.Text <> "" And body.Text <> "" Then
'Dim textSearch = siteSearch(title.Text, body.Text)
'results.Text = textSearch
For Each post In resultsList(title.Text, body.Text).Take(10)
firstTen.Items.Add(post.Title)
Next
End If
End Sub

This is pretty simple stuff, if you forgive the time spend frustrated with figuring out syntax. The OData type provider gives you intellisense and strongly typed access to any site offering the support for it.

Thanks to http://www.developerfusion.com/article/145919/an-introduction-to-f-type-providers/

Lets talk to Ebay next, whats on offer?

type Catalog = ODataService< "http://ebayodata.cloudapp.net/" >

let ebay = Catalog.GetDataContext()

let trial =
[ for deal in ebay.Deals do
yield deal]

So far, I can only get the Deals to do anything from this feed. Updates may come later.
Here is the VB WPF code – I fancied some pics but didn’t take time to build a data template.

Private Sub search_Copy_Click() Handles search_Copy.Click
DealResults.Items.Clear()
For Each item In trial
DealResults.Items.Add(buildStackPanel(item))
Next
End Sub

VB Code

Function buildStackPanel(ebayItem As Catalog.ServiceTypes.Deal)
Dim stack As New StackPanel
Dim title As New Label With {.Content = ebayItem.Title}
Dim imageStr As String = ebayItem.Picture175Url
Dim image As New Image() With {.Source = New BitmapImage(New Uri(imageStr)),
.Width = 64, .Height = 64,
.HorizontalAlignment = Windows.HorizontalAlignment.Left}
stack.Children.Add(title)
stack.Children.Add(image)
Return stack
End Function

This is what it looks like: