Encryption and Compression – something simple

I’ve been away from coding for a little while, however I needed to make a start on a new tool.

It’s dog simple, but on the off chance it would be useful to others I’m posting it up. Basically its a simple implementation of the built in compression and encryption routines in .net.

A word of warning – if the information is very confidential and high risk, storing your key in the code like I’ve done is a pretty bad idea. 30 seconds with .net reflector or Telerik will reveal it. I’ll amend this post with a more secure version once I’ve worked this out :) .

First I encrypt then I compress. However, the sharp eyed will notice that compression of an encrypted file doesn’t reduce file size – a fact I discovered a few moments ago.


Module StorageTest
    Property Content As New Content 'an arbitrary class with members like a listOfItems As List(Of ItemClass) 
    Private nl = ControlChars.NewLine

    Private Encoded As String = "C:\TestFile\encoded.txt"
    Private Decoded As String = "C:\TestFile\decoded.txt"
    Private CompressEncoded As String = "C:\TestFile\encoded.zip"
'Inexcusable hard coded key for higher risk data!
    ReadOnly TripleDES As New TripleDES(New Byte() {13, 76, 12, 24, 1, 19, 183, 122, 19, 154, 92, 125, 76, 98, 44, 33, 84, 7, 220, 13, 122, 89, 198, 136}) 

    Sub StoreList()
        Dim tempString = ""
'Home brew very quick xml hack. Next version to use proper nested xml
        Dim tagBuild = Function(i, v) i & nl & v & nl & i.replace("<", "</") & nl

'Discovered I can initialise and LINQuery a list at the point of doing a For Each :)
        For Each m In From e In Content.ListOfItems From m1 In {tagBuild("<ID>", e.ID),
                                                              tagBuild("<catagory>", e.Catagory),
                                                              tagBuild("<Name>", e.Name),
                                                              tagBuild("<Order>", e.Order)}
                                                          Select m1
                 tempString += m
        Next

        TripleDES.Encrypt(tempString, Encoded)
        Compress(Encoded, CompressEncoded)
        Decompress(CompressEncoded, Encoded)
        TripleDES.Decrypt(Encoded, Decoded)
        streamWriter.Close()
    End Sub

    Sub Compress(filename As String, zippedFile As String)
        If IO.File.Exists(zippedFile) Then IO.File.Delete(zippedFile)
        If IO.File.Exists(filename) Then
            Using archive As ZipArchive = Open(zippedFile, ZipArchiveMode.Create)
                archive.CreateEntryFromFile(filename, Path.GetFileName(filename), CompressionLevel.Fastest)
            End Using
        End If
    End Sub

    Sub Decompress(ZippedFile As String, UnzippedFile As String)
        If IO.File.Exists(UnzippedFile) Then IO.File.Delete(UnzippedFile)

        If IO.File.Exists(ZippedFile) Then
            Using archive As ZipArchive = Open(ZippedFile, ZipArchiveMode.Read)
                archive.ExtractToDirectory(Path.GetDirectoryName(UnzippedFile))
            End Using
        End If
    End Sub
End Module

Here is the encryption class:


Imports System.Security.Cryptography
Imports System.IO

Public Class TripleDES

    Protected Iv As Byte()

    Protected Key As Byte()

    Public Sub New(ByVal Key As Byte())
        MyBase.New()
        Dim numArray As Byte() = New Byte() {13, 35, 4, 152, 14, 44, 2, 12}
        Iv = numArray
        Me.Key = Key
    End Sub

    Friend Sub Decrypt(Source As String, FileName As String)

        Dim DecodedWriter As New StreamWriter(FileName)

        Using tripleDESCryptoServiceProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
            Using cryptoTransform As ICryptoTransform = tripleDESCryptoServiceProvider.CreateDecryptor(Me.Key, Me.Iv)
                Using fileStream As FileStream = File.Open(Source, FileMode.OpenOrCreate)
                    Using cryptoStream As CryptoStream = New CryptoStream(fileStream, cryptoTransform, CryptoStreamMode.Read)
                        Using srDecrypt As New StreamReader(cryptoStream)
                            DecodedWriter.WriteLine(srDecrypt.ReadToEnd())
                        End Using
                    End Using
                End Using
            End Using
        End Using
    End Sub

    Friend Sub Encrypt(ByVal Data As String, filename As String)

        Using tripleDesCryptoServiceProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
            Using cryptoTransform As ICryptoTransform = tripleDesCryptoServiceProvider.CreateEncryptor(Me.Key, Me.Iv)
                Using fileStream As FileStream = File.Open(filename, FileMode.OpenOrCreate)
                    Using cryptoStream As CryptoStream = New CryptoStream(fileStream, cryptoTransform, CryptoStreamMode.Write)
                        Using srDecrypt As New StreamWriter(cryptoStream)
                            srDecrypt.WriteLine(Data)
                        End Using
                    End Using
                End Using
            End Using
        End Using
    End Sub
