<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ahmed Fouad</title>
    <description>The latest articles on DEV Community by Ahmed Fouad (@mcc_ahmed).</description>
    <link>https://dev.to/mcc_ahmed</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F357937%2F587bf9df-c8ce-4505-b296-0e374e36dfd0.jpg</url>
      <title>DEV Community: Ahmed Fouad</title>
      <link>https://dev.to/mcc_ahmed</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/mcc_ahmed"/>
    <language>en</language>
    <item>
      <title>5 Reasons to Use AsyncFlow in Your Next Backend</title>
      <dc:creator>Ahmed Fouad</dc:creator>
      <pubDate>Wed, 06 Sep 2023 00:44:38 +0000</pubDate>
      <link>https://dev.to/mcc_ahmed/5-reasons-to-use-asyncflow-in-your-next-backend-1jk3</link>
      <guid>https://dev.to/mcc_ahmed/5-reasons-to-use-asyncflow-in-your-next-backend-1jk3</guid>
      <description>&lt;p&gt;Modern backend systems increasingly rely on asynchronous operations to manage long-running tasks efficiently. With numerous solutions available, why should you consider using &lt;a href="https://github.com/TheFo2sh/AsyncFlow"&gt;AsyncFlow&lt;/a&gt; for your next .NET application? Here are five compelling reasons!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Seamless Asynchronous Job Invocation:&lt;/strong&gt;&lt;br&gt;
Starting long-running jobs should be smooth and intuitive. With AsyncFlow, once a user calls an invoke API, they receive a job ID immediately, streamlining the initiation of asynchronous tasks.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;2. Integrated Status Tracking:&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
Keep your users informed. Rather than leaving them wondering about the status of their tasks, AsyncFlow allows them to easily track their job's progress. Whether it's still processing, completed, or has encountered an error, your users stay in the loop.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;3. Flexible Result Retrieval:&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
The beauty of AsyncFlow lies in its flexibility. Once a job is finished, users can retrieve the results at their convenience, ensuring that they have access to data when they need it.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;4. Robust Integration with Hangfire:&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
Leverage the power of Hangfire, a leading background processing library in the .NET ecosystem. AsyncFlow's seamless integration with Hangfire ensures efficient job execution without the hassles of setting up complex processes.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;5. Extensible Cache Options:&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
Whether you prefer in-memory storage or a distributed cache, AsyncFlow has got you covered. Store job results based on your application's needs, ensuring optimal performance and resource management.&lt;/p&gt;




&lt;p&gt;Asynchronous operations are the backbone of efficient backends. AsyncFlow offers an intuitive and powerful approach to managing asynchronous job flows in .NET applications. Dive into this tool and elevate your backend systems!&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>dotnet</category>
      <category>csharp</category>
      <category>backend</category>
    </item>
    <item>
      <title>The Journey from Problem to Solution: Introducing AsyncFlow</title>
      <dc:creator>Ahmed Fouad</dc:creator>
      <pubDate>Tue, 15 Aug 2023 03:24:40 +0000</pubDate>
      <link>https://dev.to/mcc_ahmed/the-journey-from-problem-to-solution-introducing-asyncflow-4cd4</link>
      <guid>https://dev.to/mcc_ahmed/the-journey-from-problem-to-solution-introducing-asyncflow-4cd4</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--8vFd7C85--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h92pejin4el69ngx117m.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--8vFd7C85--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h92pejin4el69ngx117m.png" alt="Image description" width="682" height="532"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It was a typical Tuesday afternoon when Ahmed, an astute developer, faced a daunting challenge. The request-response paradigm that he had always relied on was suddenly insufficient. With a growing user base and an expanding application, long-running tasks became the bane of his existence.&lt;/p&gt;

&lt;p&gt;Frequent timeouts, aggravated users, and sleepless nights were all Ahmed seemed to know. The pressure of scaling without compromising user experience was weighing him down.&lt;/p&gt;

&lt;p&gt;One evening, Ahmed stumbled upon the Job-based Asynchronous Processing Pattern. This was a game-changer! This pattern could handle time-consuming tasks in the background, and users could check the task's status or retrieve the results at their leisure. It was the perfect solution Ahmed had been searching for.&lt;/p&gt;

&lt;p&gt;However, implementing it was no walk in the park. He needed something that would simplify this pattern's integration into his application.&lt;/p&gt;

&lt;p&gt;Enter &lt;strong&gt;&lt;a href="https://github.com/TheFo2sh/AsyncFlow"&gt;AsyncFlow&lt;/a&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Ahmed found AsyncFlow, a library that brought the power of this pattern right into the .NET ecosystem. Built atop Hangfire's robust infrastructure, AsyncFlow made it a breeze for him to implement asynchronous task processing.&lt;/p&gt;

