<?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 Lucas Garcia on Medium]]></title>
        <description><![CDATA[Stories by Lucas Garcia on Medium]]></description>
        <link>https://medium.com/@lucasgarciaz2018?source=rss-94c32c589123------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gQusVNHYyL32I0VBjab8SQ.png</url>
            <title>Stories by Lucas Garcia on Medium</title>
            <link>https://medium.com/@lucasgarciaz2018?source=rss-94c32c589123------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 11:32:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lucasgarciaz2018/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[Generating logs with log4net still great!]]></title>
            <link>https://medium.com/@lucasgarciaz2018/generating-logs-with-log4net-still-great-4cbfe0f25d1b?source=rss-94c32c589123------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cbfe0f25d1b</guid>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[log4net]]></category>
            <dc:creator><![CDATA[Lucas Garcia]]></dc:creator>
            <pubDate>Sun, 09 Jul 2023 01:40:11 GMT</pubDate>
            <atom:updated>2023-07-12T11:44:51.313Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Logging plays a crucial role in any software development project, allowing your system to capture and analyze information about the execution of the programs. In the .NET environment, there are several logging tools and packages out there as you might have noticed already, but there’s one that has remained popular among developers since many years. This one in question is </em><strong><em>Apache’s</em></strong><em> l</em><strong><em>og4net!</em></strong></p><p><em>In this article, we will explore the importance of logging in general, discuss the available options I&#39;ve mentioned, and understand why log4net continues to be a relevant and valuable solution. Furthermore, we will provide a step-by-step implementation guide for using this package in your own NET application.</em></p><p><em>Let’s move on!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y7FxtuCparMHIWnmho-xbw.png" /></figure><h3>🤔What is Logging and Why is it Important?</h3><p>Logging is basically the process of systematically recording events, actions, results, exceptions and any other types of messages about what’s happening with your code during the execution of an application. It’s like writing a full report of the whole situation, so developers can understand when the software is being successful or not to improve and fix elusive bugs that can eventually happen (and believe me, they will happen!)</p><p>Logs can also provide valuable insights into how to identify performance bottlenecks, and track down other user’s behavior and preferences. In general, as you can see logging is pretty essential for monitoring any application, ensuring regulatory compliance, and analyzing what’s wrong.</p><p>Now you’re already understanding the importance of choosing a robust logging framework, right? So let’s expand this view and see which solutions we have for .NET environment…</p><h3>📦Interesting packages to take a look!</h3><p>Well, if you’re working in .NET environment, you will have access to various logging frameworks and related tools, each with its own strengths and downsides. Some of the most notable logging packages available in <a href="http://nuget.org/"><strong>Nuget Gallery</strong></a> includes <em>NLog</em>, <em>Serilog</em>, <em>Microsoft.Extensions.Logging</em>, and off course <strong><em>log4net</em></strong>.</p><p>Each one of these alternatives offers different levels of customization, performance, and integration capabilities. While each has its merits, <em>log4net </em>has maintained its relevance due to its extensive feature set, flexibility, and wide community support, since it’s been around for a long time so far. But before talking more about this package, let’s take a a deeper look on the other solutions:</p><h4>NLog:</h4><ul><li>Supports multiple logging targets, including files, databases, and more.</li><li>Rich set of layout <em>renderers </em>for formatting log messages.</li><li>Ability to configure logging rules and filters.</li><li>Contextual logging with Mapped Diagnostics Context (<em>MDC</em>) and Nested Diagnostics Context (<em>NDC</em>).</li><li>Integration with popular frameworks and platforms.</li></ul><h4>Serilog:</h4><ul><li>Rich support for structured logging with structured data and templates.</li><li>Easy configuration with a fluent API and flexible sink architecture.</li><li><em>Enrichers </em>to add contextual information to log events.</li><li>Sink libraries for various outputs, including files, databases, and cloud storage.</li><li>Easy integration with popular logging frameworks and platforms.</li></ul><h4><strong>Microsoft.Extensions.Logging: Pros:</strong></h4><ul><li>Support for logging levels, including Trace, Debug, Information, Warning, Error, and Critical.</li><li>Configuration options for filtering log messages.</li><li>Integration with dependency injection through <em>ILoggerFactory</em>.</li><li>Built-in providers for various outputs, including console, debug, and event log.</li><li>Ability to create custom loggers and providers for specific needs.</li></ul><p><strong><em>Remember, these are just brief summaries, and the suitability of each logging framework depends on your specific requirements and preferences. It’s always a good idea to explore the documentation and try out different options to determine which one best fits your project.</em></strong></p><h3>💡So why to still choose log4net?</h3><ol><li><strong>Mature and Battle-Tested:</strong> It has been around for more than two decades, making it one of the most mature logging frameworks ever for .NET environment. It has been extensively used and tested in numerous production environments, ensuring its stability and reliability so far.</li><li><strong>Flexibility and Customization:</strong> provides a highly configurable setup, allowing developers to fine-tune logging behavior based on their specific requirements. <em>Log4net</em> works based in different <em>appenders </em>that you can configure in your<em> .config </em>file. It also offers other options for layouts, filters, and loggers, enabling developers to customize the logging output to suit their project’s needs.</li><li><strong>Extensive Documentation and Community Support:</strong> As was mentioned before, it’s been around for so long and so it can benefits from a vast and active community that provides support, shares best practices, and contributes to its ongoing development. The framework’s documentation is comprehensive, which makes easy for you to understand and leverage its capabilities effectively.</li><li><strong>Integration Capabilities:</strong> seamlessly integrates with other popular frameworks and libraries, keeping it’s simple <em>.config</em> file based setup. This , is by far the best thing about <em>log4net</em>. It can be easily integrated into <em>ASP.NET</em>, Windows services, console applications, and more, providing consistent and centralized logging across the entire application stack.</li></ol><h3>📖And how to use log4net in your application?</h3><p><strong>Step 1:</strong> Create a new configuration file named <em>“log4net.config” </em>in your project.</p><p><strong>Step 2:</strong> Copy and paste this <em>XML</em> basic configuration into the <em>“log4net.config”</em> file.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;<br>&lt;configuration&gt;<br>  &lt;configSections&gt;<br>    &lt;section name=&quot;log4net&quot; type=&quot;log4net.Config.Log4NetConfigurationSectionHandler, log4net&quot; /&gt;<br>  &lt;/configSections&gt;<br><br>  &lt;log4net&gt;<br>    &lt;appender name=&quot;ConsoleAppender&quot; type=&quot;log4net.Appender.ConsoleAppender&quot;&gt;<br>      &lt;layout type=&quot;log4net.Layout.PatternLayout&quot;&gt;<br>        &lt;conversionPattern value=&quot;%date [%thread] %-5level %logger [%property{NDC}] - %message%newline&quot; /&gt;<br>      &lt;/layout&gt;<br>    &lt;/appender&gt;<br><br>    &lt;root&gt;<br>      &lt;level value=&quot;ALL&quot; /&gt;<br>      &lt;appender-ref ref=&quot;ConsoleAppender&quot; /&gt;<br>    &lt;/root&gt;<br>  &lt;/log4net&gt;<br>&lt;/configuration&gt;</pre><p><strong>Step 3: </strong>Make sure that your log4net configuration section is defined inside the <em>“configSections”</em> tag.</p><pre>&lt;configSections&gt;<br>  &lt;section name=&quot;log4net&quot; type=&quot;log4net.Config.Log4NetConfigurationSectionHandler, log4net&quot; /&gt;<br>&lt;/configSections&gt;</pre><p><strong>Step 4:</strong> Now you can add appenders for different logging purposes. In this case, we have<em> “ConsoleAppender”</em>(which is the basic logger for console), and we added <em>“InfoLogsFile”</em>(for information logs), <em>“ErrorLogsFile”</em>(for general bug logs), and <em>“FatalLogsFile”</em>(for critical system exception logs).</p><p>Each appender can have a specific configuration, including the file path (where the log file will be saved), the file type, size and the filter range. For example, the<em> “InfoLogsFile” </em>appender is configured as this:</p><pre>&lt;appender name=&quot;InfoLogsFile&quot; type=&quot;log4net.Appender.RollingFileAppender&quot;&gt;<br>  &lt;layout type=&quot;log4net.Layout.PatternLayout&quot;&gt;<br>    &lt;conversionPattern value=&quot;%date [%thread] %-5level %logger - %message%newline&quot; /&gt;<br>  &lt;/layout&gt;<br>  &lt;file value=&quot;${APPDATA}\MyApp\Logs\InformationsLogs.log&quot; /&gt;<br>  &lt;appendToFile value=&quot;true&quot; /&gt;<br>  &lt;rollingStyle value=&quot;Size&quot; /&gt;<br>  &lt;maxSizeRollBackups value=&quot;10&quot; /&gt;<br>  &lt;maximumFileSize value=&quot;5MB&quot; /&gt;<br>  &lt;staticLogFileName value=&quot;true&quot;/&gt;<br>  &lt;filter type=&quot;log4net.Filter.LevelRangeFilter&quot;&gt;<br>    &lt;levelMin value=&quot;INFO&quot; /&gt;<br>    &lt;levelMax value=&quot;INFO&quot; /&gt;<br>  &lt;/filter&gt;<br>&lt;/appender&gt;</pre><h4><strong>🧩Lets break this step down to understand:</strong></h4><ol><li>The type <em>RollingFile</em> means that the log files are created and managed in a <strong>cyclical</strong> manner. When a log file reaches a certain size or time limit, it is <strong>rolled over or archived</strong>, and a new log file is created to continue logging new events:</li></ol><pre>type=&quot;log4net.Appender.RollingFileAppender&quot;</pre><p>2. This is basically the log messages text format. In this case it will write the current date (when the message was generated), the specific thread, which logging level it happened(ALL, DEBUG, INFO, WARN, ERROR, FATAL, etc)</p><pre>&lt;conversionPattern value=&quot;%date [%thread] %-5level %logger - %message%newline&quot; /&gt;</pre><p>3. Then we defined the log file path for this logger, we said we wanted to write it to a log file, which will have a rolling rule based on file size, defined the maximum archived log files for this level to be 10 files and 5MB each. We also choose to have a static name for the log files (so only the backup files will have different names as they are archived )</p><pre>&lt;file value=&quot;${APPDATA}\MyApp\Logs\InformationsLogs.log&quot; /&gt;<br>  &lt;appendToFile value=&quot;true&quot; /&gt;<br>  &lt;rollingStyle value=&quot;Size&quot; /&gt;<br>  &lt;maxSizeRollBackups value=&quot;10&quot; /&gt;<br>  &lt;maximumFileSize value=&quot;5MB&quot; /&gt;<br>  &lt;staticLogFileName value=&quot;true&quot;/&gt;</pre><p>4. In the end of our <em>InfoLogsFile </em>appender configuration, we setup a new filter based on the levels I’ve mentioned before. In this case this logger will be specific for INFO level.</p><pre>&lt;filter type=&quot;log4net.Filter.LevelRangeFilter&quot;&gt;<br>    &lt;levelMin value=&quot;INFO&quot; /&gt;<br>    &lt;levelMax value=&quot;INFO&quot; /&gt;<br>  &lt;/filter&gt;</pre><p><em>Do the same proccess for any logger you want to use in your application. You can also customize other properties as needed, for more information check the</em><strong><em> </em></strong><a href="https://logging.apache.org/log4net/release/manual/configuration.html"><strong><em>official documentation</em></strong></a></p><p><strong>Step 5: </strong>To finish our configuration , define the root logger and register the <em>appender </em>for each logging level that will be used:</p><pre>&lt;root&gt;<br>  &lt;level value=&quot;ALL&quot; /&gt;<br>  &lt;appender-ref ref=&quot;ConsoleAppender&quot; /&gt;<br>  &lt;appender-ref ref=&quot;InfoLogsFile&quot; /&gt;<br>  &lt;appender-ref ref=&quot;ErrorLogsFile&quot; /&gt;<br>  &lt;appender-ref ref=&quot;FatalLogsFile&quot; /&gt;<br>&lt;/root&gt;</pre><p>In this example, the root logger will be managing all levels and using the registered <em>appenders </em>to generate separate log files based on the filters.</p><p>In the end, your configuration file should looks like this:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;<br>&lt;configuration&gt;<br>  &lt;configSections&gt;<br>    &lt;section name=&quot;log4net&quot; type=&quot;log4net.Config.Log4NetConfigurationSectionHandler, log4net&quot; /&gt;<br>  &lt;/configSections&gt;<br><br>  &lt;log4net&gt;<br>    &lt;appender name=&quot;ConsoleAppender&quot; type=&quot;log4net.Appender.ConsoleAppender&quot;&gt;<br>      &lt;layout type=&quot;log4net.Layout.PatternLayout&quot;&gt;<br>        &lt;conversionPattern value=&quot;%date [%thread] %-5level %logger [%property{NDC}] - %message%newline&quot; /&gt;<br>      &lt;/layout&gt;<br>    &lt;/appender&gt;<br><br>    &lt;appender name=&quot;InfoLogsFile&quot; type=&quot;log4net.Appender.RollingFileAppender&quot;&gt;<br>      &lt;layout type=&quot;log4net.Layout.PatternLayout&quot;&gt;<br>        &lt;conversionPattern value=&quot;%date [%thread] %-5level %logger - %message%newline&quot; /&gt;<br>      &lt;/layout&gt;<br>      &lt;file value=&quot;${APPDATA}\MyApp\Logs\InformationsLogs.log&quot; /&gt;<br>      &lt;appendToFile value=&quot;true&quot; /&gt;<br>      &lt;rollingStyle value=&quot;Size&quot; /&gt;<br>      &lt;maxSizeRollBackups value=&quot;10&quot; /&gt;<br>      &lt;maximumFileSize value=&quot;5MB&quot; /&gt;<br>      &lt;staticLogFileName value=&quot;true&quot;/&gt;<br>      &lt;filter type=&quot;log4net.Filter.LevelRangeFilter&quot;&gt;<br>        &lt;levelMin value=&quot;INFO&quot; /&gt;<br>        &lt;levelMax value=&quot;INFO&quot; /&gt;<br>      &lt;/filter&gt;<br>    &lt;/appender&gt;<br><br>    &lt;appender name=&quot;ErrorLogsFile&quot; type=&quot;log4net.Appender.RollingFileAppender&quot;&gt;<br>      &lt;layout type=&quot;log4net.Layout.PatternLayout&quot;&gt;<br>        &lt;conversionPattern value=&quot;%date [%thread] %-5level %logger - %message%newline&quot; /&gt;<br>      &lt;/layout&gt;<br>      &lt;file value=&quot;${APPDATA}\MyApp\Logs\GeneralErrorsLogs.log&quot; /&gt;<br>      &lt;appendToFile value=&quot;true&quot; /&gt;<br>      &lt;rollingStyle value=&quot;Size&quot; /&gt;<br>      &lt;maxSizeRollBackups value=&quot;10&quot; /&gt;<br>      &lt;maximumFileSize value=&quot;5MB&quot; /&gt;<br>      &lt;staticLogFileName value=&quot;true&quot;/&gt;<br>      &lt;filter type=&quot;log4net.Filter.LevelRangeFilter&quot;&gt;<br>        &lt;levelMin value=&quot;ERROR&quot; /&gt;<br>        &lt;levelMax value=&quot;ERROR&quot; /&gt;<br>      &lt;/filter&gt;<br>    &lt;/appender&gt;<br><br>    &lt;appender name=&quot;FatalLogsFile&quot; type=&quot;log4net.Appender.RollingFileAppender&quot;&gt;<br>      &lt;layout type=&quot;log4net.Layout.PatternLayout&quot;&gt;<br>        &lt;conversionPattern value=&quot;%date [%thread] %-5level %logger - %message%newline&quot; /&gt;<br>      &lt;/layout&gt;<br>      &lt;file value=&quot;${APPDATA}\MyApp\Logs\FatalErrorsLogs.log&quot; /&gt;<br>      &lt;appendToFile value=&quot;true&quot; /&gt;<br>      &lt;rollingStyle value=&quot;Size&quot; /&gt;<br>      &lt;maxSizeRollBackups value=&quot;10&quot; /&gt;<br>      &lt;maximumFileSize value=&quot;5MB&quot; /&gt;<br>      &lt;staticLogFileName value=&quot;true&quot;/&gt;<br>      &lt;filter type=&quot;log4net.Filter.LevelRangeFilter&quot;&gt;<br>        &lt;levelMin value=&quot;FATAL&quot; /&gt;<br>        &lt;levelMax value=&quot;FATAL&quot; /&gt;<br>      &lt;/filter&gt;<br>    &lt;/appender&gt;<br><br>    &lt;root&gt;<br>      &lt;level value=&quot;ALL&quot; /&gt;<br>      &lt;appender-ref ref=&quot;ConsoleAppender&quot; /&gt;<br>      &lt;appender-ref ref=&quot;InfoLogsFile&quot; /&gt;<br>      &lt;appender-ref ref=&quot;ErrorLogsFile&quot; /&gt;<br>      &lt;appender-ref ref=&quot;FatalLogsFile&quot; /&gt;<br>    &lt;/root&gt;<br>  &lt;/log4net&gt;<br>&lt;/configuration&gt;</pre><p><strong>Step 6: </strong>Lets create the logging class. First we create the enum (to verify the log types) and an interface to be implemented.</p><pre>namespace MyApp.LogServices.Models.Enum<br>{<br>  public enum LogType<br>  {<br>    Info,<br>    Error,<br>    Fatal<br>  }<br>}</pre><pre>using MyApp.LogServices.Models.Enum;<br><br>namespace MyApp.LogServices.Models<br>{<br>    public interface ILoggerService<br>    {<br>        string LogMessage { get; set; }<br>        LogType LogType { get; set; }<br><br>        void InfoLog(string message);<br>        void ErrorLog(string message, Exception ex);<br>    }<br>}</pre><p><strong>Step 7: </strong>Now implement the class based on the models. This class will be responsible to load the <em>.config</em> file and instantiate our logging service with the proper parameters. It also will implement the logger methods for each level (in this case ERROR, INFO and FATAL.</p><pre>using log4net;<br>using System;<br>using System.IO;<br>using MyApp.LogServices.Models;<br>using MyApp.LogServices.Models.Enums;<br>using System.Security;<br><br>namespace MyApp.LogServices.ModelsImplementation<br>{<br>    public class LoggerService : ILoggerService<br>    {<br>        public readonly ILog Logger;<br>        public readonly string LogPath;<br>        public string LogMessage { get; set; }<br>        public LogType LogType { get; set; }<br>        public static LoggerService Instance;<br><br>        public LoggerService(LogType logType)<br>        {<br>            LogType = logType;<br><br>            log4net.Config.XmlConfigurator.Configure(new FileInfo(&quot;log4net.config&quot;));<br><br>            switch (LogType)<br>            {<br>                case LogType.Info:<br>                    Logger = LogManager.GetLogger(&quot;InfoLogger&quot;);<br>                    break;<br>                case LogType.Error:<br>                    Logger = LogManager.GetLogger(&quot;ErrorLogger&quot;);<br>                    break;<br>                case LogType.Fatal:<br>                    Logger = LogManager.GetLogger(&quot;FatalLogger&quot;);<br>                    break;<br>            }<br><br>            LogPath = Path.Combine(LogHelper.AppDataFolder, &quot;Logs&quot;);<br><br>            Instance = this;<br>        }<br><br>        public LogType? GetLogTypeBasedOnEx(Exception ex)<br>        {<br>            LogType? result = null;<br>            if (IsFatalException(ex))<br>            {<br>                result = LogType.Fatal;<br>            }<br>            else<br>            {<br>                result = LogType.Error;<br>            }<br><br>            return result;<br>        }<br><br>        private bool IsFatalException(Exception ex)<br>        {<br>            return ex is SystemException ||<br>                ex is InvalidOperationException ||<br>                ex is SecurityException ||<br>                ex is OutOfMemoryException ||<br>                ex is StackOverflowException ||<br>                ex is AccessViolationException ||<br>                ex is DivideByZeroException ||<br>                ex is NullReferenceException;<br>        }<br><br>        public void InfoLog(string message)<br>        {<br>            if (LogType is LogType.Info)<br>                Logger.Info(message);<br>        }<br><br>        public void FatalLog(string message, Exception ex)<br>        {<br>            if (LogType is LogType.Fatal &amp;&amp; IsFatalException(ex))<br>                Logger.Fatal(message, ex);<br>        }<br><br>        public void ErrorLog(string message, Exception ex)<br>        {<br>            if (LogType is LogType.Error)<br>                Logger.Error(message, ex);<br>        }<br>    }<br>}</pre><p><strong>Step 8: </strong>We can now create an extension class to provide a better way to call and execute the loggers.</p><pre>using MyApp.LogServices.Models.Enums;<br><br>namespace MyApp.LogServices.ModelsImplementation<br>{<br>    public static class LogExtensions<br>    {<br>        public static void GenerateErrorLog(this LoggerService logger, string message, Exception ex)<br>        {<br>            logger = new LoggerService(LogType.Error);<br>            logger.ErrorLog(message, ex);<br>        }<br><br>        public static void GenerateFatalLog(this LoggerService logger, string message, Exception ex)<br>        {<br>            logger = new LoggerService(LogType.Fatal);<br>            logger.FatalLog(message, ex);<br>        }<br><br>        public static void GenerateInfoLog(this LoggerService logger, string message)<br>        {<br>            logger = new LoggerService(LogType.Info);<br>            logger.InfoLog(message);<br>        }<br>}</pre><p><strong>Step 9: </strong>Finally, you can use the class trough the extension methods, using a single unique instance like this and everytime we must use another logger, the extension class itself will mange this for you:</p><pre>using MyApp.LogServices.Models.Enums;<br>using MyApp.LogServices.ModelsImplementation;<br>using System;<br><br>namespace MyApp.Example<br>{<br>    public class Program<br>    {<br>        private static readonly LogService _log = LogService.Instance;<br><br>        public static void Main(string[] args)<br>        {<br>            try<br>            {<br>                // Example usage of log extensions<br><br>                // Error log<br>                _log.GenerateErrorLog(&quot;An unexpected error occurred.&quot;, new Exception(&quot;Example error&quot;));<br><br>                // Fatal log<br>                _log.GenerateFatalLog(&quot;A fatal error occurred.&quot;, new Exception(&quot;Example fatal error&quot;));<br><br>                // Info log<br>                _log.GenerateInfoLog(&quot;Example information log&quot;);<br>            }<br>            catch (Exception ex)<br>            {<br>                // Handle any errors that occur while logging<br>                Console.WriteLine($&quot;Error while logging: {ex.Message}&quot;);<br>            }<br>        }<br>    }<br>}</pre><p>Done! As you can see you have a great alternative in hands with <em>log4net. </em>It can be a bit different in the begining, specially if you’re not into XML files so it can feel older, but in the end what really matters is that logging remains a crucial aspect of software development, and <strong>log4net continues to be a relevant and powerful </strong>logging framework for .NET and shouldn’t be forgotten. Its maturity, reliability and flexibility, still makes it a preferred choice for many developers!</p><p><strong>Please note that this is a simplified example, and in real-world scenarios, you may need to configure additional settings, or perform more advanced operations based on your requirements.</strong></p><p>Don’t forget to connect with me on <a href="https://www.linkedin.com/in/lucasmggarcia22/"><strong>Linkedin</strong></a>… See you next time<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FWT7O2N2GlYKR5ZpHXk5XA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cbfe0f25d1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Mediator pattern and MediaTR in NET]]></title>
            <link>https://medium.com/@lucasgarciaz2018/using-mediator-pattern-and-cqrs-in-net-2a2e71cca0e1?source=rss-94c32c589123------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a2e71cca0e1</guid>
            <category><![CDATA[mediator]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[cqrs]]></category>
            <category><![CDATA[mediatr]]></category>
            <dc:creator><![CDATA[Lucas Garcia]]></dc:creator>
            <pubDate>Sun, 18 Jun 2023 15:33:05 GMT</pubDate>
            <atom:updated>2023-06-23T15:49:00.984Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using Mediator pattern with MediaTR in NET</h3><p><em>In this article, I wanna share what I’ve learned so far about Mediator pattern and its implementation with </em><a href="https://www.nuget.org/packages/MediatR"><strong><em>MediatR </em></strong></a><em>in </em><strong><em>NET 5+</em></strong><em>. With this package, we will get a helping hand to unlock all the capacity of </em><strong><em>Command Query Responsibility Segregation (CQRS) </em></strong><em>pattern.</em></p><p><em>Making a quick analogy with a theater, </em><strong><em>the Mediator pattern</em></strong><em> acts like a director, seamlessly orchestrating communication between actors on stage. Similarly, in the sphere of software, this pattern allows components to interact without direct knowledge of each other using a system of requests, handlers and responses. <br>With its help, we’ll create an architecture that is both flexible and decoupled. 🎭</em></p><p><em>We’ll also explore a bit of </em><strong><em>CQRS</em></strong><em>, a pattern that segregates </em><strong><em>read</em></strong><em> and </em><strong><em>write </em></strong><em>operations into </em><strong><em>separate paths</em></strong><em>. <br>Here we can make another analogy with a restaurant, where commands for ordering food and queries for checking the menu items have distinct queues.🍱</em></p><p><em>By separating these operations, CQRS empowers us with enhanced performance, scalability, and flexibility, making it a valuable addition to our software toolkit.</em></p><p><em>So,put on your director’s hat, and let’s know more about this duo!🔀</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9-c_bQU6HqZU59sJpadSvw.png" /></figure><h3>🚨Just a Disclaimer:</h3><p>Mediator pattern <strong>IS NOT</strong> the same thing as CQRS, they are not bounded. But you can use MediaTR to help you when working with CQRS pattern, since it helps you segregate your read (with queries) and write (with commands) models.</p><h3>🤔 When to Use the Mediator Pattern?</h3><p>The Mediator pattern shines when you have a complex system with multiple components and different types of queries and operations, that need to communicate with each other. It promotes loose coupling and simplifies the relationships between these components.</p><p>For example, you can imagine a shopping application with various subsystems such as inventory management, order processing, and payment handling. By applying the Mediator pattern, each subsystem can communicate through a central mediator, enabling easier extensibility and reducing direct dependencies.</p><h3>🤔When to Use CQRS?</h3><p>CQRS becomes valuable when you’re dealing with a system that has a high separation between read and write operations. If you have diferent needs for each operation types, such as optimizing read performance or enabling event sourcing, CQRS can be a game-changer.</p><p>Using the previous example of a shopping application, that needs to handle a high volume of read operations for product browsing while dont really need to use writing operations for placing orders, at the same frequency. If you use CQRS in this scenario, you can have dedicated read models optimized for fast queries and write models focused on maintaining data integrity and business rules.</p><h3>📖 Implementing MediatR and CQRS in NET:</h3><h4>📦 Step 1: Setting Up the Project</h4><p>Start by creating a new .NET 5+ <strong>web api project</strong>. Once the project is set up, install the <a href="https://www.nuget.org/packages/MediatR"><strong>MediatR NuGet</strong></a> package:</p><pre>dotnet new webapi</pre><pre>dotnet add package MediatR</pre><p>Now you will be able to import the necessary resources from <em>MediaTR </em>namespace.</p><h4>🧩Step 2: Define the Entity Class</h4><p>In this case, lets use a class “Person” as example. Create a “Person” class representing the entity you want to work with. For simplicity, let’s consider it has properties like “Id,” “Name,” and “Age.”</p><pre>public class Person<br>{<br>    public int Id { get; set; }<br>    public string Name { get; set; }<br>    public int Age { get; set; }<br>}</pre><h4>🎭 Step 3: Create the MediatR Requests and Commands</h4><p>Lets define the <strong>requests </strong>and <strong>commands </strong>that represents the operations you want to perform on the “Person” entity. In this example, we’ll create a “<em>CreatePersonCommand</em>” (command to perform POST actions) and a “<em>GetPersonQuery</em>” (request to perform GET actions).</p><p><strong>Requests: </strong>Used to perform actions that fetches entities from the database, such as <strong>GET </strong>(Get All Entities, Get By Id , etc) and <strong>DELETE </strong>(since its also just a query)<strong> </strong>operations;</p><p><strong>Commands</strong>: Used to perform actions that manipulate entities in the database , such as <strong>POST </strong>and<strong> UPDATE </strong>operations;</p><pre>public class CreatePersonCommand : IRequest&lt;int&gt;<br>{<br>    public string Name { get; set; }<br>    public int Age { get; set; }<br>}<br></pre><pre>public class GetPersonQuery : IRequest&lt;Person&gt;<br>{<br>    public int PersonId { get; set; }<br>}</pre><h4>💾 Step 4: Implement the Repository</h4><p>Create an interface for the person repository and implement it with a concrete class. The repository will handle the data access operations for the “Person” entity.</p><pre>public interface IPersonRepository<br>{<br>    Task AddPerson(Person person);<br>    Task&lt;Person&gt; GetPersonById(int personId);<br>}</pre><pre>public class PersonRepository : IPersonRepository<br>{<br>    private readonly List&lt;Person&gt; _persons = new List&lt;Person&gt;();<br>    public async Task AddPerson(Person person)<br>    {<br>        _persons.Add(person);<br>        await Task.CompletedTask;<br>    }<br>    public async Task&lt;Person&gt; GetPersonById(int personId)<br>    {<br>        return await Task.FromResult(_persons<br>        .FirstOrDefault(p =&gt; p.Id == personId));<br>    }<br>}</pre><h4>🙌Step 5: Implement the MediatR Handlers</h4><p>Now, lets create the corresponding handlers for the requests and commands. These handlers will contain the logic to handle the operations defined in the requests.</p><p><em>PS: </em><a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken?view=net-7.0"><strong><em>CancellationToken </em></strong></a><em>is a standard feature to make sure if something go wrong during the operation handling, it will be canceled.</em></p><pre>public class CreatePersonCommandHandler : IRequestHandler&lt;CreatePersonCommand, int&gt;<br>{<br>    private readonly IPersonRepository _personRepository;<br><br>    public CreatePersonCommandHandler(IPersonRepository personRepository)<br>    {<br>        _personRepository = personRepository;<br>    }<br>    public async Task&lt;int&gt; Handle(CreatePersonCommand request, CancellationToken cancellationToken)<br>    {<br>        var person = new Person { Name = request.Name, Age = request.Age };<br>        await _personRepository.AddPerson(person);<br>        return person.Id;<br>    }<br>}</pre><pre>public class GetPersonQueryHandler : IRequestHandler&lt;GetPersonQuery, Person&gt;<br>{<br>    private readonly IPersonRepository _personRepository;<br>    public GetPersonQueryHandler(IPersonRepository personRepository)<br>    {<br>        _personRepository = personRepository;<br>    }<br>    public async Task&lt;Person&gt; Handle(GetPersonQuery request, CancellationToken cancellationToken)<br>    {<br>        return await _personRepository.GetPersonById(request.PersonId);<br>    }<br>}</pre><h4>💉 Step 6: Register Dependencies in Dependency Injection</h4><p>In the startup class of your application, register MediatR and the repositories in the <strong>dependency injection</strong> container, which is your start up configuration file:</p><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    services.AddMediatR(typeof(Startup));<br>    services.AddScoped&lt;IPersonRepository, PersonRepository&gt;();<br>}</pre><ol><li>services.AddMediatR(typeof(Startup)): Adds MediatR to the dependency injection container. <br>The typeof(Startup) parameter specifies the assembly where MediatR should scan for request and handler types that are mean to be registered. So in this case it will scan the Startup class and register all the request and handler types found.</li><li>services.AddScoped&lt;IPersonRepository, PersonRepository&gt;(): Registers the IPersonRepository interface and its implementation PersonRepository with a <strong>scoped lifetime</strong>. It means that an instance of PersonRepository will be created per scope (typically per HTTP request) and will be shared within that scope.</li></ol><h4>🎮Step 7: Implement the Controllers and API Endpoints</h4><p>Create a controller to handle <strong>HTTP</strong> requests and use MediatR to execute the corresponding <strong>requests </strong>or <strong>commands</strong>. In this example, we’ll create a “PersonController.”</p><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class PersonController : ControllerBase<br>{<br>    private readonly IMediator _mediator;<br>    public PersonController(IMediator mediator)<br>    {<br>        _mediator = mediator;<br>    }<br>    [HttpPost]<br>    public async Task&lt;ActionResult&lt;int&gt;&gt; CreatePerson(CreatePersonCommand command)<br>    {<br>        var personId = await _mediator.Send(command);<br>        return Ok(personId);<br>    }<br>    [HttpGet(&quot;{personId}&quot;)]<br>    public async Task&lt;ActionResult&lt;Person&gt;&gt; GetPerson(int personId)<br>    {<br>        var query = new GetPersonQuery { PersonId = personId };<br>        var person = await _mediator.Send(query);<br>        return Ok(person);<br>    }<br>}</pre><p>The CreatePerson method of the PersonController is a HTTP POST request. Its received with a payload containing the details to create a person. <br>The CreatePersonCommand object represents the request to create a person and contains the necessary data based on the <em>Person</em> class .</p><p>The command object is passed to the IMediator instance (_mediator) using the .Send method. The .Send method is a generic method provided by <strong>MediatR </strong>that allows you to send a request to its <strong>corresponding handler (</strong>in this case<strong><em> </em></strong><em>CreatePersonCommandHandler</em><strong>) </strong>and retrieve the result (which in this case will be an <em>int</em> value representing the Id of the newly created <em>Person</em>).</p><p>Once the handler completes its execution and returns the personId, theOk method is called to return an <em>HTTP 200 OK</em> response with the personId as the result.</p><p>Similarly, the .Send method is used in the GetPerson method to send a GetPersonQuery request and retrieve the <em>Person</em> object based on the provided personId. Returning also an <em>HTTP 200 OK</em> response with the person object person as result.</p><p><strong><em>In summary, the </em></strong><strong><em>.Send method of MediatR is responsible for dispatching requests to their respective handlers, allowing for loose coupling and centralized handling of requests and responses.</em></strong></p><h4>🔔Step 9: Implementing Notifications</h4><p>In addition to handling commands and queries, MediatR also provides a way to implement a notification system. Notifications allow you to broadcast messages to other parts of your system. <br>Let’s enhance our example by adding notifications for the CreatePersonCommand and GetPersonQuery requests.</p><p><strong>Step 9.1: Define the Notification Classes</strong></p><p>First, let’s define two notification classes: PersonCreatedNotification and PersonFetchedNotification. Since, its just a simple example, lets keep it simple, with a single basic property but have in mind you can create complex notification systems with MediaTR.</p><pre>public class PersonCreatedNotification : INotification<br>{<br>    public int PersonId { get; set; }<br>}</pre><pre>public class PersonFetchedNotification : INotification<br>{<br>    public int PersonId { get; set; }<br>}</pre><p><strong>Step 9.2: Implement Notification Handlers</strong></p><p>Next, create the new notification handlers to handle these notifications. Notification handlers can perform different actions based on the occurrence of a specific event. For example, we can also send an email or log a message when a person is created or fetched.</p><pre>public class PersonCreatedNotificationHandler : INotificationHandler&lt;PersonCreatedNotification&gt;<br>{<br>    public Task Handle(PersonCreatedNotification notification, CancellationToken cancellationToken)<br>    {<br>        try<br>        {<br>            // Perform actions like sending an email, logging, etc.<br>            Console.WriteLine($&quot;Person with ID {notification.PersonId} has been created.&quot;);<br>        }<br>        catch (Exception ex)<br>        {<br>            // Handle the exception or log the error<br>            Console.WriteLine($&quot;Error while handling PersonCreatedNotification: {ex.Message}&quot;);<br>        }<br><br>        return Task.CompletedTask;<br>    }<br>}</pre><pre>public class PersonFetchedNotificationHandler : INotificationHandler&lt;PersonFetchedNotification&gt;<br>{<br>    public Task Handle(PersonFetchedNotification notification, CancellationToken cancellationToken)<br>    {<br>        try<br>        {<br>            // Perform actions like sending an email, logging, etc.<br>            Console.WriteLine($&quot;Person with ID {notification.PersonId} has been fetched.&quot;);<br>        }<br>        catch (Exception ex)<br>        {<br>            // Handle the exception or log the error<br>            Console.WriteLine($&quot;Error while handling PersonFetchedNotification: {ex.Message}&quot;);<br>        }<br><br>        return Task.CompletedTask;<br>    }<br>}</pre><p><strong>Step 9.3: Register Notification Handlers</strong></p><p>Finally, register the notification handlers in the dependency injection container during the application startup.</p><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    services.AddMediatR(typeof(Startup));<br>    services.AddScoped&lt;IPersonRepository, PersonRepository&gt;();<br>    services.AddScoped&lt;INotificationHandler&lt;PersonCreatedNotification&gt;, PersonCreatedNotificationHandler&gt;();<br>    services.AddScoped&lt;INotificationHandler&lt;PersonFetchedNotification&gt;, PersonFetchedNotificationHandler&gt;();<br>}</pre><p>By registering the notification handlers, MediatR will automatically invoke these handlers when the corresponding notifications are dispatched. But this is not enough to call the notification system, for that we will need to update our controller.</p><p><strong>Step 9.4: Sending the Notifications in the Controller</strong></p><p>Once we’ve created the notification system, we can update the <em>PersonController</em> to <strong>Publish </strong>the notification messages:</p><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class PersonController : ControllerBase<br>{<br>    private readonly IMediator _mediator;<br><br>    public PersonController(IMediator mediator)<br>    {<br>        _mediator = mediator;<br>    }<br><br>    [HttpPost]<br>    public async Task&lt;ActionResult&lt;int&gt;&gt; CreatePerson(CreatePersonCommand command)<br>    {<br>        var personId = await _mediator.Send(command);<br><br>        // Send PersonCreatedNotification<br>        var notification = new PersonCreatedNotification { PersonId = personId };<br>        await _mediator.Publish(notification);<br><br>        return Ok(personId);<br>    }<br><br>    [HttpGet(&quot;{personId}&quot;)]<br>    public async Task&lt;ActionResult&lt;Person&gt;&gt; GetPerson(int personId)<br>    {<br>        var query = new GetPersonQuery { PersonId = personId };<br>        var person = await _mediator.Send(query);<br><br>        // Send PersonFetchedNotification<br>        var notification = new PersonFetchedNotification { PersonId = personId };<br>        await _mediator.Publish(notification);<br><br>        return Ok(person);<br>    }<br>}</pre><p>When the CreatePerson action is complete after the person is created, we create an instance of the PersonCreatedNotification and publish it using _mediator.Publish(notification). This MediaTR method will notify the system about the action that was executed, based on the notification type we desire.</p><p>The same way, in the GetPerson action, after fetching the person, we create an instance of the PersonFetchedNotification and also publish it using _mediator.Publish(notification).</p><p>The notifications will be handled by their respective notification handlers (PersonCreatedNotificationHandler and PersonFetchedNotificationHandler).</p><h4>✅Step 10: Test the Endpoints</h4><p>You can now test the endpoints by making HTTP requests to the respective routes. For example, sending a <strong>POST </strong>request to <strong>/api/person</strong> with a <em>JSON </em>payload containing the person&#39;s name and age will create a new person. Similarly, sending a <strong>GET </strong>request to <strong>/api/person/{personId}</strong> will retrieve the person information. For this you can use <a href="https://swagger.io/"><strong>Swagger</strong></a><strong> </strong>or another API test platform such as <a href="https://www.postman.com/"><strong>Postman</strong></a>.</p><p><strong>And that’s it! You have successfully implemented the Mediator pattern using MediatR in .NET ,</strong> incorporating repositories for data access and separating the read and write operations with the CQRS pattern. Feel free to expand on this foundation and explore more advanced scenarios.</p><p><strong>Please note that this is a simplified example, and in real-world scenarios, you may need to configure additional settings, mappings, or perform more advanced operations based on your requirements.</strong></p><p>Don’t forget to connect with me on <a href="https://www.linkedin.com/in/lucasmggarcia22/"><strong>Linkedin</strong></a>… See you next time<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_RwS2oZ5DOA1lW7Rw6i64A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a2e71cca0e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Elasticsearch and NEST in NET]]></title>
            <link>https://medium.com/@lucasgarciaz2018/using-elasticsearch-and-nest-in-net-9821f64cfa76?source=rss-94c32c589123------2</link>
            <guid isPermaLink="false">https://medium.com/p/9821f64cfa76</guid>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[nest]]></category>
            <dc:creator><![CDATA[Lucas Garcia]]></dc:creator>
            <pubDate>Fri, 02 Jun 2023 23:19:55 GMT</pubDate>
            <atom:updated>2023-06-18T01:54:29.244Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Elasticsearch</em></strong><em> is an amazing distributed search engine that can handle large volumes of data in real-time. It’s the perfect solution for developers who need advanced search capabilities like sorting, filtering, and text analysis. And the best part? You can easily use </em><strong><em>Elasticsearch in your .NET</em></strong><em> applications, thanks to the powerful client libraries available!</em></p><p><em>📚 The </em><strong><em>official </em></strong><a href="http://elasticsearch.net/"><strong><em>Elasticsearch.Net</em></strong></a><em> library is a low-level client library that provides support for multiple versions of Elasticsearch. But if you want a more user-friendly and object-oriented interface for interacting with Elasticsearch, then </em><a href="https://www.elastic.co/guide/en/elasticsearch/client/net-api/7.17/nest.html"><strong><em>NEST (Elasticsearch .NET)</em></strong></a><em> is the way to go! With NEST, you can map your .NET objects directly to document types in Elasticsearch, making it incredibly </em><strong><em>easy to index and retrieve data</em></strong><em>.</em></p><p><em>🚀 Getting started with Elasticsearch in .NET is a breeze. Simply add the corresponding </em><strong><em>NuGet package</em></strong><em> for the client library you want to use (like NEST), and you’re ready to go. And with this powerful tool at your disposal, you can </em><strong><em>easily build search functionality into your applications like never before</em></strong><em>.</em></p><p><strong>In this first part So lets go check this out …</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fhJUaMXAFcQH63A9iIheXg.png" /></figure><h3>Elasticsearch Features for .NET Applications</h3><p>Elasticsearch is a powerful search and analytics engine that offers a wide range of features for building robust applications. In this article, we’ll explore some of the key features provided by Elasticsearch and how they can be utilized in .NET applications. Let’s dive in!</p><h4>1. 🔍 Advanced Text Search</h4><p>Elasticsearch provides advanced text search capabilities, enabling you to perform complex and precise searches. You can utilize features like phrase matching, fuzzy search, prefix search, wildcard search, and proximity search to enhance your search experience.</p><pre>// Perform a fuzzy search for the term &quot;hello&quot; in the &quot;content&quot; field<br>var searchResponse = client.Search&lt;Person&gt;(s =&gt; s<br>    .Query(q =&gt; q<br>        .Match(m =&gt; m<br>            .Field(f =&gt; f.Content)<br>            .Query(&quot;hello&quot;)<br>            .Fuzziness(Fuzziness.Auto)<br>        )<br>    )<br>)</pre><p>In the context of Elasticsearch, a fuzzy search is a type of search that allows for approximate matching of terms rather than exact matching. It is particularly useful when you want to find results that are similar to a given term but may contain slight variations, such as spelling mistakes, transpositions, or missing characters.</p><p>When performing a fuzzy search, Elasticsearch analyzes the search term and looks for documents that have terms similar to the provided query term. It calculates a similarity score based on the <a href="https://medium.com/@ethannam/understanding-the-levenshtein-distance-equation-for-beginners-c4285a5604f0"><strong>Levenshtein distance algorithm</strong></a>, which measures the number of single-character edits required to transform one term into another.</p><h4>2. ⏰ Real-Time Indexing</h4><p>Elasticsearch is designed for real-time indexing and search scenarios. It can handle large volumes of data and provide fast results even in high-traffic situations.</p><pre>// Index a new document in real-time<br>var person = new Person { Id = 1, Name = &quot;John Doe&quot;, Age = 30 };<br>var indexResponse = client.IndexDocument(person);</pre><h4>3. ➕ Aggregations</h4><p>Aggregations in Elasticsearch allow you to perform real-time data analysis and summarization. You can calculate statistical metrics, perform grouping, extract unique values, create histograms, and more.</p><pre>// Perform a date histogram aggregation to analyze the distribution of documents over time<br>var searchResponse = client.Search&lt;Person&gt;(s =&gt; s<br>    .Aggregations(a =&gt; a<br>        .DateHistogram(&quot;documents_over_time&quot;, dh =&gt; dh<br>            .Field(f =&gt; f.Timestamp)<br>            .CalendarInterval(DateInterval.Month)<br>        )<br>    )<br>);</pre><h4>4. 🌍 Geospatial Search</h4><p>Elasticsearch provides built-in support for geospatial search and analysis. You can store points, shapes, and geographic polygons and perform proximity queries, region filtering, and distance calculations.</p><pre>// Perform a geo-distance query to find documents within a certain radius of a specific location<br>var searchResponse = client.Search&lt;Person&gt;(s =&gt; s<br>    .Query(q =&gt; q<br>        .GeoDistance(gd =&gt; gd<br>            .Field(f =&gt; f.Location)<br>            .Distance(&quot;10km&quot;)<br>            .Location(40.7128, -74.0060)<br>        )<br>    )<br>);</pre><h4>5. 📝 Text Analysis</h4><p>Elasticsearch offers powerful text analysis capabilities, including tokenization, filtering, normalization, and stemming. You have fine-grained control over how your documents are processed during indexing and search.</p><pre>// Define a custom analyzer with tokenizers and filters<br>var createIndexResponse = client.CreateIndex(&quot;my-index&quot;, c =&gt; c<br>    .Settings(s =&gt; s<br>        .Analysis(a =&gt; a<br>            .Tokenizers(t =&gt; t<br>                .Whitespace(&quot;my-tokenizer&quot;)<br>            )<br>            .Analyzers(an =&gt; an<br>                .Custom(&quot;my-analyzer&quot;, ca =&gt; ca<br>                    .Tokenizer(&quot;my-tokenizer&quot;)<br>                    .Filters(&quot;lowercase&quot;, &quot;stop&quot;, &quot;stemmer&quot;)<br>                )<br>            )<br>        )<br>    )<br>    .Map&lt;Person&gt;(m =&gt; m<br>        .Properties(p =&gt; p<br>            .Text(t =&gt; t<br>                .Name(&quot;content&quot;)<br>                .Analyzer(&quot;my-analyzer&quot;)<br>            )<br>        )<br>    )<br>);</pre><h4>6. 👁‍🗨Filters</h4><p>In addition to queries, Elasticsearch provides filters for document filtering based on specific criteria. Filters can be used to narrow down the search to a subset of documents or to apply additional constraints to the results.</p><pre>// Apply a filter to retrieve documents with an age greater than 30<br>var searchResponse = client.Search&lt;Person&gt;(s =&gt; s<br>    .Query(q =&gt; q<br>        .Bool(b =&gt; b<br>            .Filter(f =&gt; f<br>                .Range(r =&gt; r<br>                    .Field(f =&gt; f.Age)<br>                    .GreaterThan(30)<br>                )<br>            )<br>        )<br>    )<br>);</pre><p>These are just a few examples of the features provided by Elasticsearch. There are many more features available, such as suggestions, highlighting, sorting, data pipelines, and integrations with other popular tools. The<strong> </strong><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html"><strong>official Elasticsearch documentation</strong></a> is a great resource for more detailed information.</p><h3>NEST x Elasticsearch : Which to chose?</h3><p>When working with Elasticsearch in .NET applications, you have the option to use <strong>NEST (Elasticsearch .NET)</strong>, a <strong>high-level client library </strong>built on top of Elasticsearch.Net. While <strong>Elasticsearch.Net</strong> provides a <strong>low-level interface</strong> for Elasticsearch, NEST adds convenience, simplicity, and additional features that make working with Elasticsearch in .NET more developer-friendly. Here’s why you might consider using both NEST and Elasticsearch.Net:</p><h4><strong>1. </strong>🎯 Simplified API</h4><p>NEST offers a simplified and strongly-typed API that aligns with .NET conventions. Its <strong>fluent and intuitive</strong> syntax makes Elasticsearch operations easier to work with in .NET applications.</p><h4>2. 📚 Mapping to POCO objects</h4><p>NEST allows you to define <a href="https://en.wikipedia.org/wiki/Plain_old_CLR_object"><strong>Plain Old</strong> <strong>CLR Objects (POCOs)</strong></a> to represent your documents. It automatically maps these objects to Elasticsearch data structures, simplifying indexing and retrieval. Instead of dealing with JSON directly, you can work with familiar .NET objects.</p><h4>3. 🧩 LINQ support</h4><p>NEST integrates <strong>LINQ (Language Integrated Query)</strong> expressions, enabling you to write expressive queries using LINQ syntax. This facilitates complex querying, filtering, sorting, and aggregations on your data.</p><h4>4. 🧬 Serialization and deserialization</h4><p>NEST handles <strong>serialization and deserialization</strong> of .NET objects to JSON, ensuring seamless interaction with Elasticsearch. It offers configuration options for customizing serialization, such as ignoring properties, applying converters, and controlling field name mappings.</p><h4>5.🗄️ Index management</h4><p>NEST simplifies index management tasks like creating, deleting, and updating indexes. It provides methods and helpers for handling index settings, mappings, and aliases, allowing programmatic index management.</p><h4>6. ✅ Integration with other features</h4><p>NEST integrates with various Elasticsearch features like <strong>pipelines, analyzers, ingest nodes, and scripts</strong>. Dedicated methods and abstractions in NEST make these features easily accessible from your .NET application.</p><h4>7. 🔄 Compatibility and versioning</h4><p>NEST is designed to be compatible with specific Elasticsearch versions, ensuring you can leverage the latest Elasticsearch enhancements. It provides version-specific NuGet packages, <strong>allowing you to select the appropriate NEST version</strong> for your Elasticsearch version.</p><p>Using both NEST and Elasticsearch.Net together <strong>empowers </strong>you to benefit from NEST’s <strong>simplicity and convenience</strong> while retaining access to <strong>Elasticsearch.Net’s low-level capabilities</strong> when necessary.</p><p>In summary, NEST enhances Elasticsearch usage in .NET applications by providing <strong>a higher-level API with simplified syntax</strong>, POCO mapping, LINQ support, serialization/deserialization, index management, feature integration, and version compatibility. This combination of NEST and Elasticsearch.Net enables seamless and efficient Elasticsearch integration in your .NET projects. Check here the <a href="https://www.elastic.co/guide/en/elasticsearch/client/net-api/7.17/nest.html"><strong>official NEST documentation</strong></a></p><h3>Using Elasticsearch in a .NET 5+ Application</h3><h4>Step 1: Install Elasticsearch.Net and NEST packages</h4><ul><li>Open your .NET project in your preferred code editor.</li><li>Install the Elasticsearch.Net and NEST packages using NuGet Package Manager or the .NET CLI.</li><li>For NuGet Package Manager, search for “<a href="https://www.nuget.org/packages/Elasticsearch.Net"><strong>Elasticsearch.Net</strong></a>” and “<a href="https://www.nuget.org/packages/NEST"><strong>NEST</strong></a>” and install them.</li><li>For .NET CLI, navigate to your project directory and run the following commands:</li></ul><pre>dotnet add package Elasticsearch.Net</pre><pre>dotnet add package NEST</pre><h4>Step 2: Set up Elasticsearch connection settings</h4><ul><li>In your code, add the necessary namespaces:</li></ul><pre>using Elasticsearch.Net;<br>using Nest;</pre><ul><li>Create an instance of the Elasticsearch client by providing the appropriate Elasticsearch server URL:</li></ul><pre>var connectionSettings = new ConnectionSettings<br>(<br>  new Uri(&quot;http://localhost:9200&quot;)); <br>  ElasticClient elasticClient = new ElasticClient(connectionSettings<br>);</pre><h4>Step 3: Index a document</h4><ul><li>Define a class to represent your document:</li></ul><pre>public class Person <br>{ <br>  public int Id { get; set; }    <br>  public string Name { get; set; }    <br>  public int Age { get; set; }<br> }</pre><ul><li>Index a document by calling the IndexDocumentAsync method:</li></ul><pre>Person person = new Person { Id = 1, Name = &quot;John Doe&quot;, Age = 30 };<br>var indexResponse = await elasticClient.IndexDocumentAsync(person); <br><br>if (indexResponse.IsValid)<br>  Console.WriteLine(&quot;Document indexed successfully!&quot;); </pre><h4>Step 4: Search for documents</h4><ul><li>Perform a search query using the SearchAsync method:</li></ul><pre>var searchResponse = await elasticClient.SearchAsync&lt;Person&gt;(s =&gt; s<br>    .Query(q =&gt; q<br>        .Match(m =&gt; m<br>            .Field(f =&gt; f.Name)<br>            .Query(&quot;John&quot;)<br>        )<br>    )<br>);<br><br>foreach (var hit in searchResponse.Hits)<br>{<br>    Person person = hit.Source;<br>    Console.WriteLine($&quot;Name: {person.Name}, Age: {person.Age}&quot;);<br>}</pre><h4>Step 5: Handle errors and cleanup</h4><ul><li>Handle any potential errors by checking the IsValid property of the response object:</li></ul><pre>if (!indexResponse.IsValid)<br>{<br>    Console.WriteLine(&quot;Failed to index the document!&quot;);<br>    Console.WriteLine(indexResponse.ServerError?.ToString());<br>}</pre><ul><li>Dispose of the Elasticsearch client to release resources:</li></ul><pre>elasticClient.Dispose();</pre><p><strong>Remember to handle exceptions appropriately and customize the code based on your specific use case</strong>. This example demonstrates the basic steps of indexing a document and performing a search using Elasticsearch in a .NET 5+ application.</p><p><strong>Please note that this is a simplified example, and in real-world scenarios, you may need to configure additional settings, mappings, or perform more advanced operations based on your requirements.</strong></p><p>Don’t forget to connect with me on <a href="https://www.linkedin.com/in/lucasmggarcia22/"><strong>Linkedin</strong></a>… See you next time<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ct06FM0pkxmkr3dkh6DQxw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9821f64cfa76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Fluent Find Interface on NET]]></title>
            <link>https://medium.com/@lucasgarciaz2018/using-fluent-find-interface-on-net-3561e5650300?source=rss-94c32c589123------2</link>
            <guid isPermaLink="false">https://medium.com/p/3561e5650300</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[query]]></category>
            <dc:creator><![CDATA[Lucas Garcia]]></dc:creator>
            <pubDate>Mon, 15 May 2023 23:20:26 GMT</pubDate>
            <atom:updated>2023-05-15T23:25:41.993Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Fluent Find Interface</strong> is a powerful feature of the <strong><em>MongoDB .NET</em></strong> driver that allows developers to write concise and readable queries in a fluent syntax. By using this interface, developers can easily build complex queries and filter data from their <strong><em>MongoDB </em></strong>databases with just a few lines of code. In this article, we will explore the benefits of using <strong>Fluent Find Interface</strong> and walk through the steps to install and use it in a .NET application. Whether you are new to <em>MongoDB</em> or a seasoned developer, understanding how to use<strong> </strong>Fluent Find Interface can greatly enhance your productivity and make working with <em>MongoDB</em> more efficient.</p><p>In this tutorial, we will start by introducing Fluent Find Interface and its benefits. We will then walk through the process of installing the <a href="https://www.nuget.org/packages/mongodb.driver/"><strong>MongoDB .NET driver</strong></a> and setting up a sample<strong> <em>.</em>NET Core application</strong>. After that, we will dive into the specifics of using Fluent Find Interface to filter and query data in <em>MongoDB</em>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eo80fMF3a1_RELYXOhIFvw.png" /></figure><p>Fluent Find Interface was introduced in the <a href="https://www.mongodb.com/docs/drivers/csharp/current/"><strong><em>MongoDB .NET</em></strong> </a>driver <em>version 2.0.</em> This feature was designed to provide developers with a more <strong>efficient</strong> and <strong>intuitive </strong>way to query <em>MongoDB</em> databases in their .NET applications. With Fluent Find Interface, developers can write queries in a more <strong>readable and concise</strong> syntax, making it <strong>easier to build complex queries</strong> and filter data. The interface provides a fluent API that allows developers to chain multiple methods together to build complex queries with ease. Over the years, Fluent Find Interface has become a popular choice among developers for its ease of use and powerful query capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0KN0twiA4dc1nweYHWY-8Q.png" /></figure><p>To use Fluent Find Interface in a .NET application, you will need to install the <em>MongoDB .NET </em>driver. Here are the <strong>steps to get started</strong>:</p><ol><li><strong>Install the MongoDB .NET driver using the NuGet package manager.</strong></li></ol><pre>Install-Package MongoDB.Driver</pre><p>2. <strong>Create a new instance of the MongoClient class.</strong></p><pre>var client = new MongoClient(&quot;mongodb://localhost:27017&quot;);</pre><p>3. <strong>Get a reference to the database and collection you want to query.</strong></p><pre>var database = client.GetDatabase(&quot;myDatabase&quot;);<br>var collection = database.GetCollection&lt;MyDocument&gt;(&quot;myCollection&quot;);</pre><p>4. <strong>Use the Find method to query the collection and filter the data.</strong></p><pre>var filter = Builders&lt;MyDocument&gt;.Filter.Eq(x =&gt; x.Name, &quot;John&quot;);<br>var results = collection.Find(filter).ToList();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XpdnEN5a4SKBVxw6B8z3rw.png" /></figure><p>In this image example , we are building the query using a string that contains the category to be searched. Note that we need to concatenate the category into the query string, which can be less readable and more prone to typing errors than the clearer syntax of the Fluent Find Interface.</p><p>Furthermore, if we want to add more filter criteria, we would need to concatenate multiple strings to build the query, which can become quite confusing and error-prone.</p><p>With the Fluent Find Interface, on the other hand, we can easily and clearly add more filter criteria.</p><p>In conclusion, <strong>Fluent Find Interface is a game changer </strong>for querying data in MongoDB using .NET. Not only does it offer a more fluent and concise syntax, it also provides a wide range of powerful methods and options to make querying more efficient and performant.</p><p>Compared to using <strong>LINQ</strong>, Fluent Find Interface allows developers to take full advantage of MongoDB’s unique features and functionality. It also offers more flexibility and control over the queries being executed.</p><p>So, whether you’re a <strong>data wizard</strong> or a <strong>newbie </strong>to MongoDB, don’t be afraid to give Fluent Find Interface a try!</p><p>Don’t forget to connect with me on <a href="https://www.linkedin.com/in/lucasmggarcia22/">Linkedin</a>… See you next time<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F0qehUxtweQ6_ISzsHZjfw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3561e5650300" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Cloud NET APIs, integrated with React]]></title>
            <link>https://medium.com/@lucasgarciaz2018/building-cloud-net-apis-integrated-with-react-e64b9d9eb22?source=rss-94c32c589123------2</link>
            <guid isPermaLink="false">https://medium.com/p/e64b9d9eb22</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Lucas Garcia]]></dc:creator>
            <pubDate>Sun, 23 Apr 2023 01:52:41 GMT</pubDate>
            <atom:updated>2023-04-23T14:50:35.351Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Cloud NET APIs, integrated with React using Azure and Axios</h3><p>In today’s digital world, creating robust and scalable APIs is a crucial part of software development. To achieve this, many developers turn to cloud services to handle the heavy lifting of managing their APIs. One popular choice is Microsoft Azure, which provides an array of powerful tools for building and deploying cloud-based applications.</p><p>In this tutorial, we’ll explore how to build a .NET Web API integrated with React, leveraging Azure services such as Azure SQL Database and Azure Table. We’ll also be using <em>Axios</em>, a popular library for making HTTP requests, to consume our API. By the end of this tutorial, you’ll have a solid foundation for building your own cloud-based applications that integrate with React.</p><p>It’s important to have installed some useful extensions in your VS Code to make C# development easier. So try <a href="https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp">C#</a>, <a href="https://marketplace.visualstudio.com/items?itemName=jchannon.csharpextensions">C# Extensions</a>, <a href="https://marketplace.visualstudio.com/items?itemName=k--kato.docomment">C# XML Documentation</a>, <a href="https://marketplace.visualstudio.com/items?itemName=fernandoescolar.vscode-solution-explorer">VS Solution Explorer</a>, <a href="https://marketplace.visualstudio.com/items?itemName=patcx.vscode-nuget-gallery">Nuget Gallery</a>. Also for React + Typescript development we’ll use <a href="https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer">Live Server</a>, <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode.vscode-typescript-next">JavaScript and Typescript Nightly</a>, <a href="https://marketplace.visualstudio.com/items?itemName=dsznajder.es7-react-js-snippets">ES7 + React Native Snippets</a>, <a href="https://marketplace.visualstudio.com/items?itemName=steoates.autoimport">Auto Import</a>.</p><figure><img alt="Building Cloud NET APIs, integrated with React using Azure and Axios" src="https://cdn-images-1.medium.com/max/1024/1*lcHfC5zOaSoGK_URIqNp8A.png" /></figure><p>First of all, you’ll have to create a new Azure account, it gives you free trial to test all of the available services in the<a href="https://azure.microsoft.com/en-us/get-started/azure-portal/"> Microsoft Azure Portal</a>. Remember that every service created will have a cost so pay attention to the price tier of each one while creating it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GE0JrPNGV3Vmpyla5ejB2w.png" /></figure><p>Once you created the resources and had done the configurations, you’ll be able to get the connection strings to use it on your project so you can connect directly to the cloud.</p><figure><img alt="Configuring your connection strings" src="https://cdn-images-1.medium.com/max/1024/1*d4vI9jSx6EHj5IgekJC6Ow.png" /></figure><p>Let’s create a model for the SQL Database entities that will be used to generate the Entity Framework Core migrations (ah! don’t forget to install the EF Core packages). I’ll make this tutorial short so if you wanna see the full code,<strong> you can check the </strong><a href="https://github.com/lucasgarciadev22/ReactNET/tree/main/PaymentSimulatorCloudApi"><strong>project’s repository</strong></a><strong> for more details</strong>.</p><pre>public class OrderRegistry<br>  {<br>    [Key()]<br>    public int Id { get; set; }<br>    public string StatusMessage { get; set; }<br>    [ForeignKey(&quot;Seller&quot;)]<br>    public int SellerId { get; set; }<br>    public string SellerCpf { get; set; }<br>    public string SellerName { get; set; }<br>    public string SellerEmail { get; set; }<br>    public string SellerPhone { get; set; }<br>    public string OrderNumber { get; set; }<br>    public DateTime OrderDate { get; set; }<br>    public OrderStatus OrderStatus { get; set; }<br>    public string OrderProductsJson { get; set; }<br><br>    public OrderRegistry() { }<br>    public OrderRegistry(Seller seller, DateTime orderDate, OrderProduct[] orderProducts, OrderStatus orderStatus)<br>    {<br>      SellerId = seller.Id;<br>      SellerCpf = seller.Cpf;<br>      SellerName = seller.Name;<br>      SellerEmail = seller.Email;<br>      SellerPhone = seller.Phone;<br>      OrderNumber = Guid.NewGuid().ToString().Substring(0, 8);//get first 8 nums from GUID to use as order number<br>      OrderDate = orderDate;<br>      OrderStatus = orderStatus;<br>      OrderProductsJson = JsonSerializer.Serialize(orderProducts);<br>    }<br>  }</pre><p>Now we can start to build our Controllers, is important to remember that we’re using Azure SDK to work with Azure Tables directly in C#. For now we will just create the base structure, giving some more context to our Controller.</p><figure><img alt="Using Azure Table SDK" src="https://cdn-images-1.medium.com/max/1024/1*gVB-17WQ6kQcSAZHiWICmg.png" /></figure><p>The next model we should create is for generating the logs on Azure Table. Remember that the Partition Key or the Row Key rules changes for each product, is up to you to decide how to organize your logs in your tables. In this project, to be more pratical we’ll just use <a href="https://learn.microsoft.com/en-us/dotnet/api/system.guid?view=net-7.0"><em>GUID</em></a></p><figure><img alt="Creating Log model" src="https://cdn-images-1.medium.com/max/1024/1*1eo6RPvQK2iwM6dDQZDrvQ.png" /></figure><p>Finally, lets implement the REST protocol (POST, GET, PUT, DELETE). I won’t show all the methods, but as I said, you can check the full code on my repository.</p><figure><img alt="Creating REST methods and Generating Azure Table Logs" src="https://cdn-images-1.medium.com/max/1024/1*VMSUySmPQbLCuUKs77tXXA.png" /></figure><p>Let’s change to frontend development now. We’ll use <em>Axios </em>to consume our API, but it’s not a rule since today we have several other alternatives to integrate APIs with React apps. Remember that each type of REST method you use with <em>Axios </em>can present some differences while implement, but the base is similar.</p><figure><img alt="Creating React app and using Axios" src="https://cdn-images-1.medium.com/max/1024/1*YfOTxN32NG0uzWZSRMHGyQ.png" /></figure><figure><img alt="Creating React app and using Axios" src="https://cdn-images-1.medium.com/max/1024/1*7Khh6r5edgjNtISQpC0tiA.png" /></figure><p>Uh! Finally we can put our creativity to work and create some good shaped components. In this project I tried to use <a href="https://react-bootstrap.github.io/">React-Bootstrap</a> that provides great support to standard <em>Bootstrap </em>but you can use it as React Components. Then, I edited the components with <a href="https://styled-components.com/">Styled Component</a> (just because I wanna show the possibilities of editing a style library).<br>Another important thing from now on is that we’ll be using Typescript(yeah, get rid of this vanilla JS ASAP!) to create our functional components, so make sure you’re <strong>typing it correctly.</strong></p><p>Another important package we’re using is <a href="https://reactrouter.com/en/main">React Router</a> to organize all the routes for our web app.</p><figure><img alt="Displaying fetched data on React" src="https://cdn-images-1.medium.com/max/1024/1*Oi_1LRkZBIAj-uB1vxIDuA.png" /></figure><p>We’re one step behind finishing now, just need to deploy it correctly to the cloud so other people can access our web app as an online service. To achieve this, we’ll use <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode.vscode-node-azure-pack">Azure Tools</a> extension kit, which is the official Microsoft Azure VS Code extension.</p><figure><img alt="Deploying app to Azure" src="https://cdn-images-1.medium.com/max/1024/1*uw4Z8F0_MjrRxpYjNUCBhA.png" /></figure><p>This is my first article here so is important to have your feedback. Also, I’ll leave my <a href="https://www.linkedin.com/in/lucasmggarcia22/">LinkedIn</a>, so you can contact me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YjjTF3BuWvCv3V8YnKhnVA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e64b9d9eb22" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>