Thursday, October 7, 2010

A look at Entity Framework

What I have been doing since.

Been a while since I posted here. Blame real life and some computer issues. Purchased a new laptop as spring with the intension of it being my new development machine and that I would make more use of virtual machines and such tricks.
For the last month it has been unavailable to me as it was randomly crashing. I have been on the phone with Dell tech support several times for hours on end the issue is still unresolved but meanwhile I returned to my old  machine which in spite of making the occasional funny fan noise it is still soldiering on. I rebuilt my database server on another machine and need to look into backup solutions as my 1TB NAS disk is filling up faster than I would like.

Exploration of Entity Framework

One of the things I have been researching recently is Entity Framework, this is mainly because i have been considering of applying it to a project i have been working on. However, I have noticed a couple of things on my explorations on the web; most of the code is in C# and the examples are either, trivial or very complex. So after some research I have decided to purchase a book. In general I think to learn better from books if I need more in-depth knowledge. So I choose “Entity Framework 4.0 Recipes – A problem-Solution Approach” by Larry Tenny and Zeeshan Hirani. Of course it is written in C#, one wonders is there a deliberate policy of deprecating vb.net or do they simply consider that all serious programmers are using C#. Anyway I decide it would be fun for me to rewrite all the listings in vb.net. This would serve two purposes; it would consolidate my knowledge of C# and learn some new tricks in vb.net. I even emailed Apress asking permission to list here, the vb.net translations of the code listings in the book (Never heard anything back – so I guess I won’t go there).
So far I have just completed chapter 2 which covers various scenarios concerning the way different database table structures could be modelled in the Entity Framework. Chapter 2 covers the following scenarios:
  • Creating a simple model
  • Creating a model from an Existing database
  • Modelling a Many to Many relationship with no payload
  • Modelling a Many to Many Relationship with a payload
  • Modelling a Self-Referencing Relationship
  • Splitting a Entity across multiple Tables
  • Splitting a Table across multiple Entities
  • Modelling Table per Type inheritance
  • Using Conditions to filter an ObjectSet
  • Modelling Table per Hierarchy inheritance
  • Modelling Is-a and Has-a relationships between two Entities
  • Creating, Modifying and Mapping Complex Types.
One tool that I have found invaluable is a C# to VB convertor. The content is pretty clear and gives the step by step instructions to complete the tasks. All the code examples are console applications and so far the code to write data to the database and retrieve the data and display the returned data in the console, are given in the listing for each section.
Now I am not going to create tutorials on Entity Framework. I don’t yet know enough about the topic and the basics are well covered on MSDN, what I intend to do in this and future posts is create a guide to the “Entity Framework Recipes” book mentioned above. So basically I’ll list the topics covered in a chapter and include some code, the original C# listing and my vb.net translation.
So if we take the data tables shown in  below.Tables used in example
So the business table is a base set of information and the Retail and eCommerce tables hold additional information that relate to that type of business.



When you initially create a new Entity Framework mapping you get a similar set of entities.
Initial Entity Framework mapping

Here we have the same tables as Entities in the Entity Framework mapping created by default. The relationships will be edited  and replaced by inheritance relationships.
Delete the existing relationships and replace with inheritance relationships. Also remove the primary key entries in the inherited entities and then check that the mappings are still correct.



