Friday, August 21, 2015

Xamarin.Forms - Choosing the right architecture

One of the biggest issues with writing cross platform apps using Xamarin.Forms is that it is hard to know where to start and how to establish good patterns that are scalable enough to support the full app lifecycle from development to maintenance and new feature requests.

This blog post is based on some of the experiences I've had working with on different cross platform apps with Xamarin.Forms.

One of the biggest problems when writing cross platform code that should work on multiple platforms is that you have to choose an architecture and some patterns and stick with them to avoid ending up with code that is hard to maintain and hard to extend with new features.

The architecture and patterns you choose needs to be easy to understand and extensible enough to support future features.

Patterns
My most important principle is to build n app based on loose coupling through dependency injection and then to use the service locator, messaging bus and mvvm patterns to implement the functionality and user experience.

Combining this with unit testing enables me to develop new features quickly while keeping manual testing to a minimum.
I'm using TinyIoC for both dependency injection and as our service locator container and Xamarin.Forms' MessagingCenter as my message bus.
All dependencies on these components are abstracted through interfaces so that they can be swapped out if necessary.

Services for business logic
As a rule of thumb I always write my business logic in service classes that can be configured and injected in my view models. These classes are also testable using a unit testing framework like NUnit.
Server communication
Its common to have a dependency on a cloud service. Such a service is often exposed as a REST based API that can be accessed over HTTPS. Usually I wrap services like this into simple client classes that can communicate with the server and that can be used by my services (never use clients directly in your view models!).

To accomplish this I use the HttpClient library from Microsoft with the modernhttpclient NuGet package to get native speed and performance. For serialization I use Newtonsoft Json.
Persistence
If you have the need for local storage there are many options. I'm using SQLite.Net/SQLite.Net Async since it gives me full async/await support and a nice little ORM that can be used with c# classes. For simple storage needs you can always use a file based library.
Localization
I'm using regular resx files for localization - these work as expected under Xamarin Studio. (you might need to create the localization project in Visual Studio, I've had some issues creating them in Xamarin.Studio - this might have changed by now).
Binding it all together with Mvvm
The mvvm pattern is my default choice for wiring up the business logic and the user interface in my apps. Using ViewModels that transforms data from my services to properties and commands in my view models makes it really easy to get the user experience right. Xamarin.Forms views supports data binding to the view model's properties and commands.
There are several good Mvvm frameworks out there that can be recommended - I suggest you choose a small and simple one with source code.
Custom UX
I almost always have the need for some custom UX in all the apps I'm working on. In Xamarin.Forms you have some excellent extension points called custom renderers that act as bindings between the abstracted and native user elements.

If I have smaller needs like drawing some shapes and/or lines I usually add the NControl library to my project. It lets me create custom controls using the NGraphics abstraction layer. The NControls library is written and maintained by me, you can read more about it in a blog post here.
Analytics
To get knowledge about what your app's users are doing, you should use some kind of library for app analytics. If you can find a library that also handles exceptions and crash reports, you will thank yourself for being wise at an early stage - having stack traces and exception reports from your user's crashes helps finding solutions to strange errors. 

Remember to create an abstraction layer for tracking and error reporting so that you can plug in your own favorite library.

General tips
  • Try to keep the level of customization at a minimum - it is expensive and time consuming and adds to your maintenance costs
  • Follow your patterns - don't be tempted to write business logic in your view models or views
  • Refactor often

Know your platforms - nothing beats having the knowledge about how stuff works on the underlying platforms when it comes to building new functionality and maintaining the old features.

Sunday, March 22, 2015

NControl - Cross Platform Custom Controls for Xamarin.Forms

NControl is a Xamarin.Forms wrapper control built around the NGraphics library enabling developers to create custom controls without the need for custom renderers.

The project is hosted on Github and is distributed under the MIT license.

