Windows

#CASBAN6: Creating A Serverless Blog on Azure with .NET 6 (new series)

#CASBAN6: Creating A Serverless Blog on Azure with .NET 6 (new series)

Motivation

I was planning to run my blog without WordPress for quite some time. For one, because WordPress is really blown up as a platform. The second reason is more of a practical nature – this project gives me lots of stuff to improve my programming skills. I already started to move my developer website away from WordPress with ASP.NET CORE and Razor Pages. Eventually I arrived at the point where I needed to implement a blog engine for the news section. So, I have two websites (including this one here) that will take advantage of the outcome of this journey.

High Level Architecture

Now that the ‘why’ is clear, let’s have a look at the ‘how’:

There are several layers in my concept. The data layer consists of a serverless MS SQL instance on Azure, on which I will work with the help of Entity Framework Core and Azure Functions for all the CRUD operations of the blog. I will use the powers of Azure API Management, which will allow me to provide a secure layer for the clients – of course, an ASP.NET CORE Website with RazorPages, flanked by a .NET MAUI admin client (no web administration). Once the former two are done, I will also add a mobile client for this blog. It will be the next major update for my existing blog reader that is already in the app stores.

For comments, I will use Disqus. This way, I have a proven comment system where anyone can use his/her favorite account to participate in discussions. They also have an API, so there is a good chance that I will be able to implement Disqus in the Desktop and Mobile clients.

Last but not least, there are (for now) two open points – performance measuring/logging and notifications. I haven’t decided yet how to implement these – but I guess there will be an Azure based implementation as well (until there are good reasons to use another service).

Open Source

Most of the software I will write and blog about in this series will be available publicly on GitHub. You can find the repository already there, including stuff for the next two upcoming blog posts already in there.

Index

I will update this blog post regularly with a link new entries of the series.

Additional note

Please note that I am working on this in my spare time. This may result in delays between the blog posts and the updates committed into the repository on GitHub.

Until the next post – happy coding, everyone!


Title Image by Roman from Pixabay

Posted by msicc in Android, Azure, Dev Stories, iOS, MAUI, Web, 2 comments
Xamarin.Forms, Akavache and I: ensuring protection of sensitive data

Xamarin.Forms, Akavache and I: ensuring protection of sensitive data

Recap

Some of you might remember my posts about encryption for Android, iOS and Windows 10. If not, take a look here:

Xamarin Android: asymmetric encryption without any user input or hardcoded values

How to perform asymmetric encryption without user input/hardcoded values with Xamarin iOS

Using the built-in UWP data protection for data encryption

It is no coincidence that I wrote these three posts before starting with this Akavache series, as we’ll use those techniques to protect sensitive data with Akavache. So you might have a look first before you read on.

Creating a secure blob cache in Akavache

Akavache has a special type for saving sensitive data  – based on the interface ISecureBlobCache. The first step is to extend the IBlobCacheInstanceHelperinterface we implemented in the first post of this series:

    public interface IBlobCacheInstanceHelper
    {
        void Init();

        IBlobCache LocalMachineCache { get; set; }

        ISecureBlobCache SecretLocalMachineCache { get; set; }
    }

Of course, all three platform implementations of the IBlobCacheInstanceHelperinterface need to be updated as well. The code to add for all three platform is the same:

public ISecureBlobCache SecretLocalMachineCache { get; set; }     

private void GetSecretLocalMachineCache()
{
    var secretCache = new Lazy<ISecureBlobCache>(() =>
                                                 {
                                                     _filesystemProvider.CreateRecursive(_filesystemProvider.GetDefaultSecretCacheDirectory()).SubscribeOn(BlobCache.TaskpoolScheduler).Wait();
                                                     return new SQLiteEncryptedBlobCache(Path.Combine(_filesystemProvider.GetDefaultSecretCacheDirectory(), "secret.db"), new PlatformCustomAkavacheEncryptionProvider(), BlobCache.TaskpoolScheduler);
                                                 });

    this.SecretLocalMachineCache = secretCache.Value;
}

As we will use the same name for all platform implementations, that’s already all we have to do here.

Platform specific encryption provider

Implementing the platform specific code is nothing new. Way before I used Akavache, others have already implemented solutions. The main issue is that there is no platform implementation for Android and iOS (and maybe others). My solution is inspired by this blog post by Kent Boogart, which is (as far as I can see), also broadly accepted amongst the community. The only thing I disliked about it was the requirement for a password – which either would be something reversible or causing a (maybe) bad user experience.

Akavache provides the IEncryptionProviderinterface, which contains two methods. One for encryption, the other one for decryption. Those two methods are working with byte[]both for input and output. You should be aware and know how to convert your data to that.

Implementing the  IEncryptionProvider interface

The implementation of Akavache’s encryption interface is following the same principle on all three platforms.

  • provide a reference to the internal TaskpoolSchedulerin the constructor
  • get an instance of our platform specific encryption provider
  • get or create keys (Android and iOS)
  • provide helper methods that perform encryption/decryption

Let’s have a look at the platform implementations. I will show the full class implementation and remarking them afterwards.

Android

[assembly: Xamarin.Forms.Dependency(typeof(PlatformCustomAkavacheEncryptionProvider))]
namespace XfAkavacheAndI.Android.PlatformImplementations
{
    public class PlatformCustomAkavacheEncryptionProvider : IEncryptionProvider
    {
        private readonly IScheduler _scheduler;

        private static readonly string KeyStoreName = $"{BlobCache.ApplicationName.ToLower()}_secureStore";

        private readonly PlatformEncryptionKeyHelper _encryptionKeyHelper;

        private const string TRANSFORMATION = "RSA/ECB/PKCS1Padding";
        private IKey _privateKey = null;
        private IKey _publicKey = null;

        public PlatformCustomAkavacheEncryptionProvider()
        {
            _scheduler = BlobCache.TaskpoolScheduler ?? throw new ArgumentNullException(nameof(_scheduler), "Scheduler is null");

            _encryptionKeyHelper = new PlatformEncryptionKeyHelper(Application.Context, KeyStoreName);
            GetOrCreateKeys();
        }

