AOP through Unity interceptors - Logging

, , , 0 Comments

The first thing we think when talking about interception is logging. Let's see an implementation of a Logger.

But before introducing the Logger implementation, let us scaffold a console sample project.

public interface IFoo
    {
        FooItem GetItem(string name);
    }

    public interface IStore
    {
        StoreItem Get(int id);

        IEnumerable<StoreItem> GetAll();

        void Save(StoreItem item);
       
        void ThrowException();
    }

    public class FooImpl : IFoo
    {
        public FooItem GetItem(string name)
        {
            return new FooItem { Name = name };
        }
    }

    public class StoreImpl : IStore
    {
        public StoreItem Get(int id)
        {
            Thread.Sleep(1000);
            return new StoreItem { Id = id, Name = "Fake name" };
        }

        public IEnumerables<StoreItem> GetAll()
        {
            Thread.Sleep(2000);

            return new List&ltStoreItem>()
            {
                new StoreItem {Id = 1, Name = "Fake Item 1"},
                new StoreItem {Id = 2, Name = "Fake Item 2"},
                new StoreItem {Id = 3, Name = "Fake Item 3"}
            };
        }

        public void Save(StoreItem item)
        {
            Thread.Sleep(1500);
        }

        public void ThrowException()
        {
            Thread.Sleep(500);
            throw new Exception("Sample exception");
        }
    }

    public class FooItem
    {
        public string Name { get; set; }
    }

    public class StoreItem
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

Now we can play with unity. In the Program.cs, write this:

static void Main(string[] args)
        {
            using (var container = new UnityContainer())
            {
                container.AddNewExtension<Interception>();

                // Register
                container.RegisterType<IStore, Storeimpl>(
                    new Interceptor<InterfaceInterceptor>(),
                    new InterceptionBehavior<LoggingInterceptionBehavior>());

                container.RegisterType<IFoo fooimpl="">(
                    new Interceptor(),
                    new InterceptionBehavior<LoggingInterceptionBehavior>());

                // Resolve
                IStore store = container.Resolve<IStore>();
                IFoo foo = container.Resolve<IFoo>();

                // Call
                store.Get(1);
                store.Get(2);
                store.Get(1);
                store.GetAll();
                store.Save(null);

                try
                {
                    store.ThrowException();
                }
                catch { }

                foo.GetItem("Whatever");

                Console.WriteLine("END");
                Console.ReadLine();
            }
        }

Finally, here is the implementation of the LoggingInterceptionBehavior:

public class LoggingInterceptionBehavior : IInterceptionBehavior
    {
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            var arguments = JsonConvert.SerializeObject(input.Arguments);
            WriteLog(String.Format("Invoking method {0}", input.MethodBase), arguments);

            var result = getNext()(input, getNext);

            if (result.Exception != null)
            {
                WriteLog(String.Format("Method {0} threw exception {1}", input.MethodBase, result.Exception.Message));
            }
            else
            {
                var returnValue = JsonConvert.SerializeObject(result.ReturnValue);
                WriteLog(String.Format("Method {0} returned successfully", input.MethodBase), returnValue);
            }

            return result;
        }

        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }

        public bool WillExecute
        {
            get { return true; }
        }

        private void WriteLog(string message, string args = null)
        {
            var utcNow = DateTime.UtcNow;

            Console.WriteLine(
                "[{0}]-[{1}]: {2} {3}",
                utcNow.ToShortDateString(),
                utcNow.ToLongTimeString(),
                message,
                args);
        }
    } 

0 commentaires:

[Xamarin Forms] Button text alignment issue in Android


Recently, I had to deal with custom Buttons in my Android application.
So I designed custom renderers to render it.

Unfortunately, I encountered a strange behavior with the text alignment of my buttons.
This happens when the button changes of state:

- Originally the button's text is centered
- When you click it, the text moves to the left

See images below:

 
Before / after the button click


After investigating, I found a solution to my problem.
In my Android custom button renderer, I had to overwrite a specific method: ChildDrawableStateChanged


public class ExtButtonRenderer : ViewRenderer<Extbutton, global::android.widget.button> 
{
    ...
   
    public override void ChildDrawableStateChanged(Android.Views.View child)
    {
        base.ChildDrawableStateChanged(child);

        if (Control != null)
            Control.Text = Control.Text;
    }
    ...
}


That's all !



Related links:

Custom renderers:
http://developer.xamarin.com/guides/cross-platform/xamarin-forms/custom-renderer/


0 commentaires:

[Fast&Furious guide] Get ready to build a Xamarin iOS app

0 Comments

In order to build, test and deploy an iOS application using the Xamarin SDK, you will need to setup your environement first. As you know, it's necessary to have a Mac computer that will be at least your build host...
This post is just a quick guide to help you to setup your environment ! So let's go !


Setup your environnement (2 possibilities)

The hardware needed:

A- First choice:
A MAC (MacBook Pro for instance)
with a Virtual Machine (VmWare / Parallels) running Windows and Visual Studio with Xamarin.