The final version of the used in the application looks like this.
Entity Framework Final Mapping
The C# code listing to write the data to the database and then retrieve it and display it to the console looks like the following code.
          using (var context = new EFRecipesEntities())
            {
                var business = new Business
                {
                    Name = "Corner Dry Cleaning",
                    LicenseNumber = "100x1"
                };
                context.Businesses.AddObject(business);
                var retail = new Retail
                {
                    Name = "Shop and Save",
                    LicenseNumber = "200C",
                    Address = "101 Main",
                    City = "Anytown",
                    State = "TX",
                    ZIPCode = "76106"
                };
                context.Businesses.AddObject(retail);
                var web = new eCommerce
                {
                    Name = "BuyNow.com",
                    LicenseNumber = "300AB",
                    URL = "www.buynow.com"
                };
                context.Businesses.AddObject(web);
                context.SaveChanges();

            }
            using (var context = new EFRecipesEntities())
            {
                Console.WriteLine("\n--- All Businesses ---");
                foreach (var b in context.Businesses)
                {
                    Console.WriteLine("{0} (#{1})", b.Name, b.LicenseNumber);

                }
                Console.WriteLine("\n--- Retail Businesses ---");
                foreach (var r in context.Businesses.OfType<Retail>)
                {
                    Console.WriteLine("{0} (#{1})", r.Name, r.LicenseNumber);
                    Console.WriteLine("{0}", r.Address);
                    Console.WriteLine("{0}, {1} {2}", r.City, r.State, r.ZIPCode);

                }
                Console.WriteLine("\n--- eCommerce Businesses ---");
                foreach (var e in context.Businesses.OfType<eCommerce>)
                {
                    Console.WriteLine("{0} (#{1})", e.Name, e.LicenseNumber);
                    Console.WriteLine("Online address is: {0}", e.URL);
                }
            }
        



The same code in VB.Net



  Using context As New EFRecipesEntities
            Dim business = New  Business  With {.Name = "Corner Dry Cleaning", _
                                              .LicenseNumber = "100x1"}
            context.Businesses.AddObject(business)
            Dim retail = New  Retail  With {.Name = "Shop and Save", _
                                          .LicenseNumber = "200C", _
                                          .Address = "101 Main", _
                                          .City = "Anytown", .State = "TX" _
                                         , .ZIPCode = "76106"}
            context.Businesses.AddObject(retail)
            Dim  web = New  eCommerce  With {.Name = "BuyNow.com", _
                                          .LicenseNumber = "300AB", _
                                          .URL = "www.buynow.com"}
            context.Businesses.AddObject(web)
            context.SaveChanges()

        End Using
        Using  context = New  EFRecipesEntities
            Console.WriteLine(ControlChars.Lf & "--- All Business ---")
            For Each b In context.Businesses
                Console.WriteLine("{0} (#{1})", b.Name, b.LicenseNumber)

            Next
            Console.WriteLine(ControlChars.Lf & "--- Retail Business ---")
            For Each r In context.Businesses.OfType(Of Retail)()
                Console.WriteLine("{0} (#{1})", r.Name, r.LicenseNumber)
                Console.WriteLine("{0}", r.Address)
                Console.WriteLine("{0}, {1} {2}", r.City, r.State, r.ZIPCode)
            Next
            Console.WriteLine(ControlChars.Lf & "--- eCommerce Business ---")
            For Each e In context.Businesses.OfType(Of eCommerce)()
                Console.WriteLine("{0} (#{1})", e.Name, e.LicenseNumber)
                Console.WriteLine("Online address is: {0}", e.URL)
            Next
        End Using
  

Thursday, June 24, 2010

A funny thing about Web Services in Visual Studio 2010

As mentioned in my profile, my primary activity these days is caring for mother but I have a couple of projects on the go as well when I get the chance to code. One of these project is porting a previous project to VB.NET 2010, party to learn 2010, partly to take advantage of some of the .NET 4.0 technologies to make the application more maintainable and efficient.

So far I have managed to port over all the source code and the existing NUnit tests, converting the NUnit tests to MSUnit Test as I go. So I had all my unit test running (or so I thought, it turns out I had missed some) and I tried running the application. So splash screen appears and login then I select one of the user screen from the main menu and bang! the application crashes.

The application has a dependency on Adobe Reader in several screens and Adobe does not  play well in 64bit environments. So then I get that working by setting the target CPU to x86 and now I can open the application view the screens but now there is no data on several. It turns out that the Web Services are throwing errors.

WebServiceError

So I googled the error and got a lot of info on checking that the .asmx file markup refers to the correct namespace and the code behind class is correctly named, also that the namespaces match. All of this I played around to no effect but of the 3 services one was working.

