linkedin

  • Hosting Windows Workflow Foundation in a Console Application without Ugly Code

    I’ve been using Windows Workflow Foundation for a small personal project to learn more about it and see what it can do. It’s pretty powerful and I’m looking forward to delving more into it. For my purposes though, I’m hosting the workflow in a console program.

    If you look around the internet, you’ll see lots of examples of hosting a sequential workflow in a synchronous manner, even though the WorkflowRuntime only support asynchronous operations. That code usually looks like this (example adapted from wf-training-guide.com to add support for input/output arguments):

    static void Main(string[] args)
    {
      Dictionary<string, object> inputArguments = new Dictionary<string, object>();
      inputArguments.Add("Argument1", args[0]);
      Dictionary<string, object> outputArguments;
        
      // Create the WF runtime.
      using(WorkflowRuntime workflowRuntime = new WorkflowRuntime())
      {
        // Hook into WorkflowCompleted / WorkflowTerminated events.
        AutoResetEvent waitHandle = new AutoResetEvent(false);
        workflowRuntime.WorkflowCompleted
          += delegate(object sender, WorkflowCompletedEventArgs e)
            {
              outputArguments = e.OutputParameters;
              waitHandle.Set();
            };
    
        workflowRuntime.WorkflowTerminated
          += delegate(object sender, WorkflowTerminatedEventArgs e)
            {
              Console.WriteLine(e.Exception.Message);
              waitHandle.Set();
            };
    
        // Create an instance of the WF to execute and call Start().
        WorkflowInstance instance =
          workflowRuntime.CreateWorkflow(typeof(WorkflowClass));
        instance.Start();
    
        waitHandle.WaitOne();
      }
    }

    Unfortunately, that’s a ton of code to do only a few things:

    1. Take input arguments
    2. Instantiate a WorkflowRuntime
    3. Create a workflow instance
    4. Run the workflow
    5. Handle any exceptions (poorly)
    6. Return output parameters from the workflow
    7. Do all of this in a synchronous manner.

    What if we could just call a method similar to this:

    var outputArguments = RunWorkflow<WorkflowClass>(arguments, completedEvent, terminatedEvent);

    Well, now you can! I’ve written this wrapper class to allow exactly that:

    public class WorkflowManager
    {
      public static Dictionary<string, object> RunWorkflow<T>(
        Dictionary<string, object> arguments,
        EventHandler<WorkflowCompletedEventArgs> completedEvent,
        EventHandler<WorkflowTerminatedEventArgs> terminatedEvent)
        where T : SequentialWorkflowActivity
      {
        using (WorkflowRuntime runtime = new WorkflowRuntime())
        {
          Dictionary<string, object> returnValue = null;
          Exception ex = null;
    
          using (AutoResetEvent waitHandle = new AutoResetEvent(false))
          {
            WorkflowInstance instance = runtime.CreateWorkflow(typeof(T), arguments);
            runtime.WorkflowCompleted += (o, e) =>
            {
              EventHandler<WorkflowCompletedEventArgs> temp = completedEvent;
              if (temp != null)
              {
                temp(o, e);
              }
    
              returnValue = e.OutputParameters;
    
              waitHandle.Set();
            };
    
            runtime.WorkflowTerminated += (o, e) =>
            {
              EventHandler<WorkflowTerminatedEventArgs> temp = terminatedEvent;
              if (temp != null)
              {
                temp(o, e);
              }
    
              ex = e.Exception;
    
              waitHandle.Set();
            };
    
            instance.Start();
            waitHandle.WaitOne();
          }
    
          if (runtime != null)
          {
            runtime.StopRuntime();
          }
    
          if (ex != null)
          {
            throw ex;
          }
    
          return returnValue;
        }
      }
    }

    Now you really can run the above code to execute your workflow in a synchronous manner without all kinds of messy code. Beware creating multiple WorkflowRuntime instances though. If you are managing multiple simultaneous workflows, you’ll need to pass in instance IDs and keep track in the runtime of which one is completing or throwing errors. It’s generally a bad idea to have multiple WorkflowRuntimes.

    Enjoy now being able to write:

    var outputArguments = RunWorkflow<WorkflowClass>(arguments, completedEvent, terminatedEvent);

  • Requirements Completed for Master of Business Administration

    Those words in the title now appear at the end of my MBA transcript from Louisiana Tech University. I will graduate Saturday, March 6th, 2010 with a Master of Business Administration and a concentration in Information Assurance. There is nothing else left for me to do; school is over! If I hadn’t gotten the two B’s, I’d have a 4.000 average. Unfortunately, the school doesn’t do any cum laude stuff for graduate degrees.

     -----------------------Winter 2010-------------------------
     MGMT595 084  ADMINISTRATIVE POLICY        A    3.00  12.00
     UNIV610 001  GRADUATION - BUS GRAD             0.00
     -----------------------------------------------------------
     
                         AHRS    EHRS    QHRS    QPTS     GPA
          Current         3.00    3.00    3.00   12.00   4.000
          Cumulative     36.00   36.00   36.00  138.00   3.833
     
          Requirements completed for Master of Business
          Administration
     --End of Louisiana Tech University Graduate Transcript------

  • redgate Releases SQL Search for Free

    redgate has released their SQL Search 1.0 for free, and my coworker Stephen sent our team an email letting us know about it. It is a fantastic product that integrates with SSMS and now it’s free. It keeps an index of all the text in every sproc, all the columns in every table, etc, and you can search them all instantly, limiting by type and many other options.

    These are the features they list on their page:

    • Find fragments of SQL text within stored procedures, functions, views and more
    • Quickly navigate to objects wherever they happen to be on your servers
    • Find all references to an object
    • Integrates with SSMS

    And their “Why use SQL Search?”:

    • Impact Analysis
      You want to rename one of your table columns but aren’t sure what stored procedures reference it. Using SQL Search, you can search for the column name and find all the stored procedures where it is used.
    • Work faster
      Finding anything in the SSMS object tree requires a lot of clicking. Using SQL Search, you can press the shortcut combo, start typing the name, and jump right there.
    • Make your life easier
      You need to find stored procedures you’ve not yet finished writing. Using SQL Search, you can search for stored procedures containing the text ‘TODO’.
    • Increase efficiency, reduce errors
      You are a DBA, and developers keep using ‘SELECT *’ in their views and stored procedures. You want to find all these and replace them with a correct list of columns to improve performance and prevent future bugs. Using SQL Search, you can look for ‘SELECT *’ in the text of stored procedures and views.

    If you are a user of SQL Server Management Studio, I highly recommend you check out out. You sure can’t beat the price. Check out the screenshots below as well.


  • A Lesson in How Not to Conduct Website Security

    Louisiana Tech just sent me a “reminder” email with my full username and password in there. That information is everything necessary to logon to the school student portal and get the rest of my personal information, full school transcript, etc.

    Not only do I not like them emailing my password, I don’t like that they even know my password. They should be using hashes instead. They’re doing it incorrectly.

    Here is the full email (user/pass redacted):

    Subject: Reminder
    TO: <[my.school.email]@LaTech.edu>
    Date: Thu, 11 Feb 10 12:35:23 CST    
    From: <Registrar@LaTech.edu>
    
    REMINDER:
    
              Your BOSS PIN is: XXXXXX
              Your CWID number is: 100XXXXXX
    
    PROTECT THESE NUMBERS!

    I sure wish they’d protect these numbers for me instead of emailing them to me every quarter.


  • Followup on My Predictions for Apple’s Tablet Event

    Happy birthday to me! Also, Apple announced their iPad today. One thing I meant to mention in my previous predictions: I thought it would have at least a front facing camera for video conferencing with iChat and/or Skype. I’m very surprised it doesn’t have that. I predict this will be in the first hardware revision of the device.

    Personal Thoughts

    The iPad is basically a really big iPhone, but the iPhone is great. I was already prepared to buy a Nook for $259. The question is now do I pay $140 more to get an iPad that only has WiFi and no 3G data. The iPad is so much more than the Nook, but isn’t e-ink.

    I haven’t decided yet. I was underwhelmed by what they’re offering, but impressed by the price at which it starts: $499. I would likely sling WiFi from my jailbroken iPhone to the device, rather than pay another $30 a month for unlimited 3G data and another $130 for the device with 3G built in.

    Make recommendations to me in the comments!

    iPad pricing data

    Predictions Followup

    All photos are courtesy of GDGT’s live coverage.

    These were my predictions related to the tablet and the result.

    1. Apple will announce a tablet device of some kind.

      Result: They did.

      Steve Jobs holding iPad

    2. It’s name will begin with a lower case I. I have to get at least one correct, right? I’ll guess iTablet. I don’t think they’ll do iSlate.

      Result: iPad. Not a good name in my opinion. It opens itself to many jokes.

      Name is iPad

    3. The device will not have an e-ink screen.

      Result: Correct.

    4. The device will not have an AMOLED screen.

      Result: Correct.

    5. It will be a conventional LCD screen with LED backlighting.

      Result: Correct (not sure about backlighting, but with 10 hours battery life, I would be surprised if it is not LED).

    6. It will not run full OS X. Only a subset will be allowed, such as Safari, etc. Only apps from an app store will be allowed.

      Result: Correct.

      iTunes in iPhone style interface

    7. There will be a tablet app store.

      Result: Correct.

    8. There will be backwards compatibility for iPhone apps running in some kind of emulation mode.

      Result: Correct. They can run in a pixel-perfect mode letterboxed or zoomed to full screen. All iPhone apps are compatible.

      iPhone app at 1x iPhone app at 2x

    9. There will be a innovative text input method. I can’t speculate as to what it will be, but knowing Apple, it will be good.

      Result: Wrong. Straight up QWERTY, just like the iPhone.

      Standard QWERTY input

    10. Its battery life will be expressed in hours, not days or weeks, unlike the Kindle or Nook.

      Result: Correct. 10 hours.

      10 hour battery life

    11. Verizon will be announced as a 3G data partner for the tablet device.

      Result: Wrong. AT&T only. International carriers to be announced later. All devices are unlocked, and will work with any carrier compatible with micro SIMs (not Verizon or Sprint because they are CDMA [no SIM cards]).

      AT&T data plan information

    12. The tablet will sell like hotcakes at first because Apple made it, but I think this will be a fad device and perhaps regarded as Apple’s second flop (see Newton). I am putting this down “on paper” because I think it will be funny if I’m completely wrong and I can read my own words in a year or so.

      Result: Remains to be seen. I am underwhelmed, but my personal thoughts are at the top.

    Here are the results of my other predictions for the event:

    1. No new iPhone will be announced.

      Result: Correct.

    2. No AT&T exclusivity related announcements will be made (this will be saved until WWDC in June).
      Result: Correct.
    3. Incremental changes will be made for the iPhone OS, perhaps allowing some sort of rudimentary multitasking, perhaps in a 3.5 or 4.0 revision of the OS.

      Result: Wrong. No iPhone related announcements.


  • My Predictions for Apple’s Tablet Event Tomorrow

    Update: I have created a new blog post (Jan 27th, 2010) for my response to what happened and the outcome of each of my predictions.

    Unless you’ve been living under a rock, you are no doubt aware that Apple plans to reveal their “latest creation” tomorrow, January 27th, 2009. It is most likely their long awaited iTablet/iSlate/iWhatever. I’ll be following Engadget’s live blog of the event tomorrow.

    It is also my birthday tomorrow, but I don’t care as much about that. I just want to know what Apple’s been doing all this time and what they’re going to announce. I’m pretty sure that makes me nerdy, among other qualifications.

    These are my tablet related predictions, which I will update with the results:Concept mockup, courtesy of Engadget

    1. Apple will announce a tablet device of some kind.
    2. It’s name will begin with a lower case I. I have to get at least one correct, right? I’ll guess iTablet. I don’t think they’ll do iSlate.
    3. The device will not have an e-ink screen.
    4. The device will not have an AMOLED screen.
    5. It will be a conventional LCD screen with LED backlighting.
    6. It will not run full OS X. Only a subset will be allowed, such as Safari, etc. Only apps from an app store will be allowed.
    7. There will be a tablet app store.
    8. There will be backwards compatibility for iPhone apps running in some kind of emulation mode.
    9. There will be a innovative text input method. I can’t speculate as to what it will be, but knowing Apple, it will be good.
    10. Its battery life will be expressed in hours, not days or weeks, unlike the Kindle or Nook.
    11. Verizon will be announced as a 3G data partner for the tablet device.
    12. The tablet will sell like hotcakes at first because Apple made it, but I think this will be a fad device and perhaps regarded as Apple’s second flop (see Newton). I am putting this down “on paper” because I think it will be funny if I’m completely wrong and I can read my own words in a year or so.

    My other predictions for the event are as follows, which I will also update with results:

    1. No new iPhone will be announced.
    2. No AT&T exclusivity related announcements will be made (this will be saved until WWDC in June).
    3. Incremental changes will be made for the iPhone OS, perhaps allowing some sort of rudimentary multitasking, perhaps in a 3.5 or 4.0 revision of the OS.

    Additionally, I am aware that I haven’t blogged in 5 months. I’ll be following up on this post with some sort of recap explaining what I’ve been doing.


  • Beyonc□, or How We Can All Learn From Other Developers’ Character Encoding Mistakes

    Picture of Unicode Error, displaying Beyoncé as Beyonc-block

    I’m sure everyone who reads this blog has noticed, at some point, the result of another developer’s mistake in dealing with Unicode or other character encodings. I’ve had a few issues myself. To the left, you can see how my Napster displayed a Beyoncé song as Beyonc□. You may have seen a black diamond symbol with a question mark in it while browsing a web page, or perhaps other strange symbols when interacting with programs or web pages.

    Most, if not all of these, are inconsistencies when dealing with character encoding, with most of them being Unicode. Hazarding a guess, Beyoncé’s is likely stored as Unicode (UTF-16) in Napster’s database, but when output on the screen, it is converted down to UTF-8 or ASCII. Either way, it can’t be converted down, so an entity is displayed. There is even a shirt memorializing the problem in T-shirt form:

    I {entity} Unicode T-shirt

    My issues have been even more low-level than this. I deal with a lot of interaction using EDI with older computer systems running UNIX or or some IBM mainframe OS. None of these are using Unicode for their medical claims adjudication, and are either using ASCII or EBCDIC. Yes, EBCDIC; I have to program using EBCDIC in 2009.

    I have to be very careful when I’m converting to and from Unicode, the native format of the string class in .Net, and other character encodings such as ASCII and EBCDIC, and so should you.



  • Hacked by Chinese

    On our main product, in a branch on which I’m working on a Point of Sale product, something happened in the process of checking files into source control. In our case, we’re using Team Foundation Server. My guess is that the corruption happened on my hard drive for who knows what reason, but this is the beginning of the resulting solution file that ended up in TFS: a bunch of Chinese-looking characters instead of a project name.

    Microsoft Visual Studio Solution File, Format Version 10.00
    # Visual Studio 2008
    Project("{54435603-DBB4-11D2-8724-00A0C9A8B90C}") = "펐!蝀ጢ", "ProductNameFaxServiceSetup\ProductNameFaxServiceSetup.vdproj", "{DDA7A291-A5F6-4FEA-B11E-BBE90848167D}"
    EndProject
    Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyName.Claim.Common", "CompanyName.Claim.Common\CompanyName.Claim.Common.csproj", "{11EE0005-87E4-44E0-806A-0BCB382468F0}"
    EndProject
    Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyName.Claim.Modem", "CompanyName.Claim.Modem\CompanyName.Claim.Modem.csproj", "{FE62F256-5A9C-4212-8EFB-CCD0AC0D59AF}"
    EndProject

    It took a while to track down, because it manifested itself as missing projects, missing dependencies. I kept adding back things one at a time and then ending up with two more dependencies left to add. Finally, I just looked at the raw solution file and saw how it was messed up. I went back to find a file in the source control history that wasn’t messed up, got that specific version by change set, and then added the specific projects that had been added since then back to the solution.

    Thanks to source control, I was back up and running in no time.

    The title is from the phrase with which the Code Red worm defaced web sites it infected. We didn’t really get hacked by the Chinese.


  • Accessing a Control Without Being Able to See It on a Windows Form

    Menu Key Displayed on KeyboardA coworker of mine had a problem and came to me for help. She had a windows form with a control on it that she wanted to edit or delete, but couldn’t see the control. It was listed in the properties box in the list of controls on the form, but when she selected it, she wasn’t able to click it on the form, because it was behind another control.

    I hypothesized a solution, which worked, but requires the use of a less than frequent key on your keyboard, the menu key. Usually this key is two keys to the right of the space bar on windows keyboards, between Alt and Control. A picture of it is on the right.

    Note: As pointed out by Lee, in the comments, you can press Shift + F10 if your keyboard doesn’t contain the Menu Key.

    The Form With a Hidden Label Behind the Filename TextBox) Form with hidden label control

    Properties Window Listing the Hidden Control, HiddenLabel

    Properties window list of controls

    Select the control that you can’t see. It will be highlighted on the form.

    Form with Hidden Control Highlighted

    Label highlighted after selecting from properties windowThe hidden control becomes highlighted. Click into the title bar of the form. Press the menu key on your keyboard to display the context menu.

    Context Menu Being Displayed After Pressing the Menu Key

    bringtofrontSelect “Bring to Front” to display the control. It will now be visible and can be edited or removed.

    Hidden Control Moved

    Label after being brought to front and movedAs you can see, the control that was previously hidden is now visible and has been moved.

    I know this is a basic solution to an easy problem, but I had to figure it out, and I hope that someone searching may find this useful as well. The above example was a new form I was starting; it is not the actual application in question.


  • Using Reflection to Dynamically Generate ToString() Output

    Update: Added code to show “null” when a property is null, like Visual Studio does.

    If you’ve ever used Visual Studio in any iteration in any language, you have most likely used the immediate window. It’s insanely useful and lets you just type an instance of an object and if the object doesn’t have an overridden ToString() method (I’m back in C#/.Net world here for the purposes of this post), Visual Studio will dynamically generate output for you, so that you can see the current state of the object.

    Here is what Visual Studio’s output looks like on an object I have:

    {CompanyName.CreditCard.Processor.CreditDebit.SaleResponse}
        base {CompanyName.CreditCard.Processor.Response}: {CompanyName.CreditCard.Processor.CreditDebit.SaleResponse}
        AddressVerificationSuccess: true
        AuthorizationCode: null
        AuthorizedAmount: 50
        CvvSuccess: false
        ReferenceNumber: null

    However, what if you want to be able to have ToString() generate this type of output for you, for the purposes of debugging, like using with Debug.WriteLine or Trace or any other logging framework? It is useful to be able to see later what the state of an object was during a problem situation. Sure, you can write your own ToString() code in every object to generate its state in string form, and then aggregate all the base objects using base.ToString(), but that is a lot of iterative, repetitious coding.

    My classes are simple data transfer objects and look like this:

    public class SaleResponse : Response
    {
        public virtual bool AddressVerificationSuccess { get; set; }
        public virtual bool CvvSuccess { get; set; }
        public virtual string AuthorizationCode { get; set; }
        public virtual string ReferenceNumber { get; set; }
        public virtual decimal? AuthorizedAmount { get; set; }
    }
    
    public class Response
    {
        public virtual bool Success { get; set; }
        public virtual string ResponseMessage { get; set; }
        public virtual string TransactionID { get; set; }
        public virtual string GatewayResponseCodeText { get; set; }
        public virtual string IssuerResponseCodeText { get; set; }
        public virtual GatewayResponseCode GatewayResponseCode { get; set; }
        public virtual IssuerResponseCode IssuerResponseCode { get; set; }
    }

    As you can see, Visual Studio didn’t even give me the contents of the base class, but I want this information. My ToString() method I’ve created in the SaleResponse object is the following:

    public override string ToString()
    {
        var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.FlattenHierarchy;
        System.Reflection.PropertyInfo[] infos = this.GetType().GetProperties(flags);
    
        StringBuilder sb = new StringBuilder();
    
        string typeName = this.GetType().Name;
        sb.AppendLine(typeName);
        sb.AppendLine(string.Empty.PadRight(typeName.Length + 5, '='));
    
        foreach (var info in infos)
        {
            object value = info.GetValue(this, null);
            sb.AppendFormat("{0}: {1}{2}", info.Name, value != null ? value : "null", Environment.NewLine);
        }
    
        return sb.ToString();
    }

    Which generates the following output:

    SaleResponse
    =================
    AddressVerificationSuccess: True
    CvvSuccess: False
    AuthorizationCode: null
    ReferenceNumber: null
    AuthorizedAmount: 50
    Success: True
    ResponseMessage: null
    TransactionID: AXB234234
    GatewayResponseCodeText: null
    IssuerResponseCodeText: null
    GatewayResponseCode: ExpiredDevice
    IssuerResponseCode: Error

    What I like about this approach is that it grabs all the base object’s properties recursively. Obviously, there are performance concerns with doing reflection, so I wouldn’t use this constantly, but I think it’s a good way to write out the state of an object in the event of an error. Also, I made the example simple for this blog post, but obviously, you could put that code into an extension method for System.Object or just into a static utility class, adding an object parameter and replacing “this” with the name of the object parameter.


Posts navigation