The library contains the NControlView class where real custom cross-platform drawing can be performed without the need for native implementations thanks to the NGraphics library. NControlView can be used both to do custom drawing and to create complex custom controls.

Supported Platforms:
The library currently supports native renderers for the following platforms:
  • Android
  • iOS Unified
A Windows Phone edition of the control is planned for a later release.

Installation:
Install in your iOS, Android and Forms project using this package from Nuget.

Remember to to add calls to NControlViewRenderer.Init()after Forms.Init() in your AppDelegate and in your MainActivity.

Example Usage:
In your Xamarin.Forms project, add a new NControlView element to your page in the constructor and provide a drawing function where your custom drawing is performed:

  Content = new NControlView {
      DrawingFunction = (canvas, rect) => {
          canvas.DrawLine(rect.Left, rect.Top, rect.Width, rect.Height, NGraphics.Colors.Red);
          canvas.DrawLine(rect.Width, rect.Top, rect.Left, rect.Height, NGraphics.Colors.Yellow);
      }
  };

Subclassing:
You can also create a subclass of the NControlView class and override its Draw function to add your own custom drawing:

public class MyControl: NControlView
{
  public override void Draw(NGraphics.ICanvas canvas, NGraphics.Rect rect)
  {
    canvas.DrawLine(rect.Left, rect.Top, rect.Width, rect.Height, NGraphics.Colors.Red);
    canvas.DrawLine(rect.Width, rect.Top, rect.Left, rect.Height, NGraphics.Colors.Yellow);
  }
}

Complex Controls:
NControlView supports containing other controls since it inherits from the ContentView class. Building composite controls is as simple as setting the Content property of your subclassed control:

public class MyControl: NControlView
{
  public MyControl()
  {
    Content = new Label {BackgroundColor = Xamarin.Forms.Color.Transparent};
  }

  public override void Draw(NGraphics.ICanvas canvas, NGraphics.Rect rect)
  {
    canvas.DrawLine(rect.Left, rect.Top, rect.Width, rect.Height, NGraphics.Colors.Red);
    canvas.DrawLine(rect.Width, rect.Top, rect.Left, rect.Height, NGraphics.Colors.Yellow);
  }
}

Now your custom control will have a label that can draw text in the control. Remember that you can set the Content property to point to anything as long as it is a VisualElement. This means that you can add layouts containing other controls as well as a single control.

Invalidation:
If you need to invalide the control when a property has changed, call the Invalidate() function to redraw your control:

public class MyControl: NControlView
{
  public MyControl()
  {
    Content = new Label {BackgroundColor = Xamarin.Forms.Color.Transparent};
  }

  public string Text { 
    get 
    { 
      return (Content as Label).Text; 
    }
    set 
    { 
      (Content as Label).Text = value;
      Invalidate();
    }
  }

  public override void Draw(NGraphics.ICanvas canvas, NGraphics.Rect rect)
  {
    canvas.DrawLine(rect.Left, rect.Top, rect.Width, rect.Height, NGraphics.Colors.Red);
    canvas.DrawLine(rect.Width, rect.Top, rect.Left, rect.Height, NGraphics.Colors.Yellow);
  }
}

Touch events
The NControlView class also handles touch events - look at the CircularButtonControl for an example of how this can be used.

Demo controls
The demo solution contains a few different controls based on the NControlView class:


  • RoundedCornerControl
  • CircularButtonControl
  • ProgressControl

The ProgressControl and the CircularButtonControl both internally uses the FontAwsomeLabel to display glyphs from the Font Awesome Icon font.

Notes
Note that the ProgressControl and the CircularButtonControl contains animations to make the user experience more alive. The demo solution also uses animation to add some eye candy to the demo itself.

Friday, June 11, 2010

Transforms and upgrades

Upgrading shall not be easy. In our installer we are using an MST file to configure the server connection for our clients so that they shouldn't need setting this up manually.

