Показ дописів із міткою C#. Показати всі дописи
Показ дописів із міткою C#. Показати всі дописи

середа, 6 січня 2021 р.

C#\Xamarin interesting articles

Small demo on creating C# duplex (streaming) gRPC client/server
This is a dive into how to create well behaved duplex gRPC clients/server using the pub/sub pattern.

Using Multiple Return Values instead of Exceptions

Discussion about how Exceptions are different from expected errors, and how to return errors in your methods using multiple return values.
A question that frequently arises in software engineering is whether/when you should throw exceptions or return error codes. Many developers believe that exceptions should not be used as control flow, and argue that exceptions should be used only for non-expected errors, while return codes should be used for regular expected situations. This article explains how you can return errors as return codes, and discusses multiple options using Tuples, ValueTuples, Generics, and a combination of both.

Today we are going to show you how to get started parsing Command Line arguments, following on from our series on .NET 5.

Command Line Applications, also known as Console Applications, are programs built to be used from a shell, such as cmd or bash. They have been around since the 1960’s, way before Windows, MacOS, or any other graphical user interface (GUI) came to be.


Windows Services have been a foundation of Windows since Windows NT. They help users, or system admins, manage long-running programs that execute in their own Windows sessions. It is fairly trivial to set them up and start whenever the computer boots, for example. Since they can be completely UI-less, they provide an interesting approach for tasks that don’t require user interaction, such as looking for directory or file updates, pooling a service, or logging data. Windows itself uses services for many common task that an operating system should do, like Windows Defender, and Windows Update.

This blog post will demonstrate how to build a system file watcher as a Windows service that runs in the background, and classifies images using the WinML model we’ve previously set in my previous blog post.

Unicode Art (with the source code)

Compared to ASCII art, its Unicode analog is easier for automatic generation; at the same time, the result can look more impressive, due to better tonal set of the characters — there are so many of them in Unicode!

Human visual perception is amazingly complicated thing. It presents a lot of subtle problems of the visual presentation of everything. On the other hand, the power of human perception is dramatically underestimated. Accordingly, the preparation of the photographs or other images for the conversion into a good-looking Unicode Art form takes some artistry.

At the same time, the application offered in the present article helps to get some basic experience pretty quickly, because, with almost every small reasonably contrast and clear photograph on input, it produces quite recognizable rendition of the character-composed image. Let’s see how it is done. 

Today, JSON is one of the main formats for representing complex structures and data exchange. Therefore, all major programming languages have built-in support for working with it. C# is no exception. In this article, I would like to tell you about an easy way to work with JSON file in C#/.NET. I would like to show you simple examples with this format. 

Atata Framework - C#/.NET web test automation full featured framework based on Selenium WebDriver. It uses fluent page object pattern; has unique logging system; contains triggers functionality; has a set of ready to use components. Supports .NET Framework 4.0+ and .NET Core/Standard 2.0+.

The Framework basically consists of the following concepts:

  • Components (controls and page objects)
  • Attributes of the control search
  • Settings attributes
  • Triggers
  • Verification attributes and methods

In this article, you will learn how to implement pagination over REST API, to manage voluminous data with considerable ease, using pagination technique.

Indulge a requirement of records pagination over REST API on massive data sources. So we came up with this solution using REST API, hope it will help in your endeavors as well. This article is an extension of my previous datatable.net pagination article, so try not to put plagiarism charges on me. The intention was to perform specific and multiple column searches, sorting, dynamics page sizing, have elegant code structure, least coding effort, and most of all, performance.

In this article, you will learn how to read your applications's package identity as well as the package version using their dedicated native implementations for that task.

Version and the build numbers work together to uniquely identify a particular App Store submission for an app. The conventions for how these numbers work together are verified by automatic processes when you submit your app to the App Store or Play Store, so understanding how these numbers work and how they are intended to be used will help you save time when submitting your app. In this article, we can learn how to get App version and build numbers through programming in Xamarin.Forms.

In this article, you will learn how to add a bunch of images to a Xamarin.iOS project. In this post, I am going to show you a faster way to add image assets to your Xamarin.iOS project in Visual Studio.


Delete all the records from the table using Entity Framework Core.

User account management is fundamental to any web API. This article is a concise discussion and implementation of the basics. This article is not intended to discuss user roles and permissions - all I'm presenting here is how an example web API the management of user accounts by and administrator or by the user themselves. The code here is essentially a template and needs to be modified according to your use case requirements.

