Posts

Showing posts with the label c#

[XAMARIN FORMS] Background task for 'closed' applications

Image
Background task for 'closed' applications Handling a background task in Xamarin Forms, even when the application is closed, can be challenging due to the mobile operating systems' restrictions on background activities. Here's a detailed solution using a combination of Dependency Service , Background Services , and Platform-Specific Implementations . Step 1: Create an Interface First, create an interface in your shared Xamarin Forms project that defines the method for starting the background task. public interface IBackgroundTask { void StartBackgroundTask(); } Step 2: Implement Platform-Specific Services Android Implementation: In your Android project, create a service that implements the IBackgroundTask interface. Create a Service: [Service] public class MyBackgroundService : Service { public override IBinder OnBind(Intent intent) => null; public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId

[Xamarin Forms]Page navigation summary

Image
[Xamarin Forms] Page navigation summary 1- The different navigation possibilities In this article will we list and sum up how we can navigate inside a Xamarin Forms application.  In Xamarin.Forms, you can navigate between pages using several methods, we will enumerate it and give a brief description / use case for each : Push/Pop Navigation : Using Navigation.PushAsync() and Navigation.PopAsync() for stack-based navigation. Modal Navigation : Using Navigation.PushModalAsync() and Navigation.PopModalAsync() for displaying pages modally. Master-Detail Navigation : Using MasterDetailPage to manage a master menu and a detail page. Tabbed Navigation : Using TabbedPage for navigation between different tabs. Carousel Navigation : Using CarouselPage to swipe through pages in a carousel-style interface. Shell Navigation : Using Xamarin.Forms Shell for a unified navigation paradigm with URL-based routing and flyout menus. Custom Navigation : Or if you want to customize and design a good

[Xamarin Forms] Complete guide to design a TOAST component

Image
  [Xamarin Forms] Complete guide to design a TOAST component In this guide, we will first show you how to design a toast component in Xamarin Forms (adding transition animations to the component), then in a second part, we list some existing controls that you can use directly... Custom Toast design in Xamarin Forms  Designing a "toast" component in Xamarin Forms involves creating a custom control to display brief messages to the user.  I will show you bellow a simple example on how to create a Toast component, and we will also how to add transition animation. Here are the steps to design and implement a toast component: Step 1: Create the Toast View First, you need to create a custom view that represents the toast message. You can add all the UI controls that you need to fit your needs (like an icon image...) 1.1 Create a ToastView class Create a new class ToastView that inherits from ContentView . public class ToastView : ContentView { public ToastView ( string m

[GODOT] Animate camera depending on touch screen events (C#)

Image
If you develop a 2D game for mobile, like a RPG game seen from top (Zelda like for instance), and you want to navigate on your map just by dragging the screen, here is the simple way to implement it in GODOT. In your level scene you have to add a "Camera" Node and make it the current one: public override void _Ready() { // Ensure the camera is set as current Current = true; } Then create the associated Camera script (in this example in C#). You have to handle Godot input events to animate the camera. The events to manage are: - InputEventScreenTouch - InputEventScreenDrag The goal is to determinate the delta amount of  horizontal & vertical spaces that have been dragged by the user. You can see an example of handling these events in the following code snippet (camera script):  using Godot; using System; public partial class camera : Camera2D { private Vector2 _touchStartPosition = new Vector2(); private bool _isDragging = false; // Call

[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