End Class

Posted in Uncategorized | Leave a comment

Troublesome Employees?

As a boss, you’ve gotten there on your own sweat and merit. Most likely you didn’t get hand-outs or lots of help in the beginning so you honestly feel you know what you are doing.

*You certainly did otherwise you would have failed.

Then things got more complicated and you find that some employees are difficult. You wish to give direction, state opinion and, ideally, have it taken as fact based on your prior success. Yet there are some pesky people who haven’t even owned a business, saying otherwise. They state you are wrong or haven’t quite got the whole picture, they don’t do exactly what you want in the precise way in which you want it done. They offer their own opinions and defend them just as vigorously.

What is going on?

Let’s put to one side the ones who are just wrong, lazy or even malicious: the incompetent in other words.

Let’s focus on the good ones. These are the worst to handle for the boss who prefers his position and prior success to carry the argument. The best of these may well risk being disciplined in order to ensure that the boss understands them.

How do you know if they are even any good?-a critical question when considering your options.

What to do?
1. Discipline and fire them?
2. Ignore them and issue commands any, in the hope they’ll still go away and do as asked.
3. Engage them, challenge yourself and them, see what happens.

Option 1 has the usual legal and practical implications and only helps if they are not of the good type of difficult employee. Their moving is an opportunity for new talent and even a redefinition of a role; if it’s right for the company, this may be the answer of course.

Option 2 Status quo-if they are any good, they will probably do their best to continue with what they regard as unsatisfactory commands – don’t be surprised if the essential business goal of what you wanted IS gained but the method and fine detail is quite different to the *original edict. *

Option 3 Robust engagement, challenge their thinking, challenge your own; push them to find answers and take the risk of being wrong. Give them the resources and authority to get on with it. If they are good, they will rise to this even if they stumble a lot, they will still fight to meet and exceed your challenge-a loyal but fiercely independent employee actually wants your approval-even when they are cussing behind your back at times. Don’t underestimate passion.

Option 3 has the charm of sorting wheat from chaff. If they are all mouth, shallow sentiment, sounding good business speak-a concrete challenge will floor them quickly. The caveat is the challenge must be reasonable, not “designed to fail” or be “enough rope”.

So when should you consider Option 3?
How DO you evaluate they are good?

Look at the full history of the employee, beware of relying only on surface impressions from memory or other managers; your decision, for it to work, has to rely on a lot of depth – something many will say they don’t have time for, my answer is make the time, the right decision is likely to provide a multiple return on your investment.

What effort do they put into self-development? Is it already benefitting the business?
• Do they provide wider insight than you expect from their stated role?
• Do they care enough to bring real emotion to the table and yet still be productive?
• Are they interested enough in clients to engage beyond “customer service” alone?
• Do they get client feedback and use it?
• If given a task and precise steps of how it should be done, do they achieve the task – often shortcutting or enhancing the micro instructions? **When they dismiss the instructions, is the result out of step with the big picture regularly or have they still done exactly what was needed and better?
• Are they right a LOT of the time, partially right at other times, and when wrong good at handling it?
• Would the business have gotten to this point without them? Note: if it could have gotten further, most of the points above are likely to be “No”.
Let’s be clear here, emotion and intellect in a truly creative, competent individual are equal dance partners; at times one will lead more than the other. This means that you will get passion, anger and the whole gamut of emotions if the person is committed – and that these can be directed by the person into powering the intellect.

An interesting book on this by Rob Goffee can be found here. It’s concise and I believe worth your time if you are leading clever people.