B- Second choice
A MAC (will be used only as a build host)
A PC (with Windows / Visual Studio / Xamarin SDK) on the same network

Requirements:
Minimum MAC OS versions: OS X Mountain Lion, iOS Xamarin SDK, XCode IDE
Minimum Windows versions: Windows 7, Visual Studio 2010, latest Xamarin tools




C- You will also need an iOS developer account

You need to have an iOS developer account in order to:
- test / deploy your app on a device
- publish your app to the app store

Apple need you to have a profil / certificate to establish your identity when you publish your apps to the store for instance.

There are 2 versions of your developer profile:
- one for the developer portal
- one on the local MAC machine
! keep a backup of the profile !


>> To create you account, follow the next link:
https://appleid.apple.com/account






Get your Development Certificate: (XCode required)


A- Associate your apple ID to XCode

On your MAC machine, run XCode to define your AppleID as a developper account:


In XCode\Preferences\Accounts

     
Add your AppleID




B- Setup a new developer iOS device

To be able to test your applications on a real device, you will need to define it as a development device:


Plug your iOS device, Go to "Devices" menu
  
Copy the iOS device identifier


Go to "iOS dev center" page


Add the new device (device unique identifier)

Download certificate



C- Pull your certificates into XCode (to be accessed by Xamarin Studio)

In Xamarin Studio, refresh and validate



Setup your mac

Install Xamarin Studio

THEN Turn off Firewall to allow Visual Studio to connect !

  







Connecting to the MAC build host

Next from your dev machine (here is a Windows PC running Visual Studio, Xamarin SDK installed), start or create a you Xamarin project.

When you set your iOS project as the default one, a dialog box appears to connect to a Build Host:


Click continue, and search for your Mac Build Host (it should be on the same network as your Windows PC):


Select it on follow the pairing process:

Visual Studio toolbars to build iOS apps




Normally  you are ready to build !


TIPS:

- You can also open the Mac Build Host pairing dialog box from Visual Studio:

Menu Tools\Options


- Sometimes the pairing can be lost:
On your MAC build host, stop the pairing process, close Visual Studio and restart the process.




Related links:

Xamarin
http://developer.xamarin.com/guides/ios/getting_started/installation/windows/
http://developer.xamarin.com/guides/ios/getting_started/installation/device_provisioning/

Apple accounts:
https://appleid.apple.com/account

Apple developpers:
https://developer.apple.com/account/


0 commentaires:

AOP through Unity interceptors - Introduction

, , , 0 Comments

Hello,

Today we will start a serie of blog posts concerning Aspect Oriented Programming (formely AOP).

This technic is used to have a better separation of concerns in the application you write.
Let's take a basic example. When you are writing the implementation of a class that is specialized on a task, you could write someting like this:

public class Calculator
{
    public decimal Add(decimal num1, decimal num2)
    {
        Console.WriteLine("Entering Add Method");
        var result = num1 + num2;
        Console.WriteLine("Exiting Add Method");
        return result; 
    }
}
The issue with this code is that the logging is part of the method. What will happen if you have a huge quantity of code? You will probably duplicate the logging code across te different class & methods you will write. Moreover, the Add method we wrote is not specialized on a single task: it has two different purpose: it effectly performs an adds operation and it logs.

We will use Unity as an Inversion of Control framework to attach specific behavior to the code write.
As you may know, Unity uses a proxy to represent the object you are trying to resolve. When resolved, before & after a method call, you can introduce specific code through Behaviors. Unity proposes three kinds of interception: InterfaceInterceptor, TransparentProxyInterceptor & VirtualMethodInterceptor. If you want more explanation about those, you can visit https://msdn.microsoft.com/en-us/library/dn178466%28v=pandp.30%29.aspx. In our articles, we will use the InterfaceInterceptor. Here is the pipeline applied to the associated behaviors.

Note: this representation is inspired by https://msdn.microsoft.com/en-us/library/dn178466%28v=pandp.30%29.aspx

Let's have a look at the different steps:
  1. Client calls the Resolve method
  2. One method is called upon the interface
  3. The proxy calls the Invoke method on the first interception behavior
  4. The Behavior1 calls the Invoke method on the next Behavior, without explicitely knowing it
  5. While there is behavior in the pipeline, the operation is computed
  6. When there is no more  chained behavior, the method is processed upon the real implementation
  7. The real object returns to the last behavior
  8. While there is behavior in the pipeline, a post operation can be computed
  9. The first behavior is called
  10. The result is passed to the Proxy object
  11. The result is passed to the caller
To implement interception with Unity, you need Unity, of course, and Unity Interception Extension libraries. Then, to activate the interception, simply write this line when you declare your container:

IUnityContainer container = new UnityContainer();
container.AddNewExtension<Interception>();

In the next posts we will see when the aspect oriented programmation could be useful. We will write specific classes to handle different behaviors. This is an interesting way of instrumenting easily your application, make it go faster, reduce bandwidth consumption...

0 commentaires:

[Xamarin Forms] Embed custom fonts in your apps

Recently I had some difficulties to embed custom fonts in my applications. Specially with the iOS application that was crashing with no message (while it was working for the Android version).
In fact, it was a font issue. So in this post I will show you some tips to embed quickly custom fonts in both your Android & iOS apps.



1- Select your fonts
The first step is to get some cool fonts you want to use. You'll maybe use (free) fonts from various websites like:
www.1001freefonts.com
www.dafont.com



2- Set font files properties
In your solution, include your fonts files:

iOS: 
Create a subfolder (in the the 'Resources' directory) where to embed the fonts
Build Action = BundleResource & "Copy Always"

Android:
Create a subfolder in the 'Assets' directory where to embed the fonts:
Build Action = "AndroidAsset" & "Copy Always"





3- iOS application: edit your plist file
With iOS you need to specify the embedded fonts in your *.plist file:
In your Info.plist file add the following sections (under the <dictsection):

That should be enough for iOS; You don't need to implement any specific renderer.



4- Android: Add a custom Renderer
For Android, in order to apply the font correctly, you will need to implement a custom label renderer.
So you can for instance:
- create a new view in your Forms project: ie. ExtendedLabel
- create the dedicated Android custom renderer, in your Android project

You can find below a sample code:

Extended label control:

public class ExtLabel : Label
{
     ExtLabel()            
     {
          // base for implementing a better label control
     }
}

Android ExtendedLabel renderer:

[assembly: ExportRenderer(typeof(ExtLabel), typeof(ExtLabelRenderer))]
namespace Droid.CustomRenderers
{
    public class ExtLabelRenderer : LabelRenderer
    {
        private object _xamFormsSender;

        public ExtLabelRenderer()
        {
            _xamFormsSender = null;
        }

        protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            // Update native Textview
            if (_xamFormsSender != sender || e.PropertyName == ExtLabel.FontFamilyProperty.PropertyName)
            {
                var font = ((ExtLabel)sender).FontFamily;

                // valid font 
                if (!string.IsNullOrEmpty(font))
                {
                    // check font file name
                    if (!font.Contains(".ttf")) font += ".ttf";
                    var typeface = Typeface.CreateFromAsset(Forms.Context.Assets, "Fonts/" + font);

                    // update font
                    var label = Control as TextView;
                    if (label != null)
                        label.Typeface = typeface;
                }

                _xamFormsSender = sender;
            }
        }
    }
}



5- Set the font in your Forms.xaml code

Finally you just have to reference your fonts from your forms. With the custom provided renderer, you just need to indicate the font name in the FontFamily property. Sample below:

<CTRL:ExtLabel BindingContext="{x:Reference Name=uiParent}"
   Text="{Binding Text}"
   TextColor="{Binding TextColor}"
   XAlign="Center"
   FontFamily="lato_bold"
   FontSize="Medium"
   LineBreakMode="WordWrap"
   />



Caution !

- Fonts Name:
In iOS, fonts are all loaded when the app starts. Take note that differents fonts file (specially *.ttf) can contain fonts with the same name !

For instance:
- lato_bold.ttf & lato_italic.ttf can both contain a font with 'lato' name.

How to know a font's name ?




This can crash your iOS app ! So I suggest you to rename your fonts using a specific tool like
- Typograf





0 commentaires:

C# Clean code book

, , , 0 Comments

Remember last week, I presented the website https://leanpub.com/

One interesting & free book recently published is https://leanpub.com/cleancsharp/. You will find in there a lot of good tips to write clean C# code. Some tips are really useful.

If the professional applications I work on would have be written by people who have read this book, my life would be easier!

It is only question of "good sense" in my opinion, plus a set of established rules, like proven efficiency stuff. But I have to say that most of them are not applied, even in "top" french companies.

0 commentaires:

Publishing and/or Reading books

, , 0 Comments

I would like to share with you a platform I found few weeks ago.
I've already mentionned SyncFusion ebooks in an earlier post (http://kampeki-factory.blogspot.fr/2015/03/syncfusion-free-eboks.html). Notice that they still add free books regulary.

The platform I discovered is called Leanpub (https://leanpub.com/).
  • As an author, you can propose your book, writen using your favorite tool. They are doing the publication in different formats (pdf, iPad, kindle...) on their side. An other interesting thing is that you set the price. In fact, you set two prices: the first one the is minimum price, and the second one is a suggested price.
  • As a reader, you are informed of those two prices. You can pay the minimum price (which can be 0$). Or you can follow the author advice and give him the price he thinks his book is really.

0 commentaires:

Create a startup with DotNet tools?

, 0 Comments

Here is a pretty good article if you plan to create your startup. Will you choose Microsoft tools?

http://rlacovara.blogspot.fr/2012/03/should-you-use-net-for-your-statup.html

0 commentaires: