Zip File Classes Finally Available in .Net 4.5

Right now .Net 4.5 is still in beta, but I noticed something that will make developers who must interact with zip files happy: .Net 4.5 will have native support for dealing with zip files. Up until now, the System.IO.Compression namespace only had support for GZipStream and DeflateStream.

I, like many other developers, have been using the fantastic SharpZipLib library, but I don’t like to have dependencies in my projects if I don’t have to. In order to iterate through a zip file and list its contents while extracting the code looks something like this (SharpZipLib has a lot of one-liners to allow for extracting with events as well, but bear with me):

private static void ExtractSharp(string zipFile, string extractionLocationSharp)
{
    Console.WriteLine("Extracting with SharpZipLib");
    Console.WriteLine();

    using (var archive = new ZipFile(zipFile))
    {
        int readCount;
        byte[] buffer = new byte[4096];

        foreach (ZipEntry entry in archive)
        {
            Console.WriteLine("Name: {0}, Size: {1}", entry.Name, entry.Size);

            var extractedPath = Path.Combine(extractionLocationSharp, entry.Name);
            if (entry.IsDirectory)
            {
                Directory.CreateDirectory(extractedPath);
            }
            else if (entry.IsFile)
            {
                using (var zipStream = archive.GetInputStream(entry))
                {
                    using (var outputStream = new FileStream(extractedPath, FileMode.CreateNew))
                    {
                        while ((readCount = zipStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            outputStream.Write(buffer, 0, readCount);
                        }
                    }
                }
            }
        }
    }

    Console.WriteLine();
}

I haven’t installed the .Net 4.5 beta on my work machine yet, but according to the MSDN documentation, it should look like this:

I don’t know if this compiles in .Net 4.5. I don’t have it installed yet.
private static void ExtractDotNet(string zipFile, string extractionLocationDotNet)
{
    Console.WriteLine("Extracting with .Net 4.5");
    Console.WriteLine();

    using (var archive = ZipFile.OpenRead(zipFile))
    {
        foreach (ZipArchiveEntry entry in archive.Entries)
        {
            Console.WriteLine("Name: {0}, Size: {1}", entry.FullName, entry.Length);

            var extractedPath = Path.Combine(extractionLocationDotNet, entry.FullName);

            // I'm not sure if it will create the directories or not.
            // There does not appear to be an IsDirectory or IsFile like in SharpZipLib
            entry.ExtractToFile(extractedPath);
        }
    }

    Console.WriteLine();
}

As you can see, it looks a bit cleaner, but the nice part is having it built into the framework instead of relying on yet another assembly.

As noted in the comments, I’m not sure how .Net 4.5 will handle the directory entries or if it ignores them as separate entries. I may be able to test the beta later, but feel free to comment if you know how this works.


Windows Phone Emulator Time Skew When Computer Sleeps

TLDR: If you put your computer to sleep, the Windows Phone emulator might have the wrong time when you resume. Restart the emulator to get it to have the current time in its clock.

I was working on my fork of an OAuth library for Windows Phone this weekend, and I ran across a really weird issue. I’m posting this in case someone else Googles this problem, since I couldn’t find anything.

I have a UNIX epoch timestamp generator (necessary for Twitter) class that looks like this:

public class TimestampGenerator
{
    public string Generate()
    {
        var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0);
        var now = DateTime.UtcNow;

        long stamp = ((now.Ticks - unixEpoch.Ticks) / 10000000);

        return stamp.ToString();
    }
}

I worked for hours on this on my desktop and everything was working fine. Then, when I did a git pull on my laptop, it was suddenly broken. When I’d make a request to the term.ie example OAuth service, it said my timestamp was expired every time. I set breakpoints and compared it to the current epoch timestamp, and it was definitely wrong. I tried many ways of calculating it (that division is to get to seconds from 100 microsecond increments (ticks); I haven’t benchmarked to see which is faster), but nothing made a difference.

I calculated a time difference of about 102 hours from my current time based on the timestamps. I finally figured out that my emulator could have the wrong time, since I was thinking computer time == emulator time. I killed the emulator, hit F5, and it worked like a charm. Then, I thought about the time difference, and it was about the last time I put my laptop to sleep by closing its lid.

Apparently, when the computer comes out of sleep, the computer clock stops matching the emulator clock; the emulator clock freezes when the computer sleeps and just resumes from where it left off. I’m not sure if this is a bug or not, or if it happens on a regular basis. I may try to reproduce it later, but probably not.


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.


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