A view of windows 10 new devices

0 Comments

0 commentaires:

Building a windows 10 application

, 0 Comments

Here is the "how to" for beginners, but useful to anyone who starts on building a windows 10 application.

It is a good way to start with good practices.

http://blogs.windows.com/buildingapps/2015/09/30/windows-10-development-for-absolute-beginners/?WT.mc_id=DX_MVP4025064

0 commentaires:

Unit tests

0 Comments

0 commentaires:

IT Challenges

0 Comments

Sometime, you want to do more than your day work.

This kind of website looks perfect for that:

https://www.topcoder.com/

Take a challenge, and win prizes, or just learn new things!

0 commentaires:

Typescript and Angular 2

, , 0 Comments

Using angular is a very popular way of building websites, webapplications.

You probably know that the version 2 is coming, with breaking changes.

Visual studio 2015 seems to be welcoming this new version.

Take a quick look at this video:

https://channel9.msdn.com/Events/Visual-Studio/Visual-Studio-2015-Final-Release-Event/TypeScript-and-Angular-2-in-Visual-Studio-2015

0 commentaires:

Visual Studio 2015

0 Comments

Did you ever wonder how Visual Studio is made?

Look at this video, and see the changes that happened since older versions of VS.

https://www.microsoft.com/france/visual-studio/evenements/visual-studio2015.aspx


0 commentaires:

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:

AOP through Unity interceptors - Compression

, , , 0 Comments

Today we are going to compress our data. We will still use AOP through Unity.

The scenario is the following: we have a class generating a huge set of data (in our example, data structure is string). we don't want it to be kept in memory, because we will use it later, or not often. So one solution could be to compress this data & uncompress it once we will really need it.
public interface IBigDataRepo
    {
        string GetData();
    }
 public class BigDataRepo : IBigDataRepo
    {
        public string GetData()
        {
            return new string('X', 100000);
        }
    }
We are going to use is this way:

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

                // Register
                container.RegisterType<IBigDataRepo, BigDataRepo>(
                    new Interceptor<InterfaceInterceptor>(),
                    new InterceptionBehavior<CompressionInterceptionBehavior>());

                // Resolve
                IBigDataRepo bigDataRepo = container.Resolve<IBigDataRepo>();

                // Call
                string compressedData = bigDataRepo.GetData();

                Console.WriteLine(compressedData.Length);

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

            }

        }
That's  all. Now, let's see how the CompressionInterceptionBehavior is made.

public class CompressionInterceptionBehavior : IInterceptionBehavior
    {
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            var result = getNext()(input, getNext);

            return input.CreateMethodReturn(Compress(result.ReturnValue));
        }

        private object Compress(object stringToCompress)
        {
            byte[] text = Encoding.ASCII.GetBytes(stringToCompress.ToString());
            using (MemoryStream memory = new MemoryStream())
            {
                using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress, true))
                {
                    gzip.Write(text, 0, text.Length);
                }
                 return Encoding.ASCII.GetString(memory.ToArray());
            }
        }

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

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

Simple enough. The most complicated part is the compression part :).

0 commentaires:

AOP through Unity interceptors - Performance monitoring

, , , , 0 Comments

Today we continue the serie on AOP with Performance monitoring.

The principle is very simple: we want to monitor the time a method took to execute.

Here is the code of the class.
public class PerformanceMonitoringInterceptionBehavior : IInterceptionBehavior
    {
        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }

        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            Stopwatch sw = Stopwatch.StartNew();
            var result = getNext()(input, getNext);
            sw.Stop();
             WriteLog(String.Format("Method {0} took {1} ms", input.MethodBase, sw.ElapsedMilliseconds));

            return result;
        }

        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);
        }
    }

As you can see, we only start & stop a Stopwatch to watch the time consumed by the method.

As always, you need to specify that you want to use the behavior:
container.RegisterType<IStore, StoreImpl>(
                    new Interceptor<InterfaceInterceptor>(),
                    new InterceptionBehavior<PerformanceMonitoringInterceptionBehavior>());
                 container.RegisterType<IFoo, FooImpl>(
                    new Interceptor<InterfaceInterceptor>(),
                    new InterceptionBehavior<PerformanceMonitoringInterceptionBehavior>());

0 commentaires:

AOP through Unity interceptors - Caching

, , , 0 Comments

Let's continue our serie on AOP with another popular usage of interception: caching.

