Factory File Manager Updated to Ver. 1.2.1.0

The Factory File Manager was updated:

Ver. 1.2.1.0:
AppBar Seperator Style adjusted
#341: Copy path of focused item to clipboard and show the copied path in lower left corner
#348: Active index immediately changed when opening active tab selection (Ctrl+Tab)
#350: Close ButtonAppBar when “Same Path” was pressed
#352: Changed TextTrimming from WordEllipsis to CharacterEllipsis

Download the latest version from the Windows Store.

Factory File Manager Available in Windows Store

Because of naming conflicts, we removed Instance Factory’s File Commander from the Windows Store.

You can now find the app under its new name Factory File Manager.

Factory File Manager is a side by side file management app. Multiple tabs can be created to manage different file locations within the same window. Of course, copy, move, delete, permanent delete, and rename are supported. Folders can be created too. Strong keyboard support is integrated to be highly productive.

The Factory Commander monitors changes of folder content in the background and automatically updates the view.

The features are:

  • Side by side file management (dual pane)
  • Mutiple tabs
  • Background monitoring of folder content changes
  • Copy, move, rename, delete, permanent delete of files and folders
  • Folder creation
  • Copy path of focused item to clipboard
  • Keyboard, mouse, and touch support
  • Launch files
  • Strong keyboard support for higher productivity
  • Focus items when typing
  • Shows current date & time
  • Drag’n Drop supported

Factory File Manager Screenshot

“Device Not Functioning” Exception on Invalid PrimaryLanguageOverride Value in Windows Store Apps

Oh, what a title for a post. The correct title is “‘A device attached to the system is not functioning. (Exception from HRESULT: 0x8007001F)’ Exception Occurs When Showing A TextBox and ApplicationLanguages.PrimaryLanguageOverride Is Set To An Invalid Value in Windows Store Apps on Windows 8.1“.

Symptom

Building the Factory Commander, I was using ApplicationLanguages.PrimaryLanguageOverride to set the culture-correct date and number formatting. This is how the implementation in App.OnLaunched looked like:

ApplicationLanguages.PrimaryLanguageOverride 
  = new GeographicRegion().CodeTwoLetter;

Unfortunately, I can’t recall where I found this approach.

The development of Factory Commander was started on Windows 8, where this approach worked well. But after upgrading the development machine to Windows 8.1, the Commander crashed whenever I tried to rename, copy, or move a single item.

I figured out that, whenever the apps wants to show a TextBox, an exception with the description “A device attached to the system is not functioning. (Exception from HRESULT: 0x8007001F)” was thrown. The exception did not contain any further information. Well, what kind of device is used by a TextBox that is not used by other common controls of a Windows Store app?

A newly created Windows Store app on the same machine, which did contain a TextBox only, did not threw this exception. Was the Commander not compatible with Windows 8.1? I tested it on a machine having Windows 8.1 initially installed, so no upgrade was made: no problem! Did the upgrade corrupted the development machine?

Then I installed the Commander on a Windows RT device that was upgraded to Windows 8.1: no problem! Was it an issue with upgrading the x64 version of Windows 8? That seems to be the fact, because on another x64 machine that was upgraded to Windows 8.1, the same problem occurs. So I installed Windows 8 x64 on a new virtual machine, upgraded it to Windows 8.1: no problem.

The Reason

As you might assume from the description above, it took me some time to figure out what the cause was. The exception thrown was not really helpful – in other words: absolutely misleading – and the fact that the implementation worked fine on Windows 8, but partially did not on Windows 8.1, wasn’t helpful too. At least the “good” old step-by-step comparison approach made it.

Looking at the docs, ApplicationLanguages.PrimaryLanguageOverride expects a BCP-47 language tag. Valid values are for example “en”, “en-US”, “de”, “de-DE”, and so forth. The Commander set the value to GeographicRegion.CodeTwoLetter, which “… returns the two-letter ISO 3166-1 alpha-2 code for this region“.

If you are lucky, the region’s ISO code will match to the (or at least one) BCP-47 language code. In case you have the region set to “United States” (search for “region and language”), you do not have luck. The return value of GeographicRegion.CodeTwoLetter is “US”, which does not seem to be a valid BCP-47 code.

The Solution

I completely removed the setting of ApplicationLanguages.PrimaryLanguageOverride. The docs mention that “the … setting is persisted between sessions“. Means, the app needs to be uninstalled to have the change take effect.

To format the date and number values according to the user’s regional settings, I am using the CultureInfo of the user’s first configured language now. I was not able to figure out how to get the date and time formatting settings from the system.