I find FluentMigrator to be a great tool for making revisions to a database. It's an easy to learn "fluent" syntax and accommodates 90% of what I need to do, and if there's something unique that needs to be done it provides an Execute method for custom SQL operations. As I find it useful to provide web API endpoints for performing migrations and checking on the migration version, this article is about how to do that in .NET 6.

This is a tutorial article that starts with an introduction to Fluent Interface Pattern in C#. This is followed by a discussion of Hierarchical Fluent Interface. Finally, quite a complicated inheritance problem with Fluent Interface Pattern is discussed. The intended audience is intermediate level C# programmers and above.

This article proposes considering multithreading in C#. It discusses the Thread class, creating threads, ThreadStart delegate, threads with parameters, thread synchronization, thread monitors, AutoResetEvent class and why it is needed, mutexes and semaphores.


-------------------------------------
On Windows the certificates and provisioning profiles (iOS) are stored under %LOCALAPPDATA%\Xamarin\iOS\Provisioning, there’s a folder for each of those.

------------------------------

We have two ways to DEBUG: USB Cable or WiFi.

➖ Connecting with the USB Cable: Just connect your device to your computer and it will be available to debug! (Your device gets this as a default way.)

➖ Connecting with WiFi: Another way is to connect through a Wifi network, which is very useful because we don’t have to have the cell phone connected to a USB cable, and it allows us to have a further distance between the device and the computer. To do this, you must follow the following steps:

  1. Go to Settings
  2. Tap WiFi option them select the WiFi network that the device is connected to.
  3. From the information that displays, we’ll save the IP Address.
  4. Connect your Android device to your computer via USB.
  5. Next, restart ADB so that it uses TCP on port 5555. From a command prompt, type the following command: adb tcpip 5555.
  6. Disconnect the USB cable from your device. (It can’t look for devices that are connected via USB.)
  7. Configure ADB so that it will connect to your Android device on the port that was specified in step 5 above: adb connect XXX.XXX.X.XXX:5555 (Your_IPAdress:5555)

And done! Our device has gotten WiFi connection! 😎




вівторок, 26 травня 2020 р.

Xamarin Forms – Add lifecycle events to views to be able to catch Appear (Loaded) and Disappear (Unloaded)

Who works with the Xamarin, know that is not possible to catch Appear and Disappear in View. Here is GREAT realisation by adding of an effect into your Android\iOS\UWP project. I did on Android and iOS, tested on Android only. But I'm quite sure, it's working. In one my project, I was needed to catch when view was disappeared, because ImageSource was closed when switched between screens.

Xamarin Forms – Add lifecycle events to views

For those of us who come to the Xamarin Forms world from WPF, the learning curve is not as terrible as for others.
After all, it is the same old xaml which we learned to love and a lot of concepts that we already know from WPF migrated successfully to Xamarin Forms.
However, sometimes, there are things that you take for granted and you pay a high price for it later on in your development.
Today, I’m going to talk about one such example: Lifecycle events on views.

Let me tell you, this was a real slap in the face for me.
I got so used to the fact that the Loaded and Unloaded events are something so common and easy to use that I didn’t even stop to question their existence in Xamarin Forms.
After a short period of disbelief and trying to search the web for answers, I came to the horrifying conclusion:
Xamarin Forms visual base classes don’t have lifecycle events!

 


In Short (TL;DR Version)

After calming myself down and searching the web for some more ideas and solutions,
I’ve created a Xamarin Forms Effect, with platform specific implementations, which will expose those events.

If you feel confident and just want the code, feel free to visit my GitHub page for the full solution.
If you want the complete solution and explanations, you can find it in the next sections.


 

The Long Version

Each platform provides us with different options to register to the specific lifecycle events that are provided by the specific platform.
Our mission? Unify everything under one single effect, which can be used across Xamarin Forms project.
Pretty straight forward.

Before we dig in, I strongly recommend that you get yourself familiar with Xamarin Forms Effects first. My entire implementation relies on it.

 

Xamarin Forms Project

Let’s start from the main Xamarin Forms project.
I want to keep the example as simple as possible, so no MVVM and no clever approaches (Other than the effect, obviously). Just a straight forward example.

The Routing Effect

We are going to start with the creation of our routing effect in the main Xamarin Forms project.
The effect is pretty simple and contains no logic. Just the two events and two methods that will raise those events.

1
2
3
4
5
6
7
8
9
10
11
12
13
public class ViewLifecycleEffect : RoutingEffect
{
    public const string EffectGroupName = "XFLifecycle";
    public const string EffectName = "LifecycleEffect";
 
    public event EventHandler<EventArgs> Loaded;
    public event EventHandler<EventArgs> Unloaded;
 
    public ViewLifecycleEffect() : base($"{EffectGroupName}.{EffectName}") { }
 
    public void RaiseLoaded(Element element) => Loaded?.Invoke(element, EventArgs.Empty);
    public void RaiseUnloaded(Element element) => Unloaded?.Invoke(element, EventArgs.Empty);
}

The only thing that I feel the need to explain here are the two consts.
I’ve created those simply because I don’t like literals and prefer to use consts whenever I can. 🙂

MainPage.xaml

Our main page will consist of a single button inside a grid, with a click event that will be handled in the code behind.

We will attach to the button the ViewLifecycleEffect and handle the Loaded and Unloaded events in the code behind as well.

1
2
3
4
5
6
7
<Grid x:Name="MainContainer" Margin="20">
    <Button Text="CLICK TO REMOVE" Clicked="Button_OnClicked" HorizontalOptions="Center" VerticalOptions="Center">
        <Button.Effects>
            <effects:ViewLifecycleEffect Loaded="ViewLifecycleEffect_OnLoaded" Unloaded="ViewLifecycleEffect_OnUnloaded"/>
        </Button.Effects>
    </Button>
</Grid>

The code behind will also be very simple and straight to the point:

  1. When the button is clicked, remove it.
  2. Upon Load, display the message: Loaded
  3. Upon Unload, display the message: Unloaded
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }
 
    private void Button_OnClicked(object sender, EventArgs e)
    {
        MainContainer.Children.Clear();
    }
 
    private void ViewLifecycleEffect_OnLoaded(object sender, EventArgs e)
    {
        DisplayAlert("LOADED", "Button was added", "OK");
    }
 
    private void ViewLifecycleEffect_OnUnloaded(object sender, EventArgs e)
    {
        DisplayAlert("UNLOADED", "Button was removed", "OK");
    }
}

As you can see, the Loaded and Unloaded events are handled only via the effect. But no one is raising them.

Yet… 

UWP

Coming from the WPF world, the UWP platform was the easiest for me, since there are already Loaded and Unloaded events on the FrameworkElement object.

So the solution is pretty straight forward:

  1. When the effect is attached, register to the Loaded and Unloaded events of the native view.
  2. When the effect is detached, remove the registrations to the events.
  3. The event handlers will call the raising events method on the Xamarin Forms effect.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
[assembly:ResolutionGroupName(ViewLifecycleEffect.EffectGroupName)]
[assembly:ExportEffect(typeof(UwpViewLifecycleEffect), ViewLifecycleEffect.EffectName)]
namespace XFLifecycle.UWP.Effects
{
    public class UwpViewLifecycleEffect : PlatformEffect
    {
        private FrameworkElement _nativeView;
        private ViewLifecycleEffect _viewLifecycleEffect;
 
        protected override void OnAttached()
        {
            _viewLifecycleEffect = Element.Effects.OfType<ViewLifecycleEffect>().FirstOrDefault();
            _nativeView = Control ?? Container;
             
            _nativeView.Loaded += NativeViewOnLoaded;
            _nativeView.Unloaded += NativeViewOnUnloaded;
        }
 
        protected override void OnDetached()
        {
            _viewLifecycleEffect?.RaiseUnloaded(Element);
            _nativeView.Loaded -= NativeViewOnLoaded;
            _nativeView.Unloaded -= NativeViewOnUnloaded;
        }
 
        private void NativeViewOnLoaded(object sender, RoutedEventArgs routedEventArgs) => _viewLifecycleEffect?.RaiseLoaded(Element);
        private void NativeViewOnUnloaded(object sender, RoutedEventArgs routedEventArgs) => _viewLifecycleEffect?.RaiseUnloaded(Element);
    }
}

Note the resolution group and the effect export above the namespace. Note the UWP specific type that is exported.

You may notice that I’ve also included the raise of the unloaded event in the OnDetached method. This is due to the fact that when removing the button completely from the Xamarin Forms side, it might actually not call the Unloaded event at all but will call the OnDetached method.

 

Android

The android platform turned out to be almost as easy as UWP. Digging around the web a bit, I found out that the lifecycle events that are called on the Android platform are a bit different, but their timing is very similar to the lifecycle events of the UWP platform.

In native android, this is handled by passing in a listener implementation, but Xamarin is kind enough to provide us with good old C# events. 🙂