Let's use the previously created project and add this class:
public class CachingInterceptionBehavior : IInterceptionBehavior
    {
        private static IDictionary<string, MemoryCache> Cache = new Dictionary<string, MemoryCache>();
        private static IList<string> SyncLock = new List<string>();
        private static object SyncRoot = new object();

        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            if (input.MethodBase.GetCustomAttribute<IgnoreCacheAttribute>() != null)
            {
                return getNext()(input, getNext);
            }
            var arguments = JsonConvert.SerializeObject(input.Arguments);
            string key = string.Concat(input.MethodBase.DeclaringType.FullName, "|", input.MethodBase.ToString(), "|", arguments);
if (IsInCache(input.MethodBase.DeclaringType, key))
            {
                return input.CreateMethodReturn(GetFromCache(input.MethodBase.DeclaringType, key));
            }
            lock (SyncRoot)
            {
                if (!SyncLock.Contains(key))
                {
                    SyncLock.Add(key);
                }
            }
           
            lock (SyncLock[SyncLock.IndexOf(key)])
            {
                if (IsInCache(input.MethodBase.DeclaringType, key))
                {
                    return input.CreateMethodReturn(GetFromCache(input.MethodBase.DeclaringType, key));
                }

IMethodReturn result = getNext()(input, getNext);
                if (result.ReturnValue != null)
                {
                    AddToCache(input.MethodBase.DeclaringType, key, result.ReturnValue);
                }
return result;
            }
        }
        private void AddToCache(Type declaringType, string key, object toBeAddedToCache)
        {
            if (!Cache.ContainsKey(declaringType.FullName))
            {
                Cache.Add(declaringType.FullName, new MemoryCache(declaringType.FullName));
            }

            CacheItem item = new CacheItem(key, toBeAddedToCache);
Cache[declaringType.FullName].Add(item, new CacheItemPolicy { AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddDays(1)) });
        }
private object GetFromCache(Type declaringType, string key)
        {
            return Cache[declaringType.FullName].Get(key);
        }
private bool IsInCache(Type declaringType, string key)

        {
            return Cache.ContainsKey(declaringType.FullName) && Cache[declaringType.FullName].Contains(key);
        }
        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }
        public bool WillExecute
        {
            get { return true; }
        }
    }

As you can see, we use the IgnoreCacheAttribute in order to avoid apply cache on choosen methods.

Here is its implementation:
    public class IgnoreCacheAttribute : Attribute
    {
    }

We have a global cache for every Declaring type of our application. When a method is called with the same parameters, we get info from cache instead of calling the real underlying object.

Here is a graphical explanation of how is structured our cache:



Don't forget to register:
// Register

                container.RegisterType<IStore, StoreImpl>(

                    new Interceptor<InterfaceInterceptor>(),

                   new InterceptionBehavior<CachingInterceptionBehavior>());



                container.RegisterType<IFoo, FooImpl>(

                    new Interceptor<InterfaceInterceptor>(),

                    new InterceptionBehavior<CachingInterceptionBehavior>());

0 commentaires:

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:

Swagger IO

, 0 Comments

If you are building a WebAPI, I recommend the usage of swagger IO to document your API.
It is incredibly simple to setup & provide you (and your clients) a very good way to expose and describe your data.

The website: http://swagger.io/

To see a demo: http://petstore.swagger.io/

0 commentaires:

Visual Studio Code: a new IDE is born!

One important announcement at the Build conference is the release of a new IDE.
It is called Visual Studio Code and it is a cross platform editor. It runs on Mac Linux and... Windows ;). It has Intellisense, supports multiple languages, has debugging and git built-in.

Visit https://code.visualstudio.com/ to get more information & download.

0 commentaires:

[Fast&Furious guide] Setup a continuous integration process with TFS2013



The goal of this post is to present you (very quickly) how to set up a TFS server (give you the steps) in order to get a continuous build integration environment. We will also talk about continuous deployement. For all the details, please take a look at the bottom of this post for the reference links...

To summarize, the continuous integration process will help your team to merge their working copies  of your application code and to discover faster when a build fails. The reasons why a build fail can be multiple:
- errors in code
- a test fails
- code analysis fails...


We will take a look at the following points:
- Configure the TFS Server
- Create a new build definition
- Insert tests in your build process
- Manage team project's check-in policies
- Deal with NuGet packages
- Automatically deploy your project with MsDeploy.



Setup your TFS 2013 server


First you need to have a server that will manage and build your code.
Install a TFS server and configure it (add your TFS Project and team members...)



Put your code under version control:




Manage your controllers / agents


Install the build service on the TFS build server.
Configure the build server: --> on the "Team Foundation Server Administration console", choose "build Configuration"
Create A New Controller and a new agent to manage your project (you can use one agent to build multiple projects). Each agent can run in parallel, so if you have many projects, you should configure more than one agent.

Everything is well explained here: TFS Server configuration





Setup your builds drop folders (on your publication server)


In order to publish your application / services (for testing or production purpose), you will have to set up a specific environment. On the desired environment server, create a publication folder that will receive the builds. For instance, it can be a folder representing a web site in IIS. We will see later how to manage the security for this folder.

Warning: The build agent fails on paths that exceed 259 characters.

Give permissions (READ / CHANGE) to the build server on this folder (ie, build server: $ALMSVR)





Setup your build definition in Team Web Access