        public IObservable<byte[]> DecryptBlock(byte[] block)
        {
            if (block == null)
            {
                throw new ArgumentNullException(nameof(block), "block cannot be null");
            }

            return Observable.Start(() => Decrypt(block), _scheduler);
        }

        public IObservable<byte[]> EncryptBlock(byte[] block)
        {
            if (block == null)
            {
                throw new ArgumentNullException(nameof(block), "block cannot be null");
            }

            return Observable.Start(() => Encrypt(block), _scheduler);
        }


        private void GetOrCreateKeys()
        {
            if (!_encryptionKeyHelper.KeysExist())
                _encryptionKeyHelper.CreateKeyPair();

            _privateKey = _encryptionKeyHelper.GetPrivateKey();
            _publicKey = _encryptionKeyHelper.GetPublicKey();
        }


        public byte[] Encrypt(byte[] rawBytes)
        {
            if (_publicKey == null)
            {
                throw new ArgumentNullException(nameof(_publicKey), "Public key cannot be null");
            }

            var cipher = Cipher.GetInstance(TRANSFORMATION);
            cipher.Init(CipherMode.EncryptMode, _publicKey);

            return cipher.DoFinal(rawBytes);
        }

        public byte[] Decrypt(byte[] encyrptedBytes)
        {
            if (_privateKey == null)
            {
                throw new ArgumentNullException(nameof(_privateKey), "Private key cannot be null");
            }

            var cipher = Cipher.GetInstance(TRANSFORMATION);
            cipher.Init(CipherMode.DecryptMode, _privateKey);

            return cipher.DoFinal(encyrptedBytes);
        }
    }

As you can see, I am getting Akavache’s  internal TaskpoolSchedulerin the constructor, like initial stated. Then, for this sample, I am using RSA encryption. The helper methods pretty much implement the same code like in the post about my KeyStore implementation. The only thing to do is to use these methods in the EncryptBlock and DecyrptBlock method implementations, which is done asynchronously via Observable.Start.

iOS

[assembly: Xamarin.Forms.Dependency(typeof(PlatformCustomAkavacheEncryptionProvider))]
namespace XfAkavacheAndI.iOS.PlatformImplementations
{
    public class PlatformCustomAkavacheEncryptionProvider : IEncryptionProvider
    {
        private readonly IScheduler _scheduler;

        private readonly PlatformEncryptionKeyHelper _encryptionKeyHelper;


        private SecKey _privateKey = null;
        private SecKey _publicKey  = null;

        public PlatformCustomAkavacheEncryptionProvider()
        {
            _scheduler = BlobCache.TaskpoolScheduler ??
                         throw new ArgumentNullException(nameof(_scheduler), "Scheduler is null");

            _encryptionKeyHelper = new PlatformEncryptionKeyHelper(BlobCache.ApplicationName.ToLower());
            GetOrCreateKeys();
        }

        public IObservable<byte[]> DecryptBlock(byte[] block)
        {
            if (block == null)
            {
                throw new ArgumentNullException(nameof(block), "block can't be null");
            }

            return Observable.Start(() => Decrypt(block), _scheduler);
        }

        public IObservable<byte[]> EncryptBlock(byte[] block)
        {
            if (block == null)
            {
                throw new ArgumentNullException(nameof(block), "block can't be null");
            }

            return Observable.Start(() => Encrypt(block), _scheduler);
        }


        private void GetOrCreateKeys()
        {
            if (!_encryptionKeyHelper.KeysExist())
                _encryptionKeyHelper.CreateKeyPair();

            _privateKey = _encryptionKeyHelper.GetPrivateKey();
            _publicKey = _encryptionKeyHelper.GetPublicKey();
        }

        private byte[] Encrypt(byte[] rawBytes)
        {
            if (_publicKey == null)
            {
                throw new ArgumentNullException(nameof(_publicKey), "Public key cannot be null");
            }

            var code = _publicKey.Encrypt(SecPadding.PKCS1, rawBytes, out var encryptedBytes);

            return code == SecStatusCode.Success ? encryptedBytes : null;
        }

        private byte[] Decrypt(byte[] encyrptedBytes)
        {
            if (_privateKey == null)
            {
                throw new ArgumentNullException(nameof(_privateKey), "Private key cannot be null");
            }

            var code = _privateKey.Decrypt(SecPadding.PKCS1, encyrptedBytes, out var decryptedBytes);

            return code == SecStatusCode.Success ? decryptedBytes : null;
        }

    }
}

The iOS implementation follows the same schema as the Android implementation. However, iOS uses the KeyChain, which makes the encryption helper methods itself different.

UWP

[assembly: Xamarin.Forms.Dependency(typeof(PlatformCustomAkavacheEncryptionProvider))]
namespace XfAkavacheAndI.UWP.PlatformImplementations
{
    public class PlatformCustomAkavacheEncryptionProvider : IEncryptionProvider
    {
        private readonly IScheduler _scheduler;

        private string _localUserDescriptor = "LOCAL=user";
        private string _localMachineDescriptor = "LOCAL=machine";

        public bool UseForAllUsers { get; set; } = false;

        public PlatformCustomAkavacheEncryptionProvider()
        {
            _scheduler = BlobCache.TaskpoolScheduler ??
                         throw new ArgumentNullException(nameof(_scheduler), "Scheduler is null");
        }

        public IObservable<byte[]> EncryptBlock(byte[] block)
        {
            if (block == null)
            {
                throw new ArgumentNullException(nameof(block), "block can't be null");
            }

            return Observable.Start(() => Encrypt(block).GetAwaiter().GetResult(), _scheduler);
        }

        public IObservable<byte[]> DecryptBlock(byte[] block)
        {
            if (block == null)
            {
                throw new ArgumentNullException(nameof(block), "block can't be null");
            }

            return Observable.Start(() => Decrypt(block).GetAwaiter().GetResult(), _scheduler);
        }


        public async Task<byte[]> Encrypt(byte[] data)
        {
            var provider = new DataProtectionProvider(UseForAllUsers ? _localMachineDescriptor : _localUserDescriptor);

            var contentBuffer = CryptographicBuffer.CreateFromByteArray(data);
            var contentInputStream = new InMemoryRandomAccessStream();
            var protectedContentStream = new InMemoryRandomAccessStream();

            //storing data in the stream
            IOutputStream outputStream = contentInputStream.GetOutputStreamAt(0);
            var dataWriter = new DataWriter(outputStream);
            dataWriter.WriteBuffer(contentBuffer);
            await dataWriter.StoreAsync();
            await dataWriter.FlushAsync();

            //reopening in input mode
            IInputStream encodingInputStream = contentInputStream.GetInputStreamAt(0);

            IOutputStream protectedOutputStream = protectedContentStream.GetOutputStreamAt(0);
            await provider.ProtectStreamAsync(encodingInputStream, protectedOutputStream);
            await protectedOutputStream.FlushAsync();

            //verify that encryption happened
            var inputReader = new DataReader(contentInputStream.GetInputStreamAt(0));
            var protectedReader = new DataReader(protectedContentStream.GetInputStreamAt(0));

            await inputReader.LoadAsync((uint)contentInputStream.Size);
            await protectedReader.LoadAsync((uint)protectedContentStream.Size);

            var inputBuffer = inputReader.ReadBuffer((uint)contentInputStream.Size);
            var protectedBuffer = protectedReader.ReadBuffer((uint)protectedContentStream.Size);

            if (!CryptographicBuffer.Compare(inputBuffer, protectedBuffer))
            {
               return protectedBuffer.ToArray();
            }
            else
            {
                return null;
            }
        }

        public async Task<byte[]> Decrypt(byte[] encryptedBytes)
        {
            var provider = new DataProtectionProvider();

            var encryptedContentBuffer = CryptographicBuffer.CreateFromByteArray(encryptedBytes);
            var contentInputStream = new InMemoryRandomAccessStream();
            var unprotectedContentStream = new InMemoryRandomAccessStream();

            IOutputStream outputStream = contentInputStream.GetOutputStreamAt(0);
            var dataWriter = new DataWriter(outputStream);
            dataWriter.WriteBuffer(encryptedContentBuffer);
            await dataWriter.StoreAsync();
            await dataWriter.FlushAsync();

            IInputStream decodingInputStream = contentInputStream.GetInputStreamAt(0);

            IOutputStream protectedOutputStream = unprotectedContentStream.GetOutputStreamAt(0);
            await provider.UnprotectStreamAsync(decodingInputStream, protectedOutputStream);
            await protectedOutputStream.FlushAsync();

            DataReader reader2 = new DataReader(unprotectedContentStream.GetInputStreamAt(0));
            await reader2.LoadAsync((uint)unprotectedContentStream.Size);
            IBuffer unprotectedBuffer = reader2.ReadBuffer((uint)unprotectedContentStream.Size);

            return unprotectedBuffer.ToArray();
        }
    }   
}

Last but not least, we have also an implementation for Windows applications. It is using the DataProtection API, which does handle all that key stuff and let’s us focus on the encryption itself. As the API is asynchronously, I am using .GetAwaiter().GetResult()Task extensions to make it compatible with Observable.Start.

Conclusion

Using the implementations above paired with our instance helper makes it easy to protect data in our apps. With all those data breach scandals and law changes around, this is one possible way secure way to handle sensitive data, as we do not have hardcoded values or any user interaction involved.

For better understanding of all that code, I made a sample project available that has all the referenced and mentioned classes implemented. Feel free to fork it and play with it (or even give me some feedback). For using the implementations, please refer to my post about common usages I wrote a few days ago. The only difference is that you would use SecretLocalMachineCacheinstead of LocalMachineCache for sensitive data.

As always, I hope this post is helpful for some of you.

Until the next post, happy coding!


P.S. Feel free to download my official app for msicc.net, which – of course – uses the implementations above:
iOS Android Windows 10

Posted by msicc in Android, Dev Stories, iOS, Windows, Xamarin, 3 comments
Xamarin.Forms, Akavache and I: storing, retrieving and deleting data

Xamarin.Forms, Akavache and I: storing, retrieving and deleting data

Caching always has the same job: provide data that is frequently used in very little time. As I mentioned in my first post of this series, Akavache is my first choice because it is fast. It also provides a very easy way to interact with it (once one gets used to Reactive Extensions). The code I am showing here is living in the Forms project, but can also be called from the platform projects thanks to the interface we defined already before.

Enabling async support

First things first: we should write our code asynchronously, that’s why we need to enable async support by adding using System.Reactive.Linq;to the using statements in our class. This one is not so obvious, and I read a lot of questions on the web where this was the simple solution. So now you know, let’s go ahead.

Simple case

The most simple case of storing data is just throwing data with a key into the underlying database:

//getting a reference to the cache instance
var cache = SimpleIoc.Default.GetInstance<IBlobCacheInstanceHelper>().LocalMachineCache;
var dataToSave = "this is a simple string to save into the database";
await cache.InsertObject<string>("YourKeyHere", dataToSave);

Of course, we need a reference to the IBlobCacheinstance we have already in place. I am saving a simple string here for demo purposes, but you can also save more complex types like a list of blog posts into the cache. Akavache uses Json.NET , which will serialize the data into a valid json string that you can be saved. Similarly, it is very easy to get the data deserialized from the database:

var dataFromCache = cache.GetObject<string>("YourKeyHere");

That’s it. For things like storing Boolean values, simple strings (unencrypted), dates etc., this might already be everything you need.

Caching data from the web

Of course it wouldn’t be necessary to implement an advanced library if we would have only this scenario. More often, we are fetching data from the web and need to save it in our apps. There are several reasons to do this, with saving (mobile) data volume and performance being the two major reasons.

Akavache provides a bunch of very useful Extensions. The most prominent one I am using is the GetOrFetchObject<T>method. A typical implementation looks like this:

var postsCache = await cache.GetOrFetchObject<List<BlogPost>>(feedName,
    async () =>
    {
        var newPosts = await _postsHandler.GetPostsAsync(BaseUrl, 20, 20, 1, feedName.ToCategoryId()).ConfigureAwait(false);

        await cache.InsertObject<List<BlogPost>>(feedName, newPostsDto);

        return newPosts;
    });

The GetOrFetchObject<T>method’s minimum parameters are the key of the cache entry and an asynchronous function that shall be executed when there is no data in the cache. In the sample above, it loads the latest 20 posts from a WordPress blog (utilizing my WordPressReader lib) and saves it into the cache instance before returning the downloaded data. The method has an optional parameter of DateTimeOffset, which may be interesting if you need to expire the saved data after some time.

Saving images/documents from the web

If you need to download files, be it images or other documents, from the web, Akavache provides another helper extension:

byte[] bytes = await cache.DownloadUrl("YourFileKeyHere", url);

Personally, I am loading all files with this method, even though there are some special image loading methods available as well (see the readme at Akavache’s repo). The main reason I am doing so is that until now, I always have a platform specific implementation for such cases – mainly due to performance reasons. I one of the following blog posts you will see such an implementation for image caching using a custom renderer on each platform.

Deleting data from the cache

When working with caches, one cannot avoid the situation that data needs to be removed manually from the cache.

//delete a single entry by key:
cache.Invalidate("KeyToDelete");

//delete all entries with the same type:
cache.InvalidateAllObjects<BlogPost>();

//delete all entries
cache.InvalidateAll();

If you want to continue with some other action after deletion completes, you can use the Subscribe method to invoke this action:

cache.InvalidateAll().Subscribe(x => YourMethodToInvoke());

Conclusion

Even though Akavache provides more methods to store and retrieve data, the ones I mentioned above are those that I use frequently and without problems in my Xamarin.Forms applications, while still being able to invoke them in platform specific code as well. If you want to have a look at the other methods that are available, click the link above to the GitHub repo of Akavache. As always, I hope this blog post is helpful for some of you.

Until the next post, happy coding, everyone!

Posted by msicc in Android, Dev Stories, iOS, Windows, Xamarin, 1 comment
Xamarin.Forms, Akavache and I: Initial setup (new series)

Xamarin.Forms, Akavache and I: Initial setup (new series)

Caching is never a trivial task. Sometimes, we can use built-in storages, but more often, these take quite some time when we are storing a large amount of data (eg. large datasets or large json strings). I tried quite a few approaches, including:

  • built-in storage
  • self handled files
  • plugins that use a one or all of the above
  • Akavache (which uses SQLite under the hood)

Why Akavache wins

Well, the major reason is quite easy. It is fast. Really fast. At least compared to the other options. You may not notice the difference until you are using a background task that relies on the cached data or until you try to truly optimize startup performance of your Xamarin Android app. Those two where the reason for me to switch, because once implemented, it does handle both jobs perfectly. Because it is so fast, there is quite an amount of apps that uses it. Bonus: there are a lot of tips on StackOverflow as well as on GitHub, as it is already used by a lot of developers.

Getting your projects ready

Well, as often, it all starts with the installation of NuGet packages. As I am trying to follow good practices wherever I can, I am using .netStandard whenever possible. The latest stable version of Akavache does work partially in .netStandard projects, but I recommend to use the latest alpha (by the time of this post) in your .netStandard project (even if VisualStudio keeps telling you that a pre release dependency is not a good idea). If you are using the package reference in your project files, there might be some additional work to bring everything to build and run smoothly, especially in a Xamarin.Android project.

You mileage may vary, but in my experience, you should install the following dependencies and Akavache separately:

After installing this packages in your Xamarin.Forms and platform projects, we are ready for the next step.

Initializing Akavache

Basically, you should be able to use Akavache in a very simple way, by just defining the application name like this during application initialization:

BlobCache.ApplicationName = "MyAkavachePoweredApp";

You can do this assignment in your platform project as well as in your Xamarin.Forms project, both ways will work. Just remember to do this, as also to get my code working, this is a needed step.

There are static properties  like BlobCache.LocalMachineone can use to cache data. However, once your app will use an advanced library like Akavache, it is very likely that he complexity of your app will force you into a more complex scenario. In my case, the usage of a scheduled job on Android was the reason why I am doing the initialization on my own. The scheduled job starts a process for the application, and the job updates data in the cache that the application uses. There were several cases where the standard initialization did not work, so I decided to make the special case to a standard case. The following code will also work in simple scenarios, but keeps doors open for more complex ones as well. The second reason why I did my own implementation is the MVVM structure of my apps.

IBlobCacheInstanceHelper rules them all

Like often when we want to use platform implementations, all starts with an interface that dictates the functionality. Let’s start with this simple one:

public interface IBlobCacheInstanceHelper
{
    void Init();
    IBlobCache LocalMachineCache { get; set; }
}

We are defining our own IBlobCacheinstance, which we will initialize with the Init() method on each platform. Let’s have a look on the platform implementations:

[assembly: Xamarin.Forms.Dependency(typeof(PlatformBlobCacheInstanceHelper))]
namespace [YOURNAMESPACEHERE]
{
    public class PlatformBlobCacheInstanceHelper : IBlobCacheInstanceHelper
    {
        private IFilesystemProvider _filesystemProvider;

        public PlatformBlobCacheInstanceHelper() { }

        public void Init()
        {
            _filesystemProvider = Locator.Current.GetService<IFilesystemProvider>();
            GetLocalMachineCache();
        }

        public IBlobCache LocalMachineCache { get; set; }

        private void GetLocalMachineCache()
        {

            var localCache = new Lazy<IBlobCache>(() => 
                                                  {
                                                      _filesystemProvider.CreateRecursive(_filesystemProvider.GetDefaultLocalMachineCacheDirectory()).SubscribeOn(BlobCache.TaskpoolScheduler).Wait();
                                                      return new SQLitePersistentBlobCache(Path.Combine(_filesystemProvider.GetDefaultLocalMachineCacheDirectory(), "blobs.db"), BlobCache.TaskpoolScheduler);
                                                  });

            this.LocalMachineCache = localCache.Value;
        }