The transform file path is entered in the Setup.exe MSI Command Line Arguments in Installshield. Everything ok so far.

But when upgrading to a newer version where the server configuration has changed, we'd love the installer to detect changes in the MST file and upgrade the client's configuration when upgrading. The problem now is that the installer uses a cached version of the MST file, and therefore the new configuration wont be applied!

I'll get back when or if I find a solution to this problem.

Monday, June 07, 2010

Upgrades, uninstall and major versions

While I was trying to make the new client installer uninstall previous versions of our software, I ran into a few issues that took a while to solve.

First and foremost, the previous installer (custom-built) didn't contain an upgrade code (which uniqely identifies a product across versions) that I could use in my new MSI installer's upgrade table to make sure it was uninstalled. This was simple, just create a custom action that reads the uninstall information from the registry and runs the uninstall string if it exists for your product.

Next I tried to tell Windows installer to remove two additional products that were installed using MSI installers. I used the upgrade table with the upgrade codes from the two products I wanted to uninstall.

When running the installer, only one of the products were removed, and the log told me that the other one was skipped because it was installed in a different context (machine, not for this user only).

When I removed the product that successfully was uninstalled and reran the installation, the product that was previously skipped was uninstalled! This baffled me, and I tried a lot of different solutions until I finally had to revert to a rather dirty solution.

First of all, this is whats happening when you are uninstalling previous products:
  1. When the installer runs the FindRelatedProducts action, it looks in the Upgrade table to find what products it should search for. If it finds a product installed (using the UpgradeCode in the Upgrade table), it sets the value of the property (actionprop column) for the product in the Upgrade table to the Product code (installed version of product)
  2. The uninstallation happens in the RemoveExistingProducts action which uninstalls those products marked for uninstallation (from the FindRelatedProducts action)
The problem in my case was that the FindRelatedProducts action skipped one of the products, so I had to include a small vbscript that was run before the RemoveExistingProducts action that found the product code for the product I wanted to remove and updated the according property so that it would be uninstalled:

set oWI = CreateObject("WindowsInstaller.Installer")
set related = oWI.RelatedProducts("YOUR_UPGRADECODE_HERE")
if related.Count = 1 then
Property("ACTIONPROPERTY_NAME_HERE") = related.Item(0)
end if

Forcing the product code to be set solved the issue I had even though I never found out what was wrong with the FindRelatedProducts action not picking up both products.

Tuesday, February 23, 2010

Extract COM information during build time causes Installshiled to hang

InstallShield uses a tool to extract COM information (spying on the registry) called IsRegSpy.exe. It is trying to register COM libraries and watching what happens in the registry to capture all the keys and values written during registration.