// Get all installed languages
IReadOnlyList<string> languages 
  = Windows.System.UserProfile.GlobalizationPreferences.Languages;

// In case we have at least one, set the culture info from it.
// The result will be used later on as parameter 
// of String.Format calls.
CultureInfo = languages.Count > 0 
  ? new CultureInfo(languages[0])
    : CultureInfo.DefaultThreadCurrentUICulture;

I think there should be one language defined at minimum, but who knows what might happen.

Advertisement Side Effects

A side effect of the change was that the Microsoft advertising services started to deliver ads. Before the change, I was wondering why the fill rate (quota number of items delivered by number of requests) was exactly zero. I.e. no ad was delivered at all.

After the change, ads were retrieved. This means that the app’s primary language is used to request ads in the matching language. And having an invalid language set, there will be no advertisement.

Expected Behavior

Letting the user of an API set invalid values without giving any feedback is not really helpful from my point of view.

What I expect from ApplicationLanguages.PrimaryLanguageOverride is to throw an ArgumentOutOfRangeException in case I try to set an invalid value. This would have saved me a lot of time.

It throws an ArgumentException telling the value does not fall within the expected range when I try to set it to a value like “abcd”. But as long as the format of the value matches to the BCP-47 language tag structure, like “ab” or “ab-cd”, no exception is thrown by the setter.

Try It Yourself

Are you curious and want to try it yourself? This is how I was able to reproduce the behavior:

  • Use Windows 8.1
  • Create a Blank Windows Store App, name it as you like (e.g. PrimaryLanguageOverrideTest)
  • Add ApplicationLanguages.PrimaryLanguageOverride = "US"; as the first line of App.OnLaunched
  • Insert <TextBox> into the Grid of MainPage.xaml
  • Start the app in debug mode (press F5)

This will cause the app to crash with the exception described above.

To make the positive test, follow these steps:

  • Uninstall the app (search for it, right-click, choose uninstall)
  • Change ApplicationLanguages.PrimaryLanguageOverride = "US"; to ApplicationLanguages.PrimaryLanguageOverride = "en-US";
  • Start the app in debug mode (press F5)

The app should start now without any problems.

Links

ApplicationLanguages.PrimaryLanguageOverride

BCP-47 language tag

WinRT apps and Regional settings. The correct way to format dates and numbers based on the user’s regional settings?

Factory Commander Updated to Ver. 1.1.0.6

The Factory Commander was updated:

Ver. 1.1.0.6: Fixed item #324 – app crashes when clicking the rename button and then a different item while renaming an item

Ver. 1.1.0.5: Fixed item #322 – app might crash when renaming / copying / moving single item on machines with US region settings; uninstall and re-install might be required for this fix to take effect

Download the latest version from the Windows Store.

IsTabStop Changes ListView ‘s Focusable Behaviour in Windows Store Apps

The Issue

Using the Factory Commander, I noticed some strange behavior.

I opened a folder with more items than can be displayed on the screen on the left side. Then I scrolled to the last item of the list and switched to the right list. There, I moved up or down one folder level (goto parent or child folder). The item list on the right side gets refreshed, and, to my surprise, the list on the left side scrolled up. It did so every time I moved up or down one level until the first item of the left list was displayed. Switch back to the left list, the list scrolls down to the focused last item itself.

I was able to reproduce this behavior with a simple Windows Store app having just two ListView controls, without any additional logic. So it seems to be a general issue, independent from the Factory Commander implementation.

The Solution

It took me some time, but after a while I found the (or one of the possible) solution. By default, the IsTabStop property of a ListView is set to false. Changing it to true solved my issue. It seems that setting this property enables the ListView to keep the focus even if there are no items in the list.

In WPF, there are two different properties: Focusable and IsTabStop.

Focusablegets or sets a value that indicates whether the element can receive focus“, while IsTabStopgets or sets a value that indicates whether a control is included in tab navigation.

The Control (base class of ListView) in WPF contains both properties, while the Control implementation for Windows Store apps lacks of the Focusable property. Seems the “.NET for Windows Store apps” framework team at MS decided that this property is “not related to developing Windows Store apps”.

Links

2,000 Things You Should Know About WPF; explanation of Focusable and IsTabStop in WPF

Position the PopupMenu for Drag And Drop Operations in Windows Store Apps

Preface

Sometimes it is helpful to open a PopupMenu when the user drops items on a destination, e.g. to ask the user if the items should be copied or moved.

I’d like to open the PopupMenu exactly where the user released the mouse / finger, means put the upper left corner to this point on the screen.

The DragEventArgs, passed by the Drop event, do not provide the absolute coordinates, but the drop point that is relative to an UIElement.

