Posts

Showing posts with the label c#

[Quick guide] How to create a C# Telegram bot

Image
Quick guide to setup a .NET Telegram Bot and deploy it as a Windows Service Create the bot definition (Telegram) On Telegram, search and use the “ botFather” bot (looks like the image below). Once you found the bot, type the ‘/newbot’ command and follow the instructions: You have to store: the TOKEN to access the API your bot’s name and user’s name Once your bot is created, you can customize it by different ways (type ‘ /start ’ to get the full list of available operations): General bot communication workflow After creating your bot, you have to understand the very general main communication workflow for a Telegram bot: Design a new bot (.NET example) .NET project using Telegram.BotApi package We will design a Telegram BOT in .NET. Fot this, we will use the Telegram.BotApi nuget package. First create a new .NET 8 Project (latest .NET version). ADD tht Telegram.BotApi package (one of the most complete package at this time): https://www.nuget.org/packages/Telegram.B

FFImageLoading - display pictures stored in shared assembly

Image
I already talk about the really convenient and powerful lib FFLoadingImage for Xamarin Forms (here: FFLoadingImage for Xamarin Forms (quick overview) ).  This library gives you a lot of tools to display and manage your application's pictures. Loading pictures from a shared assembly You can load pictures from different sources like:  - an HTTP Url  - An iOS or Android embedded resource picture. In this case you will need to duplicate the pictures for each specific platform project.  But did you know that you can also load images from a custom assembly like a SHARED Xamarin Forms assembly ?  It's pretty simple: Set your picture's build action to: Embedded Resource Shared assembly containing your pictures Picture's build action: Embedded Resource Then use the following syntax In your xaml file where you want to display the picture, just use the following syntax. FFLoadingImage library will do the rest to load and display correctly images for each native platforms:

Understanding .NET Standard

Image
If as me, you don't really understand all subtleties between .NET Core and .NET Standard , I suggest you to have a look at the following article. It explains some history about .NET Framework and how .NET Standard is born. >>  Xamarin blog: A brief history of .NET Standard Which version to use ? For me, an important point to master for my own projects, is to know which platforms I can reach with a specific .NET Standard or .NET Core library. The following table illustrate the compatibility between each .NET implementation: For instance, - if you build a Xamarin Android v. 7.0 application, you could use versions 1.0 up to 1.6 .NET Standard librairies into your project - or if you have a .NET Standard v. 1.4 library, you could only build Android  v. 7.0  applications ( not v. 8.0) Intersting References about .NET Standard: Xamarin blog: A brief history of .NET Standard .NET Standard official website .NET Standard, table version video

Shuffle List in C#

Image
Yesterday, I was looking for an algorithm to shuffle a list of objects in C#. So in my mind, I started to think about "complex" algorithms to do that, using random numbers and list elements switching... I say "complex" because while I was googling, I found a good solution to do that ! And it takes only 1 line :p I would have never thinked of that :) :) Here is the cool code: var shuffledList = myObjectList.OrderBy(item => Guid.NewGuid()); So, that's really simple. You can use the "OrderBy()" Linq extension to rearrange the list. This method will take a 'random' object, in this case a GUID. And we know that GUIDs are 'unique' so, it does the job! You can use variants like this one: var rnd = new Random(); var shuffledList = myObjectList.OrderBy(rnd.Next()); Next step, compare performances, between different solutions...

Android Ad-Hoc app publication guide (with Xamarin Studio)

Image
Warning before to start Before to install a custom APK app on your device, make sure it comes from a secured and trusted source ! Generate your APK using Xamarin Studio In order to have a valid package file (APK file), we have to generate a valid package signed with a security certificate. You can use a temporary certificate for test purpose. The process bellow shows you how to do that using Xamarin Studio Wizard: Generate your APK Select Archive for publishing menu Then select "Ad-Hoc" option (to generate your APK localy) Click on "Sign and distribute" Create a custom signing certificate Create a temporary certificate to sign your APK file Install the APK on the target device Configure the target device In order to accept and install a "custom" APK (application coming from other sources than the Play Store), you will need to unlock your phone. This is done in the phone's parameters

IT Challenges

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!

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

Image
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

AOP through Unity interceptors - Conclusion

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.

AOP through Unity interceptors - Cryptography

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 t

AOP through Unity interceptors - Compression

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>(),       

AOP through Unity interceptors - Performance monitoring

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;            

AOP through Unity interceptors - Caching

Image
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 (IsInCa

AOP through Unity interceptors - Logging

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>()

[Xamarin Forms] Button text alignment issue in Android

Image
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

AOP through Unity interceptors - Introduction

Image
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 lo

C# Clean code book

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.

Retryable pattern with C# 6

Thanks to the new "when" keyword in C# 6, we can easily implement a retryable pattern when an exception is thrown. http://geekswithblogs.net/BlackRabbitCoder/archive/2015/04/09/c.net-little-wonders-exception-filtering-in-c-6.aspx