http://www.whyshouldanyonebeledbyyou.com/

If you are dealing with simply a trouble maker, a nay sayer you probably only see whining, resentment and no positive effort to engage intellectually. They won’t study at home, offer solutions and solid argument, they are not interested in creating change or positive change. They just want to gripe, perhaps just too little work for more money or have other issues that are not in your control.

It is common for the most recent surface impressions be the deciding factor for many bosses when making decisions. In fact, it is common for middle management and higher to be somewhat populated by people who’s real competence is being nice and providing the correct surface impression. We are all vulnerable to this surface impression – look for my blog soon on it.

*Staying completely informed and engaged with the real world of clients and their perceptions becomes more of a challenge for the boss who doesn’t wish to be directly involved with clients. Their challenge is to ensure they get clear, unfiltered feedback sufficient to inform their ongoing day to day decisions.
**A number of times I’ve simply had to work around overly micromanaged instructions in one role or another, in order to actually achieve the important element of the instruction. This has risks; if you don’t understand the bigger picture properly you risk distorting it negatively.

Posted in Uncategorized | Leave a comment

Leverage, Business Benefit and Mutual Understanding

As a developer, one of my concerns is that the time I’m using on something has the great leverage for business benefit.

The term business benefit is just short hand for saying will it enhance our income, reputation and future viability. Enhancing either of the latter can only enhance the former.

How do I know what has great leverage? Can I rely on intuition? The best source is solid feedback, systematically obtained from all clients concerned. This is a complex and tricky ideal; an awful lot of it is subjective, difficult to capture accurately and may not even be offered in full.

Some responders may decide not to state the genuine reasons for a negative view. They may feel it’s impolite, not had time to consider it fully, other pressures may be at work or they simply haven’t had sufficient training in the product.

Is there a next best then? Possibly – I’m a believer in client involvement and I also think *depth of sale is critical for any non-trivial software solution.

The premise of specialised software is to provide a natural solution for a specific area of business. This requires deep understanding of this business, its language and its primary concerns – this is why client involvement is critical. Eric Evans in his book on Domain Driven Design tackles this subject head on.

The depth of sale is critical because from here, the relationship has to grow into a deeper mutual understanding.
Initially, the emphasis is on the developer to understand and use the language of the client’s world. Later, the client learns what the developer can really bring to their business and, **if the process is done well, actually use the developers knowledge to create new possibilities for the business.

This becomes more mutual as the developer gains expertise as his or her skill will be to synthesize a number of models of what the client needs. The developer is really looking for the greatest leverage points that benefit the clients’ business; what is the most effective intervention that can be gained with the new software?

I highly recommend Chapter 6 of Thinking in Systems for a brief discussion on leverage points – as developers the higher up the list we can help clients intervene, the greater the value of our solution. These points are something for a later blog, so please stay tuned!

In a previous blog I detail the idea of informed client feedback where, with context, a client can easily realise new possibilities that make a huge difference to the simple day to day operation of their business. This can only come from educated context – if you didn’t know this feature existed, you won’t build on it mentally to come up with a new one.

One piece of software I work with captures a seemingly trivial piece of information every time a note is made-this information is used with immense effect elsewhere in other features. One of which saved a client a large amount of hassle. This client would never have guessed that such a feature would have helped them.

As developers our job isn’t just writing code – that’s just the mechanics. Our job is to help our clients create new possibilities for the future of their business.

If we enable them to succeed in ways they may not have even conceived of, prior to our work, we also succeed.
*Depth of sale quite simply means educate effectively in order to allow clients to make a fully informed sale. Here I have to give credit to Andy Dent of http://www.innovit.co.uk/ for introducing this idea to me years ago in the context of school IT strategy.

** It doesn’t mean the client has to learn to code, but it is beneficial for them to gain an overview of the thought process and analytic skills used by the developer; this way they can ask better questions. This is a virtuous cycle of positive feedback because better feedback means better understanding expressed in the software that means more possibilities and even more feedback and so on… There is a reverse of this of course, an exercise I’ll leave to the reader!

Posted in Uncategorized | Leave a comment

Gathering Requirements

Do you like people? More specifically do you like meeting clients? What do I mean?