        //TODO: implement other cache types if necessary at some point
    }
}

Let me explain what this code does.

As SQLite, which is powering Akavache, is file based, we need to provide a file path. The Init() method assigns Akavache’s internal IFileSystemProviderinterface to the internal member. After getting an instance via Splat’s Locator, we can now use it to get the file path and create the .db-file for our local cache. The GetLocalMachineCache()method is basically a copy of Akavache’s internal registration. It lazily creates an instance of BlobCache through the IBlobCacheinterface. The create instance is then passed to the LocalMachineCacheproperty, which we will use later on. Finally, we will be using the DependencyServiceof Xamarin.Forms to get an instance of our platform implementation, which is why we need to define the Dependency attribute as well.

Note: you can name the file whatever you want. If you are already using Akavache and want to change the instance handling, you should keep the original names used by Akavache. This way, your users will not lose any data.

This implementation can be used your Android, iOS and UWP projects within your Xamarin.Forms app. If you are wondering why I do this separately for every platform, you are right. Until now, there is no need to do it that way. The code above would also work solely in your Xamarin.Forms project. Once you are coming to the point where you need encrypted data in your cache, the platform implementations will change on every platform. This will be topic of a future blog post, however.

If you have been reading my series about MVVMLight, you may guess the next step already. This is how I initialize the platform implementation within my ViewModelLocator:

//register:
var cacheInstanceHelper = DependencyService.Get<IBlobCacheInstanceHelper>();
if (!SimpleIoc.Default.IsRegistered<IBlobCacheInstanceHelper>())
     SimpleIoc.Default.Register<IBlobCacheInstanceHelper>(()=> cacheInstanceHelper);

//initialize:
//cacheInstanceHelper.Init();
//or
SimpleIoc.Default.GetInstance<IBlobCacheInstanceHelper>().Init();

So that’s it, we are now ready to use our local cache powered by Akavache within our Xamarin.Forms project. In the next post, we will have a look on how to use akavache for storing and retrieving data.

Until then, happy coding, everyone!

Posted by msicc in Android, Dev Stories, iOS, Windows, Xamarin, 1 comment

Editorial: Why the app gap on Windows Phone/10 Mobile is a bigger problem than I thought

Note: as this is an editorial, this blog post reflects my own experience and thoughts. You will agree with some points, but disagree with others. Feel free to leave a comment to start a discussion below.

Recently, I received a Nexus 5x as development device for a project I am about to start. As tech enthusiast, I could not resist to start using it as my daily driver.

As you might guess, I started with an install orgy of all the apps I am using on my Lumia 950 XL and set them up. It may be surprising, but I immediately recognized huge differences between the platform versions.

Take the Facebook app for example. Animations are smooth like butter, almost all settings are in app instead of leading to a mobile page, even loading content and scrolling is a whole lot better than on Windows 10 Mobile.

Another example is the Path app. Never been updated since its launch on Windows Phone, I was truly surprised when I opened It on Android. It is an app that really is fun to use on Android. I bet they would have a lot more users on Windows if they align the app… sadly, they abanonded the platform completely a few month ago.

The last example is the WordPress app. It exists on Windows (Phone) for existing users, but the experience on Android is galaxies away from the one the one in Windows (Phone) has/had. I am even writting this post with it, because it feels just right to do this (I only did that once on Windows Phone).

These were only three examples, but they show pretty much how different official apps can be between platforms (and how they are supported). And they all show, that Windows really has no priority anywhere (sadly).
The quality of apps that are available on Windows is not all, though. Of course, I downloaded also some apps that aren’t available for my Lumia 950 XL as well. And it does make a difference.

On my Lumia, I often use the mobile page for things to do/achieve. On Android, I have a whole lot more apps to choose from, so I never had to open the browser for:

  • my mobile carrier
  • my landline & tv carrier
  • the communal page of Winterthur (where I live)
  • swiss auction page of ricardo.ch
  • swiss page tutti.ch
  • Amazon (Bonus: the apps are connected, needed to log in only on one and all others had my account)
  • eat.ch, a swiss food order service
  • Imgur
  • Giphy
  • and more…

Some say a good mobile page is as good as an app. That’s wrong for most cases. A good written app is always handier than a website. On any platform (at least in my experience).

Android app quality has improved a lot in the last two and a half years (that’s how long it took me to deeply test the OS and the ecosystem again). They are equal to the high level on iOS (which I saw also recently, as my son broke out of the Windows world I created at home).

On Windows, we have a lot of third party apps that are trying to fill the gap. I respect those developers (at least those that use legal, public APIs), but it is just not the same. And even on Android (or iOS), there is room for third party apps besides the official ones.

The Android OS itself feels also grown up, and it is difficult to say if iOS or Android are better. It is more a question of who you prefer – Google or Apple.

Microsoft’s Windows (Phone/10 Mobile) is on a good way to get on par. Lots of the functionality is also there. But… as long as the provider of a service, no matter which kind, do not use them (for whatever reason), Windows will never grow up. The Universal App approach is a good idea, and it may pay off one day – or it may be too late already. The recent switch to focus on enterprise users does not really help. Because also enterprise users tend to have only one device. And also enterprise users tend to use apps on their mobile device.

As a WinPhan, writting this honest post deeply hurts. Even more, as I really am thinking about switching platforms for mobile things. Not as a developer, but as a user (at least until Windows has grown up).

Posted by msicc in Editorials, 4 comments

How to generate a round image button for your Windows Phone 8.1 app (to use everywhere)

Recently, I experimented a bit because I wanted a round button that contains an image that can be used everywhere where I can add a standard button (and not just in the AppBar). I managed to get a simple style out of these experiments (sample at the end of this post).

First, you should check if you have already installed Syncfusion’s free Metro Studio (we will need it later). It is a powerful helper if you need icons, so if you do not have it, go straight ahead and download it here: http://www.syncfusion.com/downloads/metrostudio

Still here/back? Great! Ok, let’s start. In our project, generate a new button:

<Button Width="72" Height="72"></Button>

If you want your round button to have a smaller size, feel free to adjust the 72 pixels mine has to your preferred value.

The next step is to generate a new Style. Right click on the Button, and select ‘Edit Template’, followed by ‘Edit a Copy’.

Screenshot (407)

 

Set the name of your style in the next window, and save define it as an app-wide Style or on your page:

Screenshot (408)

This should open your App.xaml file and display the button as well as the newly generated style.

We are starting with our custom style modifications right at the top:

image

Set both Doubles to 0 and the Thickness to 0,0.

Next, scroll down to find the Border Element of the Button Template (closing ‘VisualStateManager.VisualStateGroups’ helps a lot).

Click on the Border element and add/adjust the ‘CornerRadius’ property. At a size of 72, the minimum value is 38 for the radius. This should be fine for most cases, but it may be higher/smaller if you are using another size. Don’t worry if your button looks like this at them moment:

image

We are going to fix it right now by setting the Height and Width properties of our Border element:

Height="{Binding Path=Height, RelativeSource={RelativeSource Mode=TemplatedParent}}"
Width="{Binding Path=Width, RelativeSource={RelativeSource Mode=TemplatedParent}}"

This binds the Width and Height properties of our Button to the Style. Now we just need to define the Height and the Width of our Button to make it actually look really round. Setting both to 72 will result in a nice round button.

Like you can imagine, displaying text does not make a lot of sense in this case. Round Buttons should contain an image. You could add one through adding a background, but this will result in a strange looking button when it gets pressed. Also, it does not reflect changes like a color change. To solve this, we are going to add code that is able to draw a shape for us. This is achieved with the Path Class  in XAML. The Path class draws lines into a FrameworkElement like a Canvas or a Border.

To enable our Style to work with Path Data, we need to add some code before the ‘Template’ property Setter in our Style:

<Setter Property="ContentTemplate">
    <Setter.Value>
        <DataTemplate>
            <Path Stretch="Uniform"
                  RenderTransformOrigin="0.5,0.5"
                  Margin="2,6,2,2"
                  Fill="{Binding Path=Foreground, RelativeSource={RelativeSource Mode=TemplatedParent}}"
                  Data="{Binding Path=Content, RelativeSource={RelativeSource Mode=TemplatedParent}}"></Path>
        </DataTemplate>
    </Setter.Value>
</Setter>

What does this code do? The ContentTemplate allows us to add rich content to our UIElement, the Button. To make it resuable, we are setting it up in our custom button style. The RenderTransforOrigin property value of 0.5,0.5 centers our Path drawn shape within the border. However, I found out that some shapes do not look good with that alone. That’s why I adjusted the Margin property together with it. This should fit most icon shapes, but you might adjust this for your own needs.

The most important aspects are the Fill property as well as the Data property. Binding the Fill Brush to the Foreground Brush property is necessary to reflect changes like theme changes as well as changes in the VisualState. Only this way it behaves like a native Button. Binding the Data property allows us to enter the Path string into the Content property of a button that uses our Style without any conversion. This makes it very simple to generate a button with our desired icon.

And this is where Syncfusion’s MetroStudio comes in handy. It allows you not only to generate icons as png, but also as shape in XAML. To get the relevant Data, open MetroStudio, search for your icon. Below the icon, there is an Edit Button. Tap it to open the icon settings page. On that settings page, you set up your button. Play around a little bit to get used to it (it’s pretty easy).

Once you have your desired icon on the screen, click on the </>XAML Button. Copy the highlighted part of the XAML code:

image

Back in Visual Studio, add this copied code to the Content property of our Button:

Content="F1M181.003,-1898.78L207.077,-1902.33 207.089,-1877.18 181.027,-1877.03 181.003,-1898.78z M207.065,-1874.28L207.085,-1849.1 181.023,-1852.69 181.022,-1874.45 207.065,-1874.28z M210.226,-1902.79L244.798,-1907.84 244.798,-1877.5 210.226,-1877.22 210.226,-1902.79z M244.807,-1874.04L244.798,-1843.84 210.226,-1848.72 210.177,-1874.1 244.807,-1874.04z" 
Height="72" 
Width="72"
Style="{StaticResource RoundButtonStyle}" 
VerticalAlignment="Center" 
HorizontalAlignment="Center"/>

Which will result in this nice looking round button with a Windows logo on it:

image

If you run the sample project, you can see that the Button behaves like a native Button with text. Download the sample project here.

I am pretty sure this can be improved. I will continue to play around with this, and if I have found enough optimizations, I will write another post about them. Until then, this should help you to get started with your own round button – and the best thing: you can use it like any standard button wherever you want in your Windows (Phone) 8.1 app!

Happy coding, everyone!

Posted by msicc in Archive, 1 comment

A year in the like of MSicc – my review of 2013

dev smurf

2013 was a year with a lot of surprises. It was a year full of community work for me as well as a huge learning year in development. But my year had also dark clouds on heaven. This post is my personal review of 2013 – you can like my impressions or not.

I started the year with releasing my first Windows 8 app ever, along with an huge update to my blog reader app for Windows Phone. I wrote several blog posts and started also development of my NFC Toolkit app for Windows Phone (Archive: January). I also ran a beta test for my NFC Toolkit, and finished my series about the parts that should help other developers  to write a blog reader app for both Windows and Windows Phone (Archive February & Archive March).

Then in April, the first time I had dark clouds hanging deeply in my life, affecting all parts – family, community work and also my 9to5 job. My wife had once again problems with her back, caused by slipped discs. It went as far as she needed to rest in hospital for a pain therapy. Luckily this therapy was helping her and our life went back to normality (knocking on wood).

I also started a new series on the WinPhanDev blog – Why we started developing (WWSDEV). We are collecting stories from developers, and posting them over there to motivate other developers and keep the community spirit alive. Just have a look, we have really great stories over there.

In the last days of April/beginning of May, Iljia engaged me to start using Windows Azure Mobile Services to make an app idea reality: TweeCoMinder was born. It is a very special and unique app, interesting for those that don’t want to miss their special counts on Twitter, supported by real push notifications via WAMS for both Live Tiles and Toast Notifications. I learned a lot during setting up my WAMS for the app, and I did also write some blog posts about that (AzureDev posts).

Because of TweeCoMinder, I stopped developing my NFC app for that time, and did only bug fixing updates to my other apps.

In August (at least in the spare time I had), I moved my blog completely to run in a Windows Azure VM. I did it to get more control over the whole system and to learn more about running a web service. I still need to write my blog posts about setting the VM with LAMP on Azure, but I just didn’t have time for that until now. In August/September I also had again very very dark clouds hanging around, with my wife was very ill (you can’t even imagine how happy I am about the fact she has this part behind her). But our daily live is still affected by this – we just learned to arrange us with the new situation.

In October, I got back to my NFC Toolkit to finish it finally. The app has some cool and unique features utilizing NFC tags, and I am quite satisfied with my download numbers. NFC Toolkit is my main project for the moment.

But also on my 9to5 job I came to write code. I was asked to write an internal app for Windows Phone (Telefónica has a partnership with Microsoft, and so the company is flooded with Windows Phones). I used this to learn more about speech recognition on Windows Phone, as this is part of the application (Make your app listening to the user’s voice).

And finally, I also started with my very first Android app using Xamarin while porting the Windows Phone app I wrote before. I recently started to blog about my experiences with Xamarin (read more here).

In between all those projects, I made a basic reader app for the fan blog “This is Nokia”, using a PCL project for both Windows Phone 8 and Windows 8. I also wrote a simple car dashboard app to integrate it in my NFC Toolkit app as well as Mix, Play & Share, which was written on a lonely Saturday night while my kids where sleeping an my wife was at her best friend.

Through the year, I learned a lot of coding, but also a lot about people. I made some very positive experiences – but also bad ones. I am always willing to help (if my still growing knowledge enables me to do so) – but sharing a feature rich app to another person isn’t helping – if you want to learn about development, there are plenty ways to do so. We have really great developers that blog about their experiences in our community, and by understanding how to code, you truly learn. Just using an already working app and restyling it, is the wrong way.

Well, that is what my year was about – a lot of coding, learning and again coding.

Dear followers, friends, WinPhans & WinPhanDevs – thank you for being with me this year. Let’s make 2014 an even more exciting year.

I wish you all “a good slide into the new year”, as we say here in Germany. May god bless you and your families also in the new year.

Posted by msicc in Editorials, 0 comments
Dev Story Series (Part 1 of many): Creating a data class for both Windows 8 and Windows Phone app

Dev Story Series (Part 1 of many): Creating a data class for both Windows 8 and Windows Phone app

As I promised earlier on my application for the Intel App Innovation Contest on codeproject.com, I will do a series of blog posts for my application MSicc´s Blog for Windows 8 and Windows Phone.

This is the first article in my new Dev Story Series, where I describe the development process of the app. I am starting with the very first steps that you have to do if you plan such an application. To make the application useful, we first have to decide how we want to get the data from our blog/website into our application.

One hint that will make some of you crying out loud: At the moment I am not using the MVVM pattern. I am aware of the fact that most devs for Silverlight/C# swear on it, but I still decided to go without it – as well on Windows Phone as on Windows 8. I will continue to learn it in one of my future project, but for the moment I just want to get things done – also if that means that I have to create some – well, let us call it “compromises”.

Which way to choose?

If you consider to create a “blog reader”, you have to think about how you want to get the data from your blog into your app. There are different ways:

  • via a RSS/Atom feed (that was in the old version of my Windows Phone app for msicc.net)
  • via XMLRPC (if your blog supports that)
  • via JSON

I decided to go with JSON for the new version. There were several reasons to do so:

  • there is an app err… an plugin for that on WordPress
  • JSON is fast
  • JSON is set to be the new standard for data consumption
  • With JSON.NET you can deserialize your data with only one line(!) of code

How do we get the data in our app?

Of course, we will download it. But if you only download your JSON data, the only thing you will get is a very weird looking string that looks like this:

json_string_unserialized

That´s pretty ugly, right? Of course we could work us through all arrays and objects there. That would take hours and hours until we would have covered all data we need for our apps. Luckily, there are two tools that make the whole thing a lot easier.

Two handy tools to make a dev´s life easier

The first tool I want to show you is “Beautify JSON”. It is a web based tool that makes strings like the one above readable for a human. Find it here.

Just paste the string of your JSON API in there, and you will get a readable version of your JSON string:

beautify_json

If you want to use only some of the data that your API provides, you can now easily search the string for the objects and arrays that you need.

If you quickly want to create a data class for all data that is provided, you can do this by using json2charp.  It provides a ready-to-use code that can easily be copied and pasted into your class file in Visual Studio:

json2charp

Now let´s have a look to the class itself:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace WordPressDataClass
{
 public class Posts
    {
        [DataMember]
        public string status { get; set; }
        [DataMember]
        public int count { get; set; }
        [DataMember]
        public int count_total { get; set; }
        [DataMember]
        public int pages { get; set; }
        [DataMember]
        public List<Post> posts { get; set; }
    }
}

As you can see, I created a DataContract and DataMember based class by using System.Runtime.Serialization. If you want to know more about DataContracts and DataMembers I recommend you to read MSDN: using Data Contracts.

I am not posting the whole class, only the key DataContract Posts, which will get us our List of posts. You can download the whole class at the end of the post. It will be very helpful if you want to create an app for your WordPress based blog.

I use the class in both my Windows 8 and my Windows Phone app without any differences. As you can see, If you are familiar with Windows Phone Development, there is only a small step to Windows 8 development.

I hope this article is helpful for some of you. In my next post I will show you how easily you can use the provided JSON Data in your app/s.

source code: JsonDataClass

Posted by msicc in Archive, 4 comments
Post #200 or what exiting times we have with Microsoft

Post #200 or what exiting times we have with Microsoft

microsoft_logoI struggled with myself very long on what topic I dedicate this post with the anniversary number 200 and ended up with this article.

We all had already a very exiting year with Microsoft. Microsoft is fully in his “reimagine” phase, and the winners of this are we – as users, and as developers.

Windows 8

The year was starting for me with a key milestone: Windows 8 CP. A more fluid and fast alternative to the DP Microsoft released last year. And we finally had a good amount of apps (for a beta build). I felt really in Love with Windows 8 after using it only a few hours. Windows 8 is totally different. The Metro start screen will change the way how users will interact with their PC – also if it is non touchable.

I am currently running the final version of Windows  (RTM), and I love it to use more and more apps instead of visiting websites. It is way more fun to use a twitter app than to use their website, for example.

It is a change in the daily use of your PC, but most of the users that I personally know are exited about how easy it is to use a PC with apps. Sure, there are some people who will not be satisfied. That is not a bad thing. We all like different kind of things. But I am convinced that the majority of people will accept the Metro screen as part of their PC. Period.

For Developers it is amazing: no matter what language you are using right now, almost everyone can do Windows 8 apps. No matter if you are a Web Designer, used to Java, C# or C++, your app can be there on Windows 8! And you can even use more than one programming languages in one app.

In March this year I visited the CeBit, a trade fair that is for technology news here in Germany. I was amazed about the things I saw from Microsoft, but Germany is not a big target for the mobile/IT-industry- at least not shortly after the MWC. You can read my report about the CeBit here.

Windows Phone

Windows Phone is also an important point on our list. Microsoft´s mobile OS may not be blown up as iOS or Android – but we are satisfied with what we have! The OS is fast, does Average Joe´s daily doings way faster than the other two OS – without Multicore-CPUs!!! Microsoft demonstrated this with their “Smoked by Windows Phone” campaign, which was happening in several countries around the globe.

The best thing is: The OS will be getting even better! The existing devices will get an update with new functions, that will further enhance the user experience. And there will be the next generation: Windows Phone 8!  Windows Phone 8 will get a whole new core compared to 7, that will bring a lot more features, and for all that spec-driven users out there also multi-core support. Soon we will know more about it (I guess in September).

Xbox 360 and Xbox Live/Zune

Microsoft is also evolving the Xbox/Zune services as well as the Xbox OS itself. If you were one of the lucky one´s like me to enter the Fall 2012 beta update program, you know that it is getting better and better.  I am not allowed to go to deep into detail, but a few things have been announced, like IE for Xbox.

Xbox Live and Zune services will be merged together to further enhance our experience. Hopefully Microsoft will be providing more features to all countries, not only US. Best example is Zune Pass, which is still not available here in Germany. I don´t know what issues Microsoft has with the Germany system, but others like Deezer and Spotify were also able to solve those problems. Let us hope all the best for this.

And then there will be SmartGlass. Your Xbox companion – regardless which device you use. SmartGlass will be used to extend the experience you with your Xbox. Additional info for Movies, extensions for Games, and many many more.

Office 2013

I am also exited about the free-to-test-for-everybody Office 2013 Preview. Microsoft changed the programs into streamed applications. And they are performing very well (even with my slow 2 MBit/s connection). On top Microsoft released One Note MX, a Metro app for Windows 8 for those who use a WinRT tablet only. Get it today via the official Office 2013 website (for up to 5 PCs!). Skype integration is coming later this year via an “Office app”.  There are also further apps in the Office Beta Store.

Microsoft Account and connected Websites

Microsoft changed the formerly known “Live-ID” into “Microsoft Account”. You still have all service like before, with a new name. But there is more. Hotmail will be replaced with outlook.com (in Metro Style). outlook.com has also a “People” app, “Calendar” and of course your “Mail”. On top we now have a Metro “Messenger”. SkyDrive is the last one in this round. Also SkyDrive has been Metro overhauled an got new functions, like a url-shortening service, using skdrv.ms.

MSiccDev goes BizSpark

As some of you know, I am also developing for Windows Phone and will start with Windows 8 soon. I started to learn creating apps because there was no app for fishermen, and I needed a fishing knots app in the marketplace. I am currently planning on a big service for fishermen that targets Windows, Windows Phone and the Web. To get things done with a little help from Microsoft, I applied for Microsoft´s BizSpark program – an got approved last week! Stay tuned, soon I will reveal more information about the project. But it is great that Microsoft support startups. A special thanks goes to @AWSOMEDEVSIGNER (follow him!).

Final thoughts

I don’t know how you feel, but that was a pretty awesome year until now. Windows 8 is around the corner, and will bring new device factors like Microsoft´s surface. All big vendors announced at least one Tablet/PC-convertible. Windows Phone 8 will be the booster rocket for the phone OS version, the codename “Apollo” fits really nice in here.  Microsoft´s vision of “three screens, once experience” is getting closer and closer. And the best thing: we all can participate right now!

Posted by msicc in Archive, 0 comments

(Updated x2) How to prepare W8CP for Metro apps on devices with small screen resolutions

cantopenmetro

Microsoft stated that Windows 8 will be able to an huge amount of devices, such as PCs, tablets as well as other devices. Well, a netbook is also a kind of a PC.

There are certain netbooks out there, which can be run in 800*600 max. screen resolution by default. Currently drivers from vendors are missing for these devices, so there won´t be a possibility to change.  A colleague of me has a Nokia 3G booklet. He could not get the Metro part of the W8CP to work. He is running into an error message like the one illustrated above.

There is a solution.

Paul Thurrott posted a solution to this on his supersite for Windows. OK, it seems more than a hack, but it will lead to target.

Here is how to get the Metro part working through changing your screen resolution settings:

  • run Regedit (Win + C, search, type in regedit (note: you have to type in complete, otherwise the app shows not up)
  • search for “display1_downscalingsupported” (CTRL+F)
  • change its value from 0 to 1
  • search all entries in registry by using the F3-key of your netbook, and change again the value from 0 to 1

Paul noted that the look of the desktop part maybe a little bit skewed or squished. But now you have additional screen resolution options.

Note: if you do not know what you’re doing, you should not follow these steps! I am not responsible for any errors or damage caused by changing your registry.

I will try to do this on my colleague´s netbook, and will update this post.

Update 2: Nokia Booklet loves W8CP!

So my colleague was playing around with his netbook and installed the device graphics driver. He had do install it with the Windows device manager. He simply downloaded the driver (here), and pointed the device manager to use this file. So he is now enjoying the Metro apps on his netbook.

Until then, feel free to use the steps above and leave some comments. Most important thing:

Have fun using the Metro apps also on your netbook!

Posted by msicc in Archive, 0 comments