Devlico.Us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Derik Whittaker

Thoughts on Software Development, .Net, OOP, Design Patterns and all things cool

April 2008 - Posts

  • Multi-Column Grouping with Linq2Sql

    Today as I was diving further into my Linq2Sql Odyssey I ran into a need to do grouping on data.  Bud not just single column grouping, I needed to group by multiple columns from multiple tables.  Because it took me a few minutes to get right, I thought I would share my experiences.

    Imagine if you will you have the following SQL statement

    SELECT  COUNT(*) AS Count,
            cs.SendID,
            cs.Name AS SendName,
            cts.ListID,
            cts.ListName,
            ctom.EmailAddress
    FROM    CampaignTrackingOpenedMail AS ctom
            INNER JOIN CampaignTrackingSummary AS cts 
    			ON ctom.CampaignTrackingSummaryID = cts.[ID]
            INNER JOIN CampaignSend AS cs 
    			ON cts.SendID = cs.SendID
    GROUP BY cs.SendID,
            cs.Name,
            cts.ListID,
            cts.ListName,
            ctom.EmailAddress

    And you would like to turn that into a Linq Statement.  At first I was a little stumped because I was not using the correct syntax.  My first attempt had me trying the following

    from ctom in CampaignTrackingOpenedMails
    join cts in CampaignTrackingSummaries on ctom.CampaignTrackingSummaryID equals cts.ID
    join cs in CampaignSends on cts.SendID equals cs.SendID
    group ctom by cs.SendID, cs.Name, cts.ListID, cts.ListName, ctom.EmailAddress into emailItems
    select new { SendID = emailItems.Key.SendID,
    			SendName = emailItems.Key.Name,
    			ListID = emailItems.Key.ListID,
    			ListName = emailItems.Key.ListName,
    			EmailAddress = emailItems.Key.EmailAddress,
    			Count = emailItems.Count()
    			}

    After a bit of searching I realized the error of my ways.  I needed to use an anonymous type as my group by object value.  So I made the changes and here is my correct attempt

    from ctom in CampaignTrackingOpenedMails
    join cts in CampaignTrackingSummaries on ctom.CampaignTrackingSummaryID equals cts.ID
    join cs in CampaignSends on cts.SendID equals cs.SendID
    group ctom by new { cs.SendID, cs.Name, cts.ListID, cts.ListName, ctom.EmailAddress } into emailItems
    select new { SendID = emailItems.Key.SendID,
    			SendName = emailItems.Key.Name,
    			ListID = emailItems.Key.ListID,
    			ListName = emailItems.Key.ListName,
    			EmailAddress = emailItems.Key.EmailAddress,
    			Count = emailItems.Count()
    			}

    A few things to notice here are:

    • The use of anonymous types
      group ctom by new { cs.SendID, cs.Name, cts.ListID, cts.ListName, ctom.EmailAddress } into emailItems
    • How the group by columns are used
      select new { SendID = emailItems.Key.SendID ......

    Well, hope this helps someone else.

    BTW, If you are NOT using LinqPad for your Linq2Sql stuff, you really need to check it out.

    Till next time,

  • Nice side affect of Automatic Properties

    Today it dawned on me another nice little side affect of automatic properties.

    I was creating an interface today that ONLY had properties and when I was done I needed to create the concrete object that implemented said interface.  All I had to do was copy, paste and add the modifier (public) to each line. 

    In the past I would have had to create the private member variables and setup the formatting correctly.  Now I do not have to.  Saved me a solid 5 minutes of busy work.

    +1 for saving me time.

    Till next time,

  • Heading out to the Iowa Code Camp

    Hey all, that time as come again where I will be venturing out into theicc_logo wild to spew my knowledge (or lack there of).  This time I am heading up to the Iowa Code Camp on the 3rd.  Should be a great time.

    The topic for my session is:

    Taking your tests to the next level with Mocks

    This session will walk through the progression of testing with mocks.  In the session we will learn how to mock out dependencies that stand in our way of solid testing. You will learn how mocks can make for cleaner tests and as well as improve the reliability of tests.  We will do a quick overview of TDD using NUnit, but the crux of the session will be focused on mocking with RhinoMocks.

    Hope to see everyone there

  • Linq2Sql - Explicit Construction of Entity Exception

    Gotta say, I am kinda flustered right now.  Today I was trying to perform what I thought to be a pretty straight forward Linq2Sql query, but turns out it was not.

    Overview

    I have a query that joins a few tables together to get some data, but in place of returning explicit instance of a data entity, I wanted to do a select new XXXX.  I wanted to do this because I had extended the main entity to have a extra property that is needed based on my domain.  And because I did NOT want to create a who new entity, I thought this was the path with the least resistance.  WRONG.

    Here is what I WANTED to do.

    var items = ( from ctl in DBContextInstance().CampaignTrackingLinks
             join cts in DBContextInstance().CampaignTrackingSummaries on ctl.CampaignTrackingSummaryID equals cts.ID
             join ctcts in DBContextInstance().CampaignTrackingClickThroughStats on cts.ID equals ctcts.CampaignTrackingSummaryID
             where cts.SendID == sendID
             where ctl.Url == ctcts.URL
             select new CampaignTrackingLink
             {
                 TotalClicks = ctl.TotalClicks,
                 UniqueClicks = ctl.UniqueClicks,
                 Url = ctl.Url,
                 Alias = ctl.Alias
                 PercentOfClicks = ctcts.PercentOfClicks
             }
           ).ToList();

    However, every time I ran this code I received  the following exception 'Explicit construction of entity type 'XXXXX.CampaignTrackingLink' in query is not allowed.'.  What was throwing me at first was I KNEW that my syntax was correct, but it still did not work.

    After a bit of googling I found (here) something that I think may explain why this is happening. 

    The solution to get this to work was not to create a new instance of my extended Linq entity, but to create a whole new entity that inherits off of my Linq entity.  For some reason this worked

        public class CampaignTrackingLinkBreakdown : CampaignTrackingLink
        {
            public double PercentOfClicks { get; set; }
        }

    It really sucks that I needed to create a new class that inherited off my Linq entity, but you do what you have to get it working.

    var items = ( from ctl in DBContextInstance().CampaignTrackingLinks
             join cts in DBContextInstance().CampaignTrackingSummaries on ctl.CampaignTrackingSummaryID equals cts.ID
             join ctcts in DBContextInstance().CampaignTrackingClickThroughStats on cts.ID equals ctcts.CampaignTrackingSummaryID
             where cts.SendID == sendID
             where ctl.Url == ctcts.URL
             select new CampaignTrackingLinkBreakdown
             {
                 TotalClicks = ctl.TotalClicks,
                 UniqueClicks = ctl.UniqueClicks,
                 Url = ctl.Url,
                 Alias = ctl.Alias,
                 PercentOfClicks = ctcts.PercentOfClicks
             }
           ).ToList();

    So as you can see, I get the same end result, but have to jump through a few extra hoops.

    Based on the feedback from the forum link above, this issue is due to the fact that Linq attempts to keep track of all entities for change state reasons and allowing for explicit construction via a query could cause a caching issue.  In my situation, I DO NOT care about change state as this is a read only entity so there will be no updates/inserts done later.

    Oh well, at least now I know the issue and how to work around it.

    If anyone knows of a better/cleaner way to solve this issue, please let me know.

    Till next time,

  • Chicago Alt.Net meeting review for April 23rd

    Last nights meeting was a great success.  It was the type of meeting that every new users group needs to have.  It was our 'who are we, and what do we wish to accomplish' here meeting. 

    Our goal for the evening was 2 fold.

    1. Setup a plan of attack for the CodeCamp we wish to host later this year
    2. Talk about the direction we want this group to head.

     

    Chicago Code Camp info

    Right now the location is up in the air, but we think we have something nailed down and I will be following up with this later in the week.  We are aiming for sometime in September in order to avoid the 'summer vacation' period.

    Once we have the location/date set in stone we will make an announcement to the world and start to work with the other groups in the area as well as line up speakers.

    Direction for the group

    In the sprit of Alt, our goal is to make the meeting both informative and information, but at the same time encouraging participation.

    Our overall format for out meetings will be as follows

    6:00 - 6:30 - Socializing
    6:30 - 7:30 - Pre-Planed Presentation
    7:30 - 8:30ish - Open Spaces/Open Discussion format
    8:30 - TBA - Get our drink on

    Adam and Jordan are going to be working on getting a site up for the group ASAP, after I purchase the domain.

    We are planning on meeting the second Wednesday of each month and right now we are meeting at the AbsoluteSolutions location downtown.

    We hope this group can reach out and help raise awareness to various technologies as well as help grow the .Net community here in Chicago.

    Till next time

  • [Book Review] Brownfield Application Development - upcoming book from Manning Publications

    A few weeks ago I had the chance to review an forthcoming book that from Manning Publications that is being co-written by Kyle Baley and Donald Belcham.baley_cover150_thumb

    The focus of this book is to help developers navigate the choppy waters of Brownfield  development.  If you ask me the timing of this book is just about perfect.  The .Net development community as at a cross roads.  There are TONS of legacy code (older .net, under maintenance) out there and companies would like to start making massive changes to these applications.  But there is a right way and a wrong way to do this.

    In this book the authors are taking a two step approach to teaching the readers how to go about successfully enhancing/extending a Brownfield app.  The first half of the book is dedicated to setting up a solid ecosystem for your application.  The second half of the book targets improving the overall design of your application one step at a time.

    The first chapter start off at the bottom, understanding what a Brownfield application is.  It reviews how to find pain points in your current process, how to deal with and attach political situations that may be holding you back.  And finally how to deal the potential moral issues that may be lingering with the developers on the applications.  This chapter basically forces the readers to understand that they must know where they are, before they can move forward.

    Once you have a better understanding of where you are, it is time to start working towards where you are going.  Arguably the most critical component to any any software team is it version control systems.  The next chapter does a review of what you should look for in an VCS (version control system) and how to evaluate your options.  But the most important part of this chapter is learning the 'check-in dance' and how it plays a critical part to your teams success.

    After you have a solid grasp what your VCS can do, it is time to create a build server.  Here you will learn all benefits that a build system brings to a team.  You will learn how to detect pain points in the build process and how to resolve them.  You will also get an update on the 'check-in dance' as it needs to change because you have CI (continuous integration) in place.

    After you are a CI master, you will be walked through the concepts of testing.  You will learn the benefits and how to spot more possible pain points when it comes to integration tests into your Brownfield application.  And finally you will learn why testing and CI go hand in hand.

    Although this book is only about 30% done, I can see it is going to be a great asset to the developer community.  I am really looking forward to what the future holds for this book.

    Till next time,

  • Are you going the way of the Dinosaur???

    What are you doing to keep your skills current? 

    • Do you learn new technologies? 
    • Do you learn new tools? 
    • Do you learn new languages? 

    If you did not answer yes to at least 1 of the 3 questions above, I have one last question to ask.  What are you doing to not become a Dinosaur?

    In my opinion developers today have more at stake then ever before. 

    • Technology is changing at the speed of light
    • Business demands are getting larger and more complicated
    • Technology is getting more complicated (which is counter to its intent)

    Over the past few months I have spoken to a few different developers that have become 'complacient' in what they do.  They have no interest in learn a new language (Ruby, Java, F#, etc) or even learning to use new frameworks (RoR, MonoRail, MVC, NHibernate, etc) because they are happy with what they have.  This is fine and this is dandy, but the day will come that they will regret this decision.

    Let me tell you a little store.

    Long, long ago there was a developer that was writing his applications in his language of choice, COBOL.  This guy was as happy as a clam, he had no worries, no issues.  The language did what he need and he could make it do all sorts of cool stuff.  And most importantly he felt comfortable with his language of choice. 

    Then one day someone created a newer, hipper language (insert any OO based language here) and suddenly it became all the rage.  Now the COBOL developer thought, should I invest the time effort to learn this new language, or should I stick with COBOL.  In the end he decided he liked COBOL, cause he was happy and content.  He also did not buy into all the press surrounding that language.  He figured that it is just a passing fad.  Now he may have been right, but where he made a mistake was he did not learn. 

    Now lets fast forward to today.  In the past few years there have many new languages and frameworks/toolsets have been released.  They all have their pros and cons and some will die off and become extent.  But the ones that live on may someday push your language out of the way.  If you don't at least have a working knowledge of what they bring to the table, what makes you think will will not be like our COBOL developer from our story?

    So, let me ask you.... What are YOU doing to not become a Dinosaur?

    BTW, before you ask what I am doing, let me tell you.  I am currently learning Ruby, I am playing with IronRuby (I know, not much different the Ruby).  I plan on playing with F# to become familiar with what a Functional language can do for me.  I started learning the MS MVC framework and will be playing RoR (Ruby on Rails) to see where that is going.  I did some MOSS work a while back.  I am branching out and getting my hands on as many different tools/frameworks as possible (NHibernate, Linq2Sql, TypeMock, etc, etc, etc).  I have not intention of becoming a master of any of these, but I intend on becoming knowledgeable enough to know what they offer and what they do not.

    Till next time,

  • ReSharper 4.0, I love you but it may be time we break up

    I have been a loyal and faithful user of ReSharper for the past few years, and am generally happy with the product.  But this 4.0 EAP is starting to kill our relationship. 

    I know that you are still in 'beta' but come one, what is taking so damn long. Visual Studio 2008 have been in full production now for 5+ months, not to mention the amount of time it was in beta. Again, what is taking so damn long. 

    I know and understand that this is not a simple application but really, does  every build have to hurt me more then the previous one?  It seems to me that every day I have more and more issues with you.  A tool should be painless to use, not painful.  I have now reverted back to build 767 as it is the most stable one for me.

    I love the fact that have put it all on the line with the 'open beta' and I know it will make you better because of it, but I just don't know how much longer I can wait.

    Please, please, please hurry up and go live with the real version....

    Till next time,

    **** LET THE FLAMES BEGIN ****

  • [Book Review] Hello Silverlight - Upcoming book from Manning Publications

    Today I just finished the early review for a yet to be released book form Manning Press called 'Hello Silverlight (there is no link available on their site). 

    As the title says the focus of this book in Silverlight 2.  But unlike many Silverlight books this is for the truly aimed at someone who is new to Silverlight and RIA (Rich Internet Application) technologies in general.  It did not take me long to realize that this book is going to be a great into book for any one looking to learn Silverlight, or any RIA technology in general.  The chapters flow well, there are great code snippets and good use of illustrations.

    The early chapters chapters are meant to quickly ramp up the reader by reviewing the basics.  The first chapter starts off by explaining the history of RIA as well as giving a brief background of existing technologies that Silverlight will be competing with (Flash, OpenLaszlo and AJax).  Along with the history, you will learn the different between Vector and Raster graphics at a pretty low level.

    Next you will find yourself learning the basics of XAML and why it is so important to the layout/design of high quality UI's.  Here the author goes over the different types of objects you can use to create your drawings, ranging from Brushes, to Rectangles & Ellipses, to Point based Geometries.  He finally finishes up the chapter talking about panels and how they make you life so much easier.

    Finally the author takes you step by step in creating an simple, yet effective animation.  This chapter was the best so far.  Literally took you step by step in creating a very simple animation.  Along the way he points out various pit falls as well as various ways to accomplish the same task.

    The later chapters are going to talk about more in depth topics such as Data access, gaming, and streaming.  If the these chapters are laid out/written in the same manner as the first, they should be just as good.

    Looking forward to reading the rest of the book, be sure to check back for more details on those later.

    Till next time,

  • ANN: Chicago Alt.Net meeting on April 23rd

    All, the Chicago Alt.net group will be having our next meeting next Wednesday at 6pm.

    Location:
    6PM
    Absolute Solutions (downtown location)
    203 N. LaSalle, M18
    Chicago, IL 60601

    Out topic of this meeting is going to be about planning our upcoming Code Camp.

    Hope to see everyone there.  Also, join our news group if you would like to follow us, but cannot make it to this meeting.

    If you can make it please drop me an email so we can know how many to expect.

    Till next time,

  • Rhino Mocks and mocking Out/Ref params

    I thought I would share a little nugget of greatness with RhinoMocks

    Today I was in the process of mocking out a webservice call for an application I was working on.  But the method I wanted to mock took a out parameter in its signature.  Normally this is not an issue, but since this out parameter result was used in my code, I needed to setup an expectation on that value.

    Fortunately for us, Rhino handles this pretty easily.  In order to set expectations on an Our or Ref all I need to do is add a call to the OutRef() method on my Expect call.

    Here is an example of this:

    using ( mocker.Record() )
    {
        Expect.Call( mockAPI.Create( out emptyString, out emptyString ) ).IgnoreArguments().OutRef( "", "OK" ).Repeat.Once().Return( results );
    }

    If you notice when I call OutRef, I am providing 2 values.  The first is an empty string because I do not care about that value and the second is "OK".  The "OK" value is the value that I cared about. 

    The OutRef method takes in one parameter, a Parameter Array.  In order to use this all you need to do is pass in a value for each out/ref argument in there ordinal positions.

    Hope this helps someone.

    Till next time,

  • Re: 3 Geeks in an Elevator -- My take

    Bil Simser has a funny post that I thought I would respond to.


    My 2 people.  JDN (John) of the Alt.net list and Scott Bellware.  This would be great.  I am sure for the first 24+ hours it would be a cynical bitchfest and blood would be all over the place.  Then, as calmer heads prevailed they would hug and be life long friend.

    Till next time,

  • Wow, 250 posts just flew right by

    I did not even notice that my post from yesterday was my 250th here at Devlicio.us.  Who would have thunk that I would that much useless stuff to share with the world.

    It has been a blast, and here is to another 250 more posts.  That's right, I still have more useless knowledge to share....:)

    Till next time,

  • How to have a Single Config File for multiple developers

    In my last post I talked about how you can share a single config file among multiple project in a solution.  One of the feedback comments I got was how to have a single config file for multiple developers or even multiple environments.  So, today I thought I would chat about the different ways to handle this clumsy situation.

    Scenario Overview

    You have the standard app.config or web.config file and it holds values for your application.  But some of the config properties are either user specific (such as file path for local storage) or are environment specific (such as db connections, web services paths, etc).  When we deploy the application we need to ensure that the correct values are used, and we want to it with the least amount of friction.  The good news is there are many ways to skin this preverbal cat.

    Option One -- Works, but is lame and painful

    Probably the most common solution to this problem is also the most painful.  Simply have users 'hijack' the config file locally and modify their values.  Or when you deploy your code to another environment, you hand edit the file. 

    Although this way works, it is lame and very, very error prone.  If a developer accidentally checks in his (or her) 'hijacked' copy they can then foobar others on the development team.  Or worse yet, you deploy your code and forget to change a value on in production and something really bad and painful happens.

    Keep in mind one thing.  Manual processes are very error prone, avoid at all costs.

    Option Two -- Getting better, but still not great

    Another way that I have seen this problem solved is having multiple 'key' values in the config file.  Most of the time these values are distinguished by some sort of prefix on the key (note: there are other ways as well).   An example of this would be:
    <add key="SomeQualifierHere.SomeRealKeyValue" value="SomeValue"/>

    This method works, but is sloppy.  Now you have to add logic to your config file reader (please, please, please for the love of all things good, do not access your app.config file directly in your application.  Abstract that away into some class that handles this for you) to determine what 'environment' you are in and grab the right key/value pair.  The biggest issue with this method is that you add a ton of noise to the config file and you have to be very cautious when you deploy to new environments.

    Option Three --  The best way

    The best way that I have seen is to have a single config file, but multiple external mini-configs for each user.  This can be accomplished by using the configSource attribute items such as <connectionStrings> or <appSettings>.  This allows you to have your config file point to a single external mini-config that may be different for each user or environment.

    Using the external config files you can setup either post-build events in the IDE or build actions on your build server to copy/rename/move the correct file as needed.

    Because this actual topic has been talked about before in great detail, I am not going to rehash it here, instead I will point you towards 2 good resources I have used.

    I hope this helps everyone,

    Till next time,

  • How to share configuration files between projects

    Sharing configuration files between multiple projects in Visual Studio is a simple task, but it is not intuitive in how it is done.  In fact, until recently I did not know how to do it via the IDE, I would always hand edit the .sln file to enable this feature (sad I know).  Today I thought I would throw up a simple set of screen shots to show everyone how easy it really is.

    Overview:

    We have a solution that has multiple projects and we would like to share our app.config along with our StructureMap.config files between each of the projects.

    Step One -- Adding the config files to your soultion:

    Create a solution folder in your solution.  I like to add them here as a way of organizing my common files.   Once you have your Solution folder created, right click and choose Add -> New Item (see blow) (If you already have these files, simple do an Add -> Existing item and reference the existing ones).

    AddNewSolutionItem

    Now for some odd reason MS decided that Application Configuration files were not a valid option for solution folders so we have to do some manual work.  Select the "Text File" template and rename the file to App.Config (see blow).

    TextFileTempalte

    Finally because we did not choose the Application Configuration template we need to add the XML tags to the file by hand. Here is the XML to add.
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    </configuration>

    Step Two - Add reference to the each project:

    Now that we have created our config files in our solution folders we want to add them to each project.  We do this by right clicking the project and choosing Add -> Existing Item

    AddExistingItem

    This will open up a new dialog and this is where the magic happens (the part that always eluded me).  Change the extension type filter to 'All Files(*.*)" allowing us to see the .config files.  Choose the file you want to add, but don't click directly on the "Add" button.  Click the little drop down arrow on the right hand side.  This will give you 2 options.  1) Add 2) Add as Link.  Choose Add As Link.

    AddAsLink

    After you choose the 'Add as Link' option you will notice that the App.Config file will be added to your project.  But it will has the shortcut image on the icon, this tells you it is a link, not an actual reference.

    ShowingAppConfigFile

    Step Three -- Setting up the Properties on the file

    After we have added our config file we need to ensure that it gets copied to our output (bin) directory during a compile.  *** NOTE *** You do NOT need to do this with an App.config or Web.config as the IDE will do it for you *** END NOTE ***

    Right click the linked file and choose Properties.  This will open up a new dialog (fly out pane) and choose 'Copy Always' or 'Copy If Newer' in the Copy to Output Directory action.

    CopyAlways

     

    There you go, you now have a single config file for your solution that can be referenced by all the projects in your solution.

    Hope this helps someone.

    Till next time,

More Posts Next page »

Our Sponsors

Red-Gate!