About the Author

Bret graduated top of his class from Coleman College in 1999. Whilst completing his own studies at Coleman, he was also a student teacher and designed and taught a Beginning Visual Basic course. He is currently pursuing his Bachelor of Science degree at Palomar College. Bret has over 11 years of experience in WinForms/C++/MFC and object-oriented programming. His Network experience includes TCP/IP, UDP/IP, WCF and wireless communication, in addition to a wide variety of application types ranging from enterprise client/server software for Fortune 500 companies to cutting edge niche market solutions as well as multi-platform for Windows, Windows Mobile, Pocket PC, Smartphones, and touch screens. He currently holds a Senior Software Engineer position, responsible for developing and maintaining cutting edge Microsoft based applications for various clients. Bret specializes in XAML (both WPF and Silverlight technologies) as well as UI/UX Design. His core competency is in C# while I also have extensive C++ experience. Bret’s current focus is UI/UX Design and Development related technologies. His passion is to create professional, aesthetically pleasing software that is intuitive to use and simplifies the task at hand. “I love to innovate and create new and exciting software.”

Monotouch and iOS Storyboard limitations

Recently I’ve been doing MonoTouch research for iOS development.  While doing so I ran into a limitation when using MonoTouch and the new iOS Storyboards.  What I’ve found is that in general, MonoTouch and Storyboards play along really well together.  However, I found they only play nicely if you don’t need to create any custom controls that manage ViewControllers and navigation.  If you are just creating a simple application that has very straightforward navigation and uses only the standard iOS controls or subclassed controls, Storyboards are the way to go.  If you decide that you want custom controls that manage ViewControllers and want finer control over navigation, Storyboards are not for you.  What brought this about was I decided I wanted a neat UITabBar that would have an action button in the middle (similar to Instagram and other photo sharing applications).  I quickly realized this isn’t possible by subclassing the UITabBar without a lot of hackish techniques.  I decided I was going to create my own UITabBar.  In order to do this I needed to create a custom view to act as the tab bar and to manage the active ViewController.  This meant instantiating and managing the ViewControllers in code.  Now here is where Storyboards fail.  The problem I ran into was that the code generated by MonoTouch for my ViewControllers did not contain the proper constructors/bindings needed to instantiate them from code nor could I wire them up myself.  MonoTouch had generated some code to bind the ViewControllers’ classes to the Storyboard but it doesn’t allow access to it.  Now, sure, I know I could create a method to open the xib and search for the resource to bind to but that seems nasty to me and kludgy.  I wanted nice clean binding between my code behind and my xibs.  I found that the way to have clean bindings and be able to dynamically instantiate and manage ViewControllers from code was to keep them separate in their independent xibs.  Going this route allowed me  to use those ViewControllers in both ways, via code and via Interface Builder.  In short, if you plan on using MonoTouch to create an app that needs to be able to instantiate and show ViewControllers via code, do not use Storyboards.  Otherwise, go for it because Storyboards really simplify navigation and also give you an overview of your application flow.

Hard Drive and Memory Information

Here are some tips on obtaining information about your computer’s physical memory as well as hard drive information.

Drive Information

To obtain information about the various drives in your computer you can use the DriveInfo class.  This class contains all sorts of information regarding the drive it references.  For this example I will just show you how to obtain the total and free space in Gigabytes for the drive.  In this example I will be retrieving info about the C: drive.  Also, don’t forget that the sizes returned are in bytes and you should convert them to more meaningful types. Quick info about byte conversion:

Divide by:
2^10 for KB
2^20 for MB
2^30 for GB
2^40 for TB

DriveInfo info = new DriveInfo(“C:\\”);

int freeSpace = (int)(info.AvailableFreeSpace / Math.Pow(2, 30));
int totalSpace = (int)(info.TotalSize / Math.Pow(2, 30));

Physical Memory

To obtain information about your computer’s physical memory you have two options.  You can use P/Invoke, which offers much better performance, or WMI for .NET.  I will show you using P/Invoke because it’s faster and because I grew up with Win32 and C++ and have sentimental attachment to it.  There is a little bit of funkiness to obtaining information about your physical memory in that there are multiple ways to obtain the available memory but only two ways to obtain the total memory (which are p/invoke and WMI).  If all you need to know is the amount of available physical memory you can use the PerformanceCounter class which doesn’t require p/invoke but does come with a serious performance hit.  Example:

var memCounter = new PerformanceCounter("Memory", "Available MBytes");
var available = Math.Round(memCounter.NextValue() / Math.Pow(2, 10), 2); // Because our performance counter returns the available memory in MB we only need to divide by one magnitude to get to GB

If you want to know both available and physical then you would use p/invoke and Win32 as so:

// Win32 P/Invoke imports

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private class MEMORYSTATUSEX
{
public uint dwLength;
public uint dwMemoryLoad;
public ulong ulTotalPhys;
public ulong ulAvailPhys;
public ulong ulTotalPageFile;
public ulong ulAvailPageFile;
public ulong ulTotalVirtual;
public ulong ulAvailVirtual;
public ulong ulAvailExtendedVirtual;
public MEMORYSTATUSEX()
{
this.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));
}
}

[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);

public static double GetAvailablePhysicalMemory()
{
ulong availableMemory = 0;

MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX();
if (GlobalMemoryStatusEx(memStatus))
{
availableMemory = memStatus.ulAvailPhys;
}

return availableMemory;
}

public static double GetTotalPhysicalMemory()
{
ulong installedMemory = 0;

MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX();
if (GlobalMemoryStatusEx(memStatus))
{
installedMemory = memStatus.ulTotalPhys;
}

return installedMemory;
}

Then use those methods as so:

var Available = Math.Round(Win32Helper.GetAvailablePhysicalMemory() / Math.Pow(2, 30), 2); // I like my available to be semi-accurate so I only round to two decimals
var Total = Math.Round(Win32Helper.GetTotalPhysicalMemory() / Math.Pow(2, 30), 0, MidpointRounding.AwayFromZero); // I like my total to be a nice round number so I round up and chop the decimals

That’s it.  Pretty simple.

FlowDocuments, Images, and Text Wrapping

While working on a project, I had a requirement to display an image accompanied by text that wrapped around said image.  I knew right away that TextBlocks were not going to help me there.  I quickly set out to find something capable of flowing text; enter the FlowDocument.  Most of the samples I found discussed how to create large formatted documents and how to display them.  I was struggling to find a nice concise article on how to create a simple reusable UI snippet that incorporated wrapping text and didn’t require an actual file.  No longer will you have to suffer the same fate as I; for I am here to show you the light!  Feast your eyes upon the result:

image

First off, let’s start with the container to hold our nifty FlowDocument.  There are numerous options for displaying FlowDocuments: FlowDocumentReader, FlowDocumentScrollViewer, and FlowDocumentPageViewer.  We will be using FlowDocumentScrollViewer since it allows hiding of the default toolbar and is the easiest to configure to quickly display our fake document in a format that is desired.  Here is the definition for the FlowDocumentScrollViewer:

<FlowDocumentScrollViewer Focusable="False" IsToolBarVisible="False"
                          ScrollViewer.CanContentScroll="False"
                          ScrollViewer.HorizontalScrollBarVisibility
="Disabled"
                          ScrollViewer.VerticalScrollBarVisibility
="Disabled"
                          HorizontalAlignment="Stretch" VerticalAlignment="Center" />

This will set our FlowDocumentScrollViewer up so that it is purely for displaying our fake document and won’t get in the way of our UI.  No scrolling, no interaction.  Next we need to design our document layout: 

<FlowDocument>
    <Paragraph FontWeight="Normal" Foreground="WhiteSmoke" TextAlignment="Left">
        <Floater Width="48" HorizontalAlignment="Left" Margin="0,0,4,0" Padding="0">

           <BlockUIContainer>

                 <Image Source="file://c:/temp/bacon.png" Width="48" Height="34" />

           </BlockUIContainer> 
       </Floater><Run Text="The Baconator" FontSize="16" Foreground="WhiteSmoke" TextDecorations="Underline" /><LineBreak /><Run Text="Bacon ipsum dolor sit amet adipisicing t-bone sirloin filet mignon ribeye. Tenderloin ex strip steak, pork chop hamburger est." FontSize="12" Foreground="WhiteSmoke" />
    </Paragraph>
</FlowDocument>

There are some caveats to using FlowDocuments.  The one that you need to look out for most is that FlowDocuments are very literal, meaning it will display any white space you include in your xaml.  This is why the Run elements and LineBreaks are all on the same line because any spaces and/or line returns you place in there will be displayed in the output.  Also, by default FlowDocuments use Justify as their text alignment so if you don’t want your output getting spaced out then make sure you set your TextAlignment to Left on the Paragraph.

Obviously for discussion and sample purposes I used literal text in the flow document but you can easily replace the literal text with Bindings in the Runs (assuming using .NET 4.0) and the Image.  I hope you found this useful.  Here is the full xaml for the visual shown above.  Obviously you will need to tweak this to suit your needs but this should give you a great start.

  

<Border Background="#2B3346" BorderBrush="#212937" BorderThickness="1" Width="250" Height="100">

<FlowDocumentScrollViewer Focusable="False" IsToolBarVisible="False" ScrollViewer.CanContentScroll="False"

ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Disabled"

HorizontalAlignment="Stretch" VerticalAlignment="Center" Margin=”0,-5,0,0”>

<FlowDocumentScrollViewer.Document>

<FlowDocument>
<Paragraph FontWeight="Normal" Foreground="WhiteSmoke" TextAlignment="Left">
<Floater Width="48" HorizontalAlignment="Left" Margin="0,0,4,0" Padding="0">

<BlockUIContainer>

<Image Source="file://c:/temp/bacon.png" Width="48" Height="34" />

</BlockUIContainer>
</Floater><Run Text="The Baconator" FontSize="16" Foreground="WhiteSmoke" TextDecorations="Underline" /><LineBreak /><Run Text="Bacon ipsum dolor sit amet adipisicing t-bone sirloin filet mignon ribeye. Tenderloin ex strip steak, pork chop hamburger est." FontSize="12" Foreground="WhiteSmoke" />
</Paragraph>
</FlowDocument>

</FlowDocumentScrollViewer.Document>

</FlowDocumentScrollViewer> </Border>