And why the developer SHOULD be doing these meetings, not someone else.

Recently I sat with a number of senior managers and directors for a particular group. Not one of them has any interest in what happens deep under the hood when we are talking software. They are interested in making their work easier and more accurate. The session is part criticism and issues, not just positive feedback.

I conduct the meeting in a simple way. A few coloured pens, a hard back plain A4 notebook and a question. “Is it ok if I sit and listen to your questions in turn, make notes and then work out some answers with you?”

Some folks take longer than others to voice their specific issues but everything is written down and I take care to ensure that everyone is able to see what I note and how I *understand them. Repetition is common; I request clarification until I’m sure. About halfway through, the main issues that people have wanted to get off their chest are written down. Everything from here on is refinement.

I take a look at the points and begin with the ones that seem the most pressing, based on the way they are expressed and how important the issue is in the wider context of what they are doing. Then start working out possibilities.
This is the fun bit. Sometimes it’s easy to think users don’t know what they want; often this is partway true. However, this is a limited view. The reality is, given the opportunity, users have a damned fine idea of what they want – they often don’t quite realise it yet.

How does this change? They become aware of possibilities through daily use. Before you had Microsoft Word, did you know you would want auto save, spelling correction or even mail merge?

Before you had GPS in a car, did you know you might need to save favourite places? Search by postcode OR part address? Auto traffic alerts?

Why not? You’d not had a reason to consider the possibility.

Every feature in software has the potential to generate dozens of requirements, new things that people realise are important.

A great requirements meeting is not passive. You don’t sit there with a “customer is right” attitude. You don’t send out a verbal or written survey and hope for results.

You have to get in there and communicate. Encourage their debate and criticism, hell, if they are passionate enough to be somewhat hostile, it can be even better (said with intense caution!). Why? Because they care enough about the needs the software is supposed to meet to gift you with their time, attention and emotion on the subject.

The response to intense criticism should have an attitude of “make me understand and here are some possibilities”.
Ignore how you are going to do it under the hood, forget limitations of technology-the client doesn’t care ultimately about this part-they have **expectations and it’s your job to figure out how to manage AND meet those expectations. Often these are out of reach or possibly on the surface of it, unreasonable. They didn’t think that was the case when they formed them. From their perspective, it’s obvious and natural that feature X should happen “like this” or “look like that”.
My own experience taught me that clients, who are not technical but know their world well, may actually translate a paper based process into a literal screen version of that paper. This isn’t wrong but it can be a weak metaphor and metaphors are the real translation tool for producing real world work from a computer.

When clients discuss their needs, they are translating things that matter in their day to day work. A good developer translates the entire context of their work into something that gives the client this leverage. To give this leverage, it is rarely good enough to simply provide a computer equivalent of what they would otherwise hand write.

A case in point: There is a specific type of reading that is required very regularly, for multiple individuals. The original client request was for a blank sheet-a template-of the form that could be printed and filled in or written on when back at the computer. The form was a periodic set of values per person for a day.

On examination, I gave him the following story: “What if you staff can walk into a room with ANY suitable phone, tap it and see the person in front of them on the phone. From this point on, every single tap could be a reading being recorded. The process takes no longer than the physical act of getting the correct reading and writing it down; it may even be quicker as writing by hand takes a minute. Then the phone is put away, forgotten, whilst the real work is being done. The results end up directly in the persons files from which reports and forms can be generated.”
When the notion was laid out, the client realised I understood the work they were doing and why. I understood his world and had taken the trouble to look beyond the surface impression of the stated need.

This idea was far more welcome than the original paper template idea. The idea uses no more technology than most staff are used to-a mobile phone or indeed for many, a tablet. In addition, many people understand the use of a sat nav, so a phone knowing where it is in a building is a natural leap.

Metaphor is all that a client has when handling a computer. Get this wrong and your software is sunk. We click, swiped, pinch & shrink; open/close and many others. We don’t “0101101”.

Why does anyone bring a computer into the equation? Because they want leverage over their work; they want to it faster, have it be more accurate, more secure, more consistent and far more convenient thus giving them more time to do their real work.