After adding some our own internal libraries I noticed that the IDE startet to hang when extracting COM information from the components in the setup project. After inspecting what was happening using ProcExplorer from Microsoft (http://www.sysinternals.com) I saw that the IDE spawned IsRegSpy.exe but IsRegSpy.exe never seemed to return.

After digging back and forth for a while, I tried to extract the COM information from within the InstallShield IDE to avoid getting this error each time we built the project. The same thing happened, the IDE launched IsRegSpy.exe and stopped responding.

I tried killing IsRegSpy.exe from within ProcExplorer, and noticed that InstallShield managed to add the correct COM information to the IDE! It also turned off the "Extract COM at build" setting for the component! Doing this for all COM components in the Setup project I managed to get past the problem of hanging the IDE when building.

EDIT: The last paragraph was obviously written in a very optimistic tone.. Some of the information was saved, some was not. My final solution was to export the registry hives before and after registering the dlls and then diffing the output...

Wednesday, February 17, 2010

Localization

Seems to be rather easy using InstallShield. There are several different options to choose from. You can add all the languages you want to support to your installation, or you can build seperate installations for each language.

NOTE: The language of the installer itself and the language your application is set up to run in are not the same.

I chose to build sepearate deployment packages for each language our application is using. The reasoning behind this is that each language component weights in at around 10 megs which could be a problem to distribute to remote users when updating or servicing the application.

Using different releases and configurations under the Media/Releases node gives me the opportuntity to build more than one setup.exe from my project. I have also integrated the build of each setup into our build system using some custom code for spawning Install Shield.

To get automatic resolving of which features that should go into which of my language dependant distributions, I have set the languages property for these features to a specific language (not Language Independent). When setting a release configuration 's data languages, ui languages and default language to a given language, only those features with either the same language as the configuration (or language independent) will be included in the setup!

Transforms and Setup.exe

When starting out with the deployment project, I tried to define some areas where I had to do some research to be certain that we had a solution that was scalable and easy to maintain.

One of the first issues I ran into was the need for using transforms to change some property values in the MSI package. The background for this requirement is that our app is a typical client/server-based application where our clients perform a server installation where they customize the installation against their database setup and file locations etc.

The cusomization performed in the server setup must be replicated into the client setup so that end users shouldn't have to select odbc connections or file locations upon installation.

The first issue here is how we can make the Server Setup process modify the client installer so that it depolys the client package with the predefined settings. To make this work, we've decided to use transform files.

A transform file is a simple msi database that contains tables just like another msi file. It is used to override values in the msi file it is transforming.

Creating a transform (.mft) file is simple using InstallShield. Just select new project and choose the Transform project template. InstallShield will ask you to provide the msi-file for which you are creating a transform, so you have to have it built already.

After creating the transform file, add it to your installation project under the support file section. You can now tell setup.exe to run it by providing command lines to the msi file in the setup.exe package. Select your setup release in InstallShield (this post is about transforms, so if you only have an msi project, please stop reading..) and switch to the Setup.exe tab. In the MSI Command Line Arguments property, enter TRANSFORMS=name of your mst file.

When we're ready to start generating our own transformation files that lives outside setup.exe, we can remove the transformation file from our setup project and provide it alongside the setup itself.

Welcome back...

I'm currently working on a new MSI-based installer for our main product, and since I tend to forget how I solve the different parts of building an installation from the last time I built one, I've decided to document some of the more important solutions I find here.

Tuesday, August 05, 2008

Process.WaitForExit() never completes

It's been over a year since the last time I blogged.... Sorry for that, but it's been a busy year. I've decided to pick up again and try to post some tech-related random thoughts once in a while.

Today I just wanted to share a bug I found that might be interesting for some of you.

I had a small function that started a process and waited for it to finish it's work. The code looked something like this:

Process P = new Process();
P.StartInfo.UseShellExecute = false;
P.StartInfo.RedirectStandardOutput = true;
P.StartInfo.RedirectStandardError = true;
P.StartInfo.FileName = pathToProgram;

P.StartInfo.Arguments = programArguments;
P.Start();

P.WaitForExit();
P.Close();

Since the process sometimes takes a while to finish, I wanted to be able to watch what was going on, so I decided to read from stderr/stdinput to see if something went wrong. To do this, I made sure that the RedirectStandardError properties of the process was set to true (see code above), and inserted the following line to check if the application had encountered any errors:

P.WaitForExit();
string err = P.StandardError.ReadToEnd();

P.Close();

After this code had been used for a while, I noticed that once in a while the application was hanging when performing the above process. The problem only occured when a lot of data was written to standarderror.

I debugged the problem, and found out that omitting reading from StandardError removed the problem. I thought that this seemed like a strange problem, and continued to search for a solution.

After reading the documentation, I finally came up with the information that revealed the problem. The following remark in the msdn library for the RedirectStandardError property says:

"The Process component communicates with a child process using a pipe. If a child process writes enough data to the pipe to fill the buffer, the child will block until the parent reads the data from the pipe. This can cause deadlock if your application is reading all output to standard error and standard output, for example, using the following C# code."

So instead of asking the process to fill the buffer and wait for me to empty it so that the call to WaitForExit() would block, reading the contents of the buffer (P.StandardError.ReadToEnd()) before calling WaitForExit() solved the problem and made the solution a success.

Conclusion: Read the documentation. And make sure you read the remarks.

Wednesday, August 01, 2007

Vista and Visual Studio 2003 again..

After the computer-switch I had to set up Vista for devlopment with Visual Studio 2003 again, and was a bit disappointed by my last post about the topic - I hadn't written anything at all about how I actually set up IIS 7.0 to be able to debug and run .Net 1.1 applications! So here it is.. the short version:

  • Register .Net 1.1 ASP.NET by running the following program. The -i parameter tells the utility to install support for ASP.NET 1.1 under IIS: Windows\Microsoft.NET\Framework\v1.1.4322\aspnet_regiis.exeaspnet_regiis.exe -i
  • Change the application pool to one using the .Net framework 1.1 for the application you want to debug and run

I also enabled .Net development and CGI in the additional windows components the "Windows functions" control panel applet.

Vista OEM - Network Troubles

Since I'm usually sitting at my desk developing new and interesting stuff for my company, using a slow (but cool :-) old Tablet PC wasn't the best way to be an effective developer.

Last week I got myself a new PC that will sit at my desk at work. It's a fast and brand new dual core computer with loads of memory, a big harddrive and a DirectX 10-based video card. I choose Windows Vista Business, since I've been quite happy with the way Vista has been working on my Tablet PC.

The only problem came when I was about to check in some source code to subversion. TortoiseSVN complained with a message saying it couldn't move a file in the repository. The repository is located on a network share and accessed by a small group of programmers.

I searched all over to see if this was a common problem with subversion, but found nothing. Then I noticed that I couldn't rename files on the network, and started to search for similar reports on the net. At last I found this post, which helped me fix the issue.

So why the OEM troubles heading? Read the above post - the bug has to do with something missing in the OEM version of Vista.

Wednesday, June 27, 2007

Kids and programming

After reading Scott Hanselman's article about how to teach kids computer programming, I once more decided to try to get my children interested in the topic that has brought me so much fun and joy.


The kids are now around 11 years old, and all enjoys playing games, doing homework and surf the web on their computers. They are creative, and can spend an evening creating images in MS Paint or making a presentation in Powerpoint.


I've previously tried to get them interested in programming using tools like KPL, but the big problem was learning the syntax. They're not yet able to learn enough statements or commands to express themselves and solve abstract problems in a textual programming language.

I went along and grabbed a copy of MIT's Scratch, which is a graphical tool for building small 2D games and animations:




Scratch uses a visual representation of statemements, variables and control blocks, and this really worked out for them. They quickly learned how to set up a small loop that tested for collisions with other objects, and that could send messages to all the other sprites making interesting things happen (like getting the sun to appear in the sky)


Allthough it is not possible to build fully fledged games in Scratch, it seems like a great tool to learn the basics of programming like I once learned on my Dragon 32 from my father (yes, we still have the old Dragon, allthough we haven't booted it up for a while).

Friday, June 08, 2007

They said it couldn't be done.. :-)

Development in Visual Studio 2003 on Microsoft Vista.

It is said that it is not possible to use Visual Studio 2003 in Microsoft Vista, and as I have written about earlier on, I set out on a small journey to find out how far I could get into using it on my Tecra M4.

Here is the current list:

  • Installed .Net Framework 1.1 - OK
  • Installed Visual Studio 2003 on Vista - OK
  • Been able to compile and build my projects under 2003 - OK
  • Debug web-based applications with Visual Studio 2003 and IIS 7.0 - OK
  • Edit and continue in Visual Studio 2003 - OK

The only thing I know I will have problems with is developing plain web applications  (you know the project type APS.Net Web Application), but since I don't use them, I wont cry either..!

Monday, June 04, 2007

My Venture into Vista Land

Phew! It takes a lot of time to install all the drivers and software one needs when reinstalling a computer...

As I wrote earlier on, I was eager to see if I could get Visual Studio 2003 up and running on Windows Vista. As some people say, it shouldn't be possible. This made me think that Vista might have some functionality that could prohibit programs from even installing, but this was not the case. Visual Studio 2003 installed in a much more clean way than the latest Visual Studio Orcas Beta (for testing out Silverlight development). Installing the Orcas beta (ok, I know it's Beta) went wrong almost ten times before I finally succeeded.

But now I have a brand new Vista installation working with all the tools I need to do my job. And it feels good. And since I'm kinda geeky, I must admit that I've turned off the Aero effects and reverted back to the old Win2K-look... But it's all in the details, isn't it?

Converting myself and my Tecra to Vista

Since my Toshiba Tecra M4 has been working for ages without being treated with  a fresh install, I finally decided that it was time to:

  1. Perform a fresh install, since the machine had become a bit slow and sluggish
  2. See if I could try a Vista install and check if I could trick Visual Studio 2003 into running on Vista.
  3. If section two failed, install Windows XP and pretend I didn't listen to any of the 2 million other developers out there telling me that this wouldn't work.

So, after a while of thinking and planning, I went ahead:

  1. Identifyed all the files on my computer that needed to be backed up
  2. Backed up all the files that I found to an external harddrive
  3. Double checked and tripple checked the above sections
  4. Downloaded and collected all the necessary drivers and software from Toshiba and others
  5. Installed Windows Vista

This all went well, except for the face that I got rather ill in the middle of the process due to an allergic reaction. This was of course a bit bad, sitting with a computer with no OS and no software..

In my next post I'll tell you how it went after I got the OS up and running!

Thursday, May 31, 2007

New Tech impresses me

Read about Microsoft Surface today, which looks like a very interesting and fun platform to play with.

The concept is using multitouch (more than one pointer on the screen, just like what Steve Jobs showed with the iPhone) on a big touch screen to navigate a delicious user interface built with WPF. In addition, a system utilizing invisible ink to tag devices like cameras and smartphones, is used to make Surface interact with devices and objects from the real world.

Microsoft says that the hardware will be kind of expensive (in the $5K-$10K range). What I really would like to see is Microsoft Surface running on a TabletPC with lots of cpu and memory. That would be a nice way of using my Toshiba Tecra M4...!

Sunday, May 20, 2007

Link to PopFly

Some of my readers have pointed out that I didn't include a link to PopFly yesterday. Sorry :-) Here it is:

http://www.popfly.com

And here is the link to the video presentation on Channel9:

http://channel9.msdn.com/showpost.aspx?postid=308460

Saturday, May 19, 2007

Popfly!

Just read about PopFly from Microsoft, which seems to be a really cool solution for building mashups and sharing them afterwords. The whole thing is built on Silverlight, which is also what I am currently installing on my computer..

Wednesday, May 09, 2007

Facebook is a cool hypeapp

I finally decided to join some of the social networks out there, and went for both linkedin an facebook.

Facebook has definitely been giving me most joy out of the two, but I suspect that Linkedn will probably give me more bang for the bucks if I'd really need it sometime in the future.

I really look forward to see if people will still enjoy writing on each other's walls and keep on connecting with long lost friends and classmates six months from now.

I really need to stay on Facebook for the nex months to see for myself :-) Anyway, without the hype there wouldn't have been any fun! Hope the hype stays.

Monday, May 07, 2007

Multitasking and the joy of Media Center

I'm currently doing some serious multitasking on my new HTCP.

The kids are watching children's tv while I'm reading my RSS feeds (and blogging). All on the same screen (thanks to NRK not sending in widescreen), thanks to our LCD flatscreen. And the kids aren't complaining about my thin Firefox window taking up approx. 1/3 of the screen.