KISS is my philosophy

0 Comments

How much time lost trying to understand what an other developper is trying to achieve?
How much time lost trying to understand a x-line lambda?
How muc time lost trying to review a spaghetti code?

Well the answer is... to much.

Sorry guys, but my brain is too small for too complicated things. One of my favovite principle is KISS: Keep It Simple, Stupid.

Applying this philisophy, your code will be more readable, more comprehensive.

Read this blog post to learn more.

0 commentaires:

Windows 10 - Getting started

0 Comments

Windows 10 is here!

I hope it will be better than Windows 8 - 8.1...

From what I can hear, it will be.

Let's start a tour of this fresh new OS: http://www.hanselman.com/blog/GettingStartedWithWindows10.aspx.

0 commentaires:

Xamarin.forms.Maps - Tap to get a position on the map...

Xamarin.Forms.Map component

Xamarin.Forms.Maps is a great component. It gives you the possibility to deal with maps and geolocation problematics in a few lines of code.

This "Map" component internally use native map controls for iOS, Android and Windows Phone:



You can display and locate "Pins" with custom information on the map. I suggest you to read the reference links above.

Display pins with custom information



The problem

But actually, in my mind, the Map control miss a very important feature:
--> Tap  on the map to get the relative location (to put a new pin, to get the relative address...)


The workaround


Use renderers

Actually, to solve this problem, we need to implement custom renderers for iOS and Android. Maybe this feature will be implemented later by Xamarin...

So here is my solution (3 code files below):
- ExtMap.cs: overloaded map control that will contain our "Tapped" event to get the tapped location
- ExtMapRenderer (iOS): renderer for the iOS platform
- ExtMapRenderer (Android): renderer for the android platform

Each renderer will catch and manage the TAP event for us.

ExtMap control


This is the Xamarin forms map control that will override the Xamarin Forms Maps control. We just add the 'Tapped' event and logic to this implementation:

    /// <summary>
    /// Extended map:
    /// allow user to tap a point on the map to get the relative position.
    /// </summary>
    public class ExtMap : Map
    {
        /// <summary>
        /// Event thrown when the user taps on the map
        /// </summary>
        public event EventHandler<MapTapEventArgs> Tapped;

        #region Constructors

        /// <summary>
        /// Default constructor
        /// </summary>
        public ExtMap()
        {

        }

        /// <summary>
        /// Constructor that takes a region
        /// </summary>
        /// <param name="region"></param>
        public ExtMap(MapSpan region)
            : base(region)
        {

        }

        #endregion

        public void OnTap(Position coordinate)
        {
            OnTap(new MapTapEventArgs { Position = coordinate });
        }

        protected virtual void OnTap(MapTapEventArgs e)
        {
            var handler = Tapped;

            if (handler != null)
                handler(this, e);
        }
    }

    /// <summary>
    /// Event args used with maps, when the user tap on it
    /// </summary>
    public class MapTapEventArgs : EventArgs
    {
        public Position Position { get; set; }
    }


iOS Renderer


[assembly: ExportRenderer(typeof(ExtMap), typeof(ExtMapRenderer))]
namespace MyApp.iOS.CustomRenderers
{
    /// <summary>
    /// Renderer for the xamarin ios map control
    /// </summary>
    public class ExtMapRenderer : MapRenderer
    {
        private readonly UITapGestureRecognizer _tapRecogniser;

        public ExtMapRenderer()
        {
            _tapRecogniser = new UITapGestureRecognizer(OnTap)
            {
                NumberOfTapsRequired = 1,
                NumberOfTouchesRequired = 1
            };
        }

        private void OnTap(UITapGestureRecognizer recognizer)
        {
            var cgPoint = recognizer.LocationInView(Control);

            var location = ((MKMapView)Control).ConvertPoint(cgPoint, Control);

            ((ExtMap)Element).OnTap(new Position(location.Latitude, location.Longitude));
        }

        protected override void OnElementChanged(ElementChangedEventArgs<View> e)
        {
            if (Control != null)
                Control.RemoveGestureRecognizer(_tapRecogniser);

            base.OnElementChanged(e);

            if (Control != null)
                Control.AddGestureRecognizer(_tapRecogniser);
        }
    }
}


Android Renderer 


[assembly: ExportRenderer(typeof(ExtMap), typeof(ExtMapRenderer))]
namespace MyApp.Android.CustomRenderers
{
    /// <summary>
    /// Renderer for the xamarin map.
    /// Enable user to get a position by taping on the map.
    /// </summary>
    public class ExtMapRenderer : MapRenderer, IOnMapReadyCallback
    {
        // We use a native google map for Android
        private GoogleMap _map;

        public void OnMapReady(GoogleMap googleMap)
        {
            _map = googleMap;

            if (_map != null)
                _map.MapClick += googleMap_MapClick;
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.View> e)
        {
            if (_map != null)
                _map.MapClick -= googleMap_MapClick;

            base.OnElementChanged(e);

            if (Control != null)
                ((MapView)Control).GetMapAsync(this);
        }

        private void googleMap_MapClick(object sender, GoogleMap.MapClickEventArgs e)
        {
            ((ExtMap)Element).OnTap(new Position(e.Point.Latitude, e.Point.Longitude));
        }
    }
}



So we can now easily pick a location and get the relative address thanks to a geocoding service. You can use Google Apis or use the GeoCoder class provided by Xamarin (see references below):