It would be easy for me to get distracted by the programming specifics only; however, I truly believe a really good developer is literate, articulate and keen on understanding their client. They may well engage 50% of their attention to the specifics of their toolkits – frameworks, methodologies, platforms, but the other 50% is on domain expertise of their clientele. If you write software for doctors, you should know common doctor terminology, processes and concerns; understand their job-stopping short of actually being able to do it – this is the ideal of course.

*How you understand something, deep down, defines everything you can reason about it. If you get a subject by rules alone then everything you think of is bounded by the rules not by the principle that underlies those rules. If you understand client need X in a literal sense, you may be limited your solutions deeply to this understand. If, you understand the drive and context for need X you may find a much richer structure upon which to base your new solutions. You job is open up these possibilities, only after understanding the requirements properly.

** Managing expectations is a whole skill in its own right. This is down to how you sold the product in the first place – if the sun, moon and stars were promised, you have a long way to go back tracking in later meetings. On the other hand, if you sold your product on a fairly limited premise then trained your clients well and were consistently receptive when they need help, you shouldn’t get wild expectations-most of the time.

Posted in Uncategorized | Leave a comment

Syntax Highlighter – in 20 minutes…

Ok I cheated slightly, I had the basic sub routine at the bottom of this code already working. The dictionary and lists idea came just now and I’ve implemented it in 20 minutes. This is quick, dirty and Winforms.

Why? I want it for my custom code generator – to be blogged soon.


Module SyntaxHighLighter
    ReadOnly DarkBlue As List(Of String) = New List(Of String)(New String() {"public", "private", "sub", "byval", "byref", "integer", "Friend", "friend",
                                                                       "Shared", "shared",
                                                                    "long", "string", "object", "handles", "for", "to", "as",
                                                                    "if", "in", "then", "end", "next", "loop", "dim",
                                                                   "redim", "new", "of", "and", "function", "class", "me", "#Region", "RaiseEvent", "Return",
                                                                   "While", "With", "Get", "Set", "Property", "#End Region"})

    ReadOnly Grey As List(Of String) = New List(Of String)(New String() {"<#@", "#>"})
    ReadOnly Maroon As List(Of String) = New List(Of String)(New String() {"import", "assembly", "output"})
    ReadOnly Red As List(Of String) = New List(Of String)(New String() {" extension", "namespace"})

    Dim LightBlue As List(Of String) = New List(Of String)(New String() {"implements", "List(Of"})

    Public Sub SyntaxHighLight(richText As RichTextBox)
        richText.Font = New Font("Arial", 10, FontStyle.Regular)
        Dim colourDict As New Dictionary(Of List(Of String), Color) From {{Grey, Color.Gray},
                                                                             {Red, Color.Red},
                                                                             {Maroon, Color.Maroon},
                                                                             {DarkBlue, Color.DarkBlue},
                                                                             {LightBlue, Color.LightBlue}}

        richText.SelectAll()
        richText.SelectionColor = Color.Black

        For Each item In colourDict
            SyntaxHighLight(richText, item.Key, item.Value, FontStyle.Regular)
        Next
  

    End Sub

    Public Sub SyntaxHighlight(richText As RichTextBox, Words As List(Of String), color As Color, style As FontStyle)

        Dim FoundPos As Integer = 0
        For Each w As String In Words
            While FoundPos <> -1 And FoundPos < richText.TextLength
                FoundPos = richText.Find(w, FoundPos, RichTextBoxFinds.WholeWord)
                If FoundPos > -1 Then
                    richText.Select(FoundPos, w.Length)
                    richText.SelectionColor = color

                    richText.SelectionFont = New Font("Arial", 10, style)
                    richText.SelectionLength = 0
                    FoundPos += w.Length
                End If
            End While
            FoundPos = 0
        Next
    End Sub
End Module

Posted in Uncategorized | Leave a comment

Very simple List Comprehension

This is another rushed post making me slightly late for work, but I thought of it in the shower and decided to try and teach to my brother. So forgive the lack of testing of my syntax!

You may see something like (1..10, x > 10, x = x*x)

This is functional programming idea called a list comprehension that makes it easy to get a list and do stuff to it.

Instead of typing


For each person in a list(of person)
     If person.hashairRed and PersonIsFemale then
           GiveBadge(Person)
     end if
Next

This is a list comprehension and my syntax is generic.