Get the Position of a UIElement

Having the relative position of the drop point, we just need the absolute position of an UIElement – i.e. the drop destination, e.g. a ListView – to be able to calculate the absolute position of the PopupMenu.

Unfortunately, UIElement does not have a Position property or a GetPosition method. But it offers a method to “return a transform object that can be used to transform coordinates from the UIElement to the specified object“: UIElement.TransformToVisual.

To be honest, from reading the docs I would not have found out how to get the absolute position of a control. Because the docs do not mention that it is possible to pass null as a parameter.

The MSDN Context Menu Sample helped me out. Using this sample, I created an extension method for UIElement:

/// <summary>
/// Returns the position of the element.
/// </summary>
/// <param name="instance">The instance to be used.</param>
/// <returns>The position of the element.</returns>
public static Point GetPosition
  (
  this UIElement instance
  )
{
  // Return the position.
  return (instance.TransformToVisual(null)
          .TransformPoint(new Point()));
}

Add a Little Helper

Now that we have the absolute position of the drop destination, we just need to add the relative position of the drop point to the get the place where to open the PopupMenu.

Because Point does not offer an add operator, I created another extension method to keep the code tidy:

/// <summary>
/// Add the summand to the point.
/// </summary>
/// <param name="instance">The instance to be used.</param>
/// <param name="summand">The summand to be added.</param>
/// <returns>A new instance with the sum.</returns>
public static Point Add
  (
  this Point instance,
  Point summand
  )
{
  // Add the coordinates.
  return (new Point(instance.X + summand.X, instance.Y + summand.Y));
}

Use the Extentions

Using these extensions, the handling of the Drop event of a ListView and positioning of the PoupMenu at the drop point might look something like this:

private async void OnListViewDropAsync
  (
  object sender,
  DragEventArgs args
  )
{
  // The sender has to be a UIElement
  UIElement uiElement = sender as UIElement;

  if (uiElement == null)
  {
    return;
  }
  
  // Get the drop point in relation to the sender
  Point relativeDropPoint = args.GetPosition(uiElement);

  // Calculate the absolute position of the popup, 
  // using the extensions
  Point dropPoint = uiElement.GetPosition().Add(relativeDropPoint);

  // Create a popup
  PopupMenu menu = new PopupMenu();
  menu.Commands.Add(new UICommand("Copy"));
  menu.Commands.Add(new UICommand("Move"));
  menu.Commands.Add(new UICommand("Cancel"));

  // Show it at the drop point
  await menu.ShowAsync(dropPoint);

  // Do something depending on the user's selection.
}

Links

Context Menu Sample

Considerations Regarding Building a FileSystemWatcher for Windows Store Apps

Preface

Unfortunately, .NET for Windows Store apps does not provide a FileSystemWatcher class. Nevertheless, one might want get notified when a folder, or file in a folder, has been changed.

This post presents some points I found worth to consider when I implemented a FileSystemWatcher for Windows Store apps.

Because the implementation of such a class depends on the kind of application it is used by, there is no code sample provided. The intention of this post is to give you some ideas about what I think should be considered when creating your own FileSystemWatcher.

Receive Notifications

This is the easy part. You just have to create a StorageFolderQueryResult, add a handler to its ContentsChanged event, and execute the query.

...

private StorageFolderQueryResult QueryResult { get; set; }

...

protected override async void OnNavigatedTo
  (
  NavigationEventArgs args
  )
{
  QueryResult = KnownFolders.PicturesLibrary
    .CreateFolderQueryWithOptions(new QueryOptions() 
      { FolderDepth = FolderDepth.Shallow });

  QueryResult.ContentsChanged += OnFolderContentChanged;

  try
  {
    await QueryResult.GetFoldersAsync(0, 1);
  }
  catch (Exception)
  {
    ...
  }
}
…
private void OnFolderContentChanged
  (
  IStorageQueryResultBase sender,
  object args
  )
{
  // Do something
}

It is sufficient to get just one folder. There is no linkage between the notifications and the number of items retrieved by the query. Calling GetFoldersAsync(0, 1) keeps the runtime impact to a minimum.

You can also call another method of StorageFolderQueryResult. The important thing is that the query executes at all.

Notification Content

The “content” of the notification is the notification itself and the folder that might have changed. Why “might”? Have a look below.

No. There is no further information sent by the event. You only get notified that something has changed. You do not get any information about what has changed.

Double Notification

At the time of writing, it seems that Windows 8 is not consistent in the way it fires the event.

In case a file is changed, one event is fired.