To no avail, it turns out that the code behind should be in an App_Code folder, even though Visual Studio did not create one when I created the .asmx file.

Must play around with this  some more.

Wednesday, June 9, 2010

For the Next Time I am moving a SQL Database to another server

Not a lot to comment on this; there is a good discussion here but the key bits to lookup on Books Online are:

The stored proceedure sp_change_users_login, look up the topic Troubleshooting Orphaned Users and the proceedure sp_validatelogins. That should be enough to get it all working when I need to to do it about 2 to 3 years as that seems to be the pattern of these things.

Tuesday, May 25, 2010

The Joy of HTML

Or more precisely the joy of xhtml, Now I had a website back in the mid nineties. it is long defunct though I still have the files, having found them on an old drive I rehabilitated recently. More specifically I am using “HTML4 for Dummies” by Ed Tittel and Stephen Nelson Jame and also “HTML, XHTML & CSS” by Ed Tittel and Jeff Noble. The site is for my brothers mountaineering web site; He manages most of his activities through face book and email.
So he wanted a simple page, with very little configuration, allowing contact but protecting his email from spam harvesters. The page is pure HTML and CSS for layout. So far, we are still tweaking it. it looks good on IE8 and Firefox. I still need to check on it in Safari on the iphone and the Palm Pre.
To hide the mail I used the catchpa service provided by Google called MailHide. By default this produces an email address that looks like “nam…@domain.com” with the ellipsis providing the link. Clicking on the link opens a pop up window that has the captcha and solving this reveals the email as an embedded mailto: link.  Since we did not like this we edited the generated code to replace the ellipsis with an image and removed the remaining original text of the email address.
The other problem, I have is with the Facebook like button. Here I was getting a popup window with error and nothing else much, no error message or anything of help. Some Googling later got me to this blog entry which I hope will solve the issue. I have to test that part yet.
Turns out that the problem (may have been blindness on my part since I did not see the textbox to enter the url for the site hosting the like button. It all seems to be working now. Firefox allows one to see who has liked the site but IE8 does not.

Tuesday, April 13, 2010

The Mocks are Mocking me.

A few years ago I heard about the idea of mock testing and tried to apply it to my code. I choose to use the DotNetMock framework because it worked in a way that I could get my head around. However, my approach begged a few questions as was a lot of work. It was pretty close to the older way of working with mocks where people code the mocks and the stubs and so forth, (for a good introduction of what that is all about see Martin Fowler's article
'Mocks aren't Stubs'. So now, I decide to refractor the code to improve performance and to do it with Visual Basic 2010 using the MSUnitTest framework. So I have already posted about converting from NUnit to MSUnitTest. So adding in the DotNetMock stuff should be a piece of cake, right? Just reference the DotNetMock.dll and away you go. Not so, I try that and I get an error in the tests.
Test method TestMasterList.TestAssemblies.TestGetNewCode threw exception:

System.TypeInitializationException: The type initializer for 'DotNetMock.Assertion' threw an exception. ---> System.SystemException:
Cannot find an appropriate test framework implementation.
At this point I search around for an alternative testing framework for Mock testing and the biggest buzz seems to be about
Rhino.Mocks and TypeMock however, the latter is a commercial product. So the problems are; most of the examples are in C#, they make extensive use of lambda expression and what I can find in vb use an older syntax for the mock code. Now, I know nearly nothing about lambda expressions, part of the reason for this exercise is to learn some of the new shiny stuff that has come out over the last 4 or 5 years by refactoring the code to take advantage of this stuff and get some improvement in performance. To do that I want to know my existing tests are working. So I try to learn Rhino.Mocks and start a new project to do it. I decide to implement a view model controller in windows forms with a passive view and the view communicating to the controller using events. The test is failing for reasons that are unclear to me and I have posted to the Google Group (aka Usenet) Rhino.Mocks with this post
So meanwhile while I try to learn Rhino.Mocks and lambda syntax what do I do. DotNetMock is defunct as far as I can tell and from what I have seen in Rhino and other mocking frameworks, it was a dead end approach anyway. However, I have code that uses that approach and I need to get those tests to run. So I decided to create my own replacement for the element of DotNetMock that I use. Essentially I used the DotNetMock.Mock class and the ExpectationCounter. When I created a mock class I inherited from the base DotNetMock.Mock class so that i could use the Verify method to determine that the expectations I had set had been fulfilled. Now expectations were set using the ExpectationCounter as a member level variable in Mock class.
To give an example; for the interface IFoo declared below


    Public Interface IFoo

       Sub SomeMethod()

    End Interface

In the DotNetMock style this would be implemented as a mock class thus;

    Public Class MockFoo

       Implements IFoo
       Private _ExpectSomeMethodCall as New ExpectationCounter("SomeMethod")



       Public Sub SetExpectationOnSomeMethod(ByVal expectedCalls as integer)

          _ExpectSomeMethodCall.Expect = expectedCalls

       End Sub

       Public Sub SomeMethod() Implements IFoo.SomeMethod

          _ExpectSomeMethodCall.Inc

       End Sub
    End Class

In this case the mock class would be injected into what ever class that uses it and when your test code would call the MockFoo.Verify method it would not throw an exception if the number of calls to the "SomeMethod" method matched the value set in the expectation. Now my problem was how to do this in a testable way that was generic and would not require a custom Verify method in every case of the Mock class in the test projects.
The answer was to create a custom ExpectationCounter class.


Public Class ExpectationCounter



    Private _p1 As String



    Sub New(ByVal p1 As String)

        _p1 = p1

        _receivedCalls = 0

    End Sub



    Property Expected As Integer



    Private _receivedCalls As Integer

    Sub Inc()

        _receivedCalls += 1

    End Sub



    Sub Verify()

        If Me.Expected = 0 Then Throw New ExpectationException(String.Format("No expectations set for '{0}'", _p1))

        If _receivedCalls <> Me.Expected Then



            Throw New ExpectationException(String.Format("Expected calls for '{0}' did not occur, Expected {1} got {2}", _p1, Me.Expected, _receivedCalls))



        End If

    End Sub



End Class



and a Mock Class
Imports System.Reflection



<clscompliant(true)>

Public Class Mock



    Public Sub Verify()

        Dim ex() As FieldInfo

        Dim isAnExpectationFieldPresent As Boolean = False

        ex = Me.GetType.GetFields(BindingFlags.NonPublic Or BindingFlags.Instance)

        If ex.Length <= 0 Then Throw New ExpectationException("No expectation fields set")



        For Each expectations As FieldInfo In ex

            If expectations.GetValue(Me).GetType.ToString = "ArdoughterSoftware.MockFramework.ExpectationCounter" Then

                isAnExpectationFieldPresent = True

                CType(expectations.GetValue(Me), ExpectationCounter).Verify()

            End If

        Next

        If Not isAnExpectationFieldPresent Then

            Throw New ExpectationException("No expectation Field set")

        End If

    End Sub



End Class

Now this should let me replace the DotNetMock with my own version and get my existing test to run. I would also expect that they would pass since they did the last time I ran tests on this code. Eventually once I figure out Rhino.Mocks I will replace all the DotNetMock/MyMocks with equivalent tests in that system So then I should be back to my original state but now in VS 2010. Then I can add additional tests to check on performance and then refractor from there.
Since Rhino.Mock is poorly documented in VB.NET I fully intend to post on my learning experiences and perhaps but a full journal of the development of the fantasy calendar project as future blog posts. It will make the project a bit more complicated that the application requirements might merit but in this case the requirements are to learn the mocking framework and the working fantasy calendar is a secondary target.

Monday, March 29, 2010

Unit Testing in Visual Studio 2010 and converting from NUnit

Previously I had a project in VB.NET 2005 that was developed using a Test Driven Development approach. My test framework of choice was NUnit .
The screen shot Left should an example of the NUnit user interface in action. In this case with failing and interrupted tests.

In this case the tests are failing but in a sucess case the progress bar would be green and the unit test would have green buttons instead of red ones as in the image below.

One thing to notice is that NUnit gui automatically groups the tests according to the dll it is in and the class that it belong to.


 Now, the code is pretty simple, you can add a class, import the reference to the NUnit Framework and add the attribute to the class and a attribute to method that implements the test as shown in the code sample below.


<TestTixture()>
Public Class TestLookup

Private mLk As New Lookup

<Test()>
Public Sub TestNewLookup()

Dim lk As New Lookup
Assert.IsNotNull(lk)
End Sub

End Class


When converting to Visual Studio 2010 release candidate I found that it was most convenient to recreate the project files in Visual Studio and copy the code files in to the appropiate folder and then add them to the projects. In my case it also helped clean up the project structure that had become a little disorganised over the project cycle. So I cannot comment on the ability of Visual Studio to convert from the earlier format. I also choose this route as I wanted to use the built in unit testing rather than NUnit. Visual Studio holds unit test is a specific project type and I have not found any obvious way of converting a code library to a test project. I suppose I could go around editing the project files but at this stage that was not a route I wanted to take.




The Visual Studio Test Editor window is seen above and the test list on the left is manually organised by creating test list that correspond to the classes. The tests themselves are included automatically when you convert the NUnit attributes to their Visual Studio equivalents.

The following code shows a class originally created in NUnit now in VS test format

Imports Techrete.MasterListData
Imports Techrete.SharedLibrary
Imports System.Data.SqlClient
Imports Microsoft.VisualStudio.TestTools.UnitTesting

<testclass()> _

Public Class TestManageIndices


    Private mObject As String

    Private mPrefix As String

    Private mDoReset As Boolean = False

    Private mResetIndexValue As Integer


<testcleanup()> _
Public Sub Cleanup()

       Dim cn As SqlConnection = TestComponentsData.GetDataConnection

        Dim cmd As New SqlCommand("Update csm_ManageUserIndexes Set LastIndex = " & mResetIndexValue.ToString _
 " Where [Object] = '" & mObject & "' and Prefix = '" & mPrefix & "'", cn)

        If mDoReset Then

            Try
                cn.Open()

                cmd.ExecuteNonQuery()

            Finally

                cn.Close()

            End Try

        End If

    End Sub

    <testmethod()> _
    Public Sub TestAssemblyIndex()

        Dim lastIndex As Integer

        Dim currentIndex As Integer

        Dim prefix As String = "F"

        'Now obtain the last index and increment by 1

        'then save it - that should succeed and save it again - that should fail.

        Dim sql As String = "Select LastIndex from csm_ManageUserIndexes Where Object = 'Assembly'"

        Dim cn As SqlConnection = TestComponentsData.GetDataConnection

        Dim cmd As New SqlCommand(sql, cn)
        Try

            cn.Open()
            lastIndex = CInt(cmd.ExecuteScalar)
        Finally

            cn.Close()

        End Try

        currentIndex = IndexData.GetLastIndex("Assembly", prefix)

        Assert.AreEqual(lastIndex, currentIndex)

    End Sub
 End Class

One big difference is that in the current release of Visual Studio the Assert.AreEquals does not appear to work as in NUnit. In that you can have two object of the same type and with the same property values and in NUnit they will pass but in Visual Studio they will be considered not equal. It appears that at the moment Visual Studio only accept that two object that have the same address in memory are equal and there is no functional difference between Assert.AreEquals and Assert.AreSame.

Thursday, March 4, 2010

Windows 7 Networking

So the last time I posted about Windows 7 my desktop machine failed to boot. For a long while I ignored it as it was not all that important to anything I was doing.

Anyway recently I was passing the machine and I pressed the power button and what do you know it booted. It had to run some repair routines but it booted. So I ran a virus scan and did get some report of a virus. Also an external drive had some hidden files that I could not access. So I removed the virus and reformatted the drive.

Then I went back to installing the shared printer. The routine was the same as I described in the previous post but again no documents would print. So I found a tip (cannot remember where right now) but simply install the printer as local (after installing the networked printer) and add a local port that maps to:


\\server\pinterShareName

I then has to install the same printer on my nephews mac notebook. So from this thread I followed the steps listed, which I will repeat here.
On the Windows 7 PC:

  1. Open Control panel
  2. Select 'Programs and Features' pane
  3. Click 'Turn Windows Features on or off'
  4. Check on the LDP protocol
  5. Make sure that the printer is shared and that the shared name is short and all one word with no spaces


On the Mac:

  1. Start/Applications/Unitities/Printer Setup Utility
  2. Hold down the option key and click the 'More Printers' button
  3. From the top menu select 'Advanced'
  4. From the Device field select 'LDP/LPR Host or Printer'
  5. In the 'Device url:' field type 'lpd://PCName/PrinterShareName'
  6. Click the Add Button

Friday, February 12, 2010

eReaders

Just some thoughts on eReaders, I downloaded Stanza last week for my iPhone and have read 2 books on it since.
The books were 'Alice in Wonderland' which came with the eReader app and 'On Basilik Station' which is available on the Baen Free Library. The interesting thing is that I read both books in about a week which is unusual for me these days. I have a lot of distractions (usually the net ) and I tend to be slow reading books unless the book really grips me and I was wondering about that. It occurred to me as I was reading books on the iPhone that I had returned to a reading pattern that I had as a teenager when I always had a paperback in my pocket and I took it out and read it whenever I had a quite moment alone. In this fashion I got through quite a few books. 
My reading rate did not really diminish until I left college and most dramatically when I left fulltime farming and entered the computer industry as a developer. At that time the commutes were longer, I was reading more technical books in my spare time and paperback were no longer in a size that one could put in a pocket.
I also developed an addiction to fanfiction and D&D forums, that did not help either but the size of the books was a big issue. Now the books sit in my room and occasionally I read the book but when it is put down it could stay there for a couple of days.
Now as to reading on an iPhone, well what is it like? I hear you say (maybe not, not sure if anyone really reads this :)) I was somewhat surprised, it was not bad. 'Alice in Wonderland' lost something as the drawings were really too small on the iPhone screen to have any real impact but 'On Basilisk Station' was fine.
I could see me reading a lot more on the iPhone, though I will be sticking to free stuff for the while. 
I have not tried reading in the iPhone outdoors but so far it works pretty well in all indoors conditions that I tried it out in.
 So overall verdict, I could see myself doing most of my reading on the iPhone only buying hardcopy for books I really like and want to permanently add to my collection. I could also see me buying books and reading the electronic versions. I would like a larger screen but I have a feeling that the iPad is possibly a bit too large. I really want something about the size of a paperback.

Thursday, February 4, 2010

iPhone Rave

Treated myself to an iPhone over the Christmas and decided to post a few comments on it. Well it is a wonderful gadget. The UI is pretty slick and the touch interface is very good. It is a good music player and a pretty good video player. I have even watched some movies on it. Calendar, email,  messages are all pretty slick and easier to use than on a regular phone, though one with a keyboard may or may not be better to use.

All in all it is a pretty good PDA and a pretty good phone. As a phone voice quality is generally pertty good though it looses connection and reports poorer connections than the Nokias I was using before I got an iPhone.
Battery life is fairly good and depends on what you are doing. Bluetooth chews up battery like nothing else and is my biggest source of complaint. I have trouble detecting other bluetooth devices and really dislike that I cannot have bluetooth enabled in a hidden mode. After that the working alot with data is the next biggest draw on battery. Normal usage, now I get perhaps 36 hours or so between recharges.

One thing that I have tried that really does not work is the voice recognition, it does not understand me at all and there does not appear to be anyway to train it. Not that I have tried to hard to find out. Overall I am pertty pleased, now if only iTunes would behave itself and not lock up every so often.

Fantasygrounds Unity: Importing an NPC from a text stat block.

  Fantasygrounds has been my primary VTT of choice for many years now. For most of that time I have been running games using official WoTC ...