&lt;p&gt;Setting it up was a walk in the park:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="n"&gt;builder&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Services&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;AddHangfire&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="p"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;UseMemoryStorage&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;span class="n"&gt;builder&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Services&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;AddHangfireServer&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="n"&gt;builder&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Services&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;AddMemoryCache&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="n"&gt;builder&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Services&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;AddAsyncFlow&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;options&lt;/span&gt; &lt;span class="p"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;options&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;UseMemoryCache&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Ahmed just had to write his business logic, implement the IAsyncFlow interface, and voila, his endpoints were up and running:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="n"&gt;builder&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Services&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;AddTransient&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;GenerateDataJob&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;();&lt;/span&gt;
&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;MapFlow&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;GenerateDataJob&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;GenerateDataRequest&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;GenerateDataResponse&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;(&lt;/span&gt;&lt;span class="s"&gt;"dataGeneration"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It didn't stop there. Ahmed was also able to leverage Hangfire's capabilities, including its insightful dashboard and exceptional load balancing.&lt;/p&gt;

&lt;p&gt;Elated with his discovery, Ahmed felt the need to share this gem with the world. If you're facing challenges like Ahmed and seeking a seamless way to implement the Job-based Asynchronous Processing Pattern in .NET, give &lt;a href="https://github.com/TheFo2sh/AsyncFlow"&gt;AsyncFlow&lt;/a&gt; a glance. And if it helps you as much as it did Ahmed, consider giving it a star!&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>backenddevelopment</category>
      <category>webdev</category>
      <category>cloud</category>
    </item>
    <item>
      <title>7 ways to improve code quality in c# using option type</title>
      <dc:creator>Ahmed Fouad</dc:creator>
      <pubDate>Sat, 18 Apr 2020 21:56:03 +0000</pubDate>
      <link>https://dev.to/mcc_ahmed/7-ways-to-improve-code-quality-in-c-using-option-type-589l</link>
      <guid>https://dev.to/mcc_ahmed/7-ways-to-improve-code-quality-in-c-using-option-type-589l</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--U6ldSfUq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2A-GlOoEc0VeIIBgp4YtAo5A.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--U6ldSfUq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2A-GlOoEc0VeIIBgp4YtAo5A.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Option is relatively new for imperative programming (c#, java, …) developers also it is now a primitive type in some of these multiparadigm languages like java it is not yet natively supported in C#.&lt;/p&gt;

&lt;p&gt;I think the biggest misunderstanding regarding option type came from it is similarity was the nullable type. you will find a lot of online articles presenting Option type as a safer alternative to the nullable type or as a final solution to NullReferenceException while other material defends Nullable and say that option type is not the way to go as it simply replaces NullReferenceException with MissingValueException.&lt;/p&gt;

&lt;p&gt;Here we will show you how to use Option Type Correctly and how it will improve your code dramatically and prevent some potential bugs.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.nuget.org/packages/Optional/"&gt;Optional 4.0.0&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  1- Force you to handle the missing value case
&lt;/h3&gt;

&lt;p&gt;Option type will force you to deal with the missing case when you actually need to get the value.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public string GetEmail(string id)
{
    var user= GetUser("id");
    return user.SomeNotNull()
         .Select(context=&amp;gt;context.Email)
         .ValueOr("Not found");
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Here you have the GetUser Method which fitch the user that matches the provided id from the database and in case there no user with that Id it will return null.&lt;/p&gt;

&lt;p&gt;This is one of the classics problems in all kinds of applications where the developer starts his code like that&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var user= GetUser("id");
return user.Email;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;and then when some NullReferenceExceptions Happens you can see something like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var user= GetUser("id");
return user?.Email;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;and then the NullRefrenceException will occur at the consumer of this method.&lt;/p&gt;

&lt;p&gt;using the Option where you have to think about what to do when there is no value will have you to not to fall in the null propagation trap.&lt;/p&gt;

&lt;p&gt;you can also you .ValueOrDefault() or .ValueOrFailure() if you want but it is not recommended unless you really wanna do that.&lt;/p&gt;

&lt;h3&gt;
  
  
  2- You define when it is none and when it is some
&lt;/h3&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private static string GetEmail(string id)
        {
            var user = GetUser(id);
            var email = user.SomeNotNull()
                .Where(context=&amp;gt; IsEmail(context.Email))
                .Select(context =&amp;gt; context.Email)
                .ValueOr("Not Found");
            return email;
        }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;In some cases, you wanna ensure that the returned value satisfy some condition for example here if you have a case where some of the emails in the database are not incorrect format or not verified or anything else that you do not want to return.&lt;/p&gt;

&lt;p&gt;you can write the previous code instead of something ugly like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var user= GetUser("id");
return IsEmail(user?.Email)??NotFound;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;In some cases, even this code could fail if the IsEmail do not accept null parameters so you could end up with something like&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var user= GetUser("id");
return var user= GetUser("id");
return !string.IsNulOrEmpty(User?.Email)&amp;amp;&amp;amp;IsEmail(user?.Email)??NotFound;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;wherein the option version it will be&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private static string GetEmail(string id)
        {
            var user = GetUser(id);
            var email = user.SomeNotNull()
               .Select(context =&amp;gt; context.Email)
               .Where(email=&amp;gt;!string.IsNullOrEmpty(email))
               .Where(email=&amp;gt; IsEmail(email))
               .ValueOr(string.Empty);
            return email;
        }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h3&gt;
  
  
  3- Execute Only When Value Exist
&lt;/h3&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static void NotifyUser(string id)
       {

        var user = GetUser(id)
                  .SomeNotNull()
                  .Where(context=&amp;gt;context.IsActive)
                  .Where(context=&amp;gt;!context.NoDeleted)
                  .Where(context=&amp;gt;context.AllowNotification);

        user
            .Where(context =&amp;gt; !string.IsNullOrEmpty(context.Email))
            .Where(context =&amp;gt; IsEmail(context.Email))            
            .Where(context=&amp;gt;context.SubscribedToEmailNotification)
            .MatchSome(SendNotificationEmail);

        user    
         .Where(context=&amp;gt;!string.IsNullOrEmpty(context.PhoneNumber))
         .Where(context=&amp;gt;context.SubscribedToPhoneNotification)
         .MatchSome(SendNotificationSMS);

          }
        private static void SendNotificationSMS(User context)
        {

        }
        private static void SendNotificationEmail(User context)
        {

        }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;this code explains himself send an email notification if the email exists and send an SMS if the phone number exists.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;vau user =GetUser(id);

if(user==null || !user.IsActive || !user.IsDeleted || !user.AllowNotification)
   return;

if(!string.IsNullOrEmpty(user.Email)
    &amp;amp;&amp;amp;IsEmail(user.Email)
    &amp;amp;&amp;amp; user.SubscribedToEmailNotification)
            sendNotificationEmail(user);

if(!string.IsNullOrEmpty(user.PhoneNumber))
   &amp;amp;&amp;amp;user.SubscribedToSMSNotification)
    SendNotificationSMS(user);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;I am sure it will take less time from you to understand the first code snipped with optional.&lt;/p&gt;

&lt;p&gt;While both of them have the same number of conditions and checks but When we are using Where we are defining a rule so when we say “&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var user = GetUser(id)
                  .SomeNotNull()
                  .Where(context=&amp;gt;context.IsActive)
                  .Where(context=&amp;gt;!context.NoDeleted)
                  .Where(context=&amp;gt;context.AllowNotification);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;we are defining a contract no more than that with no actions so our user only exists if he satisfies the conditions and later on when needed we will do actions depend on he exists or not.&lt;/p&gt;

&lt;p&gt;but with if conditions we are actually forcing an execution path with contains the condition and the action normally these are harder to understand and force upfront work which could not be needed.&lt;/p&gt;

&lt;p&gt;I am sure you are familiar with this Joke&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A programmer is going to the grocery store and his wife tells him, “Buy a gallon of milk, and if there are eggs, buy a dozen.” So the programmer goes, buys everything, and drives back to his house. Upon arrival, his wife angrily asks him, “Why did you get 13 gallons of milk?” The programmer says, “There were eggs!”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I am sure he never heard of functional programming and his code is full of if-else bulls***t that is why he used the if condition to build an action set while normal humans use the requirements to build rules like that.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var milikGallon=store.GetMilikGallon().SomeNotNull();
milikGallon.MatchSome(Buy);

var egges=store.GetEggs().SomeNotNull().Select(eggs=&amp;gt;eggs.Take(13));
egges.MatchSome(Buy);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h3&gt;
  
  
  4- Async Support
&lt;/h3&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static async Task NotifyUser(string id)
        {
            var user = GetUser(id)
                .SomeNotNull()
                .Where(context =&amp;gt; context.IsActive)
                .Where(context =&amp;gt; !context.NoDeleted)
                .Where(context =&amp;gt; context.AllowNotification);

var sendEmailTask=
           user
            .Where(context =&amp;gt;context.SubscribedToEmailNotification)
            .Where(context =&amp;gt; !string.IsNullOrEmpty(context.Email))
            .Where(context =&amp;gt; IsEmail(context.Email))
            .Select(SendNotificationEmail)
            .ValueOr(Task.CompletedTask);

 var sendSmsTask=
           user
            .Where(context =&amp;gt; context.SubscribedToSMSNotification)
            .Where(context   
                     =&amp;gt;!string.IsNullOrEmpty(context.PhoneNumber))
             .Select(SendNotificationSMS)
             .ValueOr(Task.CompletedTask);

      await Task.WhenAll(sendEmailTask, sendSmsTask);

        }

private static Task SendNotificationSMS(User context)
        {
            return Task.CompletedTask;

        }

private static Task SendNotificationEmail(User context)
        {
            return Task.CompletedTask;

        }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;When it comes to async programming all we need is to select the task instead of invoking a method and if we are using the Task.CompletedTask as a replacement value for the none condition.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var sendEmailTask=
           user
            .Where(context =&amp;gt;context.SubscribedToEmailNotification)
            .Where(context =&amp;gt; !string.IsNullOrEmpty(context.Email))
            .Where(context =&amp;gt; IsEmail(context.Email))
            .Select(SendNotificationEmail)
            .ValueOr(Task.CompletedTask);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;will return a completed Task (Task.CompletedTask) when the user does not exist or is not subscribed to email notification or does not have a valid email otherwise, it returns the SendNotificationEmail task.&lt;/p&gt;

&lt;p&gt;and with Task.WhenAll we manage to run and wait for the tasks in parallel and here is the edge of functional programming when we changed the methods to async we were pushed too to run them in parallel but in the other alternative it will be&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;vau user =GetUser(id);

if(user==null || !user.IsActive || !user.IsDeleted || !user.AllowNotification)
   return;

if(!string.IsNullOrEmpty(user.Email)
    &amp;amp;&amp;amp;IsEmail(user.Email)
    &amp;amp;&amp;amp; user.SubscribedToEmailNotification)
          await sendNotificationEmail(user);

if(!string.IsNullOrEmpty(user.PhoneNumber))
   &amp;amp;&amp;amp;user.SubscribedToSMSNotification)
   await SendNotificationSMS(user);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;which of course can be refactored to run the 2 tasks in parallel but it is not part of the natural refactor path when we refactored sendNotificationEmail and SendNotificationSMS to be async.&lt;/p&gt;

&lt;h3&gt;
  
  
  5- Exception Handling
&lt;/h3&gt;

&lt;p&gt;The get user method may throw an exception if there is a DB error or something like that, our previous code does not handle this in anyways while the normal try-catch block can work perfectly with our functional programming code Option type give us a better way for exception handling.&lt;/p&gt;