But in case a folder is changed (or created or deleted), two events are fired, with a timespan of one second. The timespan was observed on Windows 8 x64, Windows 8.1 x64, and Windows 8 RT. So it seems to be hardware-and OS-independent. For the latest news on this, please refer to StorageFolderQueryResult.ContentsChanged Fires Twice.

Notification Aggregation

In case many changes are made to the file system in a very short time – e.g. the user selects 100 files by the file explorer and deletes them – the behavior is unpredictable. I observed at minimum one event, but very often two, sometimes the second one with a delay of several seconds, sometimes even more events.

Notifications About Changes in Child Folders

As you can see from the code snipped above, I set the QueryOptions.FolderDepth to FolderDepth.Shallow. This means I only want to monitor changes of the given folder. I don’t care about changes in its child folders.

Unexpectedly, I also received notifications when the content of a child folder has changed. E.g. I was monitoring the Folder “Parent”, which contains a folder names “Child”. Creating a folder name “Grandchild” in the folder “Child” also fires an event, although I am monitoring “Parent”, not “Child”. Changing the content of “Grandchild” does not trigger an event.

Discover the Changes

Because the event does not give any information about what has changed, you need to discover it yourself.

To do so, the content of the observed folder prior to the change is needed, and the content after the change is needed too. This sounds simple, but there are some details to pay attention to.

Time Matters

To get the current content of a folder, I found no other way but to call StorageFolder.GetItemsAsync (or one of it variants to retrieve folders and files, GetFoldersAsync and GetFilesAsync).

Calling StorageFolder.GetItemsAsync() on my C:\Windows\System32 folder takes more than four seconds for ~3,100 items (Directory.GetFileSystemEntries took 0.1 second [100 milliseconds]). Four seconds are an eternity on a computer. Lots of additional changes might happen while I am trying to retrieve the current state. And in addition, one second after the first notification the duplicate will be fired, but nothing has changed.

Abort Content Retrieval

So there is the need to somehow be able to abort the retrieval of the current content list, in case a real additional change occurred.

I implemented this by reading the content in small chunks. StorageFolder offers methods to read items chunk wise. Between reading a chunk, I check a flag that is set when a new change occurred. If that flag is set, reading the content is aborted and restarted.

Reading the items chunk wise had no impact on the overall time required to retrieve the content of a folder.

Ignore the Double Notification

How can you tell if the current notification is a new one or the duplicate of the last? And what to do if there is a change 800 milliseconds after the last one occurred, but the notification duplicate has not arrived?

I can’t tell. That’s because the event does not give me any information about what has changed. In my app, I decided to ignore all additional notifications that were sent in less than a second after the “initial” notification was retrieved.

How to Compare the Content?

The list returned by StorageFolder.GetItemsAsync contains the folders first, and then the files. Trying to find differences by comparing the name only will fail, because the name of a folder should not be compared to the name of a file.

The consequence is to have the content lists separated by folders and files, or to find another way to make sure a folder is not compared to a file and vice versa.

It is also worth to mention that the list returned by StorageFolder.GetItemsAsync, and the folder / file variants, is sorted in natural sort order. I found C# comparison implementations on Stack Overflow.

Depending on what your app uses, comparing the name to detect changes might not be sufficient. In case the app relies on the file’s size or the last modified date too, there is additional code to be written, because these attributes needs to be collected in a second step (see Discover Properties of Storage Items in Windows Store Apps).

Conclusion

Creating a FileSystemWatcher for Windows Store apps is heavy stuff from my point of view. Even though I found a way to handle all the ‘challenges’, I do not really feel happy with my solution.

In case you have an approach that you think works good, please feel free to share it with us.

Links

NET for Windows Store apps

StorageFolderQueryResult documentation

StorageFolderQueryResult.ContentsChanged Fires Twice

Natural Sort Order

Natural sort order C# implementations

Discover Properties of Storage Items in Windows Store Apps

Factory Commander Available in Windows Store

Instance Factory’s file commander for Windows 8.1, Factory Commander, is now available in the Windows Store.

Factory Commander is a side by side file management app. Multiple tabs can be created to manage different file locations within the same window. Of course, copy, move, delete, permanent delete, and rename are supported. Folders can be created too. Strong keyboard support is integrated to be highly productive.

The Factory Commander monitors changes of folder content in the background and automatically updates the view.

The features are:

  • Side by side file management (dual pane)
  • Mutiple tabs
  • Background monitoring of folder content changes
  • Copy, move, rename, delete, permanent delete of files and folders
  • Folder creation
  • Strong keyboard support for higher productivity
  • Keyboard, mouse, and touch support
  • Launch files

You can find the Factory Commander here.

Factory Commander Screenshot