Here is how to understand the idea:

1..10 could be any range of values. Say it is a group of ten people.

Then you can decide which people you wish to operate on. So X >10 could be replaced for X is a person with red hair who is a woman .

Then you decide what to do with those people. so X*X so instead I say give each one a badge. This is a function you wish to apply to the individual.

So really I’m saying in a room there are 10 people all mixed and I want to give red haired woman a badge.


(List (of PeopleInARoom), Person.HasHair(Red) =True And IsFemale, GiveBadgeToPerson(Person))

This is a very general way to understand the idea.

Posted in Uncategorized | Leave a comment

Is this a monad?

My first shot at a monad.

Right now my family are due to knock at the front door, yet whilst getting ready I was mulling over monads. I’m now rushing this post to my blog to make sure I have it down. I was explaining monads to myself in the shower and examining them in the light of how would I make LINQ work? I realised that LINQ must be built of continuations, passing values and functions into extension functions. Can I prove that?

This is no definitive answer, just something I created to explain it to myself. The recursion in the extension is completely unnecessary, I was simply proving I could pass in a different function if I wished.

I’m not going to try and explain monads as many others, better than I have done so – plus if the code below is mostly correct, it is probably self explanatory. Make a function that takes a both a value and another function to operate on. I have a feeling there is a bit more to it, answers on a postcard anyone?

Below is the simplest version I could come up with in ten minutes.


Module Monad

    Sub Main()
        Dim testList As New List( Of String) From { "One" , "Three" , "two" , "1" , "Nine" }
        Dim upperCase = Function(x As String) x.ToString.ToUpper
        testList.Continuation(upperCase)
    End Sub

    < Extension()>
    Function Continuation(stringList As List( Of String), f As Func( Of String, String ))

        For Each item In StringList
            Console.WriteLine(f(item))
        Next
        Console.ReadLine()

        Dim test = Function(x) x.ToString.ToLower()
        Return StringList.Continuation(test)
    End Function

End Module

Posted in Uncategorized | Leave a comment

Dyslexia, cognitive styles and “beyond not invented here”

Dyslexia, cognitive styles and “beyond not invented here”

Very crudely, people with dyslexia will rely on a top down, context driven and holistic approach to understanding new information especially text format. Non-dyslexics have an incremental, build part by part approach that requires far less reliance on the whole and context as understanding is built on smaller previous understandings.

When it comes to programming approaches, it is possible to use top down, bottom up and blended approaches. Working from the outside in, or building up function by function. There is no specific correct way, though individual programming problems may require one approach more than another.

However, what about programming psychology? What are the benefits of being more relational, context aware in your processing? What are the benefits of building up piece by piece?

How about drawbacks?

The psychology behind the relational cognitive strategy lends itself to great leaps of contextual understanding but because there is no buildup of incremental concepts, makes it much harder to adapt or adopt new approaches and techniques. This means “not invented here” becomes something more; it becomes a handicap and leads to reinventing the wheel as opposed to reusing perfectly good wheels. The reasoning behind the reinvention is a good one, for the relational thinker. It DOES cost more mentally to understand a whole new framework/technology than it does to reimage it using currently well understood techniques. The downside such reinvention is unlikely to be as deeply developed and tested as solutions publicly available.

The incremental approach has the benefit of being far less likely to suffer “not invented here”, however, it is a more cautious approach, it is possible to be uncertain of where you are in your level of understanding and may take far fewer risks – such as implementing your own wheels. Taking on board new technology and ideas however is much easier, as these can be built upon gradually and related to previous notions. The weakness may be that breakthrough ideas are slower in coming.

Can the two approaches benefit each other and can one person adopt their non native style? The former, I’d claim not only yes but I believe it essential. As to the latter, it remains to be proven.

For me, I’m a slow, incremental standard learner who does want to thoroughly understand something before doing a lot with it. I like to know what I’m building up to and have to consciously think about the contextual, holistic structure rather than starting from it. This latter assertion is open to later re-examination as what happens when I’m really solving a problem isn’t always the same!.

Posted in Uncategorized | Leave a comment

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!

Posted in Uncategorized | Leave a comment

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

<Serializable>
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.

Posted in Uncategorized | 2 Comments