&lt;p&gt;I will start by writing an extension method that wraps our GetUser method to return OptionWithException instead of T.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static Option&amp;lt;T, Exception&amp;gt; ToOption&amp;lt;P,T&amp;gt;(this Func&amp;lt;P,T&amp;gt; context,P parameter)
        {

                try
                {
                    var result = context.Invoke(parameter);
                   return result.SomeNotNull(
() =&amp;gt;
(Exception) new NullReferenceException($"{context.Method.Name} returned null"));
                }
                catch (Exception e)
                {
                    return Option.None&amp;lt;T, Exception&amp;gt;(e);
                }
        }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;and then we could use it like that&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private static string GetEmail(string id)
  {
    var userFactory=new Func&amp;lt;string,User&amp;gt;(GetUser);

    var user = userFactory.ToOption(id);
    var email= 
     user.Filter(context =&amp;gt;!string.IsNullOrEmpty(context.Email,
                () =&amp;gt;new ConditionNotMatchedException("Emptyemail"))

          .Filter(context =&amp;gt; IsEmail(context.Email), 
             () =&amp;gt; new ConditionNotMatchedException("InvalidEmail"))

          .Select(context =&amp;gt; context.Email);

     return email.ValueOr("Not found");
        }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This new code will be doing the same as the older one will return the email or not found.&lt;/p&gt;

&lt;p&gt;but as you have noticed we replaced the Where(T=&amp;gt;bool) with Filter(T=&amp;gt;bool , ()=&amp;gt;Exception). That is because we will use the exception now as a reason when the value not existing so we can know why there is no email if we want and to do we must do an additional simple change&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public struct EmailResult
   {
       public string Email { get; set; }
       public string Error { get; set; }

}
private static EmailResult GetEmail(string id)
   {
     var userFactory=new Func&amp;lt;string,User&amp;gt;(GetUser);

     var user = userFactory.ToOption(id);
     var emailResult = 
         user.Filter(context =&amp;gt;!string.IsNullOrEmpty(context.Email),   
              () =&amp;gt; new ConditionNotMatchedException("Emptyemail"))

             .Filter(context =&amp;gt; IsEmail(context.Email),
            () =&amp;gt; new ConditionNotMatchedException("InvalidEmail"))

             .Select(context =&amp;gt; context.Email)
             .MapException(ex=&amp;gt;new EmailResult(){Error =ex.Message})
             .Map(email=&amp;gt;new EmailResult(){Email = email});

     return emailResult.ValueOrException();
        }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;As we need to know the reason in case of not finding the email so we will return a ResultObject in which we will map the result and the exception using&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.MapException(ex=&amp;gt;new EmailResult(){Error =ex.Message})
.Map(email=&amp;gt;new EmailResult(){Email = email});
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h3&gt;
  
  
  6- Integration With Other contracts Frameworks like Shoudly
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://www.nuget.org/packages/Shouldly/"&gt;Shouldly 3.0.2&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Shoudly is an assertion framework and normally assertion frameworks are used for testing but here I would use it for filtering my value&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private static EmailResult GetEmail(string id)
 {
   var userFactory=new Func&amp;lt;string,User&amp;gt;(GetUser);

   var user = userFactory.ToOption(id);
   var emailResult = user
         .Filter(context=&amp;gt;context.Email.ShouldNotBeNullOrEmpty())            
         .Filter(context=&amp;gt;context.Email.ShouldMatch(Patterns.Email))
         .Select(context =&amp;gt; context.Email)
         .MapException(ex=&amp;gt;new EmailResult(){Error = ex})
         .Map(email=&amp;gt;new EmailResult(){Email = email});

   return emailResult.ValueOrException();
 }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;but it requires me to implement a simple overload for filter&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static Option&amp;lt;T, Exception&amp;gt; Filter&amp;lt; T&amp;gt;(this Option&amp;lt;T, Exception&amp;gt; context,Action&amp;lt;T&amp;gt; condition)
        {
            try
            {
                if (!context.HasValue)
                    return context;
                condition.Invoke(context.ValueOrFailure());
                 return context;
            }
            catch (Exception e)
            {
                return Option.None&amp;lt;T, Exception&amp;gt;(e);
            }
        }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;I believe this syntax is the most readable one you can achieve&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var emailResult = user
         .Filter(context=&amp;gt;context.Email.ShouldNotBeNullOrEmpty())            
         .Filter(context=&amp;gt;context.Email.ShouldMatch(Patterns.Email))
         .Select(context =&amp;gt; context.Email)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h3&gt;
  
  
  7- It can be your entry to functional Programming
&lt;/h3&gt;

&lt;p&gt;Here I have to tell you that option type is one of the building blocks of functional programming and by using it as we mentioned in the previous 6 sections you are actually writing functional Programming cold.&lt;/p&gt;

&lt;p&gt;So welcome on board, now I would suggest that you follow me on twitter and medium for more articles.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://twitter.com/MCC_Ahmed"&gt;Ahmed Fouad&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And you can buy me one coffee it will help me write more articles&lt;/p&gt;

&lt;p&gt;&lt;a href="https://ko-fi.com/ahmedfouad"&gt;Buy AhmedFouad a Coffee. ko-fi.com/ahmedfouad&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And I would really recommend you to read &lt;a href="http://Functional%20Programming%20in%20C#:%20How%20to%20write%20better%20C#%20code"&gt;Functional Programming in C#: How to write better C# code&lt;/a&gt; as it is one of few books that introduce functional programming thinking to c# developers read it and you will notice dramatic improvements in how you think and a strong boost in your code quality.&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>csharp</category>
      <category>functionalprogrammi</category>
      <category>xamarin</category>
    </item>
    <item>
      <title>Building your First async fluent API using interface extension methods pattern</title>
      <dc:creator>Ahmed Fouad</dc:creator>
      <pubDate>Sat, 11 Apr 2020 20:22:45 +0000</pubDate>
      <link>https://dev.to/mcc_ahmed/building-your-first-async-fluent-api-using-interface-extension-methods-pattern-266a</link>
      <guid>https://dev.to/mcc_ahmed/building-your-first-async-fluent-api-using-interface-extension-methods-pattern-266a</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--_eqilWw1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AsXO3lbPj9YKYuSSRer2ZEg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--_eqilWw1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AsXO3lbPj9YKYuSSRer2ZEg.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Fluent Interface is an advanced API design that really on extension methods and methods chaining. When of the most famous examples of fluent API is the linq extension methods for IEnumerable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var passed=Students.Where(s=&amp;gt;s.Passed).Select(s=&amp;gt;s.Name).ToList();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;In the asynchronous Programming, async/await, fluent APIs are kind of limited due to the nature of the Task object that it is hot build default, in this article, we will overcome this problem and will build a small library that allows fluent extension methods.&lt;/p&gt;

&lt;p&gt;as an example,&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var data=await GetDataAsync()
         .AsRepeatable(TimeSpan.FromSeconds(10))
         .FirstOrDefaultAsync(data=&amp;gt;data.Any());
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;another example could be&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var data=await GetNewsAsync()
         .Where(newsList=&amp;gt;newsList.Date&amp;gt;=DateTime.Today)
         .SelectMany(newsList=&amp;gt;newsList.NewsItems)
         .ToList();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Just to give you an idea of how this code could be written using Imperative approach&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt; var newsList=await GetNewsAsync();
 if(newsList.Date&amp;gt;=DateTime.Today)
    {
       return newsList.Select(news=&amp;gt;news.NewsItems).ToList();
    }
else
       return new List&amp;lt;NewsItem&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;It is up to you to choose which code fashion you would like, if you like the second one, you can stop reading this article as in the rest of the article we will extend the c sharp language to make the first one applicable.&lt;/p&gt;

&lt;p&gt;Good you decided to continue that show that you are a very elegant software engineer so please grape your coffee and you can invite me on as well using&lt;/p&gt;

&lt;p&gt;&lt;a href="https://ko-fi.com/ahmedfouad"&gt;Buy AhmedFouad a Coffee. ko-fi.com/ahmedfouad&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Step 1: Convert your async Task to Task&amp;gt;
&lt;/h3&gt;

&lt;p&gt;This will help us to get rid of the NullReferenceExceptions and concentrate only on the extension methods.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static Func&amp;lt;Task&amp;lt;Option&amp;lt;T&amp;gt;&amp;gt;&amp;gt; ToOption&amp;lt;T&amp;gt;(this Func&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt; context)
{
     return new Func&amp;lt;Task&amp;lt;Option&amp;lt;T&amp;gt;&amp;gt;&amp;gt;(async () =&amp;gt;{
     try
       {
          var result = await context.Invoke();
          return result.SomeNotNull();
       }
     catch (Exception e)
       {
          return Option.None&amp;lt;T&amp;gt;();
       }});

}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;This method simply invokes the async method and return Option.None when the value is null or exception happened or the value as some when there is a value.&lt;/p&gt;

&lt;p&gt;we will need to install the option type nugget package&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.nuget.org/packages/Optional/"&gt;Optional 4.0.0&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Step 2: Build a Wrapper class in which we will implement our extension methods
&lt;/h3&gt;


&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ExtendedTask&amp;lt;T&amp;gt;
    {
        private readonly Func&amp;lt;Task&amp;lt;Option&amp;lt;T&amp;gt;&amp;gt;&amp;gt; \_taskOption;
        public ExtendedTask(Func&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt; task)
        {
            \_taskOption = task.ToOption();
        }
        public ExtendedTask(Func&amp;lt;Task&amp;lt;Option&amp;lt;T&amp;gt;&amp;gt;&amp;gt; task)
        {
            \_taskOption = task;
        }
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;form here it is very easy to implement our extension methods, we will just delegate the implementation to the option type.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public ExtendedTask&amp;lt;T&amp;gt; Where(Func&amp;lt;T,bool&amp;gt; condition)
        {
            var conditionedTask = \_taskOption.Select(func =&amp;gt; new Func&amp;lt;Task&amp;lt;Option&amp;lt;T&amp;gt;&amp;gt;&amp;gt;(async () =&amp;gt;
            {
                var result = await func.Invoke();
                return result.Where(condition);
            }));

            return new ExtendedTask&amp;lt;T&amp;gt;(conditionedTask);
        }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;It will return the new ExtendedTask of value when the condition is meet and ExtendedTask of None otherwise.&lt;/p&gt;

&lt;p&gt;Now we will implement the select method and select async method using the same strategy.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public ExtendedTask&amp;lt;TP&amp;gt; Select&amp;lt;TP&amp;gt;(Func&amp;lt;T,TP&amp;gt; selector)
        {
            var conditionedTask = \_taskOption.Select(func =&amp;gt; new 
            Func&amp;lt;Task&amp;lt;Option&amp;lt;TP&amp;gt;&amp;gt;&amp;gt;(async () =&amp;gt;
            {
                var result = await func.Invoke();

                return result.Select(selector);
            }));

          return new ExtendedTask&amp;lt;TP&amp;gt;(conditionedTask);
        }

public ExtendedTask&amp;lt;TP&amp;gt; SelectAsync&amp;lt;TP&amp;gt;(Func&amp;lt;T, Task&amp;lt;TP&amp;gt;&amp;gt; selector)
        {
            var conditionedTask = \_taskOption.Select(func =&amp;gt; new  
            Func&amp;lt;Task&amp;lt;Option&amp;lt;TP&amp;gt;&amp;gt;&amp;gt;(async () =&amp;gt;
            {
                var result = await func.Invoke();

                var [@select](http://twitter.com/select) = await result.Select(selector.Invoke)
                 .ValueOr(()=&amp;gt;Task.FromResult(default(TP)));

                return [@select](http://twitter.com/select).SomeWhen(p =&amp;gt;
                {
                    var b = p.Equals(default(TP));
                    return !b;
                });
            }));
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3&gt;
  
  
  Step 3: Implement the AsTask() method
&lt;/h3&gt;


&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public async Task&amp;lt;T&amp;gt; AsTask()
        {
            return (await \_taskOption.Select(async task =&amp;gt; await 
                    task())).ValueOrDefault();
        }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;This method simply returns a new task that executes the decorated task and will simply return the default of T when the value is None.&lt;/p&gt;
&lt;h3&gt;
  
  
  Step4: Implement AsRepeatable() method
&lt;/h3&gt;

&lt;p&gt;As the repeatable method is a transformation method that transforms a scalar Task to a Vector IAsyncEnumerable&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public IAsyncEnumerable&amp;lt;T&amp;gt; AsRepeatable()
        {
            return new TaskAsyncEnumerable&amp;lt;T&amp;gt;( \_taskOption);
        }
        public IAsyncEnumerable&amp;lt;T&amp;gt; AsRepeatable(TimeSpan timeSpan)
        {
            return new TaskAsyncEnumerable&amp;lt;T&amp;gt;(\_taskOption ,timeSpan);
        }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;And here is the Implementation of TaskAsyncEnumerable&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;It is quite straight forward The enumerator will keep executing the task on iterating and will only stop when the Iterating stop or when the value becomes null.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 5: Let’s try it
&lt;/h3&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var getDataAsync = new ExtendedTask&amp;lt;News&amp;gt;(GetDataAsync);
var data = await getDataAsync
                .AsRepeatable(TimeSpan.FromSeconds(1))
                .FirstOrDefaultAsync(data =&amp;gt; data.Items.Any());
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 6
&lt;/h3&gt;

&lt;p&gt;If you like the article please share it, follow me on medium and on twitter to get my upcoming&lt;/p&gt;

&lt;p&gt;&lt;a href="https://twitter.com/MCC_Ahmed"&gt;Ahmed Fouad&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;and pay me the coffee at&lt;/p&gt;

&lt;p&gt;&lt;a href="https://ko-fi.com/ahmedfouad"&gt;Buy AhmedFouad a Coffee. ko-fi.com/ahmedfouad&lt;/a&gt;&lt;/p&gt;

</description>
      <category>xamarin</category>
      <category>dotnet</category>
      <category>csharp</category>
      <category>asyncawait</category>
    </item>
    <item>
      <title>Send Push Notification from a webhook endpoint using Azure notification hub</title>
      <dc:creator>Ahmed Fouad</dc:creator>
      <pubDate>Sat, 04 Apr 2020 21:43:55 +0000</pubDate>
      <link>https://dev.to/mcc_ahmed/send-push-notification-from-a-webhook-endpoint-using-azure-notification-hub-4p4e</link>
      <guid>https://dev.to/mcc_ahmed/send-push-notification-from-a-webhook-endpoint-using-azure-notification-hub-4p4e</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--1SbjUDPm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AwAV_oAkr-GFqE9EwLiYebQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1SbjUDPm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AwAV_oAkr-GFqE9EwLiYebQ.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Webhooks are user-defined HTTP callbacks&lt;/strong&gt; where the &lt;strong&gt;provider calls the client's web service to notify him when a new event occurred&lt;/strong&gt; by contrast to the &lt;strong&gt;API where the client calls the provider to GET some information or POST new data&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For example if you are building a continuous integration system and you want to build and create an app package every time a commit is done to the Master branch.&lt;/p&gt;

&lt;p&gt;So your build tool must get notified when a new commit is made and this can only happen using webhooks, your build server will register his endpoint in the git server and the git server will call your build server registered endpoint and therefore your build server will pull the new code and create a build.&lt;/p&gt;

&lt;p&gt;Another example and it is the one that we will do together in this article, you know that I use &lt;a href="https://ko-fi.com/ahmedfouad"&gt;ko-fi.com&lt;/a&gt; to gather donations to keep this blog running and buy tools to enhance the article quality, now I wanna receive a push notification on my mobile when a new donation is made so how I will do this.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step1: Create an Azure Lambda Function to be used as a webhook endpoint.
&lt;/h3&gt;

&lt;p&gt;This is a very straight forward open visual studio and create new Azure Lambda Function project.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;it is very straight forward I just receive the post request body, decode it and parse it to get the payload according to ko-fi.com documentation.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--K-f_3dkE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AGwKSMQldq5zzIuIAoRhG7g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--K-f_3dkE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AGwKSMQldq5zzIuIAoRhG7g.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Next, I use the azure notification hub to send an FCM notification with the message content.&lt;/p&gt;

&lt;p&gt;please remember to install the azure notification hub nugget package&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.nuget.org/packages/Microsoft.Azure.NotificationHubs"&gt;Microsoft.Azure.NotificationHubs 3.3.0&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var notificationHubClient = new NotificationHubClient(connectionString, hubName);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;the notification hub constructor takes 2 parameters connection string and hub name, we will see how we get them in step 2.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var notificationResult = await notificationHubClient.SendNotificationAsync(

new FcmNotification("{\"data\":{\"message\":\"" + payload.Message + "\"}}"));
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;we create and send the FcmNotification with a JSON payload, please check the FCM documentation for more.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step2: Create Azure Notification Hub
&lt;/h3&gt;

&lt;p&gt;using Azure Portal, create a new Notification Hub resource, then go to the resource page and navigate to Acess Policies to get the connection string.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--mOmg4est--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AYbGRl772z68ZIlwhPitrBg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--mOmg4est--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AYbGRl772z68ZIlwhPitrBg.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The DefaultFullSharedAccessSignature is the first parameter in the NotificationHubClient constructor and the second parameter is just the resource name which is the hub name.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var notificationHubClient = new NotificationHubClient("Endpoint=sb://xxx.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=53Mxxxx=", "kofihub");

var notificationResult =

await notificationHubClient.SendNotificationAsync(

new FcmNotification("{\"data\":{\"message\":\"" + payload.Message + "\"}}"));
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Now you can publish your azure lambda function from the visual studio by right-clicking on it then click publish.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 3 Create a Firebase project
&lt;/h3&gt;

&lt;p&gt;I think to create a new project on firebase.google.com is very straightforward and no need to put screenshots for it.&lt;/p&gt;

&lt;p&gt;just remember after the project is created go to the settings page and trap the web API key and put it in the azure notification hub fcm settings&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--nigS867W--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AvlxQN5X5S1l8jZOsKsfAjQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--nigS867W--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AvlxQN5X5S1l8jZOsKsfAjQ.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--9Wcx8-JK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2A1RnZIl67EM-JfYdq_EhbCw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--9Wcx8-JK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2A1RnZIl67EM-JfYdq_EhbCw.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 4 Add fcm push notification support to your xamarin app
&lt;/h3&gt;

&lt;p&gt;you can follow Microsoft excellent documentation to do this&lt;/p&gt;

&lt;p&gt;&lt;a href="https://docs.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-xamarin-forms-get-started-push"&gt;Add push notifications to your Xamarin.Forms app - Azure Mobile Apps&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 5 Register your azure function endpoint as a webhook callback
&lt;/h3&gt;

&lt;p&gt;In Azure Portal Go to your FunctionApp resource and navigate your function then click “Get Function URL “&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6DuSf4nz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2ACbQrDa4hXWpqguQspxfvmg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6DuSf4nz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2ACbQrDa4hXWpqguQspxfvmg.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;now provide the URL to your 3rd party provider, in my case it is &lt;a href="https://ko-fi.com/ahmedfouad"&gt;ko-fi.com&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--LHr1D-HR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2Af_Zlqbcv29k3SyMV28P_Sg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--LHr1D-HR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2Af_Zlqbcv29k3SyMV28P_Sg.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;and now we are done.&lt;/p&gt;

&lt;p&gt;I would like to recommend you the &lt;a href="https://amzn.to/2R8JZZT"&gt;Practical Azure Functions: A Guide to Web, Mobile, and IoT Applications&lt;/a&gt; book, it is really one of the best books that will show you the power of lambda functions.&lt;/p&gt;

&lt;p&gt;And please if you like this article, you can support me on &lt;a href="https://ko-fi.com/ahmedfouad"&gt;ko-fi.com&lt;/a&gt; it will only cost you 3 USD but it will help me publishing new content and using more professional tools to create better quality articles, I am sure that 3 USD is not a lot.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://ko-fi.com/ahmedfouad"&gt;Buy AhmedFouad a Coffee. ko-fi.com/ahmedfouad&lt;/a&gt;&lt;/p&gt;

</description>
      <category>azure</category>
      <category>dotnet</category>
      <category>csharp</category>
      <category>xamarin</category>
    </item>
    <item>
      <title>Generator Pattern using CSharp and Linq</title>
      <dc:creator>Ahmed Fouad</dc:creator>
      <pubDate>Sat, 28 Mar 2020 23:10:12 +0000</pubDate>
      <link>https://dev.to/mcc_ahmed/generator-pattern-using-csharp-and-linq-7o9</link>
      <guid>https://dev.to/mcc_ahmed/generator-pattern-using-csharp-and-linq-7o9</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--x3OpVHw6--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/500/1%2ACQJIEXn1-DP-3bNYMDN2Gw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--x3OpVHw6--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/500/1%2ACQJIEXn1-DP-3bNYMDN2Gw.png" alt=""&gt;&lt;/a&gt;Reactive Programming&lt;/p&gt;

&lt;p&gt;The Generator Pattern or the unbound list is a very old technique in functional programming (Haskell) that is possible due to the lazy execution technique.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;IEnumerable&amp;lt;int&amp;gt; EvenNumbers=EnumerableEx.From(x=&amp;gt;2x);
Console.Writeline(EvenNumbers[2]);//4
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;The previous example demonstrated how the generator pattern could be used in CSharp.&lt;/p&gt;

&lt;p&gt;When we defined our EvenNumbers=EnumerableEx.From(x=&amp;gt;2x), we only defined a strategy for calculation any element in the enumerable but the function will only get executed when you access one of it is elements.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List&amp;lt;int&amp;gt; EvenNumbers=EnumerableEx.From(x=&amp;gt;2x).Take(10).ToList();
Console.Writeline(EvenNumbers); //0,2,4,3,8,10,12,14,16,18
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;The conversation between the Inbounded list and the bounded list is simply achieved by adding bounds using linq Skip and Take operators.&lt;/p&gt;
&lt;h3&gt;
  
  
  Execution Control
&lt;/h3&gt;

&lt;p&gt;In normal c# imperative code, the execution control is usually done by loops and conditions (the natural evolution of GoTo). The factory pattern unleashes the power of LINQ for execution control.&lt;/p&gt;
&lt;h4&gt;
  
  
  Parallel programming(PLINQ)
&lt;/h4&gt;


&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var evenNumbers=EnumerableEx.From(x=&amp;gt;2x).Take(10).AsParallel().ToList();
Console.Writeline(EvenNumbers);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Conditions for skipping and Taking&lt;/strong&gt;
&lt;/h3&gt;


&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var evenNumbers=EnumerableEx.From(x=&amp;gt;2x);

var data = evenNumbers.Scan((0, 0), (tuple, i) =&amp;gt; (i, tuple.Item2 + i))
.Skip(1)
.TakeWhile(i =&amp;gt; i.Item2 &amp;lt;= 12)
.Select(tuple =&amp;gt; tuple.Item1).ToList();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;The previous method will return all the even numbers that their sum is less than or equal to 12 {0,2,4,6}.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;you can find the scan method and more linq extensions in the LinqMore Library&lt;/p&gt;

&lt;p&gt;&lt;a href="https://morelinq.github.io/"&gt;https://morelinq.github.io/&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;
  
  
  &lt;strong&gt;Memorization&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;When dealing with lazy execution memorization is a very important concept as it prevents the recalculation of enumerable elements.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var evenNumbers=EnumerableEx.From(x=&amp;gt;2x);
var data1 =evenNumbers.Take(10).ToList();
var data2 =evenNumbers.Take(20).ToList();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;the previous code problem is that it will calculate the first 10 elements in order to build the data1 list and then it will calculate the first 20 elements independently in order to build the data2 list. that means that the first 10 elements are calculated twice.&lt;/p&gt;

&lt;p&gt;In order to resolve this, I will use the .Memorize() extension method from the &lt;a href="https://morelinq.github.io/"&gt;LinqMore &lt;/a&gt;library.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var evenNumbers=EnumerableEx.From(x=&amp;gt;2x).Memorize();
var data1 =evenNumbers.Take(10).ToList();
var data2 =evenNumbers.Take(20).ToList();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Now the first 10 elements will get calculated and memorized when building the data1 list and they will get recalled when building the data2 so the elements from 10 to 20 will only get calculated.&lt;/p&gt;
&lt;h3&gt;
  
  
  Generator Pattern Implementation
&lt;/h3&gt;

&lt;p&gt;Our implementation starts with the Generator Enmurable Which implements the IEnumerable Interface&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;it is very straight forward it receives the generator function as a parameter and every time the MoveNext method is called it generates the item using the generator function and increments the index.&lt;/p&gt;

&lt;p&gt;and here the standard implementation of the IEnumerable&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;and finally the EnumerableEx helper class&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static class EnumerableEx

{

public static IEnumerable&amp;lt;T&amp;gt; From&amp;lt;T&amp;gt;( Func&amp;lt;int, T&amp;gt; generatorFunc)

{

return new Generator&amp;lt;T&amp;gt;(generatorFunc);

}

}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h3&gt;
  
  
  A Real-Life example
&lt;/h3&gt;

&lt;p&gt;Personally I have used the generator pattern in a lot of projects that I cannot reveal here so it is kind of hard to give you a high-quality real-life example but I can ask you to build a xamarin mobile app that shows the user 2 numbers on the screen and ask him to sum it, if he do it correctly add one point to his score and if the wrong deducts one point. He wins only when his score is 10 and he loose when his score is -10.&lt;/p&gt;

&lt;p&gt;if you like this article please share it on your social media and I appreciate if you would like to pay the coffee for me on&lt;/p&gt;

&lt;p&gt;&lt;a href="https://ko-fi.com/ahmedfouad"&gt;Buy AhmedFouad a Coffee. ko-fi.com/ahmedfouad&lt;/a&gt;&lt;/p&gt;

</description>
      <category>functionalprogrammi</category>
      <category>csharp</category>
      <category>xamarin</category>
      <category>reactiveprogramming</category>
    </item>
    <item>
      <title>Introduction to OPTION type in CSharp</title>
      <dc:creator>Ahmed Fouad</dc:creator>
      <pubDate>Sun, 23 Feb 2020 20:00:31 +0000</pubDate>
      <link>https://dev.to/mcc_ahmed/introduction-to-option-type-in-csharp-10e6</link>
      <guid>https://dev.to/mcc_ahmed/introduction-to-option-type-in-csharp-10e6</guid>
      <description>&lt;p&gt;Option type is a polymorphic type introduced in Type theory and has been adopted in many programming languages most of them are functional languages like (F#, Haskell, typescript,…) but some are object-oriented too like java.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--i1gO-Wg5--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2ARi2Swg1mhpS_0ARF.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--i1gO-Wg5--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2ARi2Swg1mhpS_0ARF.jpg" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In CSharp there is no yet support for OPTION type as a native type but there is a very strong and robust 3rd party implementation using this NuGet.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.nuget.org/packages/Optional/"&gt;Optional 4.0.0&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  What is Option Type?
&lt;/h3&gt;

&lt;p&gt;Option type is a type that can have value or nothing, similar to nullable types that can be a value or null, but option type is not the value but a function of value.&lt;/p&gt;

&lt;p&gt;if we try to express the difference between Nullabe and optional in a semi-formal notation it&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Object X =&amp;gt; X : Object||Null

Optional X =&amp;gt; F(x):Object||Nothing
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3&gt;
  
  
  Real-World Example
&lt;/h3&gt;


&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public ReservationViewModel AddItemToReservation(string id,string itemId)

{

var reservation = \_restaurant.GetReservation(id);

if (reservation == null)

return null;

var item = \_inventory.GetItem(itemId);

if (item == null)

return null;

reservation.Items.Add(item);

return ReservationViewModel(reservation);

}

private ReservationViewModel MapReservationViewModel(Reservation reservation)

{

if (reservation == null)

return null;

var user = \_ClientsManger.GetUser(reservation.Id);

return new ReservationViewModel()

{

From = reservation.From,

User = user != null ? $"{user.FirstName} {user.SecondName}" : "Not a client",

Id = reservation.Id,

Name = reservation.Name,

To = reservation.To

};

}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;The previous method gets a user reservation from a database and query for an inventory item and adds the inventory item to the reservation than call “MapReservationViewModel” to map the result to a reservation view model.&lt;/p&gt;

&lt;p&gt;It is clear that we need to keep checking for null values and propagate nulls to prevent crashing so the first method check if the reservation is not Null and the Inventory Item is not null and the if so it just returns null and the second method has to ensure that the reservation it gets is not null otherwise it has to return null. And so on every method that will be in the chain should handle the null cases.&lt;/p&gt;

&lt;p&gt;While you could imagine that it will be an easy task and that you can handle it with the help of the null propagation feature in c# or by manually checking, I would assure you that in complex cases you would end up with a lot of null reference exceptions.&lt;/p&gt;
&lt;h3&gt;
  
  
  The Functional Programming solution
&lt;/h3&gt;

&lt;p&gt;I would start by doing a small refactor in the GetReservation, GetInventory, GetUserMethods to return option instead of nullable&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public Optional.Option&amp;lt;Reservation&amp;gt; GetReservation(string id)

{

\_reservations.TryGetValue(id, out Reservation result);

return result.SomeNotNull();

}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Then in my AddItemToReservation method, I will join the result of GetReservation and GetInventoryItem&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public Option&amp;lt;ReservationViewModel&amp;gt; AddItemToReservation(string id, string itemId)

{

var reservationOptinal = \_restaurant.GetReservation(id);

var itemOptional = \_inventory.GetItem(itemId);

var result= reservationOptinal.Intersect(itemOptional)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;The intersection of 2 optional will return an optional tuple of both iff both has values and Nothing if any of them has nothing. ( AND in logic operators).&lt;/p&gt;

&lt;p&gt;now I will start to apply my value transformations using the select operator&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public Option&amp;lt;ReservationViewModel&amp;gt; AddItemToReservation(string id, string itemId)

{
var result= reservationOptinal.Intersect(itemOptional)

.Select(AddItemFunc);

Reservation AddItemFunc(( Reservation , Item ) tuple)

{

var (reservation, item) = tuple;

reservation.Items.Add(item);

return reservation;

}
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;AddItemFunc is an inner function that receives a value tuple of (reservation, item) and adds the item to the reservation and returns the reservation.&lt;/p&gt;

&lt;p&gt;now we will only need to build another optional value type by making a union of reservation and OptionalUser and that can be done easily using the select operator&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.Select(reservation =&amp;gt; (reservation, \_ClientsManger.GetUser(reservation.UserId)))

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Now the full method will be :&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;I think it is readability is acceptable and it is very computational efficient as at any time if the option becomes Nothing due to any transformation the method will directly return Nothing without continuing the computation.&lt;/p&gt;

&lt;p&gt;Final note the Intersect method is not yet included in the Optional library so you can find it here :&lt;/p&gt;

&lt;p&gt;&lt;a href="https://gist.github.com/TheFo2sh/121c208a6e1bb235df32e43d51b89c68"&gt;https://gist.github.com/TheFo2sh/121c208a6e1bb235df32e43d51b89c68&lt;/a&gt;&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>csharp</category>
      <category>softwaredevelopment</category>
      <category>functionalprogrammi</category>
    </item>
    <item>
      <title>The power of Reactive Programming and CancellationTokens</title>
      <dc:creator>Ahmed Fouad</dc:creator>
      <pubDate>Sun, 09 Feb 2020 22:54:19 +0000</pubDate>
      <link>https://dev.to/mcc_ahmed/the-power-of-reactive-programming-and-cancellationtokens-1cdf</link>
      <guid>https://dev.to/mcc_ahmed/the-power-of-reactive-programming-and-cancellationtokens-1cdf</guid>
      <description>&lt;p&gt;One of the most common scenarios that a mobile developer could encounter is to have an async method that depends on a platform capability like Internet connectivity, Bluetooth, Camera,…&lt;/p&gt;

&lt;p&gt;While checking for the capability availability sound straight forward and a method like this one can do the job&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public async Task&amp;lt;string&amp;gt; GetDataAsync()

{

if (Connectivity.NetworkAccess != NetworkAccess.Internet

||Connectivity.ConnectionProfiles.All(x=&amp;gt;x!=ConnectionProfile.WiFi))

return null;

HttpResponseMessage response;

using (var httpClient = new HttpClient())

{

response = await httpClient.GetAsync("https://medium.com/feed/@Medium");

}

response.EnsureSuccessStatusCode();

return await response.Content.ReadAsStringAsync();

}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;What if after the checking pass or while downloading the internet connection gets interrupted, In this case, you could get an HttpException may be in this case it can handle the exception but what the connection type changed from wifi to cellular for example, now you will download the data from the user cellular data.&lt;/p&gt;

&lt;p&gt;The good news is that HttpClient.GetAsync has an overload that takes a CancellationToken as a parameter, so now all that we need is to use this overlead and pass to it a CancellationToken that gets canceled when the internet connection changed.&lt;/p&gt;

&lt;p&gt;but here one challenged the xamarin essential expose a ConnectivityChanged event and implementing a CancellationTokenSource based on events is a bit tricky and can introduce more bugs to your code.&lt;/p&gt;

&lt;p&gt;In this article, I will provide you with a reusable method that you can use to convert any .net event to a CancellationTokenSource.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6NpCFtZ2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2ANdO1w22wkOOXkcf9H5IKQA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6NpCFtZ2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2ANdO1w22wkOOXkcf9H5IKQA.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We first will convert our Event to an &lt;a href="https://docs.microsoft.com/en-us/previous-versions/dotnet/reactive-extensions/hh244252(v%3Dvs.103)"&gt;Observable&lt;/a&gt;using C# reactive extension&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Observable

.FromEventPattern&amp;lt;Xamarin.Essentials.ConnectivityChangedEventArgs&amp;gt;(

handler =&amp;gt; Xamarin.Essentials.Connectivity.ConnectivityChanged += handler, handler =&amp;gt; Xamarin.Essentials.Connectivity.ConnectivityChanged -= handler)

.FirstAsync(x=&amp;gt;x.EventArgs.NetworkAccess!=NetworkAccess.Internet)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;and then will convert the &lt;a href="https://docs.microsoft.com/en-us/previous-versions/dotnet/reactive-extensions/hh244252(v%3Dvs.103)"&gt;observable&lt;/a&gt;to a custom implementation of CancellationTokenSource&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;our ObservableCancellationTokenSource is just an adapter that takes IObservavle As a parameter subscribe on it and just call the cancellation method when the observable publish a new value.&lt;/p&gt;

&lt;p&gt;The dispose method takes care of disposing of the &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.cancellationtokensource?view=netframework-4.8"&gt;CanellationTokenSource&lt;/a&gt;and the subscription so no memory leaks will get introduced.&lt;/p&gt;

&lt;p&gt;now the modified version of our GetDataAsync method should look like that&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static async Task&amp;lt;string&amp;gt; GetDataAsync(CancellationToken cancellationToken)

{

if (cancellationToken.IsCancellationRequested)

return null;

HttpResponseMessage response;

using (var httpClient = new HttpClient())

{

response = await httpClient.GetAsync("https://medium.com/feed/@Medium", cancellationToken);

}

response.EnsureSuccessStatusCode();

return await response.Content.ReadAsStringAsync();

}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;and the caller will look like&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var cancellationTokenSource = Observable

.FromEventPattern&amp;lt;ConnectivityChangedEventArgs&amp;gt;(

handler =&amp;gt; Connectivity.ConnectivityChanged += handler,

handler =&amp;gt; Connectivity.ConnectivityChanged -= handler)

.FirstAsync(x =&amp;gt; x.EventArgs.NetworkAccess != NetworkAccess.Internet

||Connectivity.ConnectionProfiles.All(connectionProfile =&amp;gt; connectionProfile != ConnectionProfile.WiFi))

.ToCancellationTokenSource();

using (cancellationTokenSource)

{

var result = await FullState.GetDataAsync(cancellationTokenSource.Token);

}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h3&gt;
  
  
  Rx Bonus (combine events)
&lt;/h3&gt;

&lt;p&gt;as we are using RX observable, we have the opportunity of combining multiple events to a single CancellationToken.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Func&amp;lt;EventPattern&amp;lt;ConnectivityChangedEventArgs&amp;gt;, bool&amp;gt; connectivityPredicate = x =&amp;gt; x.EventArgs.NetworkAccess != NetworkAccess.Internet

||Connectivity.ConnectionProfiles.All(connectionProfile =&amp;gt; connectionProfile != ConnectionProfile.WiFi);

Func&amp;lt;EventPattern&amp;lt;EnergySaverStatusChangedEventArgs&amp;gt;, bool&amp;gt; batteryPredicate = x =&amp;gt; x.EventArgs.EnergySaverStatus == EnergySaverStatus.On;

var connectivityObservable = Observable

.FromEventPattern&amp;lt;ConnectivityChangedEventArgs&amp;gt;(

handler =&amp;gt; Connectivity.ConnectivityChanged += handler,

handler =&amp;gt; Connectivity.ConnectivityChanged -= handler);

var batteryObservable = Observable

.FromEventPattern&amp;lt;EnergySaverStatusChangedEventArgs&amp;gt;(

handler =&amp;gt; Battery.EnergySaverStatusChanged += handler,

handler =&amp;gt; Battery.EnergySaverStatusChanged -= handler);

var cancellationTokenSource = connectivityObservable

.CombineLatest(batteryObservable,(connectivityArgs, batteryArgs) =&amp;gt; (connectivityArgs, batteryArgs))

.FirstAsync(x=&amp;gt;connectivityPredicate(x.connectivityArgs)|| batteryPredicate(x.batteryArgs))

.ToCancellationTokenSource();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;similar behavior can be achieved using CancellationTokenSource.CreateLinkedTokenSource but I prefer the observable approach.&lt;/p&gt;

</description>
      <category>mobileapps</category>
      <category>csharpprogramming</category>
      <category>xamarinforms</category>
      <category>xamarin</category>
    </item>
    <item>
      <title>How you can use Artifical Intelligence in your xamarin apps (a real-world example)</title>
      <dc:creator>Ahmed Fouad</dc:creator>
      <pubDate>Sun, 01 Dec 2019 15:26:31 +0000</pubDate>
      <link>https://dev.to/mcc_ahmed/how-you-can-use-artifical-intelligence-in-your-xamarin-apps-a-real-world-example-22ii</link>
      <guid>https://dev.to/mcc_ahmed/how-you-can-use-artifical-intelligence-in-your-xamarin-apps-a-real-world-example-22ii</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--gkotVlxD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AOPCL9ZfGHSY0xTzqV7WKTQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--gkotVlxD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AOPCL9ZfGHSY0xTzqV7WKTQ.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;For most of the mobile/web developers, AI is not an option while some have studied it in the university or have tried to read about it. They keep staking with the problem of applicability “How and what to apply”&lt;/p&gt;

&lt;p&gt;In this article, we will use make a News App and we will make use of the K-means algorithm to group our news. If you like the article and wanna more of AI topics for xamarin or mobile development please clap it, share it everywhere so I can see that more people want this topic.&lt;/p&gt;

&lt;p&gt;Our app in a news app that shows some articles from &lt;a href="https://newsapi.org"&gt;newsapi.org&lt;/a&gt; and we need to group these articles by date in a way that makes sense to the user.&lt;/p&gt;

&lt;p&gt;A way that makes sense means that depending on the data itself we will generate the groups and the groups.&lt;/p&gt;

&lt;p&gt;We will use the K-means algorithm to do this, let me explain first how it works but anyways it is already implemented in &lt;a href="http://accord-framework.net/"&gt;Accord.net framework&lt;/a&gt; so we will not implement it but ourselves.&lt;/p&gt;

&lt;p&gt;1- Pick random centroids which will be the centers of your groups&lt;/p&gt;

&lt;p&gt;2- measure the distance of each element and the centroid.&lt;/p&gt;

&lt;p&gt;3- recalculate the centroids so the distance is minimized&lt;/p&gt;

&lt;p&gt;4- keep doing this for a number of iteration or until the distance within each group reaches a threshold that you already defined.&lt;/p&gt;

&lt;p&gt;the nuggets packages that we will need to implement our app are&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.nuget.org/packages/Accord.MachineLearning/"&gt;https://www.nuget.org/packages/Accord.MachineLearning&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;for AI&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public async void Init()

{

var news=await GetNews().ToArrayAsync();

var points = news.Select(x =&amp;gt; new double[] {x.PublishedAt.ToUnixTimeSeconds()}).ToArray();

var kmeans = new KMeans(5);

var clusters = kmeans.Learn(points);

var labels = clusters.Decide(points);

Articles = news.Select((value, index) =&amp;gt; (value, clusters[labels[index]]))

.OrderByDescending(x =&amp;gt; x.Item2.Centroid[0])

.Select(x =&amp;gt; new ArticleViewModel()

{

Title = x.value.Title,

Description = x.value.Description,

Image = x.value.UrlToImage?.ToString(),

Group = DateTimeOffset.FromUnixTimeSeconds((long) x.Item2.Centroid[0]).Humanize()

}).ToList();

}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;so at first, I get all the news articles in an array and I mapped every news item to an array of a single double which represents the publishing date.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var kmeans = new KMeans(5);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;create a kmeans object that will cluster our points in 5 clusters (you can change 5 to anything you want).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var clusters = kmeans.Learn(points);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;will generate the 5 centroids for our date.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var labels = clusters.Decide(points);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;will group the data in the previously generated clusters.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Articles = news.Select((value, index) =&amp;gt; (value, clusters[labels[index]]))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;will return a list of value tuples that contain (Article, Centroid in Unix millisecond)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.Select(x =&amp;gt; new ArticleViewModel()

{

Title = x.value.Title,

Description = x.value.Description,

Image = x.value.UrlToImage?.ToString(),

Group = DateTimeOffset.FromUnixTimeSeconds((long) x.Item2.Centroid[0]).Humanize()

}).ToList();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;we create a view model for each article that contains the Title, Description, Image and the humanized form of it is centroid using &lt;a href="https://github.com/Humanizr/Humanizer"&gt;Humanizer&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The full view model&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using System;

using System.Collections.Concurrent;

using System.Collections.Generic;

using System.ComponentModel;

using System.Diagnostics;

using System.Linq;

using System.Net.Http;

using System.Runtime.CompilerServices;

using System.Text;

using System.Threading.Tasks;

using Accord.MachineLearning;

using App9.Annotations;

using Dasync.Collections;

using Humanizer;

using Newtonsoft.Json;

using QuickType;

using Xamarin.Forms;

namespace App9

{

public class ArticleViewModel

{

public string Group { get; set; }

public string Title { get; set; }

public string Image { get; set; }

public ImageSource ImageSource =&amp;gt; Image != null ? ImageSource.FromUri(new Uri(Image,UriKind.RelativeOrAbsolute)) : null;

public string Description { get; set; }

}

class MainPageViewModel:INotifyPropertyChanged

{

private List&amp;lt;ArticleViewModel&amp;gt; \_articles;

public List&amp;lt;ArticleViewModel&amp;gt; Articles

{

get =&amp;gt; \_articles;

set

{

\_articles = value;

OnPropertyChanged();

}

}

public async void Init()

{

var news=await GetNews().ToArrayAsync();

var points = news.Select(x =&amp;gt; new double[] {x.PublishedAt.ToUnixTimeSeconds()}).ToArray();

var kmeans = new KMeans(5);

var clusters = kmeans.Learn(points);

var labels = clusters.Decide(points);

Articles = news.Select((value, index) =&amp;gt; (value, clusters[labels[index]]))

.OrderByDescending(x =&amp;gt; x.Item2.Centroid[0])

.Select(x =&amp;gt; new ArticleViewModel()

{

Title = x.value.Title,

Description = x.value.Description,

Image = x.value.UrlToImage?.ToString(),

Group = DateTimeOffset.FromUnixTimeSeconds((long) x.Item2.Centroid[0]).Humanize()

}).ToList();

}

private async IAsyncEnumerable&amp;lt;Article&amp;gt; GetNews()

{

using (var httpClient = new HttpClient())

{

var rawResponse = await httpClient.GetStringAsync(

"https://newsapi.org/v2/top-headlines?sortBy=popularity&amp;amp;pageSize=100&amp;amp;country=us&amp;amp;apiKey=dd652e7605d54451a4179d0b28d3f928");

var response = JsonConvert.DeserializeObject&amp;lt;Response&amp;gt;(rawResponse);

foreach(var article in response.Articles)

{

yield return article;

}

}

}

public event PropertyChangedEventHandler PropertyChanged;

[NotifyPropertyChangedInvocator]

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)

{

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

}

}

}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The view&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?xml version="1.0" encoding="utf-8" ?&amp;gt;

&amp;lt;ContentPage xmlns="http://xamarin.com/schemas/2014/forms"

xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

xmlns:d="http://xamarin.com/schemas/2014/forms/design"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

mc:Ignorable="d"

xmlns:syncfusion="clr-namespace:Syncfusion.ListView.XForms;assembly=Syncfusion.SfListView.XForms"

xmlns:data="clr-namespace:Syncfusion.DataSource;assembly=Syncfusion.DataSource.Portable"

x:Class="App9.MainPage"&amp;gt;

&amp;lt;StackLayout&amp;gt;

&amp;lt;syncfusion:SfListView ItemSize="100" ItemSpacing="20" ItemsSource="{Binding Articles}" &amp;gt;

&amp;lt;syncfusion:SfListView.DataSource&amp;gt;

&amp;lt;data:DataSource&amp;gt;

&amp;lt;data:DataSource.GroupDescriptors&amp;gt;

&amp;lt;data:GroupDescriptor PropertyName="Group"/&amp;gt;

&amp;lt;/data:DataSource.GroupDescriptors&amp;gt;

&amp;lt;/data:DataSource&amp;gt;

&amp;lt;/syncfusion:SfListView.DataSource&amp;gt;

&amp;lt;syncfusion:SfListView.ItemTemplate&amp;gt;

&amp;lt;DataTemplate&amp;gt;

&amp;lt;Grid ColumnSpacing="5"&amp;gt;

&amp;lt;Grid.ColumnDefinitions&amp;gt;

&amp;lt;ColumnDefinition Width="3\*"&amp;gt;&amp;lt;/ColumnDefinition&amp;gt;

&amp;lt;ColumnDefinition Width="7\*"&amp;gt;&amp;lt;/ColumnDefinition&amp;gt;

&amp;lt;/Grid.ColumnDefinitions&amp;gt;

&amp;lt;Image Source="{Binding ImageSource}" VerticalOptions="Start" Grid.Column="0"/&amp;gt;

&amp;lt;StackLayout Grid.Column="1" Spacing="10"&amp;gt;

&amp;lt;Label Text="{Binding Title}" FontSize="Title" MaxLines="1" /&amp;gt;

&amp;lt;Label Text="{Binding Description}" FontSize="Body" MaxLines="3" /&amp;gt;

&amp;lt;/StackLayout&amp;gt;

&amp;lt;/Grid&amp;gt;

&amp;lt;/DataTemplate&amp;gt;

&amp;lt;/syncfusion:SfListView.ItemTemplate&amp;gt;

&amp;lt;/syncfusion:SfListView&amp;gt;

&amp;lt;/StackLayout&amp;gt;

&amp;lt;/ContentPage&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



</description>
      <category>android</category>
      <category>xamarin</category>
      <category>ai</category>
      <category>csharpprogramming</category>
    </item>
    <item>
      <title>How to use CanellationToken With ICommand A Solid Implementation of ICommand</title>
      <dc:creator>Ahmed Fouad</dc:creator>
      <pubDate>Fri, 15 Nov 2019 00:10:37 +0000</pubDate>
      <link>https://dev.to/mcc_ahmed/how-to-use-canellationtoken-with-icommand-a-solid-implementation-of-icommand-3aaa</link>
      <guid>https://dev.to/mcc_ahmed/how-to-use-canellationtoken-with-icommand-a-solid-implementation-of-icommand-3aaa</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ZTwvCLU5--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1000/0%2A7M9y-4W6Fj1lursy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ZTwvCLU5--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1000/0%2A7M9y-4W6Fj1lursy.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This article can be considered a part 2 of &lt;a href="https://medium.com/@csharpwriter/async-command-a-modern-implementation-of-icommand-1933ca6ea9a5"&gt;Async Command A Modern Implementation of ICommand&lt;/a&gt; in which we were addressing the async problem in ICommand by blocking the CanExecuteStatus to false in case the previous task was not yet completed.&lt;/p&gt;

&lt;p&gt;In this article, we will address the same problem using a different way we will use CancellationToken to cancel the pending task and execute the new one, imagine you have a news app where the user should click on one title in a listview the app will download the news article and will show it, what happens when the user clicks on a title and before the download complete he clicks on another one.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;And you can use it in your ViewModel like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CommandAsync&amp;lt;Uri&amp;gt; commandAsync = new CommandAsync&amp;lt;Uri&amp;gt;(async (uri,cancellationToken)=&amp;gt;await client.GetAsync(uri,cancellationToken));
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;or can be simplified to this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CommandAsync&amp;lt;Uri&amp;gt; commandAsync = new CommandAsync&amp;lt;Uri&amp;gt;(httpclient.GetAsync);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



</description>
      <category>androidappdevelopm</category>
      <category>asynchronous</category>
      <category>csharp</category>
      <category>xamarin</category>
    </item>
  </channel>
</rss>
