<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by José Rojas on Medium]]></title>
        <description><![CDATA[Stories by José Rojas on Medium]]></description>
        <link>https://medium.com/@rojasjimenezjosea?source=rss-d049fd9e8668------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HLdTtFIdwm5a2xvFKojR6Q.png</url>
            <title>Stories by José Rojas on Medium</title>
            <link>https://medium.com/@rojasjimenezjosea?source=rss-d049fd9e8668------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:57:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rojasjimenezjosea/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[MVVM Fundamentals — Examples with .NET MAUI]]></title>
            <link>https://medium.com/@rojasjimenezjosea/mvvm-fundamentals-examples-with-net-maui-5b0af71e99d6?source=rss-d049fd9e8668------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b0af71e99d6</guid>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[José Rojas]]></dc:creator>
            <pubDate>Tue, 23 Apr 2024 19:07:33 GMT</pubDate>
            <atom:updated>2024-04-23T19:07:33.512Z</atom:updated>
            <content:encoded><![CDATA[<h3>MVVM Fundamentals — Examples with .NET MAUI</h3><p>The Model-View-ViewModel (MVVM) is an architectural pattern that allows applications to decouple the business logic from its representation, commonly known as User Interface (UI).<br>Furthermore, this approach helps in writing code that is easier to test and maintain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6IDbtqMlc89Y0a1wzhqiSw.png" /></figure><h3>MVVM</h3><p>The components of the MVVM pattern are:</p><ul><li><strong>Model</strong>: it is the object that contains the data process and display to the user.</li><li><strong>View</strong>: it is the user interface.</li><li><strong>ViewModel</strong>: it contains the presentation logic.</li><li><strong>Binder</strong>: it is the component responsible for the communication between the ViewModel and the View.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/0*v5MVwXvS0MkBeKbQ.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel">https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel</a></figcaption></figure><h3>Model</h3><p>The model can be a simple data class or a feature reach domain model. This depends on the paradigm used in the project. Nevertheless, the model should be unknown to the view because the ViewModel will manipulate it to have a suitable structure to be used by the view.</p><h3>ViewModel</h3><p>As already mentioned, the ViewModel will process the model, or aggregate various models, into a structure that is easy to use during the representation. It will also expose the functionalities that the user can perform.<br>In normal scenarios, the majority of the code can be find in the ViewModel. However, it is not recommended having too complex ViewModels even if the view offers a lot features.</p><h3>View</h3><p>The view is the user interface. It should contain only the mark-up code and bindings to the data and commands exposed by the ViewModel.</p><h3>Data binder</h3><p>The data binder is the component that is always forgotten since it is not mention in the pattern’s name. Even so, it is the fundamental piece that makes the communication possible between our View and ViewModels.<br>Il allow the decoupling of business logic from the UI. In facts, thanks to it is possible to avoid writing the majority of &quot;code behind&quot; to set for example the value of a label in a imperative way:</p><p>myLabel.Text = myModel.FirstName</p><p>Instead, it will be possilbe to use a more declarative approch and just bind the property.</p><p>&lt;Label Text=&quot;{Binding FirstName}&quot; /&gt;</p><p>The same approach can be used also for the funtionalities (commands).</p><h3>MVVM in practice</h3><h3>The code behind way</h3><p>Let’s inspect this simple login page implemented with the code behind approach:</p><pre>//Page code (view)<br>&lt;ContentPage xmlns=&quot;http://schemas.microsoft.com/dotnet/2021/maui&quot;<br>             xmlns:x=&quot;http://schemas.microsoft.com/winfx/2009/xaml&quot;<br>             x:Class=&quot;LessonsLog.Pages.TestPage&quot;&gt;<br>    &lt;ContentPage.Content&gt;<br>        &lt;VerticalStackLayout&gt;<br>            &lt;Entry x:Name=&quot;UsernameEntry&quot;/&gt;<br>            &lt;Entry x:Name=&quot;PasswordEntry&quot;/&gt;<br>            &lt;Button x:Name=&quot;LoginButton&quot; Text=&quot;Login&quot;&gt;&lt;/Button&gt;<br>        &lt;/VerticalStackLayout&gt;<br>    &lt;/ContentPage.Content&gt;<br>&lt;/ContentPage&gt;<br></pre><pre>// Code behind<br>public partial class LoginPage : ContentPage<br>{<br>    public LoginPage()<br>    {<br>        InitializeComponent();</pre><pre>        LoginButton.Clicked += OnLoginButtonClicked;<br>    }</pre><pre>    private async void OnLoginButtonClicked(object? sender, EventArgs e)<br>    {<br>        var username = UsernameEntry.Text;<br>        var password = PasswordEntry.Text;</pre><pre>        if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))<br>        {<br>            await DisplayAlert(&quot;Error&quot;, &quot;Invalid credentials&quot;, &quot;Ok&quot;);<br>            return;<br>        }</pre><pre>        //Addional validation code omitted<br>        // ...<br></pre><pre>        var dto = new LoginDto<br>        {<br>            Username = username,<br>            Password = password<br>        };</pre><pre>        var httpClient = new HttpClient();<br>        var result = await httpClient.PostAsJsonAsync(&quot;https://mydomain.com/login&quot;, dto);</pre><pre>        if (!result.IsSuccessStatusCode)<br>        {<br>            await DisplayAlert(&quot;Error&quot;, &quot;Invalid credentials&quot;, &quot;Ok&quot;);<br>            return;<br>        }</pre><pre>        await Shell.Current.GoToAsync(&quot;homepage&quot;);<br>    }<br>    <br>    class LoginDto<br>    {<br>        public string Username { get; set; }</pre><pre>        public string Password { get; set; }<br>    }<br>}</pre><p>This implementation may work but it has several problems:</p><ol><li>It is hardly testable because all the logic is tight to the view. There is no way to access to its methods from an unit tests.</li><li>The OnLoginButtonClicked has to return void in order to be assigned to the Clicked event handler but since we are performing await-able calls we had to mark it async void. This should be avoided according to the <a href="https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming">Microsoft Async/Await - Best Practices</a>.</li><li>The code is not reusable because, again, it belongs solely to the LoginPage.</li><li>The code is not maintainable in long terms since it heavily depends on the UI Framework, specially for displaying the error messages and navigation.</li></ol><h3>The MVVM approach</h3><pre>//Page code (view)<br>&lt;ContentPage xmlns=&quot;http://schemas.microsoft.com/dotnet/2021/maui&quot;<br>             xmlns:x=&quot;http://schemas.microsoft.com/winfx/2009/xaml&quot;<br>             x:Class=&quot;LessonsLog.Pages.TestPage&quot;<br>             xmlns:viewModels=&quot;clr-namespace:YourNamespace.ViewModels&quot;&gt;<br>    &lt;ContentPage.BindingContext&gt;<br>        &lt;viewModels:LoginPageViewModel/&gt;<br>    &lt;/ContentPage.BindingContext&gt;<br>    &lt;ContentPage.Content&gt;<br>        &lt;VerticalStackLayout&gt;<br>            &lt;Entry Text=&quot;{Binding Username}&quot; Placeholder=&quot;Username&quot;/&gt;<br>            &lt;Entry Text=&quot;{Binding Password}&quot; Placeholder=&quot;Password&quot; IsPassword=&quot;True&quot;/&gt;<br>            &lt;Button Text=&quot;Login&quot; Command=&quot;{Binding LoginCommand}&quot;&gt;&lt;/Button&gt;<br>        &lt;/VerticalStackLayout&gt;<br>    &lt;/ContentPage.Content&gt;<br>&lt;/ContentPage&gt;<br></pre><pre>public class LoginPageViewModel : INotifyPropertyChanged<br>{<br>    private string _username;<br>    public string Username<br>    {<br>        get { return _username; }<br>        set<br>        {<br>            if (_username != value)<br>            {<br>                _username = value;<br>                OnPropertyChanged();<br>            }<br>        }<br>    }</pre><pre>    private string _password;<br>    public string Password<br>    {<br>        get { return _password; }<br>        set<br>        {<br>            if (_password != value)<br>            {<br>                _password = value;<br>                OnPropertyChanged();<br>            }<br>        }<br>    }</pre><pre>    public ICommand LoginCommand { get; }</pre><pre>    public LoginPageViewModel()<br>    {<br>        LoginCommand = new Command(async () =&gt; await ExecuteLoginCommand());<br>    }</pre><pre>    private async Task ExecuteLoginCommand()<br>    {<br>        if (string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Password))<br>        {<br>            await Application.Current.MainPage.DisplayAlert(&quot;Error&quot;, &quot;Invalid credentials&quot;, &quot;Ok&quot;);<br>            return;<br>        }</pre><pre>        // Addional validation code omitted<br>        // ...</pre><pre>        var dto = new LoginDto<br>        {<br>            Username = Username,<br>            Password = Password<br>        };</pre><pre>        var httpClient = new HttpClient();<br>        var result = await httpClient.PostAsJsonAsync(&quot;https://mydomain.com/login&quot;, dto);</pre><pre>        if (!result.IsSuccessStatusCode)<br>        {<br>            await Application.Current.MainPage.DisplayAlert(&quot;Error&quot;, &quot;Invalid credentials&quot;, &quot;Ok&quot;);<br>            return;<br>        }</pre><pre>        await Shell.Current.GoToAsync(&quot;homepage&quot;);<br>    }</pre><pre>    // Implement INotifyPropertyChanged interface<br>    public event PropertyChangedEventHandler PropertyChanged;<br>    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)<br>    {<br>        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));<br>    }<br>}</pre><p>This implementation brings the following benefits:</p><ol><li>The code is more testable than before, even though there are still a few elements that can cause some challenge in the test’s setup (navigation and error messages).</li><li>The method ExecuteLoginCommand is marked as async Task. However, we have to notice that still the problem of the async void persist but has been moved to the command declaration: LoginCommand = new Command(async () =&gt; await ExecuteLoginCommand());.<br>We can get rid of it by using the AsyncCommand of the CommunityToolkit.Mvvm.</li><li>The code doesn’t belong to a single page anymore and can be shared between multiple implementations of the login page.</li></ol><h3>Conclusion</h3><p>The MVVM pattern improves the testability, reusability and helps in keeping a better separation of concerns. Additional benefits can be obtained by using it in conjunction with the Dependency injection and other architectural patterns.</p><p>In this simple example the code is still dependent on the UI Framework and the Separation of Concern principle has been violated, hardly.<br>The .NET Framework offers a variety of features to easily fix those issues.<br>I might discuss them in future blog posts.</p><p>🚀🚀 Good bye and happy coding! 🚀🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b0af71e99d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 scenarios where Moq comes in more than handy for testing your .NET project]]></title>
            <link>https://medium.com/@rojasjimenezjosea/5-scenarios-where-moq-comes-in-more-than-handy-for-testing-your-net-project-0ec9b2ef8159?source=rss-d049fd9e8668------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ec9b2ef8159</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[maui]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[José Rojas]]></dc:creator>
            <pubDate>Sun, 04 Feb 2024 10:44:00 GMT</pubDate>
            <atom:updated>2024-02-04T10:44:00.319Z</atom:updated>
            <content:encoded><![CDATA[<h3>5 scenarios where Moq comes in more than handy for testing your .NET project</h3><h4>Moq is a mocking library that helps software engineers to test their units in isolation. Discover how to use it effectively in your projects to ensure the correctness of your implementation. We wil implement a Music Player in .NET MAUI to demonstrate all the benefits that mocking brings to unit tests.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jh6thGpcMGG0krUXaOzizw.png" /></figure><p>In this example we will implement a simple Music Player (MyMp3Player) on .NET MAUI and relying on the Plugin.Maui.Audioto play the audio files.</p><p>First of all, you might be wondering why do you should even bother with mocking. Furthermore, you could be questioning, “what problem does mocking aim to solve?”. Ok, I got you. Let me explain.</p><h4>The application</h4><p>Let’s say that in our MyMp3Player app, we have a MainPageViewModelthat depends on the AudioPlayerService to actually play the sound.</p><pre>public class MainPageViewModel<br>{<br>    public Task Play(AudioManager audioManager)<br>    {<br>        var audioPlayer = new AudioPlayerService();<br>        return audioPlayer.Play(audioManager);<br>    }<br>}</pre><pre>public class AudioPlayerService<br>{<br>    public async Task Play(AudioManager audioManager)<br>    {<br>        var file = await FileSystem.OpenAppPackageFileAsync(&quot;Audio/run-staccato-string.mp3&quot;);<br>        var player = audioManager.CreatePlayer(file);<br>        player.Play();<br>    }<br>}</pre><p>If we try to test the MainPageViewModel as it is implemented now, we will encounter multiple problems.</p><h4>MAUI configuration</h4><p><strong>Attention</strong>: Ensure that the TargetFramework is configured correctly in your MAUI project; otherwise the unit test project won’t be able to build.</p><p>In the MyMp3Player.csprojwe modified the TargetFrameworks configuration as shown below.</p><pre>&lt;TargetFrameworks&gt;net8.0;net8.0-android;net8.0-ios;net8.0-maccatalyst&lt;/TargetFrameworks&gt;</pre><p>Additionally, we change the configuration of the OuputType to</p><pre>&lt;OutputType Condition=&quot;&#39;$(TargetFramework)&#39; != &#39;net8.0&#39;&quot;&gt;Exe&lt;/OutputType&gt;</pre><h4>The unit tests problem</h4><p>Now, let’s break down all the problems that our unit tests will have to deal with:</p><ul><li>We might won’t be able create an instance of the AudioManager.</li><li>We have to deal with the audio file, making it reachable also for the unit tests.</li><li>We have to consider that FileSystem.OpenAppPackageFileAsync method is not implemented for the portable version of the application.</li></ul><p>Moreover, even if we configure all dependencies correctly, there is still a major issue: the sound will be played while running the tests.</p><p>In addition, the current version of the application is hadly testable. In fact, the only test that we might be able to execute is that the Play method is executed without throwing exceptions.</p><pre>public class MainPageViewModelTests<br>{<br>    private MainPageViewModel _sut;<br><br>    [SetUp]<br>    public void Setup()<br>    {<br>        _sut = new MainPageViewModel();<br>    }<br>    <br>    [Test]<br>    public async Task Play_NoOtherSoundIsPlaying_NoExceptionAreThrown()<br>    {<br>        try<br>        {<br>            await _sut.Play(AudioManager.Current as AudioManager);<br>        }<br>        catch<br>        {<br>            Assert.Fail();<br>        }<br>    }<br>}</pre><p>However, the Play_NoOtherSoundIsPlaying_NoExceptionAreThrown test fails and its implementation is quite creepy.</p><p>Let’s refactor by adding Interfaces and setting up the Dependency injection.</p><h4>A testable application</h4><p>After the refactoring, we will have a working version of the application that has the same functionality as before, but this time, its testability has been drastically improved.</p><p>Let’s take a look at the Service layer. First, the IAudioFileStreamProvider will enable us to overcome all issues related to loading a valid file in the correct location and so on.</p><pre>public interface IAudioFileStreamProvider<br>{<br>    Task&lt;Stream&gt; GetStream(string filename);<br>}<br><br>public class AudioFileStreamProvider : IAudioFileStreamProvider<br>{<br>    public Task&lt;Stream&gt; GetStream(string filename)<br>    {<br>        return FileSystem.OpenAppPackageFileAsync($&quot;Audio/{filename}&quot;);<br>    }<br>}</pre><p>Secondly, the IAudioPlayerService will give us the ability to verify if we are interacting with theIAudioManager as expected.</p><pre>public interface IAudioPlayerService<br>{<br>    void Play(Stream audioStream);<br>}<br><br>public class AudioPlayerService : IAudioPlayerService<br>{<br>    private readonly IAudioManager _audioManager;<br><br>    public AudioPlayerService(IAudioManager audioManager)<br>    {<br>        _audioManager = audioManager;<br>    }<br>    <br>    public void Play(Stream audioStream)<br>    {<br>        var player = _audioManager.CreatePlayer(audioStream);<br>        player.Play();<br>    }<br>}</pre><p>Now it’s time to fix our unit test, we will do that usingMoq to mock our dependencies in the various units. Please install Moq using Nuget.<br>Once we have fixed our first test, we will write more tests to verify that every unit performs its tasks correctly.</p><h4>1 Exception handling with Moq</h4><p>With Moq, it’s possible to configure the dependencies to throw exceptions for both synchronous and asynchronous methods.</p><pre>[TestFixture]<br>public class MainPageViewModelTests<br>{<br>    private MainPageViewModel? _sut;<br>    <br>    private Mock&lt;IAudioFileStreamProvider&gt;? _audioFileStreamProviderMock;<br>    private Mock&lt;IAudioPlayerService&gt;? _audioPlayerServiceMock;<br>    <br>    [SetUp]<br>    public void Setup()<br>    {<br>        _audioFileStreamProviderMock = new Mock&lt;IAudioFileStreamProvider&gt;();<br>        _audioPlayerServiceMock = new Mock&lt;IAudioPlayerService&gt;();<br>        <br>        _sut = new MainPageViewModel(_audioFileStreamProviderMock.Object, _audioPlayerServiceMock.Object);<br>    }<br>    <br>    [Test]<br>    public void Play_NoOtherSoundIsPlaying_NoExceptionAreThrown()<br>    {<br>        Assert.DoesNotThrowAsync(async () =&gt; await _sut.Play(&quot;test&quot;));<br>    }<br>    <br>    [Test]<br>    public void Play_FileIsNotFound_ThrowsCannotReproduceAudioException()<br>    {<br>        _audioFileStreamProviderMock.Setup(p =&gt; p.GetStream(It.IsAny&lt;string&gt;() ))<br>            .ThrowsAsync(new FileNotFoundException());<br>        <br>        Assert.ThrowsAsync&lt;CannotReproduceAudioException&gt;(async () =&gt; await _sut.Play(&quot;test&quot;));<br>    }<br>    <br>    [Test]<br>    public void Play_AudioManagerFails_ThrowsCannotReproduceAudioException()<br>    {<br>        _audioPlayerServiceMock.Setup(p =&gt; p.Play(It.IsAny&lt;Stream&gt;() ))<br>            .Throws&lt;InvalidDataException&gt;();<br>        <br>        Assert.ThrowsAsync&lt;CannotReproduceAudioException&gt;(async () =&gt; await _sut.Play(&quot;test&quot;));<br>    }<br>}</pre><p>As you can see our tests now are more valuable and easier to understand.</p><h4>2 Verify method invocations</h4><p>Moq enable us to verify all actions performed on the dependencies. Commonly, what people tent to verify is that a certain method has been invoked a given amount of times.</p><pre>[Test]<br>public async Task Play_Always_GetStreamIsCalledOnce()<br>{<br>    await _sut.Play(&quot;test&quot;);<br>        <br>    _audioFileStreamProviderMock.Verify(p =&gt; p.GetStream(It.IsAny&lt;string&gt;()), Times.Once);<br> }</pre><h4>3 Verify method invocations with correct parameters</h4><p>The moking library allows to verify not only that the method has been called a certain number of time but also to check the correctness of the parameters.</p><pre>    [Test]<br>    public async Task Play_Always_GetStreamIsCalledOnce()<br>    {<br>        await _sut.Play(&quot;test&quot;);<br><br>        _audioFileStreamProviderMock.Verify(p =&gt; p.GetStream(It.Is&lt;string&gt;(p =&gt; p == &quot;test&quot;)), Times.Once);<br>    }</pre><p>There is a tiny difference but this is the kind of detail that make the difference in detecting regressions. To be fair, using only one of the 2 alternatives is not enough to ensure the accuracy of our implementation.</p><p>With the first verification, the parameter could be incorrect. To address this issue, we verified that the argument of GetStream is set to &#39;test&#39; and it is called only once. However, in this scenario, the test will still pass if the method is called twice — once with the string &#39;test&#39; and another time with any other string. A better test can be achieved by combining these two approaches.</p><pre>    [Test]<br>    public async Task Play_Always_GetStreamIsCalledOnce()<br>    {<br>        await _sut.Play(&quot;test&quot;);<br><br>        Assert.Multiple(() =&gt;<br>        {<br>            _audioFileStreamProviderMock.Verify(p =&gt; p.GetStream(It.Is&lt;string&gt;(p =&gt; p == &quot;test&quot;)), Times.Once);<br>            _audioFileStreamProviderMock.Verify(p =&gt; p.GetStream(It.IsAny&lt;string&gt;()), Times.Once);<br>        });<br>    }</pre><h4>4 Check event handler registration</h4><p>It is time to improve our application with new features. Our product owner wants us to build an auto play functionality. When a song has been played, the player should pick up the next one in the list and play it.</p><p>In this scenario the IAudioPlayerService should be able to communicate to the ViewModel that the song has finished playing. This is the new version of the interface and its implementation.</p><pre>public interface IAudioPlayerService<br>{<br>    void Play(string name, Stream audioStream);<br><br>    event Action SongEnded;<br>}<br><br>public class AudioPlayerService : IAudioPlayerService<br>{<br>    private readonly IAudioManager _audioManager;<br>    <br>    private IDictionary&lt;string, IAudioPlayer&gt; _players;<br>    private string _currentSong = string.Empty;<br>    <br>    public event Action? SongEnded;<br><br>    public AudioPlayerService(IAudioManager audioManager)<br>    {<br>        _audioManager = audioManager;<br>        _players = new Dictionary&lt;string, IAudioPlayer&gt;();<br>    }<br><br>    public void Play(string name, Stream audioStream)<br>    {<br>        if (!_players.TryGetValue(name, out var audioPlayer))<br>        {<br>            audioPlayer = _audioManager.CreatePlayer(audioStream);<br>            _players[name] = audioPlayer;<br>        }<br>        <br>        var playing = _players.FirstOrDefault(p =&gt; p.Value.IsPlaying).Value;<br>        playing?.Stop();<br>        <br>        audioPlayer.PlaybackEnded += PlayerOnPlaybackEnded;<br><br>        audioPlayer.Play();<br>        _currentSong = name;<br>    }<br><br>    private void PlayerOnPlaybackEnded(object? sender, EventArgs e)<br>    {<br>        SongEnded?.Invoke();<br>        _players[_currentSong].PlaybackEnded -= PlayerOnPlaybackEnded;<br>    }<br>}</pre><p>As you can see in the Play method a new AudioPlayer is created for every song that we want to listen to. To be notified when it has finished, we register for its PlaybackEnded event. When the event handler PlayerOnPlaybackEnded is triggered, we unregister to avoid memory leaks.</p><p>This feature seems to be non-trivial to test but Moq has our backs covered, and allow us to write a simple test to check the registration for thePlaybackEnded event.</p><pre>    [Test]<br>    public void Play_ValidStream_RegisteredToPlaybackEndedEvent()<br>    {<br>        var playerMock = new Mock&lt;IAudioPlayer&gt;();<br>        _audioManagerMock.Setup(m =&gt; m.CreatePlayer(It.IsAny&lt;Stream&gt;()))<br>            .Returns(playerMock.Object);<br>        <br>        _sut.Play(&quot;test&quot;, new MemoryStream());<br>        <br>        playerMock.VerifyAdd(p =&gt; p.PlaybackEnded += It.IsAny&lt;EventHandler&gt;(), Times.Once);<br>    }</pre><h4>5 Fire events</h4><p>Additionally, we can fire thePlaybackEnded to verify that the SongEnded event is invoked. The arrangement phase is a bit longer than before but still it allows us to ensure that our component behaves as expected.</p><pre>    [Test]<br>    public void SongEnded_PlaybackEndedIsRaised_SongEndedIsInvoked()<br>    {<br>        //Arrange<br>        var playerMock = new Mock&lt;IAudioPlayer&gt;();<br>        _audioManagerMock.Setup(m =&gt; m.CreatePlayer(It.IsAny&lt;Stream&gt;()))<br>            .Returns(playerMock.Object);<br>        <br>        var songEndedInvoked = false;<br>        _sut.SongEnded += () =&gt; songEndedInvoked = true;<br>        _sut.Play(&quot;test&quot;, new MemoryStream());<br>     <br>        //Act<br>        playerMock.Raise(p =&gt; p.PlaybackEnded += null, null, null);<br>        <br>        //Assert<br>        Assert.Multiple(() =&gt;<br>        {<br>            Assert.That(songEndedInvoked, Is.True);<br>            playerMock.VerifyRemove(p =&gt; p.PlaybackEnded -= It.IsAny&lt;EventHandler&gt;());<br>        });<br>    }</pre><h4>Conclusion</h4><p>Moq offers more features like support for support for mocking properties, verifying the invocation order of methods, callbacks for customizing behavior, support for recursive mocks, strict mocking with Strict() configuration, mocking indexers and range matchers, mocking extension methods, verification of no other calls with VerifyNoOtherCalls().</p><p>In conclusion, these simple examples demonstrate the versatility and power of Moq in unit testing C# projects allowing you to isolate and validate specific behaviours within your codebase. With this newfound knowledge, I hope you feel more confident and well-equipped to leverage Moq in your C# projects, ultimately contributing to the robustness and reliability of your software.</p><p>If you are curious about the full implementation of the MyMp3Playe take a look at my <a href="https://github.com/rojasjo/MyMp3Player">GitHub repository</a>.</p><h4>🚀 <strong>Enjoy</strong> 🚀</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ec9b2ef8159" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coding Challenge #42— HTTP Load Tester in C#]]></title>
            <link>https://medium.com/@rojasjimenezjosea/coding-challenge-42-http-load-tester-in-c-cdb40ea2180d?source=rss-d049fd9e8668------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdb40ea2180d</guid>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[José Rojas]]></dc:creator>
            <pubDate>Sat, 13 Jan 2024 20:47:14 GMT</pubDate>
            <atom:updated>2024-01-13T20:47:14.510Z</atom:updated>
            <content:encoded><![CDATA[<h4>Discover what Load Testing is, how to build an alpha version of a http loading test software and more popular open-source solutions like JMeter and Netling</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zp5Qma9uuGmRAzLXwjG51Q.png" /></figure><p>The last 2023 coding challenge (#42) proposed by <a href="https://www.linkedin.com/in/johncrickett/?lipi=urn%3Ali%3Apage%3Ad_flagship3_pulse_read%3B9paS6BkUTE%2BRZkDU2PcmFw%3D%3D">John Crickett</a> helps in get ting familiar with load testing and understanding how such tools are built from the ground up. However, I feel the need to recommend to those who are willing to solve it to keep the solution simple and stick to the given requirement: <a href="https://codingchallenges.fyi/challenges/challenge-load-tester">https://codingchallenges.fyi/challenges/challenge-load-tester</a>. Mind that implementing a fully functional load testing tool requires substantial commitment.</p><h3>What is a Load Testing tools</h3><p>A load testing software is a tool crafted to evaluate how well a software application performs under different levels of simulated user activity. By gradually increasing the load, it helps highlight potential bottlenecks and weaknesses in the system. This ensures that the application can gracefully handle expected user traffic without compromising performance or stability.</p><h4>The 5 features that cannot be missing in a Load Testing solution</h4><ol><li><strong>Simultaneous user</strong>: simulating multiple concurrent users to replicate real-world usage patterns and stress test the application.</li><li><strong>Test execution and scheduling</strong>: execute tests on-demand or according to a predefined schedule to simulate different levels of load.</li><li><strong>Monitoring and reporting</strong>: Monitoring key performance indicators (KPIs) in real-time and generating comprehensive reports on system performance.</li><li><strong>Scenario recording</strong>: allowing users to record and replay user interactions for simulating realistic scenarios.</li><li><strong>Parameterisation</strong>: enabling variation of input values during tests to mimic diverse user inputs.</li></ol><h4>Useful metrics that a load test should provide</h4><ol><li><strong>Response Time</strong>: average, minimum, and maximum response times.</li><li><strong>Throughput</strong>: number of requests processed per unit of time.</li><li><strong>Error rate</strong>: the percentage of requests that result in errors.</li><li><strong>Concurrency</strong>: the number of concurrent users or connections during the test.</li><li><strong>Latency</strong>: the time taken for a request to travel from the client to the server and back.</li><li><strong>Transaction rate</strong>: the number of completed transactions per unit of time. This metric provides a more granular view of performance for specific business transactions.</li></ol><p>The reporting of these metrics is crucial for understanding how the system performs and its reliability under certain load. It helps identify the performance bottlenecks and potential network-related issues.</p><h3>JMeter</h3><p>To shed more light on what a loading test is, we can use <a href="https://jmeter.apache.org/">Apace JMeter</a>, which is an open source software written in Java and designed to load test functional behaviour and measure performance.</p><h4>How to setup a load test</h4><p><strong>Thread Group<br></strong>The first thing to add to your Test Plan is a Thread Group. Right click on the Test Plan -&gt; Add -&gt; Threads (Users) -&gt; Thread Group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dtk36gg6jebt4iuciAey1Q.png" /></figure><p>By selecting it from the left side it is possibile to configure the following parameters:</p><ul><li><strong>Number of Threads (users)</strong>: specifies the total number of virtual users or threads that will be simulated during the test.</li><li><strong>Ramp-up period (seconds)</strong>: indicates the time it takes for JMeter to fully launch all specified threads, gradually increasing the load to the defined level.</li><li><strong>Loop Count</strong>: specifies the number of times each thread will execute the test scenario.</li><li><strong>Same user on each iteration</strong>: determines whether the same user credentials will be used for each iteration of the test.</li><li><strong>Delay Thread creation util need</strong>: delays the creation of additional threads until they are required.</li><li><strong>Specify Thread lifetime:</strong> defines the duration or lifetime of a thread, specifying how long a virtual user will execute the test scenario before terminating.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mNnObcDtOd8GoYiJXOFq9g.png" /></figure><p><strong>Http request</strong><br>The next step is to add one or more http request to the Thread Group by simply right clicking on the Thread Group -&gt; Sample -&gt; HTTP Request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IVnyDO30hynS3u09exHKiQ.png" /></figure><p>As usual by selecting it from the left side it is possible to configure it.<br>The basic setup allow us to set the followign properties:</p><ul><li><strong>Protocol [http]</strong>: communication protocol, typically HTTP or HTTPS.</li><li><strong>Server name or IP</strong>: domain name or IP address of the server.</li><li><strong>Port Number</strong>: port number on the server.</li><li><strong>Method</strong>: http method (GET, POST, PUT, DELETE, etc.).</li><li><strong>Path</strong>: specifies the specific resource or endpoint on the server.</li><li><strong>Content encoding</strong>: encoding format for the content.</li><li><strong>Redirect Automatically</strong>: determines whether JMeter should automatically follow HTTP redirects.</li><li><strong>Follow Redirects</strong>: determines whether the HTTP client should follow server redirects.</li><li><strong>Use KeepAlive</strong>: indicates whether the connection should be kept alive for multiple requests.</li><li><strong>Use multipart/form-data</strong>: specifies whether the request should use the multipart/form-data content type, tipically used for file upload.</li><li><strong>Browser-compatible headers</strong>: configures the HTTP request headers to be compatible with common browsers.</li><li><strong>Parameters</strong>: query string parameters.</li><li><strong>Body Data</strong>: data to be included in the request body.</li><li><strong>File Upload</strong>: allows to configure the file to upload.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rgaNaNS_6xqR6eJcS2AysA.png" /></figure><p>At this point it is possible to run the test but we won’t get any report or result, so lets set a simple report.</p><p><strong>Summary Report</strong></p><p>To view the test result it is possible to add to the Test plan a Summary report. Simple right click on the Test Plan-&gt; Add -&gt; Listener -&gt; Summary Report.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XJi12zct4CGGyrg1ohGmVQ.png" /></figure><p>To run the test you can simply click the Big Green Arrow and when it is completed the result will be available for review.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Me_enPnta1jPXoqVn2MUow.png" /></figure><p>JMeter offers many more features to configure your tests according to your requirements.</p><h3>Netling</h3><p>Netling is an open-source load tester written entirely in C# and it has an easy command line interface as well as a WPF client for Windows.<br>It is downloadable from the this <a href="https://github.com/hallatore/Netling#readme">GitHub repository</a>.</p><p>The Netling command permits to configure the number of threads to spawn, duration of the run in seconds and the amount of request per thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*Bu92QmWv2MsQi0jkm0MIiQ.png" /></figure><p>What is notable about this solution is that the <a href="https://github.com/hallatore">developer</a> uses the TcpClient instead of the HttpClient, enabling grain control over communication. However, the downside is that he had to implement almost the entire http protocol, which is challenging. Probably for this reason, the developer invites anyone who as unhandled needs, such as custom headers and data to revisit the code and extend it.</p><p>I recommend to read this code to understand how you could implement the Http protocol and manage standard headers, methods, response types and chucked responses.</p><p>Compliments for this repo that count more than 1.3k ⭐ !!!</p><h3>Challenge #42</h3><p>My solution in C# is available at on this <a href="https://github.com/rojasjo/HttpLoadTester">repository</a>.</p><p>I’ve developed the solution until the step 5 therefore the command line application offers the following features:</p><ul><li>send GET requests to the given URL</li><li>setup the number of requests to send</li><li>configure the number of users (threads)</li><li>view the detail of every single request</li><li>view the result summary: number of total successful and failed requests, total time of the test execution, request/second, total request time, time to first byte and Time to last byte.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*nnWaUqB-ecKLKAKxK0jTKQ.png" /></figure><h4>CLI</h4><p>The following one is an example of test that can be executed using the CLI:</p><p>./HttpLoadTester -u https://localhost:7102/api/v1/account/show -n 100 -c 5</p><p>The result are displayed as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*iKKBndQoSBbBJQi9PWZBOA.png" /></figure><h4>Technical details</h4><p>The approach that I used is straightforward. In facts, I relied on the HttpClient to manage the communication effectively.</p><p>To implement this solution I used the following libraries:</p><ul><li><a href="https://www.nuget.org/packages/CommandLineParser">CommandLineParser</a>: to manage the parameters set by the user in a easy way</li><li><a href="https://www.nuget.org/packages/Microsoft.Extensions.DependencyInjection">Microsoft.Extensions.DependencyInjection</a>: to setup the DI pattern properly allowing the code to be more testable and improve the separation of concerns.</li></ul><p>The precision of the time to first and last byte could be improved for instance using the TcpClient in order to manage the response byte by byte instead of relying on the HttpClient.</p><h3>Conclusion</h3><p>Implementing this challenge was interesting and enabled my to discover more about load tester and the available solution that I might use professionally in a future.</p><p>I hope this post gave more insights over the load tests and how useful they are to guarantee that our application performs as expected.</p><p>As usual fell free to visit the repository at <a href="https://github.com/rojasjo/HttpLoadTester">https://github.com/rojasjo/HttpLoadTester</a> .</p><p><strong>Enjoy</strong> 🚀🚀🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdb40ea2180d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Docker]]></title>
            <link>https://medium.com/@rojasjimenezjosea/introduction-to-docker-1fab69ff4964?source=rss-d049fd9e8668------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fab69ff4964</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[José Rojas]]></dc:creator>
            <pubDate>Sat, 09 Dec 2023 16:18:22 GMT</pubDate>
            <atom:updated>2023-12-22T14:34:39.494Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding the basics of Docker — dockerfile, images and containers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-f0pjTnTlPTGQX3uqu7kgQ.png" /></figure><p>In this article, we will explore Docker, emphasizing key concepts such as images, containers, and the Dockerfile.</p><p>After following this guide, you should feel more comfortable using Docker in your projects.</p><h3>Docker</h3><p>Docker, developed by Docker Inc., is a platform that uses OS-level virtualisation to deliver software in containers. In the cloud context, it is categorised as Platform as a Service (PaaS). It purpose is to facilitate the deployment of software.</p><h4>Docker Hub</h4><p><a href="http://hub.docker.com/">Docker Hub</a> is the central hub for Docker. It’s the online platform where you can discover, share, and use containers — pre-packaged software units. If you need software for your project, Docker Hub is the place to find it. It’s the go-to spot where the Docker community shares their software solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nq54MI1W2DdXSm-W8SqRyw.png" /></figure><p>In Docker Hub, a repository is like a folder for your containers. It’s a place to keep your packaged software organized. Each repository can hold different versions of your containers, making it simple to manage and share them. Think of it as a neat storage space for your software in Docker Hub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YkwXOqfxUeYhq65EaQvwdw.png" /></figure><h4>Installing Docker</h4><p>In this tutorial we are going to install Docker on a linux CentOS (7.9.2009).</p><p>As first thing we need to install the following packages:</p><ul><li>yum-utils: provides additional utilities and plugins for yum, enhancing its functionality.</li><li>device-mapper-persistent-data: is part of the device-mapper storage driver, used in systems that use LVM (Logical Volume Manager) for managing disk space.</li><li>lvm2: is the user-space toolset that provides logical volume management facilities on Linux.</li></ul><p>The command is:</p><pre>sudo yum install -y yum-utils device-mapper-persistent-data lvm2</pre><p>Then we will add the Docker repository configuration to the yum package manager.</p><pre>sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo</pre><p>Finally we can install Docker with the command:</p><pre>sudo yum install docker -y</pre><p>To enable and start Docker daemon on your system just run the following commands:</p><pre>sudo systemctl enable docker<br>sudo systemctl start docker</pre><h4>Add your user to docker group</h4><p>To improve security and streamline Docker container management, it is recommended to add your user to the ‘docker’ group. This allows the user to interact with the Docker daemon without needing elevated privileges, reducing the need to use sudo for Docker commands.</p><p>Verify if the docker group exists executing:</p><pre>grep docker /etc/group</pre><p>If the <strong>docker group exists</strong> the output should be something similar to:</p><pre>docker:x:1005:<br>docker:x:1005:user1</pre><p>The you can add your user to this group to be able to run the command without the elevate privilege</p><pre>sudo usermod -aG docker cloud_user</pre><ul><li>If the <strong>docker group doesn’t exists</strong> you can create it by running:</li></ul><pre>sudo groupadd docker</pre><p>Add the user to it</p><pre>sudo usermod -aG docker cloud_user<br>newgrp docker //apply the group changes without having to logout and login</pre><p>Now, change the ownership of the socket process to the user root and group docker</p><pre>sudo chown root:docker /var/run/docker.sock</pre><p>Then restart the docker deamon</p><pre>sudo systemctl restart docker</pre><p>At this point you will be able to verify your installation by simply running:</p><pre>[cloud_user@39cae74b321c ~]$ docker run hello-world</pre><p>If you followed all the steps correctly the output will be similar to the one below</p><pre>Hello from Docker!<br>This message shows that your installation appears to be working correctly.<br><br>To generate this message, Docker took the following steps:<br> 1. The Docker client contacted the Docker daemon.<br> 2. The Docker daemon pulled the &quot;hello-world&quot; image from the Docker Hub.<br>    (amd64)<br> 3. The Docker daemon created a new container from that image which runs the<br>    executable that produces the output you are currently reading.<br> 4. The Docker daemon streamed that output to the Docker client, which sent it<br>    to your terminal.<br><br>To try something more ambitious, you can run an Ubuntu container with:<br> $ docker run -it ubuntu bash<br><br>Share images, automate workflows, and more with a free Docker ID:<br> https://hub.docker.com/<br><br>For more examples and ideas, visit:<br> https://docs.docker.com/get-started/</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jQrBy8KeZTqHqUBa" /><figcaption><a href="https://cto.ai/blog/docker-image-vs-container-vs-dockerfile/">https://cto.ai/blog/docker-image-vs-container-vs-dockerfile/</a></figcaption></figure><h3>Dockerfile</h3><p>The dockerfile is a script that contains instructions to build a Docker image. It species the base image, adds files, run command and sets up the environment for the application.</p><p>In this example we need to structure a folder with the following content:</p><pre>/web/dockerfile<br>/web/index.html</pre><p>The dockerfile will contain the following instucttions</p><pre># Use an official Nginx image as the base image<br>FROM nginx:latest<br><br># Copy the HTML file to the default Nginx document root<br>COPY index.html /usr/share/nginx/html<br><br># Expose port 80 to the outside world<br>EXPOSE 80</pre><p>The simple index.html file will look something like:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Hello, World!&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;Hello, World!&lt;/h1&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>At this point we can create our web app Docker image by exectuting the command:</p><pre>docker build . -t hello-web-app:v1</pre><p>This will create an image named <em>hello-web-app</em> and tagged with <em>v1.</em></p><h3>Docker images</h3><p>A Docker image is a lightweight, standalone, and executable package that includes everything needed to run a piece of software, including the code, runtime, libraries and system tools.</p><p>Images are created from a Dockerfile using the <em>docker build </em>command.</p><p>To list all images on your system simple run</p><pre>docker image ls #alternatively: docker images</pre><p>The output should be something similar to the one below.</p><pre>REPOSITORY                     TAG                 IMAGE ID            CREATED             SIZE<br>hello-web-app                  latest              33e032ce84c4        7 minutes ago       187 MB<br>hello-web-app                  v1                  33e032ce84c4        7 minutes ago       187 MB</pre><p>In the table you find a list of useful commands.</p><pre>| Command                              |          Explanation                                              |<br>| ------------------------------------ | -------------------------------------------------------- |<br>| `docker pull image_name:tag`         |       Download an image from Docker Hub.                        |<br>| `docker rmi image_name:tag`          | Remove one or more Docker images.                         |<br>| `docker image prune`                 | Remove all dangling (unused) Docker images.               |<br>| `docker tag old_image:old_tag new_image:new_tag` | Add a new tag to an existing image.        |<br>| `docker image inspect image_name:tag` | Display detailed information about an image.            |<br>| `docker push image_name:tag`         | Upload an image to Docker Hub.                            |<br>| `docker search image_name`           | Search for images on Docker Hub.                         |<br></pre><h3>Docker containers</h3><p>A Docker container is a runnable instance of a Docker image. It’s an isolated environment that runs your application. Containers are created from Docker images using the <em>docker run</em> command.</p><pre>docker container run -d -p 8080:80 --name hello-web-app-container-1 hello-web-app:v1</pre><p>To verify that the container is running you can run the <em>docker ps </em>command or <em>docker container ls.</em></p><pre>[cloud_user@39cae74b321c web]$ docker ps<br>CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES<br>0ed45ef18723        hello-web-app:v1        &quot;/docker-entrypoin...&quot;   4 seconds ago       Up 4 seconds        0.0.0.0:8080-&gt;80/tcp   hello-web-app<br>[cloud_user@39cae74b321c web]$ docker container ls<br>CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES<br>0ed45ef18723        hello-web-app:v1        &quot;/docker-entrypoin...&quot;   55 seconds ago      Up 55 seconds       0.0.0.0:8080-&gt;80/tcp   hello-web-app</pre><p>Now if you navigate to your web page you will see the content of the index.html. Let’s do it with <em>curl</em>:</p><pre>[cloud_user@39cae74b321c web]$ curl http://localhost:8080<br>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Hello, World!&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;Hello, World!&lt;/h1&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>Conclusion</h3><p>Docker is a powerful tool for deploying web applications, streamlining release processes through automation. Its comprehensive and user-friendly command-line interface (CLI) makes it accessible for users of all levels. For further study, I recommend exploring the official documentation and leveraging the valuable resources available in the GitHub repository <a href="https://github.com/wsargent/docker-cheat-sheet">Docker Cheat Sheet</a>.</p><p>If you are looking to understand the best practice for managing your docker files I recommend to read the post <a href="https://spacelift.io/blog/dockerfile">https://spacelift.io/blog/dockerfile</a>.</p><h3><strong>What’s next</strong></h3><p>With a clearer understanding of Docker, the next article will dive into enabling Docker support for ASP.NET Core applications. We’ll dissect the default Dockerfile generated by the Rider IDE when setting up Docker support for ASP.NET Core projects and expose it on the internet.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fab69ff4964" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AZ-900 Exam Study Notes #3]]></title>
            <link>https://medium.com/@rojasjimenezjosea/az-900-exam-study-notes-3-8236403c6b4d?source=rss-d049fd9e8668------2</link>
            <guid isPermaLink="false">https://medium.com/p/8236403c6b4d</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[az900]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[José Rojas]]></dc:creator>
            <pubDate>Thu, 30 Nov 2023 18:06:19 GMT</pubDate>
            <atom:updated>2023-11-30T18:06:19.597Z</atom:updated>
            <content:encoded><![CDATA[<h4>Sharing my personal study notes about Azure AZ-900 — Authentication</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*laYNwU6b4MZmpwQsdG4L_Q.png" /></figure><h3>Authentication</h3><h4>Azure Active Directory (AAD)</h4><p>AAD is part of the new Microsoft Entra product family, along with Permission Management, Verified ID and others.</p><p>AAD must not be confused with Active Directory (AD) which is designed on-premises infrastructure.</p><p><strong>AAD =! AD</strong></p><ul><li>Every Azure account belongs to an AAD instance.</li><li>A Tenant corresponds to an organisation with its dedicated AAD instance.</li><li>A user belongs to a tenant but could be guest in other tenants.</li><li>An AAD Tenant can have multiple Subscriptions (billing entity)</li><li>AAD helps in facilitating the implementation of hybrid cloud infrastructures</li></ul><h4>Zero Trust</h4><p><strong>Trusted perimeter</strong>: corporate network. Every user or device outside the network is not trusted, therefore they cannot access to resources.</p><p><strong>Extend the perimeter (VPN)</strong>: the VPN “extends” the corporate network perimeter to trust devices and users and grant access to resources.</p><p><strong>Zero trust</strong>: implies that no one is trusted, inside or outside the corporate network, until the verification of the user identity.</p><ul><li>Assign least privilege access</li><li>Trusted by identity regardless of location</li><li>Simplified, centralised management with conditional access policies</li><li>allow access only from approved managed devices (regardless of the network)</li></ul><p>Zero trust can be combined with a trusted perimeter to further improve security.</p><h4>Multi Factor Authentication</h4><ul><li>Something you know (password/PIN)</li><li>Something you have (Smart card)</li><li>Something you are (fingerprint/Face ID)</li></ul><h4>Conditional Access</h4><p>Uses if/then policies to grant access, access is granted if the user meets the conditions (signals).</p><ol><li><strong>Assign Signals:</strong></li></ol><ul><li>Users/groups</li><li>Application to grant/deny access</li><li>Location (IP)</li><li>Approved devices</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*Wtimh51r1ZhCr_MO_YApkA.png" /></figure><p>2. Access decisions (grant/block access)</p><ul><li>To grant access</li><li>To enforce MFA</li></ul><p>Scenario: enforce MFA, block signing with legacy protocols<br>Gran access</p><h4>Passwordless</h4><p>Remove password from system login and replace it with something you have (phone/key fob) or something you know/are (on device) -&gt; unlock/PIN or fingerprint/face.</p><p>The 3 Passwordless methods are:</p><ul><li>Microsoft Authenticator App — MFA mobile app/configure in Azure AD</li><li>Windows Hello — face recognition</li><li>FIDO2 Security Key — Hardware key</li></ul><h4>Guest Users</h4><p>If anyone outside the organisation has an account compatible with AAD it can be invited as a guest in the Tenant.</p><ol><li>Invite the user as external collaborator (B2B collaborator).<br>The account could be from Microsoft, Google or Facebook account, but there are also the possibility to configure others external identity providers.</li></ol><p>2. Assign permission</p><p><strong><em>Permissions are different between Azure AD and Azure Subscription</em></strong></p><p>Optionally:</p><ul><li>Assign the guest user to an specific application</li><li>Apply cross-tenant Conditional Access policy</li></ul><h4>Azure Active Directory Domain Service (A AD DS)</h4><p>A AD DS helps in migrating legacy apps to the cloud. The legacy application is not using OAuth 2.0 and it might require traditional Active Directory (group policies, LDAP, NTLM, Kerberos).</p><p>Solutions:</p><ul><li>continue using on-premise AD by syncing to Azure AD with Azure AD Connect</li><li>Configure AD server on Azure VM</li><li>Azure Active Directory Domain Services (Azure AD DS): managed active directory domain service with classic AD features</li></ul><p><strong>A AD DS is managed service:</strong></p><ul><li>no OS configuration/management</li><li>2 Windows domain controller for high availability</li><li>Unique namespace/domain name</li><li>Standalone domain, it is not an extension of on-premises AD domain</li></ul><p><strong>One-way sync from ADD to A AD DS</strong></p><ul><li>sync users, groups and credentials</li><li>Azure AD may also bidirectional sync with on-premises AD</li></ul><h4>Single Sign-On</h4><p>Azure Active Directory Seamless Single Sign-On</p><ul><li>Enable SSO in AAD</li><li>seamlessly use all apps without login</li><li>Single username/password</li></ul><h4>Summary</h4><p>Azure offers a great set of feature to secure your applications. Understanding their purposes and uses cases is fundamental to keep your users and corporate data safe.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8236403c6b4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AZ-900 Exam Study Notes #2]]></title>
            <link>https://medium.com/@rojasjimenezjosea/az-900-exam-study-notes-2-faaee758fe21?source=rss-d049fd9e8668------2</link>
            <guid isPermaLink="false">https://medium.com/p/faaee758fe21</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[José Rojas]]></dc:creator>
            <pubDate>Sat, 18 Nov 2023 13:16:28 GMT</pubDate>
            <atom:updated>2023-11-18T13:16:28.262Z</atom:updated>
            <content:encoded><![CDATA[<h4>Sharing my personal study notes about Azure AZ-900 — High availability</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LE9bnUyuAK5Oi6E-SyNJtg.png" /></figure><h3>High Availability</h3><p>High Availability refers to the assurance of consistent performance under temporary load fluctuations or service, hardware, or datacenter failures.</p><p>To guarantee high availability for your applications Azure offers tree kind of services: Availablility Set, Availability Zones and Paired Regions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*9jpb7F2FvgBYDZ0dNHvFDw.png" /><figcaption><a href="https://learn.microsoft.com/en-us/azure/architecture/aws-professional/regions-zones">https://learn.microsoft.com/en-us/azure/architecture/aws-professional/regions-zones</a></figcaption></figure><h4>Availability set</h4><ul><li><strong>Definition</strong>: an Availability set is a logical grouping of virtual machines (VMs) within a datacenter to ensure high availability and reliability.</li><li><strong>Purpose</strong>: VMs within an availability set are placed in different physical racks. This distribution helps protect against hardware failures or maintenance events, ensuring that at least one VM is available.</li><li><strong>Example</strong>: If a hardware failure impacts one VM, the others in the set, located in different physical racks, remain unaffected.</li></ul><h4>Availability zone</h4><ul><li><strong>Definition</strong>: an Availability zone is one or more physically separate datacenter within a region. Each zone is designed with its own independent power sources, networks, and cooling infrastructure to enhance resilience.</li><li><strong>Purpose</strong>: by deploying resources across availability zones, users can ensure high availability and protect against localised failures. The multiple datacenter within each zone operate independently, reducing the risk of widespread outages.</li><li><strong>Example</strong>: an application deployed across multiple availability zones benefits from the redundancy and isolation of datacenter, minimising the impact of failures on overall service availability.</li></ul><h4>Paired Region</h4><ul><li><strong>Definition</strong>: a region is a geographically dispersed area offering a set of Azure services and includes multiple Availability Zones. Paired regions are two regions located at least 300 miles apart, each with its own set of Availability Zones.</li><li><strong>Purpose</strong>: Paired regions are strategically separated to ensure that large-scale disasters only impact one region in the pair, while neighbouring pairs allow for data and service synchronisation.</li><li><strong>Example</strong>: deploying an application across multiple regions, with the support of Azure Traffic Manager, improves availability. Paired regions offer geo-redundancy, with data automatically backed up to the appropriate paired region for enhanced data protection.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/0*5KQXuy30KjYcTtZ-.png" /><figcaption><a href="https://learn.microsoft.com/en-us/azure/architecture/high-availability/building-solutions-for-high-availability">https://learn.microsoft.com/en-us/azure/architecture/high-availability/building-solutions-for-high-availability</a></figcaption></figure><h4>Summary</h4><p>The following table summarise the aspect discussed above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*xUVz3MFLphnSEcujAqQ1CA.png" /><figcaption><a href="https://learn.microsoft.com/en-us/azure/architecture/aws-professional/regions-zones">https://learn.microsoft.com/en-us/azure/architecture/aws-professional/regions-zones</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faaee758fe21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AZ-900 Exam Study Notes #1]]></title>
            <link>https://medium.com/@rojasjimenezjosea/az-900-exam-study-notes-1-3327267d4cde?source=rss-d049fd9e8668------2</link>
            <guid isPermaLink="false">https://medium.com/p/3327267d4cde</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[study]]></category>
            <dc:creator><![CDATA[José Rojas]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 05:02:02 GMT</pubDate>
            <atom:updated>2023-11-15T05:02:02.800Z</atom:updated>
            <content:encoded><![CDATA[<h4>Sharing my personal study notes about Azure AZ-900 — Fundamentals cloud concepts</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8LuXko99JsmDnqsTYnG6Wg.png" /></figure><p>Recently, I’ve decided to take the Exam “AZ-204: Developing Solutions for Microsoft Azure” but every journey begins with the first step. Before I can start the preparation for the aforementioned exam I recognise the importance of gaining a solid foundation by preparing for the “AZ-900: Microsoft Azure Fundamentals”. Understanding the fundamentals is crucial; just as it would be challenging to comprehend polymorphism without knowledge of variable declaration, it would be difficult to develop solutions for Azure without a clear understanding of what Azure is.</p><p>In this first article of the series, I will highlight the concepts that were more important to me to understand when approaching this subject.</p><h3>Fundamental cloud concepts</h3><h4>What is the cloud?</h4><p>Cloud computing is the on-demand availability of computing resources for your personal or business use, billed on a pay-as-you-go model.</p><h4>What is Azure?</h4><p>Azure is the Microsoft public cloud computing platform.</p><h4>What is serverless?</h4><p>A cloud model where the provider sets up and manages servers, letting developers concentrate on app building rather than infrastructure management.</p><h3>Everything as a Service</h3><p>There are three basic concepts to get familiar with: Infrastructure as a Service (<strong>IaaS</strong>), Plastform as a Service (<strong>PaaS</strong>) and Software as a Service (<strong>SaaS</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_H9tcQ00EQ1EmlbnLAcQVw.jpeg" /><figcaption><a href="https://azure.microsoft.com/en-us/resources/cloud-computing-dictionary/what-is-paas/">https://azure.microsoft.com/en-us/resources/cloud-computing-dictionary/what-is-paas/</a></figcaption></figure><h4><strong>Infrastructure as a Service (IaaS)</strong></h4><p>IaaS is a cloud computing service model where a cloud services provider delivers computing resources. The provider furnishes storage, networking, servers, and virtualisation.</p><p><strong>Services</strong>: Azure Virtual Machines (VMs), Azure Blob Storage, Azure Virtual Network, Azure Disk Storage, Azure VPN Gateway,</p><h4><strong>Platform as a Service (PaaS)</strong></h4><p>PaaS simplifies the process of setting up and managing computing platforms and applications in the cloud, eliminating the need for users to handle infrastructure complexities.</p><p><strong>Services</strong>: Azure App Service, Azure Functions, Azure SQL Database, Azure Logic Apps, Azure Kubernetes Service (AKS).</p><h4><strong>Software as a Service (SaaS)</strong></h4><p>SaaS is a subscription-based software licensing and delivery model where the software is centrally hosted.</p><p><strong>Services</strong>: Microsoft 365, Dynamics 365.</p><h4><strong>Responsibilities</strong></h4><p>Depending on the service, certain aspect would be managed by Azure while others would be responsibility of the user. The image below shows how responsibilities are distributed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*T2fgQejk227lpEHQcNr1jg.png" /><figcaption><a href="https://learn.microsoft.com/en-us/azure/security/fundamentals/shared-responsibility">https://learn.microsoft.com/en-us/azure/security/fundamentals/shared-responsibility</a></figcaption></figure><h3>Conclusion</h3><p>To get familiar with the correct cloud lexicon I recommend to visit the <a href="https://azure.microsoft.com/en-us/resources/cloud-computing-dictionary/">official Microsoft documentation</a>.</p><p>In the next article of this series I will share my notes about the concept of high availability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3327267d4cde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lucene.NET: Facets — made simple]]></title>
            <link>https://medium.com/@rojasjimenezjosea/lucene-net-facets-made-simple-1de9e2cdc314?source=rss-d049fd9e8668------2</link>
            <guid isPermaLink="false">https://medium.com/p/1de9e2cdc314</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[José Rojas]]></dc:creator>
            <pubDate>Sun, 12 Nov 2023 22:11:58 GMT</pubDate>
            <atom:updated>2023-11-13T14:12:04.248Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lucene.NET: Facets — made simple</h3><h4>Faceted Search: elevate user experience with a feature your users will truly love</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*72Y8SAJYr61QPP36FSKAdQ.png" /></figure><h3><strong>What are Facets?</strong></h3><p>Facets in Lucene.NET are useful for categorising documents and using such categories to filter search results.</p><p>In a practical example, you could have a document representing a product, which belongs to a category such as ‘Furniture’ or ‘Technology.’ Enabling the category field as a facet will empower your users to efficiently filter products based on their categories, streamlining the search experience.</p><p>Nowadays, every e-commerce site incorporates some sort of facet mechanism. As you can imagine, even the popular online bookstore Amazon has this feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A69eOD5CudgmH4ALWJMBHg.png" /></figure><p>However, implementing facets manually is not recommended due to the inherent complexities involved. The process requires intricate logic for categorising and aggregating data, leading to code that is both error-prone and challenging to maintain. Custom implementations often struggle to scale efficiently as datasets grow, resulting in potential performance issues. Maintenance becomes a concern as changes in data models or facet requirements demand extensive modifications to the codebase. Specialised search engine libraries like <strong>Lucene.NET</strong>, designed for handling large datasets, offer optimised performance and a range of features beyond basic facet implementation.</p><p>Your users expect this feature to filter their search results, and certainly, you are eager to provide it to them, aren’t you?</p><h3><strong>Enabling facets with the SearchLibrary</strong></h3><p>In my journey of exploring the Lucene.NET search engine, I’m implementing a reusable library to help avoid the repetition of boilerplate code when willing to use a particular feature of Lucene.NET.</p><p>In my opinion, the most effective way to enable the library users to set up the facets mechanism is by providing an easy-to-implement way to configure the fields and apply the facets filters.</p><h4>Configuration</h4><p>You can easily enable a property by annotating it with the FacetProperty attribute. For instance, in the Movie class, the TitleType property is designated as a facet:</p><pre>public class Movie : IDocument<br>{<br>    ...<br>    [FacetProperty]<br>    public string TitleType { get; set; }<br>    ...<br>}</pre><p>For properties of type string[], such as the Genres property, you not only add the FacetProperty attribute but also configure the field as a multivalued field:</p><pre>public class Movie : IDocument<br>{<br>    ...<br>    [FacetProperty]<br>    public string[] Genres { get; set; }<br>    ...<br>}</pre><p>To correctly configure the multivalued field, refer to the MoviesConfiguration class, implementing IIndexConfiguration&lt;Movie&gt;. Here, the FacetConfiguration property specifies the multivalued field, ensuring that facets work seamlessly:</p><pre>public class MoviesConfiguration : IIndexConfiguration&lt;Movie&gt;<br>{<br>    public string IndexName =&gt; &quot;movies-index&quot;;<br><br>    public FacetConfiguration&lt;Movie&gt;? FacetConfiguration =&gt; new()<br>    {<br>        MultiValuedFields = new[] { nameof(Movie.Genres) }<br>    };<br>}</pre><p>By following this simple configuration approach, you empower users to efficiently set up and use the facets mechanism for a more refined search experience.</p><h4>Applying the facets to search</h4><p>In a context of REST API, the first component responsible for retrieving facets from the user is the controller, which would extracts them from the query parameters. To prevent a long list of parameters, I will encapsulate the fields for the facets in a dedicated class:</p><pre>public class MoviesQuery : QueryParameters<br>{<br>    public string[]? TitleTypeFacets { get; set; }<br>    <br>    public string[]? GenreFacets { get; set; }<br>}</pre><p>This gives the opportunity to the client to send a list of TitlesType and Genre to be used as filters.</p><p>In Swagger, this is simply done adding a string item to the field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7qTR5Q6N91MLO-6EBYe_SQ.png" /></figure><p>This will send the following GET request:<br>curl -X &#39;GET&#39; \<br> &#39;https://lucenenet-search.azurewebsites.net/api/movies/search?TitleTypeFacets=tvMovie&amp;GenreFacets=Drama&amp;GenreFacets=Romance&#39; \<br> -H &#39;accept: */*&#39;</p><p>The ASP.NET Core framework is that claver that it will bind the query parameters to the correct properties of the MoviesQuery object.</p><p>The must send the list of filters in the correct format to the search library by constructing a dictionary. The dictionary has the field name as the key associated with the received list of values.</p><pre>private static IDictionary&lt;string, IEnumerable&lt;string?&gt;?&gt; GetFacets(MoviesQuery query)<br>{<br>        var facets = new Dictionary&lt;string, IEnumerable&lt;string?&gt;?&gt;();<br>        if (query.GenreFacets != null)<br>        {<br>            facets.Add(nameof(Movie.Genres), query.GenreFacets);<br>        }<br><br>        if (query.TitleTypeFacets != null)<br>        {<br>            facets.Add(nameof(Movie.TitleType), query.TitleTypeFacets);<br>        }<br><br>        return facets;<br> }</pre><pre>public SearchResult&lt;Movie&gt; FullTextSearchMovies(SearchMovieQuery query)<br>{<br>    var facets = GetFacets(query);<br>    return _searchEngine.Search(new FullTextSearchQuery<br>    {<br>        SearchTerm = query.Term,<br>        PageNumber = query.PageNumber,<br>        PageSize = query.PageSize,<br>        Facets = facets<br>    });<br>}</pre><p>Voilà! Facet filter enabled in a glimpse!</p><h4>Facets results</h4><p>The SearchResult&lt;T&gt; exposes the found facets in the Facets field structured in this way:</p><pre>public class FacetFilter<br>{<br>    /// &lt;summary&gt;<br>    /// Facet name<br>    /// &lt;/summary&gt;<br>    public string Name { get; set; }<br>    <br>    /// &lt;summary&gt;<br>    /// Facet values<br>    /// &lt;/summary&gt;<br>    public IEnumerable&lt;FacetValue&gt;? Values { get; set; }<br>}<br><br><br>public class FacetValue<br>{<br>    /// &lt;summary&gt;<br>    /// Value associated with the facet<br>    /// &lt;/summary&gt;<br>    public string? Value { get; set; }<br>    <br>    /// &lt;summary&gt;<br>    /// Number of documents associated with the facet value<br>    /// &lt;/summary&gt;<br>    public int Count { get; set; }<br>}<br></pre><p>The json format for the client will be the one below and should be straightforward for any client.</p><pre>{<br>    &quot;items&quot;: [...],<br>    &quot;pageNumber&quot;: 0,<br>    &quot;pageSize&quot;: 10,<br>    &quot;totalItems&quot;: 19440,<br>    &quot;totalPages&quot;: 1944,<br>    &quot;facets&quot;: [<br>        {<br>            &quot;name&quot;: &quot;TitleType&quot;,<br>            &quot;values&quot;: [<br>                {<br>                    &quot;value&quot;: &quot;tvMovie&quot;,<br>                    &quot;count&quot;: 19440<br>                }<br>            ]<br>        },<br>        ..<br>    ]<br>}</pre><p>Again, I’m always impressed and eager to highlight the outstanding performance of Lucene.NET. In fact, it was able to drill down into the 2 million indexed documents and filter those with ‘TitleType’ as ‘tvMovie’ and ‘Genre’ as either ‘Drama’ or ‘Romance,’ providing a response in less than 400 ms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iVENILxT25kGlo92hAUK0A.png" /></figure><h3>Conclusion</h3><p>The implemented behavior of the facets may not be optimal for every application, but at this stage, enabling the library with this capability sets the fundamentals to extend the code, making it more flexible while maintaining an easy-to-use public API.</p><p>As usual, you are welcome to explore the code in <a href="https://github.com/rojasjo/FullTextSearchDemo">Github</a> and play with the example application on <a href="https://lucenenet-search.azurewebsites.net/swagger/index.html">Azure</a>.</p><h3>🚀 Enjoy! 🚀</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1de9e2cdc314" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C# Search library powered by LUCENE.NET]]></title>
            <link>https://medium.com/@rojasjimenezjosea/c-search-library-powered-by-lucene-net-238026614107?source=rss-d049fd9e8668------2</link>
            <guid isPermaLink="false">https://medium.com/p/238026614107</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[lucene]]></category>
            <dc:creator><![CDATA[José Rojas]]></dc:creator>
            <pubDate>Sun, 05 Nov 2023 00:09:47 GMT</pubDate>
            <atom:updated>2023-11-05T00:09:47.885Z</atom:updated>
            <content:encoded><![CDATA[<h4>Discover the ease of using the search library by implementing ASP.NET Core Web APIs for searching movies and evaluate its performance.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rY9zOd-1-SP24K7zsqcDZA.png" /></figure><h3>🚀 New features 🚀</h3><p>First of all, let me illustrate the latest features added to the search library powered by Lucene.NET:</p><ul><li><strong>Update</strong>: it is now possible to update the document in the Lucene Index by simply calling the update method: _searchEngine.Update(product);</li><li><strong>Delete</strong>: a missing feature was the ability to delete a document from the Lucene Index, which now can be easely achieved by calling the Remove method: _searchEngine.Remove(product);</li><li><strong>Pagination</strong>: the search method now returns a data structure with the pagination information for the given query:</li></ul><pre>public class SearchResult&lt;T&gt; where T : IDocument<br>{<br>    /// &lt;summary&gt;<br>    /// The list of items found by the search query.<br>    /// &lt;/summary&gt;<br>    public IEnumerable&lt;T&gt; Items { get; init; }<br>    <br>    /// &lt;summary&gt;<br>    /// The page number from which the items are retrieved.<br>    /// &lt;/summary&gt;<br>    public int PageNumber { get; init; }    /// &lt;summary&gt;<br>    /// The number of items contained on each page.<br>    /// &lt;/summary&gt;<br>    public int PageSize { get; init; }    /// &lt;summary&gt;<br>    /// The total count of items that match the search query.<br>    /// &lt;/summary&gt;<br>    public int TotalItems { get; init; }<br><br>    /// &lt;summary&gt;<br>    /// The total number of pages based on the total item count and page size.<br>    /// &lt;/summary&gt;<br>    public int TotalPages =&gt; (int)Math.Ceiling(TotalItems / (double)PageSize);<br>}</pre><ul><li><strong>Clear</strong>: it removes all documents from the index.</li><li><strong>AddRange: </strong>it provides an efficient way to add a collection of documents to a Lucene index in a single operation. This batching approach minimises the performance impact associated with frequent disk I/O operations and improves indexing speed, making it particularly useful when updating or inserting a large number of documents.</li></ul><h3>The ASP.NET Core Web APIs</h3><p>To demonstrate the versatility, precision and speed of using the Lucene.NET search engine, I’ll build an a API to search movies, using different configuration to compare the results.</p><p>The movies that will be indexed and searched are retrieved from the IMDb Non-Commercial Datasets (<a href="https://developer.imdb.com/non-commercial-datasets/">https://developer.imdb.com/non-commercial-datasets/</a>). For this demonstration, I’ll be using the title.basics.tsv.gz dataset, which contains over 800MB of data related to 10,000,000 of movies.</p><h3>Configuration</h3><p>To be able to use the search library I’ve to create a class representing the movie and implementing the ÌDocument interface.</p><p>Here you can see the Movie model:</p><pre>public class Movie : IDocument<br>{<br>    public string UniqueKey =&gt; TConst;<br>    <br>    public string TConst { get; set; }<br>    <br>    public string TitleType { get; set; }<br>    <br>    public string PrimaryTitle { get; set; }<br>    <br>    public string OriginalTitle { get; set; }<br>    <br>    public bool IsAdult { get; set; }<br>    <br>    public int StartYear { get; set; }<br>    <br>    public int? EndYear { get; set; }<br>    <br>    public int? RuntimeMinutes { get; set; }<br>    <br>    public string[] Genres { get; set; }<br>}</pre><p>The next step is to implement the IIndexConfiguration interface to configure the path to the folder that will contain the Lucene index.</p><pre>public class MoviesConfiguration : IIndexConfiguration&lt;Movie&gt;<br>{<br>    public string IndexName =&gt; &quot;movies-index&quot;;<br>}</pre><p>The last configuration step is to register the the SearchEngine service:</p><pre>builder.Services.AddSearchEngineServices(new MoviesConfiguration());</pre><h3>Adding the data to the index</h3><p>There are several way to add the data to the index, but in this example, we will use the background service provided by ASP.NET Core in order to perform a batch import when the application starts.</p><p>Due to the size of the dataset, which includes more than 10 million movies, a full import can take a considerable amount of time. To reduce the waiting time, the import will process the first 2,000,000 movies and should be completed in less than 5 minutes.</p><pre>public class MovieImporterService : BackgroundService<br>{<br>    private readonly ISearchEngine&lt;Movie&gt; _searchEngine<br>    <br>    public MovieImporterService(IServiceScopeFactory scopeFactory)<br>    {<br>        using var scope = scopeFactory.CreateScope();<br>        _searchEngine = scope.ServiceProvider.GetRequiredService&lt;ISearchEngine&lt;Movie&gt;&gt;();<br>    }<br><br>    protected override async Task ExecuteAsync(CancellationToken stoppingToken)<br>    {<br>        var result = _searchEngine.Search(new AllFieldsSearchQuery());<br><br>        if (result.TotalItems &gt; 0)<br>        {<br>            return;<br>        }<br><br>        var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, &quot;Data&quot;, &quot;title.basics.tsv&quot;);<br>        var index = 0;<br><br>        using var reader = new StreamReader(filePath);<br>        var batch = new List&lt;Movie&gt;();<br><br>        while (await reader.ReadLineAsync(stoppingToken) is { } line)<br>        {<br>            //skip headers<br>            if (index == 0)<br>            {<br>                index++;<br>                continue;<br>            }<br><br>            try<br>            {<br>                batch.Add(GetMovie(line));<br>            }<br>            catch<br>            {<br>                //skip invalid lines<br>            }<br><br>            if (index % 500_000 == 0)<br>            {<br>                _searchEngine.AddRange(batch);<br>                batch.Clear();<br>            }<br><br>            index++;<br><br>            if (index &gt; 2_000_000)<br>            {<br>                break;<br>            }<br>        }<br>    }<br><br>    private static Movie GetMovie(string line)<br>    {<br>        var fields = line.Split(&#39;\t&#39;);<br><br>        if (fields.Length &lt; 9)<br>        {<br>            Console.WriteLine($&quot;Error: Insufficient fields - {line}&quot;);<br>            throw new Exception();<br>        }<br><br>        try<br>        {<br>            return new Movie<br>            {<br>                TConst = fields[0],<br>                TitleType = fields[1],<br>                PrimaryTitle = fields[2],<br>                OriginalTitle = fields[3],<br>                IsAdult = fields[4] == &quot;1&quot;,<br>                StartYear = ParseInt(fields[5]),<br>                EndYear = ParseInt(fields[6]),<br>                RuntimeMinutes = ParseInt(fields[7]),<br>                Genres = fields[8].Split(&#39;,&#39;),<br>            };<br>        }<br>        catch<br>        {<br>            Console.WriteLine($&quot;Error: {line}&quot;);<br>            throw;<br>        }<br>    }<br><br>    private static int ParseInt(string value)<br>    {<br>        var result = ParseNullableInt(value);<br>        return result ?? 0;<br>    }<br><br>    private static int? ParseNullableInt(string value)<br>    {<br>        if (value == @&quot;\N&quot; || string.IsNullOrWhiteSpace(value))<br>        {<br>            return null;<br>        }<br><br>        if (int.TryParse(value, out var result))<br>        {<br>            return result;<br>        }<br><br>        return null;<br>    }</pre><p>In order to execute this procedure the MovieImporterService must be resgistered as Hosted Service.</p><pre>builder.Services.AddHostedService&lt;MovieImporterService&gt;();</pre><h3>The MoviesController</h3><p>The movies Rest API will allow users to search movies based on specific fields or search a term across all fields in the Movie model. Therefore, it is necessary to handle all parameters cleanly. Using the GetMoviesQuery class as parameter for our API will result in a cleaner method signature, avoiding a lengthy list of query parameters.</p><pre>public class GetMoviesQuery : QueryParameters<br>{<br>    <br>    public string? TitleType { get; set; }<br>    <br>    public string? PrimaryTitle { get; set; }<br>    <br>    public string? OriginalTitle { get; set; }<br>    <br>    public bool? IsAdult { get; set; }<br>    <br>    public int? StartYear { get; set; }<br>    <br>    public int? EndYear { get; set; }<br>    <br>    public int? RuntimeMinutes { get; set; }<br>    <br>    public string[]? Genres { get; set; }<br>}</pre><p>The GetMovies method can be developed as shown below:</p><pre>    [HttpGet]<br>    public IActionResult GetMovies([FromQuery] GetMoviesQuery query)<br>    {<br>        try<br>        {<br>            var searchFields = new Dictionary&lt;string, string?&gt;();<br><br>            if (query.PrimaryTitle != null)<br>            {<br>                searchFields.Add(nameof(query.PrimaryTitle), query.PrimaryTitle);<br>            }<br>            <br>            //...<br>            //check if other query parameteres have been set or not<br>            //...<br>            <br>            var result = _searchEngine.Search(new FieldSpecificSearchQuery<br>            {<br>                SearchTerms = searchFields,<br>                Type = SearchType.PrefixMatch,<br>                PageNumber = query.PageNumber,<br>                PageSize = query.PageSize<br>            });<br>            <br>            return Ok(result);<br>        }<br>        catch (Exception ex)<br>        {<br>            return StatusCode(500, $&quot;Error: {ex.Message}&quot;);<br>        }<br>    }</pre><p>The search method can be implemented easily as follow:</p><pre>    [HttpGet(&quot;search&quot;)]<br>    public IActionResult SearchMovies([FromQuery] SearchMovieQuery query)<br>    {<br>        try<br>        {<br>            var result = _searchEngine.Search(new AllFieldsSearchQuery<br>            {<br>                SearchTerm = query.Term,<br>                Type = SearchType.PrefixMatch,<br>                PageNumber = query.PageNumber,<br>                PageSize = query.PageSize<br>            });<br><br>            return Ok(result);<br>        }<br>        catch (Exception ex)<br>        {<br>            return StatusCode(500, $&quot;Error: {ex.Message}&quot;);<br>        }<br>    }</pre><p>And also the fulltextsearch endpoint is easy to implement:</p><pre>    [HttpGet(&quot;fulltextsearch&quot;)]<br>    public IActionResult FullTextSearchMovies([FromQuery] SearchMovieQuery query)<br>    {<br>        try<br>        {<br>            var result = _searchEngine.Search(new FullTextSearchQuery<br>            {<br>                SearchTerm = query.Term,<br>                PageNumber = query.PageNumber,<br>                PageSize = query.PageSize<br>            });<br>            <br>            return Ok(result);<br>        }<br>        catch (Exception ex)<br>        {<br>            return StatusCode(500, $&quot;Error: {ex.Message}&quot;);<br>        }<br>    }</pre><p>Note that the FullTextSearchQuery doesn&#39;t allow the user to configure the type of search. This is because it is preconfigured to use a combination of the Fuzzy search and the Wildcard search in order to provide as mays results as possible. Due to the use of the wildcard operator the query can be very slow.</p><h3>API timing</h3><p>Now that the index a good amount of data is time to test the API response time.</p><p>Locally, by calling the search endpoint with the term “ada” and requiring 2000 items per page we will be able to obtain the 1467 movies in almost half second:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vdHQ_-QkiLLAYBcH2QOPaQ.png" /></figure><p>Whereas, when we test it on Azure, the result takes much time to be retrieved, about 2.5 seconds to get the same result. Most likely, this difference in performance is due to the limited hardware used by the App Service: it is using the F1 free plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*45BQhAcm6BH5r26K21lrFQ.png" /></figure><p>On the other hand, by making the same request to the fulltexstsearch endpoint the results, 2000 movies, will be given in almost 700 ms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VB5zDwQT8vdmo1RtGaqa5w.png" /></figure><h3>Summary</h3><p>In this article, we have explored how to import a large amount of data into the Lucene Index using its batch update feature, taking full advantage of its impressive performance. Achieving the import of 2 million records in less than 5 minutes is truly remarkable.</p><p>Additionally, we have configured and implemented the REST API for searching movies and evaluated its performance using Postman.</p><p>We learned that using the wildcard operator can lead to performance issues and that it should be used only in specific scenarios where the user expects the query to take some time.</p><h3>What’s next</h3><p>To gain more insight into the library built around Lucene.NET, I am planning to benchmark its implementation in the coming weeks. Additionally, I will work on improving the configurability of the query to address more advanced scenarios.</p><p>As always, you can access the code in <a href="https://github.com/rojasjo/FullTextSearchDemo">GitHub</a> and experiment with it on <a href="https://lucenenet-search.azurewebsites.net/swagger/index.html">Azure</a>.</p><h4>🚀 Enjoy! 🚀</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=238026614107" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AAA Unit Testing]]></title>
            <link>https://medium.com/@rojasjimenezjosea/aaa-unit-testing-688e3e61902a?source=rss-d049fd9e8668------2</link>
            <guid isPermaLink="false">https://medium.com/p/688e3e61902a</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[nunit]]></category>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[José Rojas]]></dc:creator>
            <pubDate>Sun, 29 Oct 2023 10:45:38 GMT</pubDate>
            <atom:updated>2023-10-29T10:57:15.612Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guideline to write triple A unit tests with NUnit</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dkdKbJO1GzD6Ja8w6Z7uOA.png" /></figure><p>The quality of our code is important because it can be the difference between a success company and a big failure. There are many examples of companies that had to shutdown their businesses because the codebase was too complex to add new functionalities or correct malfunctions.</p><p>A effective way to avoid such scenario and maintain code quality is to utilise unit tests. Some might argue: “They are difficult to write! Implement them is time-consuming! We don’t do that in this company.” The list of excuses to avoid writing them goes on and on, just as the list of bugs in the backlog does.</p><p>Unit tests are not written for the sake of adding more code but to validate the correctness of the production code. Just as you expect pharmaceutical companies to conduct rigorous testing before selling drugs at your pharmacy, you must test the correctness of you software.</p><p>Unit tests are powerful because they enable the creation testing procedures that are repeatable and always executed in the same way, following the consistent steps.</p><p>Unit testing practices help improving the quality of the code because certain principles and tactics should be used to write effective.</p><h3><strong>AAA</strong></h3><p>AAA is the abbreviation of Arrange, Act and Assert. In a unit test those should be the only action that your code should perform and in this exact order.</p><ol><li><strong>Arrange</strong>: In this phase, you set up the initial conditions or context for the test. This includes creating objects, initializing variables, and configuring the environment to prepare it for the test. The goal of the Arrange phase is to establish the necessary state for the test scenario.</li><li><strong>Act</strong>: This is where you perform the specific action you want to test. It involves invoking the method or code that you are testing with the prepared setup from the Arrange phase.</li><li><strong>Assert</strong>: In the Assert phase, you verify the outcome of the action taken in the Act phase. This includes checking whether the method being tested produced the expected result or if the internal state of the system has changed as expected. If the actual outcome matches the expected outcome, the test passes; otherwise, it fails.</li></ol><h3>Test methods naming</h3><p>Test method naming conventions are essential in unit testing to provide clear, descriptive, and self-documenting names for your test cases.</p><ol><li><strong>Descriptive Method Names</strong>: test method names should be descriptive and reflect the behaviour or functionality being tested. A good practice is to start the name with the method or scenario you are testing. For example, “AddItem_WhenValidItemAdded” clearly indicates that the test is checking the “AddItem” behaviour when a valid item is added.</li><li><strong>Use Underscores</strong>: to improve readability, it’s common to use underscores to separate different parts of the method name. For example, “ReduceItem_WhenItemNotInItemsList” is readable and clear.</li><li><strong>Include Context or Condition</strong>: including the context or condition under which the test is being conducted is beneficial. It provides additional information about the scenario being tested. For instance, “WhenItemNotInItemsList” indicates a specific condition in the test scenario.</li><li><strong>Expected Outcome</strong>: it’s a good practice to include the expected outcome in the test method name. This helps convey the expected result of the test without having to inspect the test code itself. For example, “RemovesItem” indicates the test’s expected result.</li></ol><h3>Code example</h3><p>To better understand how to do this, let’s take a look at the ShoppingCart class and some of its tests.</p><pre>public class ShoppingCart<br>{<br>    private readonly ICollection&lt;CartItem&gt; _items;<br><br>    public IReadOnlyCollection&lt;CartItem&gt; Items =&gt; _items.ToList();<br><br>    public ShoppingCart()<br>    {<br>        _items = new List&lt;CartItem&gt;();<br>    }<br><br>    public void AddItem(Product product, int quantity)<br>    {<br>        if (product == null)<br>        {<br>            throw new ArgumentNullException(nameof(product));<br>        }<br><br>        if (quantity &lt;= 0)<br>        {<br>            throw new ArgumentException(&quot;Quantity must be greater than 0.&quot;, nameof(quantity));<br>        }<br><br>        var existingItem = Items.FirstOrDefault(item =&gt; item.Product.Id == product.Id);<br>        if (existingItem != null)<br>        {<br>            existingItem.Quantity += quantity;<br>        }<br>        else<br>        {<br>            _items.Add(new CartItem<br>            {<br>                Product = product,<br>                Quantity = quantity<br>            });<br>        }<br>    }<br><br>    public void ReduceItem(Product product, int quantity)<br>    {<br>        if (product == null)<br>        {<br>            throw new ArgumentNullException(nameof(product));<br>        }<br><br>        if (quantity &lt;= 0)<br>        {<br>            return;<br>        }<br><br>        var item = Items.FirstOrDefault(item =&gt; item.Product.Id == product.Id);<br>        if (item == null)<br>        {<br>            return;<br>        }<br><br>        item.Quantity -= quantity;<br><br>        if (item.Quantity &lt;= 0)<br>        {<br>            RemoveItem(product);<br>        }<br>    }<br><br>    public void RemoveItem(Product product)<br>    {<br>        if (product == null)<br>        {<br>            throw new ArgumentNullException(nameof(product));<br>        }<br><br>        var itemToRemove = Items.FirstOrDefault(item =&gt; item.Product.Id == product.Id);<br>        if (itemToRemove != null)<br>        {<br>            _items.Remove(itemToRemove);<br>        }<br>    }<br>}</pre><p>As you can see this ShoppingCart allow to keeping track of the products added to the shopping cart.</p><p>A simple but yet useful test is to verify the correctness of the implementation of the AddItem method.</p><pre>    [Test]<br>    public void AddItem_WhenValidItemAdded_ItemIsInCart()<br>    {<br>        // Arrange<br>        var product = new Product { Id = 1 };<br><br>        // Act<br>        _shoppingCart.AddItem(product, 2);<br><br>        // Assert<br>        var item = _shoppingCart.Items.FirstOrDefault(item =&gt; item.Product.Id == product.Id);<br>        Assert.That(item, Is.Not.Null);<br>        Assert.That(item!.Quantity, Is.EqualTo(2));<br>    }</pre><h4>Arrange</h4><p>In the Arrange phase, you set up the initial conditions for the test.</p><pre>// Arrange<br>var product = new Product { Id = 1 };</pre><p>Here, you create an instance of the Product class and assign it an Id of 1. This product will be used in the test to add it to the shopping cart.</p><h4>Act</h4><p>In the Act phase, you perform the action you want to test.</p><pre>// Act<br>_shoppingCart.AddItem(product, 2);</pre><p>Here, you call the AddItem method of the _shoppingCart object, which adds the product to the shopping cart with a quantity of 2.</p><h4>Assert</h4><p>In the Assert phase, you check whether the action taken in the Act phase produced the expected outcome.</p><pre>var item = _shoppingCart.Items.FirstOrDefault(item =&gt; item.Product.Id == product.Id);<br>Assert.That(item, Is.Not.Null);<br>Assert.That(item!.Quantity, Is.EqualTo(2));</pre><ol><li>In the first line of the Assert phase, you use LINQ to find an item in the shopping cart’s Items collection where the Product.Id matches the Id of the product added earlier. This is to verify that the product was indeed added to the shopping cart.</li><li>The second line of the Assert phase checks if the item found in the previous step is not null. This ensures that the item was indeed added to the shopping cart, and it exists.</li><li>The third line of the Assert phase checks if the quantity of the item (found in the Arrange phase) is equal to 2. This verifies that the quantity of the added product matches the expected quantity.</li></ol><h4>Conclusions</h4><p>Following the AAA pattern in your tests and using descriptive test method names are essential practices in unit testing. These principles not only make your tests more structured and easy to understand but also aid other developers in comprehending the purpose and expected outcomes of your tests. By adhering to these conventions, you promote clarity and maintainability in your test suite, ensuring that your tests remain a valuable tool for validating the correctness of your code.</p><p>If you like to see more test example you can visit: <a href="https://github.com/rojasjo/ShoppingChartTestsExample">https://github.com/rojasjo/ShoppingChartTestsExample</a></p><p>🚀 <strong>Enjoy!</strong> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=688e3e61902a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>