The interesting part for us, is to configure a new build. This build definition will manage all the steps of the build process.

In Visual Studio, Team Explorer Menu:

Creating a Continuous Integration build process





Integrate tests in your build process


Tests can be run to validate a build process; these tests are often called Build Verification Tests (BVTs).
These tests can be of type:
- Unit Tests
- Coded UI tests
- Web performance Tests
- Load Tests
- Generic Tests


1- Develop your tests (in separate tests projects) and checkin it into your source control (preferably, you will name the projects containging your tests with a pattern like this: *Test*)



2- Create a new build definition: In Visual Studio , Team Explorer:


3- Specify the tests (assemblies) to embed in the integration process: (use a custom search pattern as bellow):


This search string will search recursively through directories looking for any DLLs that match *test*.dll in the Binaries directory.


4- Tests settings
You can select a test settings file to use during the build process:


5- (Advanced configuration) Select a specific agent to run the tests;


6- Save your build


7- Queue a new build






Check in policy


You can also configure / enforce some rules before to check in new code:

Here are example of rules  that you can add for your project:
- set a check in comment
- the last build must be successfull
- code analysis rules should pass (you can also activate code analysis on your TFS Server - but you will activate it from your build definition)













Custom NuGet Packages


Add packages sources (documentation from NuGet website):

First, you can add your custom package repositories in Visual Studio\Options\Package Manager\
NuGet Config File machine wide settings


Then, you can configure the packages used by each project. It's recommend to manage packages at "solution" level (images below):




Below you can find a sample configuration file to add a new package repository, in order to download the packages during the build process:

The config file can be found at the root of your solution in the ".nuget" folder (this folder appear after you "managed packages for the solution": nuget config file "Nuget.config"

> Don't forget to checkin your .Nuget folder.

> But don't checkin the packages themselves ! They will be downloaded automatically on the TFS server.


Nuget config sample:
<?xml version="1.0" encoding="utf-8"?> <configuration> <config> <!-- Used to specify the default location to expand packages. See: NuGet.exe help install See: NuGet.exe help update --> <add key="repositorypath" value="External\Packages" /> <!-- Used to specify default source for the push command. See: NuGet.exe help push --> <add key="DefaultPushSource" value="http://MyRepo/ES/api/v2/package" /> </config>
<packageRestore> <!-- Allow NuGet to download missing packages --> <add key="enabled" value="True" /> <!-- Automatically check for missing packages during build in VS --> <add key="automatic" value="True" /> </packageRestore> <!-- Used to specify the default Sources for list, install and update. See: NuGet.exe help list See: NuGet.exe help install See: NuGet.exe help update --> <packageSources> <add key="NuGet official package source" value="https://nuget.org/api/v2/" /> <add key="MyRepo - ES" value="http://MyRepo/ES/nuget" /> </packageSources> </configuration>





Continuous delivering with MsDeploy

Another option with TFS Server, is to deploy automatically (after the build) your applications to a specific server (but for that the build must be successfull for sure !).

Here, we will use "MsDeploy" tool, but there are other (more powerfull, customisable...) tools like:
Microsoft Release Management


1- (Target publication server) Be sure to have or Add "Management Service" role to your server




2-  (Target publication server) Install WebDeploy



3- Security: 
Give access to the "administration web service" (NT Service\WmSvc) to the target publication folder.
- Update & Write rights



4- ? If needed ?: Add a registry key entry

Maybe you will need to add this registry key, if you still have "permission" issues when deploying your application:

reg add HKLM\Software\Microsoft\WebManagement\Server /v WindowsAuthenticationEnabled /t REG_DWORD /d 1



5- Generating a Publish profil

You can generate a publish profil (the one that will be used by MsDeploy) in Visual Studio; take a look at the following screenshots:




You have to checkin this profil file into your source code control.

If you want to publish several projects from your solution, you have to duplicate the generate a "publish" file with THE SAME NAME for every of these projects (see screenshot below):





6- Setup the deploy command line in your build definition:

By default, WebDeploy uses HTTPS so normally you would need a certifcate installed on your publishing server.
You can override this behavior, allowing auto generated certificates and using integrated authentication.

MsDeploy command line parameters:
- Allow auto generated certificates: /p:AllowUntrustedCertificate=true
- Use integrated authentication: /p:AuthType=NTLM username="" password=""


Full MsDeploy command line sample:

/p:DeployOnBuild=True /p:PublishProfile="Test_PublishWebServices" /p:AllowUntrustedCertificate=true /p:AuthType=NTLM /p:username="" /p:password=""


You have noticed that we reference the publish profil in our command line. 





References


TFS integration: 

Nuget package restore: 

Deploy and configure a build server:

MsDeploy command line:

Adding TFS checkin policy:

InRelease, Continuous delivering:

[VIDEO] Release Management - Configuring release Pipeline:





0 commentaires: