Personal

  • Pretty IPropertyNotifyChanged Declarations for Windows Phone

    The Problem

    I’ve been doing a bit of WPF/Windows Phone development. Usually INotifyPropertyChanged declarations for properties are really ugly. The big problem is that the INotifyPropertyChanged interface relies on strings, which don’t refactor well.

    I’m also using the fantastic MVVM Light Toolkit, which makes life a lot easier when doing Windows Phone development.

    MVVM Light has a snippet that you invoke with the shortcut mvvminpc that produces the following:

    /// <summary>
    /// The <see cref="ScreenName" /> property's name.
    /// </summary>
    public const string ScreenNamePropertyName = "ScreenName";
    
    private string _screenName = String.Empty;
    
    /// <summary>
    /// Sets and gets the ScreenName property.
    /// Changes to that property's value raise the PropertyChanged event. 
    /// </summary>
    public string ScreenName
    {
    	get
    	{
    		return _screenName;
    	}
    
    	set
    	{
    		if (_screenName == value)
    		{
    			return;
    		}
    
    		_screenName = value;
    		RaisePropertyChanged(ScreenNamePropertyName);
    	}
    }

    That saves quite a bit of work, but it’s still ugly. It still doesn’t refactor well because you have to change that property that corresponds to the string. MVVM Light also includes another snippet with the shortcut mvvminpclambda that gets closer to what I want, but it’s still a large declaration with the equality checking, but instead of using ScreenNamePropertyName (and you get to lose that property), that call looks like:

    RaisePropertyChanged(() => ScreenName);

    That’s getting there, but it’s still messy. I found a great solution for this problem from Christian Mosers, but it doesn’t compile in Windows Phone Silverlight due to the lambda compile, and it relies on PropertyChangedEventHandler. Also, Christian’s sets the value after the event handler is called. I’m not sure if that’s a mistake, but it seems like it is, and someone else already pointed that out in his comments.

    I’ve modified it a bit and now it works, gives me an inpcpretty shortcut, and cleans up my declarations a lot. I tried making it an extension method of the delegate I created, but that doesn’t work. In the end, I made it an extension of the value type T.

    The New Code

            private string _screenName = String.Empty;
            public string ScreenName
            {
                get { return _screenName; }
                set { value.ChangeAndNotify(RaisePropertyChanged, ref _screenName, () => ScreenName); }
            }

    The Extension Method

    namespace System
    {
        public static class INotifyPropertyChangedExtensions
        {
            public delegate void OnPropertyNotifyChangedDelegate(string input);
    
            public static bool ChangeAndNotify<T>(this T value, OnPropertyNotifyChangedDelegate handler,
                ref T field, Expression<Func<T>> memberExpression)
            {
                if (memberExpression == null)
                {
                    throw new ArgumentNullException("memberExpression");
                }
                var body = memberExpression.Body as MemberExpression;
                if (body == null)
                {
                    throw new ArgumentException("Lambda must return a property.");
                }
                if (EqualityComparer<T>.Default.Equals(field, value))
                {
                    return false;
                }
    
                var vmExpression = body.Expression as ConstantExpression;
                if (vmExpression != null)
                {
                    field = value;
    
                    if (handler != null)
                    {
                        handler(body.Member.Name);
                    }
                }
                return true;
            }
        }
    }

    The Snippet

    <?xml version="1.0" encoding="utf-8"?>
    <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
      <CodeSnippet Format="1.0.0">
        <Header>
          <SnippetTypes>
            <SnippetType>Expansion</SnippetType>
          </SnippetTypes>
          <Title>INPC Property</Title>
          <Author>Chris Benard</Author>
          <Description>A property raising PropertyChanged with a string. The class using this property should inherit GalaSoft.MvvmLight.ObservableObject.</Description>
          <HelpUrl>http://www.galasoft.ch/mvvm</HelpUrl>
          <Shortcut>inpcpretty</Shortcut>
        </Header>
        <Snippet>
          <Declarations>
            <Literal Editable="true">
              <ID>Type</ID>
              <ToolTip>Property type</ToolTip>
              <Default>bool</Default>
              <Function>
              </Function>
            </Literal>
            <Literal Editable="true">
              <ID>AttributeName</ID>
              <ToolTip>Attribute name</ToolTip>
              <Default>_myProperty</Default>
              <Function>
              </Function>
            </Literal>
            <Literal Editable="true">
              <ID>InitialValue</ID>
              <ToolTip>Initial value</ToolTip>
              <Default>false</Default>
              <Function>
              </Function>
            </Literal>
            <Literal Editable="true">
              <ID>PropertyName</ID>
              <ToolTip>Property name</ToolTip>
              <Default>MyProperty</Default>
              <Function>
              </Function>
            </Literal>
          </Declarations>
          <Code Language="csharp">
            <![CDATA[private $Type$ $AttributeName$ = $InitialValue$;
            public $Type$ $PropertyName$
            {
                get { return $AttributeName$; }
                set { value.ChangeAndNotify(RaisePropertyChanged, ref $AttributeName$, () => $PropertyName$); }
            }]]>
          </Code>
        </Snippet>
      </CodeSnippet>
    </CodeSnippets>

    Conclusion

    There is probably a better way to do this, but I’m not that experienced in WPF/Silverlight/Windows Phone yet. If you know of a better way, please let me know.

    To use this snippet, click the raw button in the code listing (looks like <>), save the contents as inpcpretty.snippet. Then, in Visual Studio, go to Tools -> Code Snippets Manager. Switch the language to C# and select Import. Choose the .snippet file you saved and you should be in business!


  • Speaking at the Dallas PHP User Group

    On January 11, 2011 I spoke at the Dallas PHP User Group on the topic of the Kohana v3 MVC Framework and Facebook integration. The introductory slides are below. To download the sample code yourself, head on over to the GitHub project page. Scroll to the bottom of the GitHub page to see the instructions on how to install it on your own server. An example site is available for you to view the running code on the Internet.


  • First Impressions with Google’s Cr-48 Chrome OS Netbook

    On December 7, 2010, Google announced their Chrome OS Notebook reference hardware, the Cr-48 (a bit of a chemistry joke). They also announced a pilot program, by which participants would receive a free netbook running the release version of Chrome OS, with the understanding that the user would provide Google feedback about the operating system. I immediately signed up, since I was listening to the live broadcast of the announcement.

    When they announced the pilot program, they put a QR code on the screen at 1:20:24 on the applicable slide. I scanned the QR code using my iPhone and it took me to a signup page. After filling in the information it thanked me for my information and said they would follow up or something. I didn’t think I’d actually get a notebook, but on the following Thursday, people all across the United States started receiving Cr-48s; I hoped I would be one of them. By the end of the day, I was very disappointed.

    However, late in the afternoon on Friday, December 10, 2010, I went out to the mailbox to check the mail and a Cr-48 was sitting on my porch.

    Here is my initial video right after unboxing:

    Additionally, I took pictures of the unboxing, in case anyone cares, because I was so excited (click to see the album):

    chromeosalbum

     

    Initial thoughts

    • The setup process confused me because I kept tapping to click. I didn’t know you needed to press down hard to click the actual trackpad itself. The entire trackpad is a physical button. This is apparently common to Apple notebooks, I have been told. After the setup process, you can change this in settings to allow “tap-to-click”.
    • It boots up from a power-off state really quickly.
    • It came with at least half a charge. Thanks Google!
    • It takes awhile to set up the free Verizon 100MB data. They really need your information first; I assume this is to address DMCA/child pornography type violations, so they can associate an IP with a physical person.
    • It wakes from sleep instantly, just like in the presentation.
    • The keyboard is insanely good, and all the letters are lower case: an odd touch, not that I spend most of my time looking at the keyboard.
    • In the car at night, I did find myself wishing the keyboard was backlit, so I could see some of the new buttons they’ve replaced, like the function keys.
    • It bogs down really hard on internet videos that are not from you-tube. Comedy Central works fine. Hulu and NBC do not work well at all. They get very choppy. None of these are in HD.
    • YouTube has no option to enable HD. I even tried to force it with “hd=1” in the URL and it ignored it, forcing 480p. I knew it wouldn’t be good, but I wanted to test it and they won’t let me.
    • Logging into the netbook logs you into your Google Account. You don’t have to log in anymore for things like YouTube, Gmail, Reader, Voice, and all the other things that Google runs in my life (Latitude, etc).
    • It’s heavier than it looks; I haven’t weighed it yet, but I’m sure that info is already out there.
    • There was nothing I wanted to do on it that I wasn’t able to do with a webapp or a webpage yet. I even set up IRC through IM+ and IRC through Mibbit.
    • The back on the bottom gets a bit warm after extended use.
    • The battery seems to last forever, but takes awhile to charge.
    • You don’t seem to be able to login with Google Apps accounts. My girlfriend could not login, even when I’d added her ID as a valid ID for use with the Netbook in settings.

    If anyone has any questions I haven’t addressed, please ask them in the comments and I’ll answer in my next blog post.


  • 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);

  • Chase Visa Fraud

    I just got a call from the Chase fraud computer voice. He told me that somebody had just charged my card about $250 to a clothing website called ASOS.com. He asked if it was me and I kept pressing zero so I could talk to a person. I knew if I said it wasn’t me that they would just close my card and send me a new one in about a week more or less.

    I finally got a person (in India of course), and she told me that not only had they charged that to my card, but also $1.00 to Apple’s iTunes store on February 25th. I didn’t even see that show up in my online activity today on Chase’s web site, so I assume they deactivated the charge when they figured out it was fraud. I assume the Apple charge was to test the card for validity.

    I told the lady that a week was unacceptable, because I put everything on that Chase Freedom card. I told her I needed it tomorrow. She obliged without any complaint; she said it will be here tomorrow via UPS and I will have to sign for it. I told her that’s no problem since I work from home.

    Kudos to Chase for their aggressive, accurate anti-fraud algorithms and their customer service relating to shipping out a card overnight upon request.


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


Posts navigation