So after everything combined, the code looks very similar to the UWP platform code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
[assembly: ResolutionGroupName(ViewLifecycleEffect.EffectGroupName)]
[assembly: ExportEffect(typeof(AndroidViewLifecycleEffect), ViewLifecycleEffect.EffectName)]
namespace XFLifecycle.Droid.Effects
{
    public class AndroidViewLifecycleEffect : PlatformEffect
    {
        private View _nativeView;
        private ViewLifecycleEffect _viewLifecycleEffect;
 
        protected override void OnAttached()
        {
            _viewLifecycleEffect = Element.Effects.OfType<ViewLifecycleEffect>().FirstOrDefault();
 
            _nativeView = Control ?? Container;
            _nativeView.ViewAttachedToWindow += OnViewAttachedToWindow;
            _nativeView.ViewDetachedFromWindow += OnViewDetachedFromWindow;
        }
 
        protected override void OnDetached()
        {
            _viewLifecycleEffect.RaiseUnloaded(Element);
            _nativeView.ViewAttachedToWindow -= OnViewAttachedToWindow;
            _nativeView.ViewDetachedFromWindow -= OnViewDetachedFromWindow;
        }
 
        private void OnViewAttachedToWindow(object sender, View.ViewAttachedToWindowEventArgs e) => _viewLifecycleEffect?.RaiseLoaded(Element);
        private void OnViewDetachedFromWindow(object sender, View.ViewDetachedFromWindowEventArgs e) => _viewLifecycleEffect?.RaiseUnloaded(Element);
    }
}

Note the resolution group and the effect export above the namespace. Note the Android specific type that is exported.

 

iOS

Now comes the tricky part. At least it was that way for me.

iOS exposes the lifecycle events as overridable method in the derived type. These methods are actually very useful in case you actually derive from one of the iOS classes.
But sadly, this is not our case, so I had to be creative.

Digging around the web, I’ve stumbled upon this interesting answer on SO.

Basically speaking, we can assume that once the Superview property is initialized, the view is loaded. This is great! But how can we observe it?

Experienced iOS developers would probably yell right away: “KVO”! But for me it was something completely new. If this is also new to you, I recommend to read this article: Key Value Observing (KVO) on iOS for Xamarin, by David Seilaff. It gives a great overview on the topic and helped me understand what is going on with it.

This lead me to the following solution on the iOS platform:

  1. When the effect is attached, observe the superview property on the view.
  2. When the effect is detached, stop observing the property.
  3. On the observer callback, check the change on the superview property and act accordingly.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
[assembly:ResolutionGroupName(ViewLifecycleEffect.EffectGroupName)]
[assembly:ExportEffect(typeof(IosLifecycleEffect), ViewLifecycleEffect.EffectName)]
namespace XFLifecycle.iOS.Effects
{
    public class IosLifecycleEffect : PlatformEffect
    {
        private const NSKeyValueObservingOptions ObservingOptions = NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.OldNew | NSKeyValueObservingOptions.Prior;
 
        private ViewLifecycleEffect _viewLifecycleEffect;
        private IDisposable _isLoadedObserverDisposable;
 
        protected override void OnAttached()
        {
            _viewLifecycleEffect = Element.Effects.OfType<ViewLifecycleEffect>().FirstOrDefault();
             
            UIView nativeView = Control ?? Container;
            _isLoadedObserverDisposable = nativeView?.AddObserver("superview", ObservingOptions, IsViewLoadedObserver);
        }
 
        protected override void OnDetached()
        {
            _viewLifecycleEffect.RaiseUnloaded(Element);
            _isLoadedObserverDisposable.Dispose();
        }
 
        private void IsViewLoadedObserver(NSObservedChange nsObservedChange)
        {
            if (!nsObservedChange.NewValue.Equals(NSNull.Null))
                _viewLifecycleEffect?.RaiseLoaded(Element);
            else if (!nsObservedChange.OldValue.Equals(NSNull.Null))
                _viewLifecycleEffect?.RaiseUnloaded(Element);
        }
    }
}

Note the resolution group and the effect export above the namespace. Note the iOS specific type that is exported.

 

The Result – Xamarin Forms Views Lifecycle Events

If everything went well, you should be able to see the highly anticipated messages on all 3 platforms:

Lifecycle Events

Also, after clicking the button (Which is hidden underneath the message), you should be able to see the unloaded message as well:Lifecycle events

This concludes the journey to achieve lifecycle events in Xamarin Forms.

I realize that this solution is not perfect, and to be honest, it is very far from it. But I think it might suit a lot of initial needs.

I know that for my current needs, it is exactly what I need. 🙂

Feel free to browse the complete solution on my GitHub🙂

See you in my next blog post!