Tap on the map to get the street address.



References:

Xamarin Forms Map control overview:
http://developer.xamarin.com/guides/cross-platform/xamarin-forms/user-interface/map/

Xamarin Forms Geocoding, GeoCoder class
http://developer.xamarin.com/recipes/cross-platform/xamarin-forms/reverse-geocode/
http://developer.xamarin.com/recipes/cross-platform/xamarin-forms/geocode/



5 commentaires:

Microservices architecture

, 0 Comments

Building a monolithic app, even subdivided in different layers is not the only path...

Recently, I discovered the Microservices architecture.

This allow to separate the whole application itself in autonomous part of sub application.

It has pros & cons. You can see this website for an advanced comparison.

Martin fowler speaks about it: http://martinfowler.com/articles/microservices.html.

Paul Mooney has also started an interesting series on this kind of architecture. Here are the first two parts:
http://insidethecpu.com/2015/07/17/microservices-in-c-part-1-building-and-testing/.
http://insidethecpu.com/2015/07/31/microservices-in-c-part-2-consistent-message-delivery/.

0 commentaires:

AOP through Unity interceptors - Conclusion

, , , 0 Comments

We have seen how pleasant could be the programmation with Unity and interceptors.
Of course, you can use another IoC framework to achieve what we have done in this series. A good advice would be to use Autofac. This framework has more capabilities than Unity.

An other point of attention is performance. Enabling interception is not cost free. You should take care of it: I would advice to measure the impact of enabling/disabling interception.

0 commentaires:

VS2013 Xamarin's incompatible plugin when installing VS2015...


As a good .NET developer, yesterday I installed the new Visual Studio 2015 IDE to discover all its new features...


VS2015 installed !


I was previously developping mobile apps with Xamarin on VS2013. So as I am impatient I installed VS2015 without thinking of all the modifications it can bring to my environment...


And bingo ! When I started back VS2013 to edit my Xamarin's projects, I had a bad surprise:

iOS & Android projects no more compatible...


But, fortunately, I find a really quick solution to restore Xamarin compatibility with VS2013. In fact in the windows programs / functionnalities menu, I  changed the Xamarin app components configuration like above:

Xamarin, change installation


Xamarin for Visual Studio 2013 is disabled !



Re-enable it and it s all good :)



And go you can continue to develop Xamarin projects with VS2013 !




0 commentaires:

AOP through Unity interceptors - Cryptography

, , , 0 Comments

Today, in our AOP serie, we will use Unity to encrypt/decrypt our data.

Let's imagine that you have a repo that stores personal information about users.
You may want some of this data to be encrypted, in case your database is stolen, or accessed illegaly.

Once again, AOP helps us in this situation. Let's build our sample. We will need an interface & an implementation representing the user repository.
public interface IUserRepo
    {
        bool IsUserAuthenticated(string login, [Encrypt] string password);         
        [Decrypt]
        string GetPasswordForUser(string login);
    }

public class UserRepoImpl : IUserRepo
    {
        public bool IsUserAuthenticated(string login, string password)
        {
            if (password == "1234")
                return false;

            return true;
        }

        public string GetPasswordForUser(string login)
        {
            return "wOSHX/n2NyWWn53YXVvJIg==";
        }
    }

Using this fake implementation, we just want to check that the password we use is really encrypted.
The  Decrypt & Encrypt attributes are really simple:
public class DecryptAttribute : Attribute
    { }


public class EncryptAttribute : Attribute
    { }


Finally, here is the service usage:

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

                // Register
                container.RegisterType<IUserRepo, UserRepoImpl>(
                    new Interceptor<InterfaceInterceptor>(),
                    new InterceptionBehavior<CryptographicInterceptionBehavior>());

                // Resolve
                IUserRepo userRepo = container.Resolve<IUserRepo>();
             
                // Call
                bool isUserAuthenticated = userRepo.IsUserAuthenticated("John Doe", "1234");
                if (isUserAuthenticated == false)
                    throw new Exception("Encryption did not work");                 string password = userRepo.GetPasswordForUser("John Doe");

                if (password != "1234")
                    throw new Exception("Encryption did not work");

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


Let's now see how the CryptographicInterceptionBehavior is defined
public class CryptographicInterceptionBehavior : IInterceptionBehavior
    {
        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }

        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            var parameters = input.MethodBase.GetParameters();

            foreach (var parameter in parameters)
            {
                if (parameter.GetCustomAttribute<EncryptAttribute>() != null)
                {
                    input.Arguments[parameter.Position] = Encrypt(input.Arguments[parameter.Position]);
                }
            }            var result = getNext()(input, getNext);

            if (input.MethodBase.GetCustomAttribute<DecryptAttribute>() != null)
            {
                return input.CreateMethodReturn(Decrypt(result.ReturnValue));
            }

            return result;
        }

        private object Encrypt(object input)
        {
            return StringCipher.Encrypt(input.ToString(), "");
        }

        private object Decrypt(object input)
        {
            return StringCipher.Decrypt(input.ToString(), "");
        }

        public bool WillExecute
        {
            get { return true; }
        }
    }

The StringCipher class used in this class is the one described by CraigTP in this blog post: http://stackoverflow.com/questions/10168240/encrypting-decrypting-a-string-in-c-sharp.

One advantage of using AOP to encrypt/decrypt data is that all the stuff are centralized into one place.

0 commentaires: