<?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 Onafeso Olawale on Medium]]></title>
        <description><![CDATA[Stories by Onafeso Olawale on Medium]]></description>
        <link>https://medium.com/@onafesowale?source=rss-49c59b67c139------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fYNupzE9jg_0Vnq4ZRd2rg.jpeg</url>
            <title>Stories by Onafeso Olawale on Medium</title>
            <link>https://medium.com/@onafesowale?source=rss-49c59b67c139------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 02:36:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@onafesowale/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[Automating .NET API Deployment: A Step-by-Step Guide Using AWS EC2, ECR and GitHub Actions]]></title>
            <link>https://medium.com/@onafesowale/automating-net-api-deployment-a-step-by-step-guide-using-aws-ec2-ecr-and-github-actions-b7899684b245?source=rss-49c59b67c139------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7899684b245</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Onafeso Olawale]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 06:33:14 GMT</pubDate>
            <atom:updated>2024-11-01T06:42:26.944Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automating .NET API Deployment: A Step-by-Step Guide Using AWS EC2, ECR and GitHub Actions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*tOsNautQFPVgyP0J8R0qTg.jpeg" /></figure><p>In this article, we’ll deploy a .NET 8 minimal API to AWS EC2, setting a CI/CD pipeline to automate future deployments using AWS Elastic Container Registry (ECR) and GitHub Actions.</p><p>To follow along with this guide, you’ll need a GitHub account and an AWS account. This article assumes a basic knowledge of AWS, Docker and GitHub Actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hdAX7AbzAHB1GN75Yq87XQ.png" /></figure><p><strong>Create a GitHub Repository and Set Up the Project<br></strong>Start by creating a new repository on GitHub. Once you’ve created it, clone the repository to your local machine to set up your project workspace.</p><pre>git clone &lt;the-repository-url&gt;<br>cd &lt;repository-name&gt;</pre><pre>dotnet new sln -n Deploy // this will create a solution file<br>dotnet new webapi -n Deploy // this will create a webapi project<br>dotnet sln add Deploy // this will add the webapi project to the solution</pre><p>I’ve added code to ‘<em>program.cs</em>’, including an endpoint that returns a list of books, as shown below.</p><pre>var builder = WebApplication.CreateBuilder(args);<br><br>// Add services to the container.<br>// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle<br>builder.Services.AddEndpointsApiExplorer();<br>builder.Services.AddSwaggerGen();<br><br>var app = builder.Build();<br><br>// Configure the HTTP request pipeline.<br>if (app.Environment.IsDevelopment())<br>{<br>    app.UseSwagger();<br>    app.UseSwaggerUI();<br>}<br><br>app.UseHttpsRedirection();<br><br>app.MapGet(&quot;/api/books&quot;, () =&gt;<br>{<br>    return Results.Ok(Book.All);<br>})<br>.WithName(&quot;GetBooks&quot;)<br>.WithOpenApi();<br><br>app.Run();<br><br>public class Book<br>{<br>    public Book(int id, string name)<br>    {<br>        Id = id; <br>        Name = name;<br>    }<br><br>    public int Id { get; set; }<br>    public string Name { get; set; }<br><br>    public static List&lt;Book&gt; All = [<br>        new Book(1, &quot;Things Fall Apart&quot;),<br>        new Book(2, &quot;Lord Of The Rings&quot;),<br>        new Book(3, &quot;Romeo and Juliet&quot;)<br>        ];<br>}</pre><p><strong>Containerize the Application</strong><br>Let’s now containerize our application. I’ve added a Dockerfile at the solution level of the project. To add a Dockerfile to your project, right-click on the solution, select ‘<em>Add</em>’ and then ‘<em>New Item…</em>’. Name the file ‘<em>Dockerfile</em>’ (without an extension).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*mqQCEc-xIo07HWSphokELQ.png" /></figure><pre>FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base<br>WORKDIR /app<br>EXPOSE 8080<br>EXPOSE 8081<br><br>FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build<br>ARG BUILD_CONFIGURATION=Release<br>WORKDIR /app<br>COPY [&quot;Deploy/Deploy.csproj&quot;, &quot;Deploy/Deploy.csproj&quot;]<br>RUN dotnet restore &quot;Deploy/Deploy.csproj&quot;<br>COPY . .<br>WORKDIR &quot;/app/Deploy&quot;<br>RUN dotnet build -c $BUILD_CONFIGURATION -o /app/build<br><br>FROM build AS publish<br>ARG BUILD_CONFIGURATION=Release<br>RUN dotnet publish -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false<br><br>FROM base AS final<br>COPY --from=publish /app/publish .<br>ENTRYPOINT [&quot;dotnet&quot;, &quot;Deploy.dll&quot;]</pre><p>Let’s build an image from this Dockerfile to verify everything is set up correctly. In the solution directory, run the following commands. Note that Docker must be installed on your local machine to execute these commands</p><pre>docker build -t deploy . // build the image from docker file<br>docker run -d --name deploy-cont -p 8080:8080 deploy // run a container from the image</pre><p>The first command builds an image from the Dockerfile located in the current directory. The second command runs a container from this image. If you’ve followed along, you can now navigate to <a href="http://localhost:8080/api/books">http://localhost:8080/api/books</a> to access the API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*Qj6eX_SO5GJsZIpBVtYE4w.png" /></figure><p>You can now push your code to GitHub.</p><pre>git add .<br>git commit -m &quot;init&quot;<br>git push origin main </pre><p><strong>Set up Cloud Services(EC2, ECR)<br></strong>In this section, we will set up an EC2 instance and create a private repository in Amazon Elastic Container Registry (ECR). We will push our docker image to this repository, and then the EC2 instance will pull the Docker image to run the container from it.</p><p>To automate this process, GitHub Actions will handle these tasks on our behalf. To authenticate with ECR and push the Docker image, we need to create the necessary IAM roles.</p><p>Let’s create a role for this purpose using AWS Cloud Formation. You can either download the CloudFormation template from the <a href="https://d38mtn6aq9zhn6.cloudfront.net/configure-aws-credentials-latest.yml">link provided</a> or copy the template below and paste in into a .<em>yml</em> file</p><pre>Parameters:<br>  GitHubOrg:<br>    Description: Name of GitHub organization/user (case sensitive)<br>    Type: String<br>  RepositoryName:<br>    Description: Name of GitHub repository (case sensitive)<br>    Type: String<br>  OIDCProviderArn:<br>    Description: Arn for the GitHub OIDC Provider.<br>    Default: &quot;&quot;<br>    Type: String<br>  OIDCAudience:<br>    Description: Audience supplied to configure-aws-credentials.<br>    Default: &quot;sts.amazonaws.com&quot;<br>    Type: String<br><br>Conditions:<br>  CreateOIDCProvider: !Equals <br>    - !Ref OIDCProviderArn<br>    - &quot;&quot;<br><br>Resources:<br>  Role:<br>    Type: AWS::IAM::Role<br>    Properties:<br>      AssumeRolePolicyDocument:<br>        Statement:<br>          - Effect: Allow<br>            Action: sts:AssumeRoleWithWebIdentity<br>            Principal:<br>              Federated: !If <br>                - CreateOIDCProvider<br>                - !Ref GithubOidc<br>                - !Ref OIDCProviderArn<br>            Condition:<br>              StringEquals:<br>                token.actions.githubusercontent.com:aud: !Ref OIDCAudience<br>              StringLike:<br>                token.actions.githubusercontent.com:sub: !Sub repo:${GitHubOrg}/${RepositoryName}:*<br><br>  GithubOidc:<br>    Type: AWS::IAM::OIDCProvider<br>    Condition: CreateOIDCProvider<br>    Properties:<br>      Url: https://token.actions.githubusercontent.com<br>      ClientIdList: <br>        - sts.amazonaws.com<br>      ThumbprintList:<br>        - ffffffffffffffffffffffffffffffffffffffff<br><br>Outputs:<br>  Role:<br>    Value: !GetAtt Role.Arn </pre><p>Next, let’s proceed to AWS CloudFormation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NKRqH_HEiB4ba09u5FN41g.png" /></figure><p>Click on <strong>Create Stack</strong> and select <strong>With new resources (standard)</strong><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*ltsH07SQ3qKyYkHBpqGGtQ.png" /></figure><p>Under <strong>Prerequisite — Prepare template</strong> select <strong>Choose an existing template.</strong> Then under <strong>Specify template,</strong> choose <strong>Upload a template file </strong>and proceed to upload the <em>.yml</em> file you downloaded earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*tjxIcpjwCeLemp-ARkwYaA.png" /></figure><p>Click <strong>Next. </strong>Enter a name for your stack. Under <strong>Parameters</strong>, provide your GitHub username for <strong>GitHubOrg</strong>, and the name of the repository you want to deploy for <strong>RepositoryName</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*huXOFBvkdt9S7Yo0MkMPLQ.png" /></figure><p>Click <strong>Next</strong>. Check the box to acknowledge that ‘AWS CloudFormation might create IAM resources’ and click <strong>Next </strong>again. Finally, click <strong>Submit</strong>.</p><p>Once the process is complete, navigate to the IAM service to confirm the role. Under <strong>AccessManagement</strong>, click on <strong>Identity providers</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*FMY01EozinhWDFVwa0H7Qw.png" /></figure><p>Under <strong>Identity providers</strong>, you should see an entry similar to the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*frlzi-WF8-GAIe9l3p_d2w.png" /></figure><p>Let’s confirm the role that was created. Under <strong>Access management</strong>, click on <strong>Roles</strong>. Since I named my Cloud Formation stack <strong>github-role-stack, </strong>I will search for that name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*sN9CcVdOSi6sUE5wuIl6Sg.png" /></figure><p>We can confirm that the role has been created. Remember, GitHub Actions will push to ECR on our behalf, so we need to grant the necessary permissions. Click on the role, click <strong>Add permissions </strong>followed by <strong>Attach policies</strong>. Assign the permission checked below to this role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A-FuNzdpuNnp1DnDq5CdyA.png" /></figure><p><strong>Setup EC2 Instance<br></strong>Now let’s set up the EC2 instance. Navigate to the EC2 dashboard; you can find it using the search bar. Click on <strong>Launch instance</strong>. <br>1. Give your server a name. <br>2. Under <strong>Application and OS Images</strong>, select <strong>Amazon Linux</strong>. <br>3. For instance types, I will be using the <strong>t2.micro </strong>instance type (free tier eligible). <br>4. Click on <strong>Create new key pair </strong>and under <strong>Key pair (login)</strong>. We will need the private key to SSH into the EC2 instance. <br>5. Enter a key pair name, leave the other settings as default and click <strong>Create new pair</strong>. A <em>.pem</em> file will be downloaded to your local machine. We will reference this file shortly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*c_FPidQl-M4VbBdaEQmwSg.png" /></figure><p>Leave the other settings as they are. Under <strong>Configure storage</strong>, set the EBS (Elastic Block Store) volume to <strong>24 GiB</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*CpJQYWfVfrmv6TJ9nXMVnw.png" /></figure><p>Under <strong>Advanced details,</strong> paste the following script under <strong>User data</strong>. This script will run only once, during the initialization of your EC2 instance to install Docker. Then click on <strong>Launch instance</strong>.</p><p>Since our EC2 instance needs to pull images from ECR, we need assign an IAM role to it. Navigate to the EC2 instance you just created. Click on <strong>Actions</strong>, then <strong>Security</strong> and select <strong>Modify IAM role</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*7WAH8cFZUi66ZxMFDfOQDg.png" /></figure><p>Click on <strong>Create new role</strong>. This will take you to the <strong>Roles</strong> section under IAM. Then click on <strong>Create role</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*925c2dnninoQ86CjjqHhNg.png" /></figure><p>Leave the <strong>Trusted entity type </strong>as <strong>Aws service </strong>and the <strong>Use case</strong> as <strong>EC2</strong>. Click <strong>Next</strong>. Assign the same permission we granted to the role created earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A-FuNzdpuNnp1DnDq5CdyA.png" /></figure><p>Click <strong>Next</strong>. Enter a name for your role, then click <strong>Create role</strong>. <br>Next, navigate back to <strong>Modify IAM Role</strong> and select the role you just created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*T6-K1Vq5EcmuxmbsW9_GCA.png" /></figure><p>Click on <strong>Update IAM role</strong>.</p><p>Next, go back to the EC2 instance you created and click on <strong>Connect</strong>. We will use <strong>EC2 Instance Connect</strong> to connect to our EC2 server. Take note of the username displayed below, as it will be referenced later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*282H_fCfakYr7xXi89ilIg.png" /></figure><p>Click on <strong>Connect</strong>. Then, run the following commands:</p><pre>#start docker<br>sudo systemctl start docker<br><br># to ensure docker is running evry time the instance reboots<br>sudo systemctl enable docker</pre><p><strong>Create Repository<br></strong>Lastly, let’s create a private repository on ECR. Navigate to ECR and click on <strong>Repositories</strong> under <strong>Private registry</strong> in the left panel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*G73b4DOuq4g_VHgXtD5R6g.png" /></figure><p>Click on <strong>Create repository</strong>. Enter a name for your repository and leave the other settings as they are.</p><p><strong>Set up GitHub Actions</strong><br>GitHub actions would be responsible for pushing our image to ECR. After a successful push, it will SSH into our server, pull the image from ECR, and start a container using that image. Before we set up the YAML file, let’s add some secrets that we will use in the configuration.</p><p>Navigate to your GitHub account where the repository is located. Go to the repository, and click on <strong>Settings</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pbCqIIqafE1ptrGntjoQLQ.png" /></figure><p>On the left sidebar, under <strong>Security</strong>, click on <strong>Secrets and variables</strong> and then select <strong>Actions</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2CpBFLY0t0OLnFhvTCZn8g.png" /></figure><p>Add the following repository secrets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*Ovc_J1ORoO5R2RwxvwzRXg.png" /></figure><p>For <strong>HOST</strong>, the value should be the Public IPv4 address of the EC2 instance you created. For <strong>SSH_PRIVATE_KEY</strong>, open the <em>.pem</em> file you downloaded earlier while creating your EC2 instance with a text editor, copy its entire contents, and paste it as the value. For <strong>USERNAME</strong>, use the username displayed earlier, most likely, it should be <strong>ec2-user</strong>.</p><p>Now, let’s create the YAML file that will contain instructions on how GitHub Action should handle subsequent changes. Click on <strong>Add file</strong> &gt; <strong>Create new file,</strong> and enter <em>.github/workflows/deploy.yml</em>.</p><p>You do not have to name it <em>deploy.yml</em>. you can choose any name you prefer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VSDYdXtWCbJDxqPZ29OFzQ.png" /></figure><p>Paste the snippet below into the YAML file. Replace <strong>role-to-assume</strong> with the ARN of the role you created from the CloudFormation template. I am using <strong>eu-west-2</strong> as my AWS Region; you should replace that with the region you are using. Additionally, update the repository(on ECR) name as needed.</p><pre>name: Deploy to EC2<br>on:<br>    push:<br>        branches:<br>            - main<br><br>env:<br>    AWS_REGION: &lt;your-aws-region&gt;<br>    CONTAINER_NAME: &lt;container-name-of-your-choice&gt;<br><br>permissions:<br>    id-token: write<br>    contents: read<br><br>jobs:<br>    build:<br>        runs-on: ubuntu-latest<br>        strategy:<br>            matrix:<br>                dotnet-version: [8.0.103]<br>        steps:<br>            - name: Checkout repo<br>              uses: actions/checkout@v3<br>        <br>            - name: Set up .NET<br>              uses: actions/setup-dotnet@v4<br>              with:<br>                dotnet-version: ${{matrix.dotnet-version}}<br><br>            - name: Build project<br>              run: | <br>                dotnet build -c Release<br>                echo &quot;build successful&quot;<br>    push:<br>        runs-on: ubuntu-latest<br>        needs: build<br>        steps:<br>            - name: Checkout repo<br>              uses: actions/checkout@v3<br>            <br>            - name: Configure credentials<br>              uses: aws-actions/configure-aws-credentials@v4<br>              with:<br>                role-to-assume: &lt;paste-arn-of-role-created-from-cloud-formation&gt;<br>                aws-region: ${{env.AWS_REGION}}<br><br>            - name: Login to ECR repo<br>              id: login-ecr<br>              uses: aws-actions/amazon-ecr-login@v2<br><br>            - name: Build, tag and push image to ecr<br>              env:<br>                REGISTRY: ${{steps.login-ecr.outputs.registry}}<br>                REPOSITORY: &lt;the-name-of-repo-you-created-on-ecr&gt;<br>                IMAGE_TAG: ${{github.sha}}<br>              run: |-<br>                docker build -t $REGISTRY/$REPOSITORY:$IMAGE_TAG .<br>                docker push $REGISTRY/$REPOSITORY:$IMAGE_TAG<br><br>            - name: Deploy to EC2<br>              env:<br>                REPOSITORY: books-repo<br>                REGISTRY: ${{steps.login-ecr.outputs.registry}}<br>                IMAGE_TAG: ${{github.sha}}<br>                EC2_PRIVATE_KEY: ${{secrets.SSH_PRIVATE_KEY}}<br>                HOSTNAME: ${{secrets.HOST}}<br>                USER_NAME: ${{secrets.USERNAME}}<br>              uses: appleboy/ssh-action@v1.1.0<br>              with:<br>                host: ${{env.HOSTNAME}}<br>                port: 22<br>                key: ${{env.EC2_PRIVATE_KEY}}<br>                username: ${{env.USER_NAME}}<br>                envs: REGISTRY, REPOSITORY, IMAGE_TAG, AWS_REGION, CONTAINER_NAME<br>                script: |-<br>                    aws ecr get-login-password --region $AWS_REGION | sudo docker login --username AWS --password-stdin $REGISTRY<br>                    sudo docker pull $REGISTRY/$REPOSITORY:$IMAGE_TAG<br>                    if sudo docker ps -a --format &#39;{{.Names}}&#39; | grep -w &quot;$CONTAINER_NAME&quot; &gt; /dev/null; then<br>                        echo &quot;Container &#39;$CONTAINER_NAME&#39; exists. Stopping...&quot;<br>                        sudo docker stop &quot;$CONTAINER_NAME&quot;<br>                        sudo docker rm &quot;$CONTAINER_NAME&quot;<br>                    else<br>                        echo &quot;Container does not exist. No action taken.&quot;<br>                    fi<br>                    sudo docker run -d --name $CONTAINER_NAME -p 8080:8080 -e ASPNETCORE_ENVIRONMENT=Development $REGISTRY/$REPOSITORY:$IMAGE_TAG</pre><p>The YAML file essentially builds the project, tags it, pushes it to ECR, and then pulls the image from the EC2 instance. Be sure to replace any placeholder values in the file with the relevant information.</p><p>Commit the changes. All the jobs should run and complete successfully. Next, let’s check our repository on ECR to see if any images were pushed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6T_QVudZUarsx_hk6312qA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yPofZ-tgY9KCEZgOlBxnBg.png" /></figure><p>We can see that the image was pushed to our repository on ECR. Now, let’s try to access the Swagger documentation. You can view it using <a href="http://18.175.151.157:8080/swagger/index.html">http://your-ec2-public-ip4-address:8080/swagger/index.html</a></p><p>If this does not open, let’s check the security group attached to the EC2 instance and confirm the inbound traffic rules. Go to your EC2 instance, scroll down, click on <strong>Security,</strong> and then click on the security group listed under <strong>Security groups</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*SKEYTxHg9Nw8dRjSe9u9Rg.png" /></figure><p>We currently have only one inbound rule allowing SSH connections on port 22. Let’s add another inbound rule. Click on <strong>Edit inbound rules</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qq5omJSHs2-EgXxC2IqKXQ.png" /></figure><p>Add this rule</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5UWvZiKzyVAB17baWueLSA.png" /></figure><p>Now, connections on port 8080 from anywhere will be allowed. Click on <strong>Save rules.</strong></p><p>Lets try accessing the Swagger documentation again. You should see it open, displaying our endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I3lwk91cLXvoVjc66kW7KA.png" /></figure><p>Let’s add a second endpoint. Before doing so, run the command below to ensure that any changes made to the repository online are reflected on your local machine.</p><pre>git pull</pre><pre>app.MapGet(&quot;/api/books/{id}&quot;, (int id) =&gt;<br>{<br>    var book = Book.All.FirstOrDefault(x =&gt; x.Id == id);<br><br>    if (book is null) return Results.NotFound(&quot;Book not found&quot;);<br><br>    return Results.Ok(book);<br>})<br>.WithName(&quot;GetBook&quot;)<br>.WithOpenApi();</pre><p>Lets push to GitHub and see if our GitHub Actions will be triggered.</p><pre>git add .<br>git commit -m &quot;book-by-id&quot;<br>git push origin main</pre><p>After successful completion of the jobs, we can check the Swagger documentation and see that the endpoint has been added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*3zwZq1nKFu_3mSRlAC2EeQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zSFYkR9ImuqeOrm9t7UCKA.png" /></figure><p>As we conclude this article, I sincerely hope it has proven beneficial, providing a clearer understanding of the concepts discussed. Your feedback is immensely valuable; feel free to share comments and suggestions.</p><p>Thank you for your time and engagement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7899684b245" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.NET API Deployment to AWS Lambda with CodePipeline, CodeCommit and CodeBuild]]></title>
            <link>https://awstip.com/net-app-deployment-to-aws-lambda-with-codepipeline-codecommit-and-codebuild-e07518e9525c?source=rss-49c59b67c139------2</link>
            <guid isPermaLink="false">https://medium.com/p/e07518e9525c</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Onafeso Olawale]]></dc:creator>
            <pubDate>Mon, 22 Jul 2024 06:11:50 GMT</pubDate>
            <atom:updated>2024-11-01T01:02:35.850Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*djBovuUveshzYa9_TqPJzg.png" /></figure><p>While there are many ways to set up a CI/CD pipeline to automate your deployment process to AWS Lambda, this article will show you an easy approach using AWS CodePipeline. We will use CodeCommit with GitHub as our source repository and CodeBuild to build and update our Lambda function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FqyJEGLK3rxtkPs1MC9j0w.jpeg" /></figure><p>This article assumes the reader has a basic knowledge of AWS.</p><p>I created a repository on GitHub and cloned it to my local machine, where I created a simple .NET 8 minimal API. Additionally, I created a staging branch for making all the changes. You can create any branch you prefer or or use the main branch.</p><pre>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddAWSLambdaHosting(LambdaEventSource.HttpApi);<br><br>var app = builder.Build();<br><br>app.MapGet(&quot;/&quot;, () =&gt; &quot;Hello World&quot;);</pre><p>The extension method ‘<em>AddAWSLambdaHosting()</em>’ adds AWS Lambda support. When the application is run in Lambda, kestrel is swapped out as the web server with <strong>Amazon.Lambda.AspNetCoreServer</strong>. This package will act as the web server translating request and responses between the lambda event source and ASP .NET Core. For more information, see the official <a href="https://docs.aws.amazon.com/lambda/latest/dg/csharp-package-asp.html">documentation</a>.</p><p>In the root of the project directory, I created a <strong><em>buildspec.yml</em></strong> file. Please do the same and paste the following content:</p><pre>version: 0.2<br><br>phases:<br>    install:<br>        runtime-versions:<br>            dotnet: 8.0<br>        commands:<br>            - echo Installing .NET 8.0<br>            - dotnet --version<br>    <br>    pre_build:<br>        commands:<br>            - echo Restoring dependencies<br>            - dotnet restore<br>            <br>    build:<br>        commands:<br>            - echo Building the .NET project<br>            - dotnet build -c Release<br>     <br>    post_build:<br>        commands: <br>            - echo Packaging the application<br>            - dotnet publish -c Release -o ./publish<br>            - echo Zipping the application<br>            - cd ./publish<br>            - zip -r ../my_function.zip .<br>            - cd ..<br>            - echo Updating Lambda function<br>            - aws lambda update-function-code --function-name ${FUNCTION_NAME} --zip-file fileb://my_function.zip</pre><p>We specify the version of our build specification, which is 0.2 in this case.<br>The build process is divided into several phases.</p><ul><li><strong>Install Phase</strong>: We specify the .NET runtime version to use.</li><li><strong>Pre_build Phase</strong>: We restore the dependencies specified in the project.</li><li><strong>Build Phase</strong>: We build the project in the Release configuration.</li><li><strong>Post_build Phase</strong>: We publish the project, placing the output in the <strong>./publish</strong> directory. Then, we change the directory to <strong>./publish</strong> and create a ZIP file named <strong>my_function.zip</strong> containing all the files in the directory. Finally, we update the Lambda function with this new ZIP file. ‘${FUNCTION_NAME}’ is a placeholder for the name of our Lambda function, which we will create later and is expected to be set as an environment variable.</li></ul><p>Let’s proceed to AWS Management console to complete the setup. Navigate to Lambda section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OkN5Gl8ufdYuGfce4QwHMQ.png" /></figure><p>Click <strong>Create Function</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*EVE4JgNVYUqHVNJ3SL6fDQ.png" /></figure><p>Fill in the information similar as shown below, leaving the other settings unchanged. You may choose a different name for your function if you prefer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*2vkYflstXlQgo03DkpvjAA.png" /></figure><p>Click <strong>Create Function</strong></p><p>Your function is now created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5xzEyc1TkdbKewRr0h2tAA.png" /></figure><p>Now that we have our function, let’s deploy our code to it. In the search bar at the top of the AWS Management Console, type <strong>CodePipeline</strong> and select it from the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A0wqPVPmoWszohnsbOul6A.png" /></figure><p>Click ‘<em>Create pipeline</em>’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*mPSWKomP5X1DOLDBTNcDOw.png" /></figure><p>Give your pipeline a name leaving other settings unchanged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*aqsgFcXDgpBs9ftrOmuzTg.png" /></figure><p>A new service role will be created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*KVWYrRtvqR4Ed4X5giiKjw.png" /></figure><p>Click <strong>Next</strong></p><p>In the <strong>Source Stage</strong>, select <strong>GitHub (Version 2)</strong> as the provider since we are using GitHub. Note that you can also use other providers such as Amazon ECR, AWS CodeCommit, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jEFBCrpWm2QWbUXHb-c-cA.png" /></figure><p>Now, we have to connect to GitHub. Click <strong>Connect to GitHub</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*nl5l4Upg6gcKHCikX5_niQ.png" /></figure><p>A window pops up. Give your connection a name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*mZ_6Iz3BbsYAFw-UfA-0JA.png" /></figure><p>Click <strong>Install a new app</strong> and follow the steps. You should now have your GitHub account connected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*EwhVzitYAN-UQ4lXZOrHHg.png" /></figure><p>Enter the repository name and the branch. As mentioned earlier, I will be making changes on the <strong>staging</strong> branch which is why I am using <strong>staging </strong>here</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*-5Fi1bTdWasuKvlno7h0qg.png" /></figure><p>For <strong>Trigger</strong>, click <strong>No filter</strong> and click <strong>Next</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*9kjt-2EWu4ehuZogUCzi6g.png" /></figure><p>For the build stage, we select <strong>AWS CodeBuild</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*BiEpuR4Kvb2mNAO55VT12g.png" /></figure><p>Select your region and click <strong>Create project</strong>. We need to create a build project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*oee3b00KrhS8a4XxqrDD5g.png" /></figure><p>A window will pop up. Give your build project a name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*USTwvgRvDk6NhgxsnHPmzA.png" /></figure><p>Leave the other settings unchanged. In the <strong>Role</strong> section, click <strong>New service role</strong> and give your role a name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*ti7XLz-UNK_GUAblJf5OuA.png" /></figure><p>In the <strong>Buildspec</strong> section, select <strong>Use a buildspec file</strong>. Since our file (the <strong>buildspec.yml</strong> file we created earlier) is located at the root of our project and is named <strong>buildspec.yml</strong>, you don’t need to enter anything under <strong>Buildspec name</strong>. Click <strong>Continue to code pipeline</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*XAvKtuqfIUlsv7SRpp-4Iw.png" /></figure><p>Replace the environment variable ‘<em>FUNCTION_NAME</em>’ with the name of the lambda function you created earlier</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*V_SEO8OiUNRJtDWUc1-kew.png" /></figure><p>Click <strong>Next</strong><em>.</em> In the Deploy stage, select <strong>Skip deploy stage</strong>. Then click <strong>Create pipeline</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*r0aVSJhedjU29-apEB4SeQ.png" /></figure><p>Our build has failed. Let’s inspect the logs to determine the cause.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rvrLgorJ225rp6eZFvHZaQ.png" /></figure><p>It appears that the role we created earlier lacks the necessary permissions. Enter <strong>IAM</strong> in the search bar and navigate to the IAM service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*pzBpB6m4lVbBAU8IUhB5EA.png" /></figure><p>Click <strong>Roles</strong> in the left sidebar and search for the role you created earlier. I named mine <strong>my_func_role</strong> so I will search for that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*SBGBGG15eKVpAM7_5i7Ccw.png" /></figure><p>Click on the role. Then click <strong>Add permissions</strong> and select <strong>Attach policies</strong>. You should be directed to a page similar to this one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XlMtYBW8xGcI3hm-YJiDqg.png" /></figure><p>Search for <strong>lambda</strong>, and then check the box next to <strong>AWSLambda_FullAccess.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GpPtvCD4jaFW0oz0Kh8_Zg.png" /></figure><p>Click <strong>Add permissions</strong> at the bottom.</p><p>Return to the <strong>CodePipeline </strong>and select the pipeline you created. In the build stage, click <strong>Retry stage</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*r7srrN7RC6hbqiTyrcS1yQ.png" /></figure><p>Our build should now be a success.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*QbHJjKrn0X7QI3SKp7kc9g.png" /></figure><p>Let’s return to our lambda function to expose our endpoints using a URL. Navigate back to your Lambda function and click on <strong>Configuration</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LmJH4zrJC_tY-Oz92YwEkQ.png" /></figure><p>Click on <strong>Function URL</strong> and then select <strong>Create function URL.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Fc8wNtCWzeZj2vfAYm0jA.png" /></figure><p>You should be taken to the <strong>Configure Function URL</strong> page. For <strong>Auth type</strong>, select <strong>None</strong>, leave the other settings as they are and click <strong>Save.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*OwhDA_BGMzgSwuHE7n-5fA.png" /></figure><p>Click on the function URL When the browser opens, you should see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*6GL_zVquW0oEwBVBseODxw.png" /></figure><p>If you encounter an <strong>Internal Server Error, </strong>verify this before attempting to troubleshoot. Go to your Lambda function, scroll down to <strong>Runtime settings</strong>, and ensure that the name under <strong>Handler</strong> matches the name of your API project. If it does not match, update it accordingly by clicking <strong>Edit</strong>. Save the changes. Click on the Function URL again, and if you followed the previous steps correctly, you should see <strong>Hello world </strong>in the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZjxywKaE07c-yV2R7PPl1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*JTZViWSrHE3Y7dvJ0V1lvA.png" /></figure><p>Let’s make some changes to our staging branch and push them to GitHub . Then, check if the pipeline runs and updates the code accordingly.</p><pre>app.MapGet(&quot;/api/books/{id}&quot;, (int id) =&gt;<br>{<br>    BookRepository repo = new();<br><br>    var book = repo.GetBook(id);<br><br>    if (book is null) return Results.NotFound(&quot;Book not found&quot;);<br><br>    return Results.Ok(book);<br>});<br><br>app.MapGet(&quot;api/books&quot;, () =&gt;<br>{<br>    BookRepository repo = new();<br><br>    return Results.Ok(repo.GetBooks());<br>});</pre><pre>public class Book<br>{<br>    public int Id { get; set; }<br>    public string Title { get; set; }<br>    public int Version { get; set; }<br>    public string Author { get; set; }<br>}<br><br>public class BookRepository<br>{<br>    private readonly List&lt;Book&gt; _books = new()<br>    {<br>        new Book{Id = 1, Title = &quot;Lord of The Rings&quot;, Author = &quot;John Ronald&quot;, Version = 1},<br>        new Book{Id = 2, Title = &quot;Purple Hibiscus&quot;, Author = &quot;Chimamda Ngozi&quot;, Version = 3},<br>        new Book{Id = 3, Title = &quot;Arms and the man&quot;, Author = &quot;Bernard Shaw&quot;, Version = 2},<br>        new Book{Id = 4, Title = &quot;Game of Thrones&quot;, Author = &quot;George Martin&quot;, Version = 4},<br>    };<br><br>    public Book? GetBook(int id) =&gt;<br>        _books.FirstOrDefault(x =&gt; x.Id == id);<br><br>    public List&lt;Book&gt; GetBooks() =&gt; _books;   <br>}</pre><p>Let’s push these changes to the staging branch on GitHub.</p><pre>git add . <br>git commit -m books<br>git push origin staging</pre><p>When you push your changes, go to your code pipeline, and you’ll notice the spinner indicating that the pipeline is running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1IvZci3a9nI4VNpTYjhobQ.png" /></figure><p>Once it’s done, let’s visit our books endpoint</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*d3xR_-mClUk09hZweaLr4g.png" /></figure><p>You should see the changes reflected and be able to access your book resources.</p><p>As we conclude this article, I sincerely hope it has proven beneficial, providing a clearer understanding of the concepts discussed. Your feedback is immensely valuable; feel free to share comments and suggestions.</p><p>Thank you for your time and engagement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e07518e9525c" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/net-app-deployment-to-aws-lambda-with-codepipeline-codecommit-and-codebuild-e07518e9525c">.NET API Deployment to AWS Lambda with CodePipeline, CodeCommit and CodeBuild</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why you should use IHttpClientFactory in .NET for HTTP requests]]></title>
            <link>https://blog.stackademic.com/why-you-should-use-ihttpclientfactory-in-net-for-http-requests-2ddf899945f8?source=rss-49c59b67c139------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ddf899945f8</guid>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[aspnet-mvc]]></category>
            <category><![CDATA[ihttpclientfactory]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[httpclientfactory]]></category>
            <dc:creator><![CDATA[Onafeso Olawale]]></dc:creator>
            <pubDate>Mon, 20 May 2024 15:50:13 GMT</pubDate>
            <atom:updated>2024-05-21T00:28:39.633Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why you should use IHttpClientFactory in .NET for HTTP requests</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owH3LC7VnzpM8JV4RtY8oA.jpeg" /></figure><p>IHttpClientFactory is an opinionated factory for creating HttpClient instances to be used in your applications. The well-known HttpClient class can easily be used to create these instances, but it isn’t being properly used by many developers.</p><p>Though the HttpClient class implements IDisposable, declaring and instantiating it within a using statement is not preferred because when the HttpClient<em> </em>object gets disposed of, the underlying socket is not immediately released, which can lead to a socket exhaustion problem. For more information, see this blog <a href="https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/">post</a>.</p><p>HttpClient<em> </em>is intended to be instantiated once and reused throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This issue will result in SocketException errors.</p><p>The issue isn’t really with HttpClient per se, but with the default constructor for HttpClient. When an instance of HttpClient is created using the ‘new HttpClient()’, a new instance of HttpMessageHandler is also created by default. The HttpMessageHandler is responsible for managing the underlying HTTP connections and sockets. This can lead to the creation of new sockets, and if HttpClient instances are not properly disposed of, it can result in socket exhaustion due to many sockets being left in the ‘TIME_WAIT’ state.</p><p>To address the issues mentioned above and to make HttpClient instances manageable, one approach is to use the IHttpClientFactory. It is an interface that’s used to configure and create HttpClient instances in an app through Dependency Injection(DI).</p><p><strong>Benefits of using IHttpClientFactory include:</strong><br>1. Avoidance of Socket Exhaustion: IHttpClientFactory pools HttpMessageHandler instances, which manage the underlying HTTP connections. This pooling allows for the reuse of these handlers, preventing the frequent creation and disposal of sockets that can lead to socket exhaustion.</p><p>2. Connection Management: By reusing existing connections, IHttpClientFactory helps in maintaining a stable number of open sockets, which is particularly important in high load applications where many HTTP requests are made.</p><p>3. Provides a central location for naming and configuring logical HttpClient instances. For example, a client named ‘<em>github</em>’ could be registered and configured to access GitHub. A default client can be registered for general access.</p><p>4. Codifies the concept of outgoing middleware via delegating handlers in HttpClient. Provides extensions for Polly-based middleware to take advantage of delegating handlers in HttpClient. <br>In a future article, we will discuss more on Polly and how it can be utilized to implement resilient HTTP requests.</p><p>5. Enhanced Testability: Using IHttpClientFactory makes it easier to mock HttpClient instances in unit tests. For integration tests, we can easily override the configuration and send fake requests using WireMock. Refer to this article if you want to learn how to simulate API calls in your integration tests with WireMock. <a href="https://medium.com/stackademic/integration-testing-in-net-api-simulate-external-api-calls-49eb21e6f8bd">Link</a></p><p>For more information, see this article by <a href="https://learn.microsoft.com/en-gb/aspnet/core/fundamentals/http-requests?view=aspnetcore-8.0#consumption-patterns">Microsoft</a></p><p><strong>Multiple ways to use IHttpClientFactory<br></strong>1. Basic usage<br>2. Use Named Clients<br>3. Use Typed Clients<br>4. Use Generated Clients</p><p>For demonstration, I have a simple .NET API, with one endpoint which returns a list of books. If you want to follow with same project, you can create a new web project (select ASP.NET Core Empty in project templates if you’re using Visual Studio to create the project) and paste this in the Program.cs</p><pre>var builder = WebApplication.CreateBuilder(args);<br>var app = builder.Build();<br><br>app.MapGet(&quot;/&quot;, () =&gt; &quot;Hello World!&quot;);<br><br>app.MapGet(&quot;/api/books&quot;, () =&gt;<br>{<br>    List&lt;Book&gt; books =<br>    [<br>        new(Guid.NewGuid(), &quot;Lord of the Rings&quot;, 450),<br>        new(Guid.NewGuid(), &quot;Harry Potter&quot;, 790),<br>        new(Guid.NewGuid(), &quot;Game of Thrones&quot;, 400)<br>    ];<br><br>    return Results.Ok(books);<br>});<br><br>app.Run();<br><br><br>internal class Book<br>{<br>    internal Book(Guid id, string title, int pages)<br>    {<br>        Id = id;<br>        Title = title;<br>        Pages = pages;<br>    }<br><br>    public Guid Id { get; set; }<br>    public string Title { get; set; }<br>    public int Pages { get; set; }<br>}</pre><p>Run the project and test the endpoint</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*2DldOToxbLqgUkFeNorZLA.png" /></figure><p>Now we create a second web API project similar to the first one, this project will send requests to this API(the first project).</p><p><strong>Basic Usage<br></strong>Register IHttpClientFactory by calling ‘AddHttpClient()’ in Program.cs</p><pre>builder.Services.AddHttpClient();</pre><p>Take note that we are doing this in the second project.<br>We create a ‘<em>BookService</em>’ class. We request for IHttpClientFactory by using dependency injection (DI). We then create an instance of HttpClient.</p><pre>public class BookService<br>{<br>    private readonly IHttpClientFactory _httpClientFactory;<br><br>    public BookService(IHttpClientFactory httpClientFactory)<br>    {<br>        _httpClientFactory = httpClientFactory;<br>    }<br><br>    public async Task&lt;List&lt;Book&gt;&gt; GetBooksAsync()<br>    {<br>        var httpClient = _httpClientFactory.CreateClient();<br><br>        var books = await httpClient.GetFromJsonAsync&lt;List&lt;Book&gt;&gt;<br>            (&quot;https://localhost:7094/api/books&quot;); // replace with the books endpoint from the first project<br><br>        return books;<br>    }<br>}</pre><p>We then call this service in an endpoint</p><pre>app.MapGet(&quot;/api/books&quot;, async (BookService bookService) =&gt;<br>{<br>    var books = await bookService.GetBooksAsync();<br><br>    return Results.Ok(books);<br>});</pre><p>Register ‘<em>BookService</em>’ in your DI container</p><pre>builder.Services.AddTransient&lt;BookService&gt;();</pre><p>When we send the request from the second project to the books endpoint, we get the list of books.</p><p><strong>Named Clients<br></strong>When many HttpClients have different configuration, we can use named clients. With named clients, we can specify configuration for it during registration in Program.cs. This configuration can include specific values such as the base server, HTTP headers or time outs.</p><p>I have removed this line of code</p><pre>builder.Services.AddHttpClient(); // remove from program.cs</pre><p>We register our named clients</p><pre>builder.Services.AddHttpClient(&quot;book-client&quot;, client =&gt;<br>{<br>    client.BaseAddress = new Uri(&quot;https://localhost:7094/&quot;);<br>});</pre><p>Perhaps, we need to pass an API key in the header before we send any request, we can do that here also</p><pre>builder.Services.AddHttpClient(&quot;book-client&quot;, client =&gt;<br>{<br>    client.BaseAddress = new Uri(&quot;https://localhost:7094/&quot;);<br>    client.DefaultRequestHeaders.Add(&quot;x-api-key&quot;, &quot;book-api-key&quot;);<br>});</pre><p>I have added a simple API key authorization to the first project. In the Program,cs</p><pre>app.Use(async (ctx, next) =&gt;<br>{<br>    string? apiKey = ctx.Request.Headers[&quot;x-api-key&quot;];<br><br>    if (apiKey is null || apiKey != &quot;book-api-key&quot;)<br>    {<br>        ctx.Response.StatusCode = (int)HttpStatusCode.Forbidden;<br>        await ctx.Response.WriteAsJsonAsync(new <br>            { error = &quot;Invalid or api key missing in header&quot; });<br>        return;<br>    }<br><br>    await next();<br>});</pre><p>When we start the project, we can see the error which means our API key authorization is working</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*Axu6hrSOpOflajR-FEU-1A.png" /></figure><p>I have modified the ‘<em>GetBooksAsync()</em>’ method</p><pre> public async Task&lt;List&lt;Book&gt;&gt; GetBooksAsync()<br> {<br>     var httpClient = _httpClientFactory.CreateClient(&quot;book-client&quot;); // the name we passed when we were registering it<br><br>     var response = await httpClient.GetAsync(&quot;/api/books&quot;);<br><br>     if (!response.IsSuccessStatusCode)<br>    {<br>        await Console.Out.WriteLineAsync(await response.Content<br>          .ReadAsStringAsync());<br><br>        return new();<br>    }<br><br>     var books = await response.Content.ReadFromJsonAsync&lt;List&lt;Book&gt;&gt;();<br><br>     return books;<br> }</pre><p>In the preceding code, the request doesn’t need to specify a hostname. The code can just pass the path, since the base address configured for the client is used.</p><p>When we call our endpoint in the second project, it works as expected.</p><p><strong>Typed Clients<br></strong>Typed clients provide the same capabilities as named clients without the need to use strings as keys. Typed clients provide a single location to configure and interact with a particular HttpClient. For example, a single typed client might be used for a single backend endpoint or to encapsulate all logic dealing with the endpoint.</p><p>A typed client accepts an HttpClient parameter in its constructor. Let’s refactor our <em>BookService</em></p><pre>public class BookService<br>{<br>    private readonly HttpClient _httpClient;<br><br>    public BookService(HttpClient httpClient)<br>    {<br>        _httpClient = httpClient;<br><br>        _httpClient.BaseAddress = new Uri(&quot;https://localhost:7094/&quot;);<br>        _httpClient.DefaultRequestHeaders.Add(&quot;x-api-key&quot;, &quot;book-api-key&quot;);<br>    }<br><br>    public async Task&lt;List&lt;Book&gt;&gt; GetBooksAsync() =&gt;<br>        await _httpClient.GetFromJsonAsync&lt;List&lt;Book&gt;&gt;(&quot;api/books&quot;);<br>}</pre><p>In the preceding code, the configuration is moved into the typed client. <br>In Program.cs</p><pre>builder.Services.AddHttpClient&lt;BookService&gt;();</pre><p>The typed client is registered as transient with DI. In the preceding code, <em>AddHttpClient </em>registers <em>BookService </em>as a transient service. This registration uses a factory method to create an instance of HttpClient and create an instance of BookService, passing in the instance of HttpClient to its constructor. An HttpMessageHandler is also assigned from a pool to the HttpClient.</p><p>We also remove this from the Program.cs as we do not need it again</p><pre>builder.Services.AddTransient&lt;BookService&gt;(); // remove from program.cs</pre><p>When we send a request to the endpoint, it works as expected.</p><p><strong>Generated Clients<br></strong>IHttpClientFactory can be used in combination with third-party libraries such as <a href="https://github.com/reactiveui/refit">Refit</a>. Refit is a REST library for .NET. It converts REST APIs into live interfaces. Call <em>AddRefitClient </em>to generate a dynamic implementation of an interface, which uses HttpClient to make the external HTTP calls.</p><p>Install these packages in your project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*Krh3T--k1xVP6FNzFVdbXQ.png" /></figure><p>Create an ‘<em>IBookService</em>’ interface</p><pre>public interface IBookService<br>{<br>    [Get(&quot;/api/books&quot;)] // the relative path<br>    Task&lt;List&lt;Book&gt;&gt; GetBooksAsync();<br>}</pre><p>In the preceding code, we use the ‘GET’ attribute from Refit on the method and pass the relative path to it.</p><p>You can remove this code from Program.cs as we no longer need it</p><pre>builder.Services.AddHttpClient&lt;BookService&gt;(); // remove</pre><p>Let’s refactor the endpoint by injecting <em>IBookService</em>. <em>BookService </em>class is also not needed for this.</p><pre>app.MapGet(&quot;/api/books&quot;, async (IBookService bookService) =&gt;<br>{<br>    var books = await bookService.GetBooksAsync();<br><br>    return Results.Ok(books);<br>});</pre><p>Everything still works as expected when we send a request to the endpoint.</p><p>It is worth noting that each time you get an HttpClient object from the IHttpClientFactory, a new instance is returned. But each HttpClient uses an HttpMessageHandler that’s pooled and reused by the IHttpClientFactory to reduce resource consumption, as long as the HttpMessageHandler’s lifetime hasn’t expired.</p><p>Pooling of handlers is desirable as each handler typically manages its own underlying HTTP connections; creating more handlers than necessary can result in connection delays. Some handlers also keep connections open indefinitely, which can prevent the handler from reacting to DNS changes. For more information, see ‘<em>.NET Microservices Architecture for Containerized .NET Applications</em>’ by Microsoft. You can download the pdf using this <a href="https://dotnet.microsoft.com/en-us/download/e-book/microservices-architecture/pdf">link</a>.</p><p>As we conclude this article, I sincerely hope it has proven beneficial, providing a clearer understanding of the concepts discussed. Your feedback is immensely valuable; feel free to share comments and suggestions.</p><p>Thank you for your time and engagement.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>Tired of blogging platforms that force you to deal with algorithmic content? Try <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ddf899945f8" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/why-you-should-use-ihttpclientfactory-in-net-for-http-requests-2ddf899945f8">Why you should use IHttpClientFactory in .NET for HTTP requests</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integration Testing in .NET API: Simulate external API calls]]></title>
            <link>https://blog.stackademic.com/integration-testing-in-net-api-simulate-external-api-calls-49eb21e6f8bd?source=rss-49c59b67c139------2</link>
            <guid isPermaLink="false">https://medium.com/p/49eb21e6f8bd</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[wiremock]]></category>
            <category><![CDATA[net-core]]></category>
            <dc:creator><![CDATA[Onafeso Olawale]]></dc:creator>
            <pubDate>Tue, 30 Apr 2024 08:14:53 GMT</pubDate>
            <atom:updated>2024-05-01T00:15:10.431Z</atom:updated>
            <content:encoded><![CDATA[<h3>Integration Testing in .NET API: Simulate external API calls</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owH3LC7VnzpM8JV4RtY8oA.jpeg" /></figure><p>In a previous article, which you can find <a href="https://medium.com/stackademic/integration-testing-in-net-api-a-step-by-step-guide-de37bf3abd6f">here</a>, I provided a step-by-step guide on how to write integration tests for your .NET API. If you haven’t read it yet, I highly recommend doing so, as it establishes the groundwork for this discussion.</p><p>Within your API endpoints, there are instances where requests are sent to external APIs. In this article, we will delve into the process of simulating such external requests in your integration tests. There are several reasons why you might opt to simulate these API calls:</p><p>1. Request limits: Many external APIs enforce limits on the number of requests you can make within a specific time frame.<br>2. API Downtime: If the external API experiences downtime, it may not be desirable for this to impact the integrity of your tests.</p><p>Before delving into fake external API calls within a .NET API, let’s first introduce the library we’ll be utilizing and provide a brief overview of its functionality using a C# console application. The library in question is <strong>WireMock.Net</strong>. <strong>WireMock</strong>.<strong>Net</strong> is a library for stubbing and mocking web HTTP responses. For more information about this library, feel free to explore its GitHub <a href="https://github.com/WireMock-Net/WireMock.Net">repository</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*v_eTi3yaLutfbrZMf9ecEQ.png" /></figure><p>I’ve created a C# console application to illustrate how we can simulate API calls.</p><pre>internal class BookApiServer<br>{<br>    private readonly WireMockServer _apiServer;<br><br>    public BookApiServer()<br>    {<br>        _apiServer = WireMockServer.Start(server =&gt;<br>        {<br>            server.Urls = new[] { &quot;http://localhost:50000&quot; };<br>        });<br>    }<br>}</pre><p>I’ve created a class, ‘<em>BookApiServer</em>’. Within this class, there’s a field named ‘<em>_apiServer</em>’ of type ‘<em>WireMockServer</em>’ (from the <em>WireMock.Server</em> namespace). In the class constructor, we start the <em>WireMockServer </em>by calling the ‘<em>Start()</em>’ method and providing specific settings to it. Here we’ve only set up the URL.</p><pre>internal class BookApiServer<br>{<br>    private readonly WireMockServer _apiServer;<br><br>    public BookApiServer()<br>    {<br>        _apiServer = WireMockServer.Start(server =&gt;<br>        {<br>            server.Urls = new[] { &quot;http://localhost:50000&quot; };<br>        });<br>    }<br><br>    public void GetBooks()<br>    {<br>        List&lt;Book&gt; books = new()<br>        {<br>            new Book { Id = 1, Title = &quot;Romeo and Juliet&quot;},<br>            new Book { Id = 2, Title = &quot;Lord of the Flies&quot;},<br>        };<br><br>        _apiServer.Given(Request.Create()<br>            .WithPath(&quot;/books&quot;)<br>            .UsingGet())<br>            .RespondWith(Response.Create()<br>            .WithHeader(&quot;content-type&quot;, &quot;application/json&quot;)<br>            .WithBodyAsJson(books)<br>            .WithStatusCode(System.Net.HttpStatusCode.OK));<br>    }<br>}</pre><p>I’ve implemented a method ‘<em>GetBooks()</em>’. Essentially, when a request is sent to the URL we set with a path matching ‘<em>/books</em>’ (achieved with ‘<em>.WithPath(“/books”)</em>’) and it’s a GET request, this method creates a response. It sets the headers and the response body (a list of books) just as we set above and the status code to 200. You can include additional headers as needed.</p><p>Before testing this functionality in postman, we start the server</p><pre>BookApiServer apiServer = new();<br><br>apiServer.GetBooks();<br><br>Console.ReadLine();</pre><p>Now, we run our console application and proceed to test it using postman</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*ulqcYbY7HED3KvzPwuhlUA.png" /></figure><p>It’s as straightforward as that. Now, let’s apply this approach within a .NET API.</p><p>I have a simple .NET API that integrates OMDB <a href="https://www.omdbapi.com/">API</a>.</p><pre>public interface IMovieService<br>{<br>    Task&lt;Result&lt;MovieSearchResult&gt;&gt; Search(string searchTerm, int page);<br>}<br><br>public class MovieService : IMovieService<br>{<br>    private readonly HttpClient _httpClient;<br>    private readonly string _url;<br><br>    public MovieService(HttpClient httpClient, <br>        IOptions&lt;ImdbCredentials&gt; credentials)<br>    {<br>        _httpClient = httpClient;<br>        _url = httpClient.BaseAddress + <br>      $&quot;?apiKey={credentials.Value.ApiKey}&quot;; // your api key<br>    }<br><br>    public async Task&lt;Result&lt;MovieSearchResult&gt;&gt; Search(string searchTerm, <br>        int page)<br>    {<br>        string url = _url + $&quot;&amp;s={searchTerm}&amp;page={page}&quot;;<br><br>        var response = await _httpClient.GetAsync(url);<br><br>        if (!response.IsSuccessStatusCode)<br>        {<br>            var errorMessage = response.ReasonPhrase;<br><br>            var errorDetails = await response.Content.ReadAsStringAsync();<br><br>            return new Error(&quot;SEARCH_MOVIES&quot;, $&quot;{errorMessage} \n {errorDetails}&quot;);<br>        }<br><br>        var movies = await response.Content<br>          .ReadFromJsonAsync&lt;MovieSearchResult&gt;();<br><br>        return movies;<br>    }<br>}</pre><p>We add this to the Service Collection</p><pre>services.AddHttpClient&lt;IMovieService, MovieService&gt;(client =&gt;<br>{<br>    client.BaseAddress = new Uri(&quot;http://www.omdbapi.com&quot;);<br>});</pre><p>The endpoint essentially injects the <em>IMovieService</em>, invokes the search method, maps the result to an object and returns the response to the client. This is what we are going to be write an integration test for.</p><p>Let’s proceed by creating a test project.</p><pre>dotnet new xunit -o tests/Movies.API.IntegrationTests // create new xunit project in tests folder<br>dotnet sln add tests/Movies.API.IntegrationTests // add test project to solution</pre><p>I’ve created a ‘<em>Utils</em>’ folder and within it, I’ve added a class named ‘<em>MoviesApiServer</em>’</p><pre>internal class MoviesApiServer : IDisposable<br>{<br>    private WireMockServer _server;<br><br>    public string Url =&gt; _server.Url;<br><br>    public void Start() =&gt; _server = WireMockServer.Start(new WireMockServerSettings<br>    {<br>        Urls = new[] { &quot;http://localhost:59000&quot; },<br>    });<br><br>    public void SearchMovies()<br>    {<br>        List&lt;Movie&gt; movies = new Faker&lt;Movie&gt;()<br>            .RuleFor(x =&gt; x.Title, &quot;superman&quot;)<br>            .RuleFor(x =&gt; x.ImdbId, faker =&gt; Guid.NewGuid().ToString())<br>            .RuleFor(x =&gt; x.Poster, faker =&gt; faker.Lorem.Text())<br>            .RuleFor(x =&gt; x.Year, faker =&gt; faker.Date.Past(10).Year.ToString())<br>            .GenerateBetween(3, 7);<br><br>        MovieSearchResult searchResult = new()<br>        {<br>            Response = &quot;True&quot;,<br>            Search = movies,<br>            TotalResults = movies.Count.ToString()<br>        };<br><br>        string result = JsonSerializer.Serialize(searchResult);<br><br>        _server.Given(Request.Create()<br>            .WithParam(&quot;s&quot;, &quot;superman&quot;)<br>            .WithParam(&quot;page&quot;, &quot;1&quot;)<br>            .UsingGet())<br>            .RespondWith(Response.Create()<br>            .WithBody(result)<br>            .WithHeader(&quot;content-type&quot;, &quot;application/json&quot;)<br>            .WithStatusCode(System.Net.HttpStatusCode.OK));<br>    }<br><br>    public void Dispose()<br>    {<br>        _server.Stop();<br>        _server.Dispose();<br>    }<br>}</pre><p>This class inherits from <em>IDisposable. I</em>n the ‘<em>Dispose()</em>’ method, we stop the server and dispose of its’ instance. Additionally, we have a ‘<em>Start()</em>’ method to initiate the server along with its setup. The ‘<em>Url</em>’ property represents the server’s URL, set to ‘<em>http://localhost:59000</em>’.</p><p>Lastly, we have a ‘<em>SearchMovies()</em>’ method. We want to test the search movies endpoint in our application which calls the OMDB API search endpoint. This OMDB API search endpoint accepts query parameters such as the page and the search term (‘s’). To accommodate this, we chain ‘<em>.WithParams()</em>’ when creating the Request. This ensures that any request sent to the OMDB API within our application, containing query parameters matching those we’ve set, will receive the response generated from this method. Unlike before, where we used ‘.<em>WithPath()</em>’ here we utilize ‘<em>.WithParams()</em>’.</p><p>Additionally, I’ve created a ‘<em>Fixtures</em>’ folder containing a class named ‘<em>MovieApplicationFactory</em>’.</p><pre>public class MovieApplicationFactory : <br>    WebApplicationFactory&lt;IApiMarker&gt;, IAsyncLifetime<br>{<br>    private readonly MoviesApiServer _apiServer = new();<br><br>    public Task InitializeAsync()<br>    {<br>        _apiServer.Start();<br><br>        _apiServer.SearchMovies();<br><br>        return Task.CompletedTask;<br>    }<br><br>    protected override void ConfigureWebHost(IWebHostBuilder builder)<br>    {<br>        builder.ConfigureTestServices(services =&gt;<br>        {<br>            services.AddHttpClient&lt;IMovieService, MovieService&gt;(client =&gt;<br>            {<br>                client.BaseAddress = new Uri(_apiServer.Url);<br>            });<br>        });<br>    }<br><br>    public new Task DisposeAsync()<br>    {<br>        _apiServer.Dispose();<br><br>        return Task.CompletedTask;<br>    }<br>}</pre><p>In our services, we replace the URL with the one obtained from our ‘<em>MoviesApiServer</em>’. Essentially, we’re overriding the previously registered <em>HttpClient </em>so that any requests sent will be directed to the URL provided by our ‘<em>MovieApiServer</em>’.</p><p>Additionally, I’ve created a ‘<em>EndpointTests</em>’ folder containing a class named ‘<em>GetMoviesEndpointTests</em>’</p><pre>public class GetMoviesEndpointTests : IClassFixture&lt;MovieApplicationFactory&gt;<br>{<br>    private readonly HttpClient _httpClient;<br><br>    public GetMoviesEndpointTests(MovieApplicationFactory appFactory)<br>    {<br>        _httpClient = appFactory.CreateClient();<br>    }<br><br>    [Fact]<br>    public async Task SearchMovies_WithValidSearchTerm_ReturnsListOfMovies()<br>    {<br>        string url = $&quot;/api/movies/search?searchTerm=superman&amp;page=1&quot;;<br><br>        var response = await _httpClient.GetAsync(url);<br><br>        response.StatusCode.Should().Be(System.Net.HttpStatusCode.OK);<br><br>        var result = await response.Content<br>          .ReadFromJsonAsync&lt;SearchMovieResponse&gt;();<br><br>        result.Should().NotBeNull();<br><br>        result!.TotalRecords.Should().BeGreaterThan(1);<br><br>        result!.Movies.Count.Should().Be(result.TotalRecords);<br><br>        result!.Movies.ForEach(movie =&gt; movie.Title.Contains(&quot;superman&quot;));<br>    }<br>}</pre><p>When we run the test, it passes. It’s worth noting that several concepts have not been thoroughly explained here, as they have been previously discussed in an earlier <a href="https://medium.com/stackademic/integration-testing-in-net-api-a-step-by-step-guide-de37bf3abd6f">article</a>.</p><p>As we conclude this article, I sincerely hope it has proven beneficial, providing a clearer understanding of the concepts discussed. Your feedback is immensely valuable; feel free to share comments and suggestions.</p><p>Thank you for your time and engagement.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49eb21e6f8bd" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/integration-testing-in-net-api-simulate-external-api-calls-49eb21e6f8bd">Integration Testing in .NET API: Simulate external API calls</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integration Testing in .NET API: A step by step guide]]></title>
            <link>https://blog.stackademic.com/integration-testing-in-net-api-a-step-by-step-guide-de37bf3abd6f?source=rss-49c59b67c139------2</link>
            <guid isPermaLink="false">https://medium.com/p/de37bf3abd6f</guid>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[integration-testing]]></category>
            <dc:creator><![CDATA[Onafeso Olawale]]></dc:creator>
            <pubDate>Fri, 19 Apr 2024 04:14:13 GMT</pubDate>
            <atom:updated>2024-04-22T00:52:32.336Z</atom:updated>
            <content:encoded><![CDATA[<h3>Integration Testing in .NET API: A Step-by-Step Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owH3LC7VnzpM8JV4RtY8oA.jpeg" /></figure><p>Integration tests ensure that an app’s component function correctly at a level that includes the app’s supporting infrastructure, such as database, file system, and network. Integration tests evaluate an app’s component on a broader level than unit tests. Unit tests are used to test isolated software components, such as individual class methods.</p><p>In contrast to unit tests, integration tests: <br>* Use the actual components that the app uses in production<br>* Require more code and data processing<br>* Takes longer to run<br>For more information, see this article by <a href="https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-8.0">Microsoft</a> on Integration Testing in .NET.</p><p>This article assumes that the reader has a basic understanding of unit tests.</p><p>In this article, I will demonstrate integration testing using a School Management System API, specifically focusing on the ‘Department’ module. You can follow along using any API you have available, whether built with minimal APIs or controllers. This API utilizes Postgres as the database. We’ll cover all CRUD ( Create, Read, Update, Delete) endpoints, allowing you to adapt the testing approach to any API you are working with. For our testing framework, we’ll be using xUnit.</p><p>In the root directory of your project, create a ‘<em>tests</em>’ folder. This folder will house all our tests. Within the ‘<em>tests</em>’ directory,</p><pre>dotnet new xunit -n SMS.API.IntegrationTests // this will create a new xunit project<br><br>cd ../ // go a level up to the root directory<br><br>dotnet sln add tests/SMS.API.IntegrationTests // add test project to solution</pre><p>What we’ve essentially done is create a new xUnit project in the ‘<em>tests</em>’ folder called ‘<em>SMS.API.IntegrationTests</em>’. Returning to the root directory, we then add the test project to the solution. Additionally, include your API project as a project reference within this Integration test project.</p><p>Let’s begin writing our tests.</p><p>We want to write a test to retrieve a department using its ID. This is the endpoint tested in Postman, along with its expected response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*BDgIL9DRVOdcyHtd9IwfxA.png" /></figure><p>In ‘<em>SMS.API.Integration.Tests</em>’, create a folder named, ‘<em>EndpointTests</em>’. Within this folder, create another folder named, ‘<em>DepartmentEndpointTests</em>’. Inside this folder, create a class named, ‘<em>GetDepartmentEndpointTests</em>’</p><pre>public class GetDepartmentEndpointTests<br>{<br>    [Fact]<br>    public async Task Get_ReturnDepartment_WhenDepartmentExist()<br>    {<br>        Guid departmentId = Guid.Parse(&quot;f002392c-70e1-42dd-a3e9-467ee9c42284&quot;);<br><br>        var httpClient = new HttpClient<br>        {<br>            BaseAddress = new Uri(&quot;http://localhost:7200&quot;) // the base address of our API projext<br>        };<br><br>        var response = await httpClient<br>          .GetAsync($&quot;/api/department/{departmentId}&quot;);<br><br>        Assert.NotNull(response);<br><br>        Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode);<br><br>        var department = await response.Content<br>            .ReadFromJsonAsync&lt;GetDepartmentResponse&gt;();<br><br>        Assert.Equal(departmentId, department.Id);<br>    }<br>}</pre><p>To run this test, we’ll need to launch our API project. Once the project is up and running, simply right-click on the ‘<em>GetDepartmentEndpointTests</em>’ in your solution explorer and select ‘Run Tests’. This will run your test execution. (I assume you’re also using Visual Studio as your IDE). Upon completion, you’ll observe that the test has passed successfully.</p><p>We’ve completed our first integration test. However, it’s worth noting that we had to launch our API project before running this test. Additionally, we’re currently executing this test against our actual database. We’ll address these two concerns shortly.</p><p><strong>Web Application Factory<br>‘</strong><em>WebApplicationFactory</em>’ allows us to to execute our tests without the need to manually start our API project. It is used to create a TestServer for the integration tests.</p><p>Go to the Nuget Package Manager and search for ‘<em>Microsoft.AspNetCore.Mvc.Testing</em>’. Install the version that’s appropraite for the .NET version you’re using. Additionally, install ‘<em>FluentAssertions</em>’. With these two packages installed, let’s proceed to refactor our test class.</p><p>In your API project, create an interface. This interface will act as a marker that the ‘<em>WebApplicationFactory</em>’ will use to identify our API project assembly. Let’s name this interface ‘<em>IApiMarker</em>’.</p><pre>public interface IApiMarker<br>{<br>}</pre><p>In your test project, ensure that you’ve added your API project as a project reference if you haven’t already done so.</p><pre>public class GetDepartmentEndpointTests : <br>  IClassFixture&lt;WebApplicationFactory&lt;IApiMarker&gt;&gt;<br>{<br>    private readonly HttpClient _httpClient;<br><br>    public GetDepartmentEndpointTests(WebApplicationFactory&lt;IApiMarker&gt; appFactory)<br>    {<br>        _httpClient = appFactory.CreateClient();<br>    }<br><br>    [Fact]<br>    public async Task Get_ReturnDepartment_WhenDepartmentExist()<br>    {<br>        Guid departmentId = Guid.Parse(&quot;f002392c-70e1-42dd-a3e9-467ee9c42284&quot;);<br><br>        var response = await _httpClient<br>          .GetAsync($&quot;/api/department/{departmentId}&quot;);<br><br>        response.StatusCode.Should().Be(System.Net.HttpStatusCode.OK);<br><br>        response.Should().NotBeNull();<br><br>        var department = await response.Content<br>          .ReadFromJsonAsync&lt;GetDepartmentResponse&gt;();<br><br>        department.Id.Should().Be(departmentId);<br>    }<br>}</pre><p>Now, our test class inherits from ‘<em>WebApplicationFactory&lt;&gt;</em>’ with ‘<em>IApiMarker</em>’ specified as the type argument. You’ll also notice a difference in our assertions, thanks to the ‘FluentAssertions’ package we installed earlier. When we run the test, it should pass seamlessly.</p><p>We utilize ‘<em>IClassFixture&lt;&gt;</em>’ to provide shared object instances across the tests in the class. In simpler terms, if we have five(5) test methods, a single instance of ‘<em>WebApplicationFactory</em>’, will be shared and utilized by all these test methods.</p><p>We aim to modify this test method to enable the testing of multiple department IDs . How do we do so?</p><pre> [Theory]<br> [InlineData(&quot;f002392c-70e1-42dd-a3e9-467ee9c42284&quot;)]<br> [InlineData(&quot;8D88F56D-21C6-4F46-89A4-E849F62ECBD9&quot;)]<br> public async Task Get_ReturnDepartment_WhenDepartmentExist(Guid departmentId)<br> {<br>     var response = await _httpClient.GetAsync($&quot;/api/department/{departmentId}&quot;);<br><br>     response.StatusCode.Should().Be(System.Net.HttpStatusCode.OK);<br><br>     response.Should().NotBeNull();<br><br>     var department = await response.Content<br>      .ReadFromJsonAsync&lt;GetDepartmentResponse&gt;();<br><br>     department.Id.Should().Be(departmentId);<br> }</pre><p>To achieve that, we use the ‘<em>Theory</em>’ attribute along with ‘<em>InlineData</em>’. The number of arguments in our test method must match the number of arguments passed in ‘<em>InlineData</em>’. In this scenario, we only have ‘<em>departmentId</em>’ as the argument. Another example for clarification</p><pre>[Theory]<br>[InlineData(&quot;f002392c-70e1-42dd-a3e9-467ee9c42284&quot;, &quot;Business Admin&quot;)]<br>public async Task Get_ReturnDepartment_WhenDepartmentExist(Guid departmentId, <br>  string departmentName){}</pre><p>When we run our tests, only the first one passes. This is because there isn’t any record in the database with the department ID ‘<em>8D88F56D-21C6–4F46–89A4-E849F62ECBD9</em>’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m8P1mDhV779QhXMPK5Yxmg.png" /></figure><p>Let’s write another test method. This time, we’re focusing on a scenario where a department with a specific ID does not exist.</p><pre> [Fact]<br> public async Task Get_ReturnNotFound_WhenDepartmentDoesNotExist()<br> {<br>     Guid departmentId = Guid.Parse(&quot;1680F9D6-C6D5-4648-A614-8EF46E073692&quot;);<br><br>     var response = await _httpClient<br>      .GetAsync($&quot;/api/department/{departmentId}&quot;);<br><br>     response.StatusCode.Should().Be(System.Net.HttpStatusCode.NotFound);<br> }</pre><p>When we run the test, it should pass successfully.</p><p>Now, let’s proceed to create a test method to verify the creation of a department. In the ‘<em>DepartmentEndpointTests</em>’ folder, we’ll create a class named ‘<em>CreateDepartmentEndpointTests</em>’. Like before, this will inherit from ‘<em>WebApplicationFactory</em>’ and we’ll utilize the ‘<em>IClassFixture&lt;&gt;</em>’ to provide shared object instances across the tests in this class.</p><pre>  [Fact]<br>  public async Task Create_CreateDepartment_WhenDataIsValid()<br>  {<br>      CreateDepartmentCommand department = <br>          new(&quot;Math&quot;, &quot;MTH&quot;, <br>          new List&lt;Application.Courses.Request.CreateCourseRequest&gt;());<br><br>      var response = await _httpClient<br>        .PostAsJsonAsync(&quot;api/department&quot;, department);<br><br>      response.StatusCode.Should().Be(System.Net.HttpStatusCode.Created);<br><br>      var deptCreated = await response.Content<br>        .ReadFromJsonAsync&lt;CreateDepartmentResponse&gt;();<br><br>      response.Headers.Location.Should()<br>        .Be($&quot;http://localhost/api/department/{deptCreated.Id}&quot;);<br><br>      deptCreated!.Code.Should().Be(department.Code);<br>  }</pre><p>We’re testing for the expected status code, which should be ‘<em>201</em>’ for a successful creation. Additionally, we can verify other aspects such as the response headers, as we’ve done for the ‘<em>Location</em>’ header. Upon running the test, we observe that it passes successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*Wq4RfuWtrgiynU8FU-FGPg.png" /></figure><p>One unresolved issue is that all the tests we’ve conducted so far have utilized our actual database. However, this approach is not ideal, as we prefer not to test against the actual database. In production, you wouldn’t be testing against the live database. To address this, we’ll use Docker to create a test container database that we can use for our tests. To continue with the remainder of this write-up, ensure that Docker is installed on your machine.</p><p>To set up our database test container, we’ll begin by adding the Nuget Package ‘<em>Testcontainers.PostgreSql</em>’. Additionally, within the same project, let’s create a folder named ‘<em>Fixtures</em>’. Inside this folder, we’ll create a class named ‘<em>CustomApplicationFactory</em>’</p><pre>public class CustomApplicationFactory : WebApplicationFactory&lt;IApiMarker&gt;, <br>    IAsyncLifetime<br>{<br>    private readonly PostgreSqlContainer _container = <br>          new PostgreSqlBuilder().Build();<br><br>    public async Task InitializeAsync()<br>    {<br>        await _container.StartAsync();<br>    }<br><br>    public new async Task DisposeAsync()<br>    {<br>        await _container.DisposeAsync();<br>    }<br>}</pre><p>We inherit from the ‘<em>WebApplicationFactory&lt;IApiMarker&gt;’</em>, and I’ll provide the reasons shortly. Additionally, we inherit from ‘<em>IAsyncLifetime</em>’, an interface that provides us with two methods: ‘<em>InitializeAsync</em>’ and ‘<em>DisposeAsync</em>’. The ‘<em>InitializeAsync</em>’ method is called when an instance of this class, ‘<em>CustomApplicationFactory</em>’ is created, while ‘<em>DisposeAsync</em>’ is called when the instance is destroyed. In the ‘<em>InitializeAsync</em>’ method, we start our PostgreSQL container and in the ‘<em>DisposeAsync</em>’ method, we dispose of it. Let’s verify if a PostgreSQL container is indeed created for us.</p><p>In the ‘<em>CreateDepartmentEndpointTests</em>’ class, I’ve made some modifications to the code.</p><pre>public class CreateDepartmentEndpointTests : <br>    IClassFixture&lt;CustomApplicationFactory&gt;<br>{<br>    private readonly HttpClient _httpClient;<br><br>    public CreateDepartmentEndpointTests(CustomApplicationFactory appFactory)<br>    {<br>        _httpClient = appFactory.CreateClient();<br>    }<br><br><br>    [Fact]<br>    public async Task CheckDb()<br>    {<br>        await Task.Delay(8000);<br>    }<br><br>}</pre><p>Instead of inheriting from ‘<em>IClassFixture&lt;WebApplicationFactory&lt;&gt;&gt;</em>’, we now inherit from ‘<em>IClassFixture&lt;CustomApplicationFactory&gt;</em>’ and inject it into our constructor. Additionally, I’ve added a dummy method. When we run the test on this method and check our Docker Desktop, we’ll observe that a test container was indeed created. You should see something similar to the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X1ePeeTO52X7LIEaGez32w.png" /></figure><p>If you observe something similar, we’re on the right track. The next step involves replacing our actual database with this test database during testing. How do we achieve this? In the ‘<em>CustomApplicationFactory</em>’ class, remember that we inherited from ‘<em>WebApplicationFactory</em>’. Because of this, we can override a method that allows us to modify our services during testing. Let’s proceed with this in the ‘<em>CustomApplicationFactory</em>’ class</p><pre> protected override void ConfigureWebHost(IWebHostBuilder builder)<br> {<br>     builder.ConfigureTestServices(services =&gt;<br>     {<br>         // remove actual database<br>         <br>         // replace with test container db<br><br>         // apply migrations/ seed initial data<br>     });<br> }</pre><p>We’ve overridden the ‘<em>ConfigureWebHost</em>’ method. Now let’s create a class to contain the methods responsible for the tasks commented in the code snippet above. At the root of our integration test project, we’ll create a ‘<em>Utils</em>’ folder. Within that folder, we’ll create a ‘<em>ServiceCollectionExtensions</em>’ class. The first method in this class will handle the removal of the actual database.</p><pre>public static class ServiceCollectionExtensions<br>{<br>    public static void RemoveDbContext&lt;TContext&gt;(this IServiceCollection services)<br>    {<br>        var dbDescriptor = services.SingleOrDefault(x =&gt; x.ServiceType == <br>            typeof(DbContextOptions&lt;SchoolDbContext&gt;));<br><br>        if(dbDescriptor is not null)<br>            services.Remove(dbDescriptor);<br>    }<br>}</pre><p>Now, let’s call this method within our ‘<em>ConfigureWebHost</em>’ method.</p><pre>protected override void ConfigureWebHost(IWebHostBuilder builder)<br> {<br>     builder.ConfigureTestServices(services =&gt;<br>     {<br>         // remove actual database<br>          services.RemoveDbContext&lt;SchoolDbContext&gt;();<br>         <br>         // replace with test container db<br><br>         // apply migrations/ seed initial data<br>     });<br> }</pre><p>Next, we’ll replace the removed database with the one from our test container.</p><pre>protected override void ConfigureWebHost(IWebHostBuilder builder)<br> {<br>     builder.ConfigureTestServices(services =&gt;<br>     {<br>         // remove actual database<br>          services.RemoveDbContext&lt;SchoolDbContext&gt;();<br>         <br>         // replace with test container db<br>          services.AddDbContext&lt;SchoolDbContext&gt;(opt =&gt;<br>          {<br>              opt.UseNpgsql(_container.GetConnectionString());<br>          });<br><br>         // apply migrations/ seed initial data<br>     });<br> }</pre><p>Notice that we’re using the connection string obtained from our test container. Finally, we apply migrations or seed any initial data. In our ‘<em>ServiceCollectionExtensions</em>’ class</p><pre>public static class ServiceCollectionExtensions<br>{<br>    public static void RemoveDbContext&lt;TContext&gt;(this IServiceCollection services)<br>    {<br>        var dbDescriptor = services.SingleOrDefault(x =&gt; x.ServiceType == <br>          typeof(DbContextOptions&lt;SchoolDbContext&gt;));<br><br>        if(dbDescriptor is not null)<br>            services.Remove(dbDescriptor);<br>    }<br><br>    public static void DbContextInit&lt;TContext&gt;(this IServiceCollection services)<br>    {<br>        var serviceProvider = services.BuildServiceProvider();<br><br>        using var scope = serviceProvider.CreateScope();<br><br>        var context = scope.ServiceProvider<br>            .GetRequiredService&lt;SchoolDbContext&gt;();<br><br>        context.Database.Migrate();<br>    }<br>}</pre><p>Now, let’s call the second method within our ‘<em>ConfigureWebHost</em>’ method.</p><pre>protected override void ConfigureWebHost(IWebHostBuilder builder)<br> {<br>     builder.ConfigureTestServices(services =&gt;<br>     {<br>         // remove actual database<br>          services.RemoveDbContext&lt;SchoolDbContext&gt;();<br>         <br>         // replace with test container db<br>          services.AddDbContext&lt;SchoolDbContext&gt;(opt =&gt;<br>          {<br>              opt.UseNpgsql(_container.GetConnectionString());<br>          });<br><br>         // apply migrations/ seed initial data<br>        services.DbContextInit&lt;SchoolDbContext&gt;();<br>     });<br> }</pre><p>Now, we’ve effectively substituted our actual database with a test database that we can use for testing purposes, and it will be disposed of after our tests are completed.</p><p>Let’s retest our ‘<em>Create_CreateDepartment_WhenDataIsValid()</em>’ method. You’ll notice that our test passes, and upon inspecting our actual database, we won’t find any record with the code ‘<em>SSC</em>’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BLYXbLtHH4-hEl0XPxiKcg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*WW2_8x_u4Tuh0YehG396Ig.png" /></figure><p>It is worthy to note that our test classes, ‘<em>CreateDepartmentEndpointTests</em>’ and ‘<em>GetDepartmentEndpointTests</em>’ will run in parallel whenever we execute our tests. This is because both classes uses ‘<em>IClassFixture&lt;&gt;</em>’. ‘<em>IClassFixture&lt;&gt;</em>’ ensures that each test class receives its own instance of the ‘<em>CustomApplicationFactory’, </em>resulting in separate database instances. To make all test classes share the same instance, including the same database, we need to use ‘<em>ICollectionFixture&lt;&gt;</em>’ .</p><p><strong>ICollectionFixture<br></strong>We utilize ‘<em>ICollectionFixture&lt;&gt;</em>’ for shared instances among our various test classes. When we use ‘<em>ICollectionFixture&lt;&gt;</em>’, our tests run sequentially, one after the other. In this scenario, the second test class won’t begin until all the tests in the first class have finished.</p><p>Conversely, if we were to use the ‘<em>IClassFixture&lt;&gt;</em>’, as we’re currently doing, each test class would run concurrently since they use different instances.</p><p>In the ‘<em>Fixtures</em>’ folder, let’s create a class named ‘<em>SharedFixture</em>’,</p><pre>[CollectionDefinition(&quot;Api Collection&quot;)]<br>public class SharedFixture : ICollectionFixture&lt;CustomApplicationFactory&gt;<br>{<br>}</pre><p>We inherit from ‘<em>ICollectionFixture&lt;CustomApplicationFactory&gt;</em>’. Additionally, we use the ‘<em>CollectionDefinition</em>’ attribute and assign it the name ‘<em>Api Collection</em>’. We’ll use this name in our test classes.</p><p>Now, in the ‘<em>CreateDepartmentEndpointTests</em>’ test class, we’ll utilize this shared fixture.</p><pre>[Collection(&quot;Api Collection&quot;)]<br>public class CreateDepartmentEndpointTests<br>{}</pre><p>Two differences are notable here: first, we’ve removed the inheritance from ‘<em>IClassFixture&lt;CustomApplicationFactory&gt;</em>’. Second, we’re using an attribute where we’ve passed the name we earlier assigned to our collection, ‘<em>Api Collection</em>’. We’ll apply the same approach to the ‘<em>GetDepartmentEndpointTests</em>’ test class.</p><pre>[Collection(&quot;Api Collection&quot;)]<br>public class GetDepartmentEndpointTests<br>{}</pre><p>Let’s run the tests to ensure everything is functioning as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CPTpMjY0lSkd-X2XWE5rRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qfNytWfm0krfDFcDGdwQcg.png" /></figure><p>Unlike before where we were testing with the actual database, the test database doesn’t have any department with that ID, hence the failure of the first test. Let’s rectify this.</p><pre> [Fact]<br> public async Task Get_ReturnDepartment_WhenDepartmentExist()<br> {<br>     CreateDepartmentCommand dept =<br>         new(&quot;Law&quot;, &quot;LW&quot;, <br>        new List&lt;Application.Courses.Request.CreateCourseRequest&gt;());<br><br>     var createResponse = await _httpClient.PostAsJsonAsync(&quot;api/department&quot;, <br>        dept);<br><br>     createResponse.StatusCode.Should().Be(System.Net.HttpStatusCode.Created);<br><br>     var departmentCreated = await createResponse.Content<br>      .ReadFromJsonAsync&lt;CreateDepartmentResponse&gt;();<br><br>     var response = await _httpClient<br>      .GetAsync($&quot;/api/department/{departmentCreated.Id}&quot;);<br><br>     response.StatusCode.Should().Be(System.Net.HttpStatusCode.OK);<br><br>     response.Should().NotBeNull();<br><br>     var department = await response.Content<br>      .ReadFromJsonAsync&lt;GetDepartmentResponse&gt;();<br><br>     department!.Id.Should().Be(departmentCreated.Id);<br> }</pre><p>Now that our test passed, let’s proceed to write a test for retrieving a list of departments. But before we do that, we need to seed data into our test database during initialization. To accomplish this, let’s create a class named ‘<em>Database</em>’ within the ‘<em>Utils</em>’ folder. Additionally, we’ll generate fake data using ‘<em>Bogus</em>’. Let’s install ‘<em>Bogus</em>’ from the Nuget Package Manager in your test project. In the ‘<em>Database</em>’ class, we’ll define methods for seeding data</p><pre>internal static class Database<br>{<br>    private static readonly Faker&lt;Department&gt; _departmentGenerator = <br>        new Faker&lt;Department&gt;()<br>        .RuleFor(x =&gt; x.Id, faker =&gt; Guid.NewGuid())<br>        .RuleFor(x =&gt; x.Name, faker =&gt; faker.Lorem.Letter(10))<br>        .RuleFor(x =&gt; x.Code, faker =&gt; faker.Lorem.Letter(3));<br><br>    internal static void Initialize(SchoolDbContext context)<br>    {<br>        List&lt;Department&gt; departments = _departmentGenerator<br>          .GenerateBetween(2, 6);<br><br>        context.Departments.AddRange(departments);<br><br>        context.SaveChanges();<br>    }<br>}</pre><p>We use Bogus to generate fake data, which we then add to our database. During the initialization of our database, we want this seeding method to be invoked. As a reminder, we previously created a ‘<em>ServiceCollectionExtensions</em>’ class, which contains a method named ‘<em>DbContextInit</em>’. In that method, we call the ‘<em>Database.Initialize()</em>’ while passing the context to it.</p><pre>public static void DbContextInit&lt;TContext&gt;(this IServiceCollection services)<br>{<br>    var serviceProvider = services.BuildServiceProvider();<br><br>    using var scope = serviceProvider.CreateScope();<br><br>    var context = scope.ServiceProvider.GetRequiredService&lt;SchoolDbContext&gt;();<br><br>    context.Database.Migrate();<br><br>    Database.Initialize(context); // we are calling it here<br>}</pre><p>With data being seeded when our database is created, let’s proceed to write a test for retrieving a list of departments. In the ‘<em>GetDepartmentEndpointTests</em>’ class, we’ll add this test</p><pre> [Fact]<br> public async Task Get_ReturnsListOfDepartment_WhenDepartmentsExists()<br> {<br>     var response = await _httpClient<br>      .GetFromJsonAsync&lt;List&lt;GetDepartmentResponse&gt;&gt;(&quot;api/department&quot;);<br><br>     response.Should().NotBeNullOrEmpty();<br><br>     response.Capacity.Should().BeGreaterThan(1);<br><br>     response.ForEach(dept =&gt;<br>     {<br>         dept.Code.Should().NotBeNullOrWhiteSpace();<br><br>         dept.Name.Should().NotBeNullOrWhiteSpace();<br>     });<br> }</pre><p>Upon running the test, it passes successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t2waL7LluFqYuqECSjxieA.png" /></figure><p>In the ‘<em>CreateDepartmentEndpointTests</em>’ test class, let’s add a test to attempt to creating a record with invalid data.</p><pre> [Fact]<br> public async Task Create_ReturnsValidationError_WhenDataIsNotValid()<br> {<br>     CreateDepartmentCommand department =<br>         new(&quot;&quot;, &quot;SSC&quot;, <br>        new List&lt;Application.Courses.Request.CreateCourseRequest&gt;());<br><br>     var response = await _httpClient.PostAsJsonAsync(&quot;api/department&quot;, <br>        department);<br><br>     response.StatusCode.Should()<br>        .Be(System.Net.HttpStatusCode.UnprocessableEntity);<br><br>     var error = await response.Content.ReadFromJsonAsync&lt;ProblemDetails&gt;();<br><br>     error.Title.Should().Be(&quot;One or more validation error(s)&quot;);<br><br>     error.Detail.Should().Be(&quot;{\&quot;Name\&quot;:[\&quot;Name can not be empty\&quot;]}&quot;);<br> }</pre><p>We’ve passed an empty string as the ‘<em>Name</em>’ of the department, which should trigger a validation error. Upon running the test, it passes as expected.</p><p>Now, let’s move on to writing a test for deleting a record. Within our integration test project, specifically in the ‘<em>EndpointTests/DepartmentEndpointTests</em>’ folder, let’s create a class named ‘<em>DeleteDepartmentEndpointTests’</em>.</p><pre>[Fact]<br>public async Task Delete_DeleteDepartment_WhenDataExist()<br>{<br>    CreateDepartmentCommand department =<br>        new(&quot;Social Sciences&quot;, &quot;SSC&quot;, <br>        new List&lt;Application.Courses.Request.CreateCourseRequest&gt;());<br><br>    var createResponse = await _httpClient.PostAsJsonAsync(&quot;api/department&quot;, <br>      department);<br><br>    createResponse.StatusCode.Should().Be(System.Net.HttpStatusCode.Created);<br><br>    var deptCreated = await createResponse.Content<br>    .ReadFromJsonAsync&lt;CreateDepartmentResponse&gt;();<br><br>    var response = await _httpClient<br>      .DeleteAsync($&quot;api/department/{deptCreated.Id}&quot;);<br><br>    response.StatusCode.Should().Be(System.Net.HttpStatusCode.NoContent);<br>}</pre><p>After executing the test, it passes successfully. Now, let’s address the scenario where the department being deleted does not exist.</p><pre> [Fact]<br> public async Task DeleteDepartment_ReturnNotFound_WhenDataDoesNotExist()<br> {<br>     Guid departmentId = Guid.NewGuid();<br><br>     var response = await _httpClient<br>        .DeleteAsync($&quot;api/department/{departmentId}&quot;);<br><br>     response.StatusCode.Should().Be(System.Net.HttpStatusCode.NotFound);<br> }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VOtA2vWZQxGOHNCxgMMCDg.png" /></figure><p>Writing tests for PUT endpoints (i.e., endpoints to update records) follows a similar pattern to the POST endpoint test classes. You can practice writing those tests by mimicking the structure and approach we’ve used in the POST endpoint test classes, but with modifications to suit the update operations. If you run into any difficulties, feel free to leave a comment below. I’ll do my best to provide assistance and help you out.</p><p>As we conclude this article, I sincerely hope it has proven beneficial, providing a clearer understanding of the concepts discussed. Your feedback is immensely valuable; feel free to share comments and suggestions.</p><p>Thank you for your time and engagement.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de37bf3abd6f" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/integration-testing-in-net-api-a-step-by-step-guide-de37bf3abd6f">Integration Testing in .NET API: A step by step guide</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handle PDF Generation, Merge and Conversion in your .NET App with ConvertApi]]></title>
            <link>https://blog.stackademic.com/handle-pdf-generation-merge-and-conversion-in-your-net-app-with-convertapi-02610d828b9c?source=rss-49c59b67c139------2</link>
            <guid isPermaLink="false">https://medium.com/p/02610d828b9c</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[pdf-converter]]></category>
            <dc:creator><![CDATA[Onafeso Olawale]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 03:54:01 GMT</pubDate>
            <atom:updated>2025-11-04T07:02:09.118Z</atom:updated>
            <content:encoded><![CDATA[<h3>Handle PDF Generation, Merge, and Conversion in your .NET App with ConvertApi</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sENZhoVUtgwr37DyvUkb7Q.jpeg" /></figure><p>In many web applications, there arises a need to generate PDFs, whether they are invoices, receipts, or other documents. While several other libraries in .NET address this requirement, it’s worth understanding your options. QuestPDF offers a code-first approach for building PDFs from scratch. IronPDF takes a different approach. It’s a comprehensive library that handles everything from <a href="https://ironpdf.com/tutorials/html-to-pdf/">HTML-to-PDF conversion</a> with Chrome rendering to advanced PDF manipulation, all running directly in your .NET application without external API calls.</p><p>What makes IronPDF particularly versatile is its all-in-one nature. You’re not just getting PDF generation, you’re getting <a href="https://ironpdf.com/how-to/merge-or-split-pdfs/">merge capabilities, splitting</a>, form handling, watermarking, digital signatures, and more, all in a single library. Since it uses Chrome’s rendering engine internally, your HTML (with full CSS3 and JavaScript support) converts to PDF exactly as it appears in the browser. No surprises with missing styles or broken layouts.</p><p>The key difference here is deployment flexibility. IronPDF runs entirely within your application — perfect if you need to keep data processing in-house, avoid API rate limits, or work in air-gapped environments. Plus, it’s not limited to .NET anymore; IronPDF now supports Java, Python, and Node.js, so your PDF handling logic can follow you across tech stacks.</p><p>Now, one noteworthy cloud-based option is ConvertAPI. Unlike self-hosted libraries, ConvertAPI operates as a REST API service, which brings its own set of advantages for certain scenarios. It seamlessly integrates with various platforms beyond .NET, and handles the processing load on their servers. To get started, you can sign up for an account using this <a href="https://www.convertapi.com/a/signin">link</a>. Upon registration, you’ll receive a secret key, essential for initiating conversion tasks. Additionally, you’ll benefit from a one-time allocation of 250 free conversions, valid for one month. Following the expiration, you can select a plan that best suits your requirements.</p><p>ConvertAPI provides a wide array of services, including, but not limited to , PDF generation and conversion from various sources — such as DOCX to PDF, XLS to PDF— PDF merging, XLS to CSV and much more. For detailed documentation, refer to this <a href="https://www.convertapi.com/doc">link</a></p><p>Enough talk; let’s dive into coding. In the following sections, I’ll demonstrate some practical use cases of the library. To begin, let’s set up a .NET web application.</p><pre>dotnet new sln -o pdf-app // create a solution file<br>cd pdf-app<br>dotnet new web -o pdf-app // create a web application<br>dotnet sln add pdf-app //add the web app to the solution</pre><p>Now that we’ve created our project, let’s set it up. Open the web project, navigate to Nuget Package Manager, and search for ‘ConvertApi’. Install the package. That’s all you need to do. Let’s start exploring the package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y72HUHDdh3DerBvl0PuDvQ.png" /></figure><ol><li><strong>Merging PDFs</strong><br>If your application requires merging one or more PDFs into a single document, you can achieve this seamlessly. For demonstration purposes, let’s consider a random PDF link obtained from Google: <a href="https://www.orimi.com/pdf-test.pdf">pdf-link</a>.</li></ol><pre>app.MapGet(&quot;/pdf-merge&quot;, async () =&gt;<br>{<br>    Uri? uri = default;<br><br>    try<br>    {<br>        // random file url<br>        string pdfLink = &quot;https://www.orimi.com/pdf-test.pdf&quot;; <br><br>        // The files we want to merge<br>        List&lt;ConvertApiFileParam&gt; fileParams = new()<br>        {<br>            new ConvertApiFileParam(&quot;Files&quot;, pdfLink),<br>            new ConvertApiFileParam(&quot;Files&quot;, pdfLink),<br>            new ConvertApiFileParam(&quot;Files&quot;, pdfLink),<br>        };<br><br>        var convertApi = new ConvertApi(&quot;your-secret-key&quot;);<br><br>        var response = await convertApi.ConvertAsync(&quot;pdf&quot;, &quot;merge&quot;, <br>            fileParams);<br><br>        if(response is not null &amp;&amp; response.Files.Any())<br>            uri = response.Files.First().Url;<br>    }<br>    catch (ConvertApiException ex)<br>    {<br>        throw;<br>    }<br><br>    return uri;<br>});</pre><p>Now, let’s test in postman</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*hWuwplzo8C8e3ulMiOMv7A.png" /></figure><p>You can download the merged PDF using the link provided in the response.</p><p>2. <strong>PDF Generation (from HTML)</strong><br>If you need to generate a PDF from an HTML document, you can do seamlessly. To demonstrate, I’ve prepared a simple HTML document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2dSCmIfEhn_iMys-MsJcQ.png" /></figure><pre>app.MapGet(&quot;/html-to-pdf&quot;, async () =&gt;<br>{<br>    Uri? uri = default;<br><br>    try<br>    {<br>        // Get the directory of the html file<br>        string templateDir = Path.Combine(Directory.GetCurrentDirectory(), <br>          &quot;hello.html&quot;);<br><br>        var convertApi = new ConvertApi(&quot;your-secret-key&quot;);<br><br>        var response = await convertApi.ConvertAsync(&quot;html&quot;, &quot;pdf&quot;, <br>            new ConvertApiFileParam(&quot;File&quot;, templateDir));<br><br>        if (response is not null &amp;&amp; response.Files.Any())<br>            uri = response.Files.First().Url;<br>    }<br>    catch (ConvertApiException ex)<br>    {<br>        throw;<br>    }<br><br>    return uri;<br>});</pre><p>Now, let’s test in postman</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*aCBZ0Bjg4k9-nmynHsAQBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t4WFDW3T5XrbXHFahqyJgQ.png" /></figure><p>3. <strong>JPEG to PDF</strong><br>If you need to convert an image(.jpeg) to PDF format, it can be done effortlessly. For demonstration purposes, I’ll use a random image: <a href="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRd6E5w2lpSgBtaHO947h9fq_v9BZRyDUg0n_snavDU8CDZdjjLFco09b0Drg&amp;s">Image link</a></p><pre>app.MapGet(&quot;/jpeg-to-pdf&quot;, async () =&gt;<br>{<br>    Uri? uri = default;<br><br>    try<br>    {<br>        string imageUrl = <br>        &quot;https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRd6E5w2lpSgBtaHO947h9fq_v9BZRyDUg0n_snavDU8CDZdjjLFco09b0Drg&amp;s&quot;;<br><br>        var convertApi = new ConvertApi(&quot;your-secret-key&quot;);<br><br>        var response = await convertApi.ConvertAsync(&quot;jpeg&quot;, &quot;pdf&quot;,<br>            new ConvertApiFileParam(&quot;File&quot;, imageUrl));<br><br>        if (response is not null &amp;&amp; response.Files.Any())<br>            uri = response.Files.First().Url;<br>    }<br>    catch (ConvertApiException ex)<br>    {<br>        throw;<br>    }<br><br>    return uri;<br>});</pre><p>Now, let’s test in postman</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*Mul07tzVwXNY_HP-8tYbdg.png" /></figure><p>Feel free to explore other conversions with various file types. It’s nearly impossible to cover all possibilities.</p><p>If you’ve previously used this library, please do share your experiences. Additionally, if you employ a different method for handling PDF generation, please feel free to share it in the comments section below.</p><p>Thank you for your time and engagement.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02610d828b9c" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/handle-pdf-generation-merge-and-conversion-in-your-net-app-with-convertapi-02610d828b9c">Handle PDF Generation, Merge and Conversion in your .NET App with ConvertApi</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular State Management: Beginners Guide to NgRx]]></title>
            <link>https://blog.stackademic.com/angular-state-management-beginners-guide-to-ngrx-698c820ccde7?source=rss-49c59b67c139------2</link>
            <guid isPermaLink="false">https://medium.com/p/698c820ccde7</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[ngrx]]></category>
            <category><![CDATA[angular-state-management]]></category>
            <dc:creator><![CDATA[Onafeso Olawale]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 17:54:08 GMT</pubDate>
            <atom:updated>2024-01-25T05:09:36.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*-0JtZWOXkX4SIor6NLgjdg.jpeg" /></figure><p>In a previous article, I explored State Management using Subjects and its variants. If you missed that discussion, you can find it <a href="https://medium.com/@onafesowale/angular-state-management-exploring-subject-behaviorsubject-replaysubject-and-asyncsubject-f8987d2b1ab8">here</a>. In this article, our focus shifts to NgRx. Have you ever tried to comprehend NgRx without much success? Throughout this piece, I aim to break the concepts in simpler terms. By the end of this read, I am confident you will have a solid grasp of the discussed concepts.</p><p>Our goal is to simulate a shopping cart within an e-commerce application — a concept familiar to us all. This simulation involves viewing a list of products, with the ability to add and remove items to the cart.</p><p>What is NgRx? <br>NgRx is a framework for building reactive applications in Angular. Among its features, NgRx provides libraries for managing global and local state. One of its primary goals is to facilitate state management in complex applications.</p><p>Now let’s get started by creating a new Angular application for this tutorial</p><pre>ng new cart-ngrx</pre><p>Before we proceed, let’s delve into some key concepts in NgRx</p><ol><li><strong>Store </strong>: This serves as the repository where data is stored and managed. Components can read data from the store and listen for changes to that data.</li><li><strong>Selectors </strong>: We’ve discussed the store where our data resides. But how do we read or retrieve data from the store? This is where Selectors come into play. They are utilized to read data, enabling components to access data stored in the store.</li><li><strong>Reducers </strong>: Beyond reading data, there is also the need to modify it. Reducers handle these changes in the store’s data. They contain logic for altering the state. A reducer takes data as input and returns the updated data. To determine whether to create, update or delete data, Actions come in play.</li><li><strong>Actions </strong>: You can think of Actions as messages which are intercepted by reducers. When dispatched, actions are picked up by the reducer, guiding it on what logic to execute for the data.</li></ol><p>If these concepts still feel unfamiliar, don’t worry — we will be applying them shortly and I’m confident you’ll understand better. Additionally, there’s another concept called <strong>Effects</strong> which we’ll cover in a future article.</p><p>Now that we’ve set up our project, let’s add NgRx to it.</p><pre>ng add @ngrx/store</pre><p>The command above will add NgRx to your application. After installation, you’ll observe the addition of ‘<em>StoreModule</em>’ to the imports array in the app module. This ‘<em>StoreModule</em>’ is responsible for setting up the store in our application.</p><pre>  imports: [<br>    StoreModule.forRoot({}, {})<br>  ],</pre><p>This article will be divided into various tasks, each focusing on specific aspects of NgRx. Before we begin, let’s perform some project setup by creating the necessary models and components.</p><p>In the ‘<em>src/app</em>’ directory, we create a folder, ‘<em>models</em>’ which will contain the interfaces we need. Within this folder, I’ve created a file, ‘<em>product.model.ts</em>’</p><pre>export interface IProduct{<br>  id: number;<br>  name: string;<br>  price: number;<br>}</pre><p>I’ve also created another file, ‘<em>cart.model.ts</em>’</p><pre>export interface ICart{<br>  cartId: string;<br>  cartItems: ICartItems[];<br>}<br><br>export interface ICartItems{<br>  itemId: string;<br>  productName: string;<br>  quantity: number;<br>  price: number;<br>  productId: number;<br>}</pre><p>Now that we have our interfaces, let’s proceed to create the components we’ll need. Navigate to the ‘<em>src/app</em>’ directory in your terminal and execute the following command.</p><pre>ng g c products --skip-tests</pre><p>The command will generate a product component along with the corresponding HTML and CSS files. The ‘ <em>— skip-tests</em>’ flag is used to prevent the generation of a test file. Similarly, create the navbar and cart components in a similar manner</p><pre>ng g c nav-bar --skip-tests<br>ng g c cart --skip-tests</pre><p>Finally, go to the ‘<em>app.component.html</em>’, replace its content with the following</p><pre>&lt;app-nav-bar&gt;&lt;/app-nav-bar&gt;<br>&lt;app-product&gt;&lt;/app-product&gt;</pre><p>When you run your code and open it in your browser, you should see something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*U_rJfVk2YxJ7aBsQUpXh8A.png" /></figure><p>Now that we have completed the basic setup, let’s outline the various tasks we will be undertake before proceeding:<br>1. Retrieve all products from the store and display them in the product component’s html<br>2. Display the count of items in the cart on the navbar<br>3. Display the items in the cart in the cart component<br>4. Add items to cart<br>5. Remove items from the cart<br>6. Show the discount percentage and discounted price for products</p><p><strong>Task 1: Retrieve All Products from Store and Display them in Product Component HTML</strong><br>Navigate to the ‘<em>src/app</em>’ directory, create a folder named, ‘<em>store</em>’. Inside the ‘<em>store</em>’ folder, create a ‘<em>products</em>’ folder. In the ‘<em>products</em>’ folder, create a new file, ‘<em>products.reducer.ts</em>’. This will be our first reducer.</p><pre>export const productReducer = createReducer(); // Import from &#39;@ngrx/store&#39;</pre><p>The code above creates a reducer, but you might encounter an error at this point. This is because the function, ‘<em>createReducer()</em>’ requires at least one argument which is the initial state. Let’s rectify this</p><pre>const initialState: IProduct[] = [<br>  {<br>    id: 1, name: &quot;Keyboard&quot;, price: 100,<br>  },<br>  {<br>    id: 2, name: &quot;Monitor&quot;, price: 300,<br>  },<br>  {<br>    id: 3, name: &quot;Mouse&quot;, price: 200,<br>  },<br>]<br><br>export const productReducer = createReducer(initialState);</pre><p>What we have simply done is create a variable, ‘<em>initialState</em>’ of type ‘<em>IProduct[]</em>’ and added some items for illustration purposes. In a real application, this data might come from a backend API, and you will typically use ‘<em>Effects</em>’ for that purpose. After creating the variable, we pass it to ‘<em>createReducer()</em>’. Subsequently, we add the reducer to our store module. It’s important to note that when a reducer is created, you must add it to the store module in the ‘<em>imports</em>’ array within the app module.</p><pre>   imports: [<br>    StoreModule.forRoot({<br>      product : productReducer<br>    })<br>  ],</pre><p>In the provided code above, we’ve added the product reducer and assigned it the key ‘<em>product</em>’. Now let’s retrieve our products from the store in the product component.</p><pre>export class ProductComponent {<br><br>  product$!: Observable&lt;IProduct[]&gt;;<br><br>  constructor(private store: Store){<br>    this.product$ = this.store.select(&#39;product&#39;);<br>  }<br>}</pre><p>In the code snippet above, we start by creating a variable, ‘<em>product$</em>’ which is of type ‘<em>Observable&lt;IProduct[]&gt;</em>’. Next, we then inject ‘<em>Store</em>’ from ‘<em>@ngrx/store</em>’ in the constructor. The ‘<em>select()</em>’ method enables us choose data from our store. To select data, we pass a key. It’s crucial to use the same key we employed when adding the reducer to the store module. In this case, we added the ‘<em>productReducer</em>’ in the app module with the key ‘<em>product</em>’, hence we use ‘<em>product</em>’ as well. The ‘<em>select’</em> method returns an Observable, hence why we created the Observable ‘<em>product$</em>’.</p><p>Notice we have an error. This is because typescript doesn’t automatically infer that our store will have the ‘<em>product</em>’ key. To resolve this issue we add generic type annotations.</p><pre> constructor(private store: Store&lt;{product: IProduct[]}&gt;){<br>    this.product$ = this.store.select(&#39;product&#39;);<br>  }</pre><p>Here, we inform typescript that our store will be an object that will have a ‘<em>product</em>’ key. The ‘<em>productReducer</em>’ returns an array of products and was added to the store module using ‘<em>product</em>’ as the key, hence, the generic type annotation above. If for example we had a ‘<em>counterReducer</em>’ returning a number and added to the ‘<em>StoreModule</em>’ with a key, ‘<em>count</em>’, then we would have this</p><pre>constructor(private store: Store&lt;{count: number}&gt;){<br>    this.product$ = this.store.select(&#39;count&#39;);<br>  }</pre><p>Let’s display the products in the product component html</p><pre>&lt;div style=&quot;margin-top: 2rem;display: flex;flex-direction: column;width: 700px;&quot;&gt;<br>  &lt;div style=&quot;display: flex;justify-content: space-between;padding: 0 1rem;&quot;<br>    *ngFor=&quot;let product of (product$ | async)&quot;&gt;<br>    &lt;p&gt;{{product.name}}&lt;/p&gt;<br>    &lt;p&gt;{{product.price}}&lt;/p&gt;<br>    &lt;button style=&quot;margin: .5rem 0;&quot;&gt;Add To Cart&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>We use the <em>async </em>pipe because it is deals with observables. This pipe subscribes to the Observable and automatically unsubscribes when the component is destroyed. The resulting view should look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*0cnxphbHDhsOu_CPFOp-xg.png" /></figure><p>And just like that, we have successfully fetched our products from the store and displayed them on the view. However, we haven’t used selectors yet.</p><p>Selectors are functions that take in the state as an argument, where the shape of this state corresponds to the overall shape of the store. In ‘<em>src/app/store/products</em>’ directory, we create a file named ‘<em>products.selectors.ts</em>’ to contain our product selectors.</p><pre>export const selectProducts = (state: {product: IProduct[]}) =&gt; state.product;</pre><p>In the snippet above, as mentioned earlier, the term ‘<em>product</em>’ is used here because it is the key we used when adding the ‘<em>productReducer</em>’ to the store module. If you used a different key when adding the ‘<em>productReducer</em>’, it is that key you will use here.</p><p>Now let’s proceed to use the selector</p><pre>  constructor(private store: Store&lt;{product: IProduct[]}&gt;){<br>    this.product$ = this.store.select(selectProducts);<br>  }</pre><p>In the constructor of the product component, we have replaced the string ‘<em>product</em>’ with the selector we created. The view remains the same and the products are still displayed.</p><p><strong>Task 2 : Display the Count of Items in the Cart on the Navbar</strong><br>Similar to what we accomplished in <strong>Task 1</strong>, let’s follow the same process here. If you’d like to give it a try at this point, feel free to create the reducer, add it to the store, and create the selector</p><p>If you find it a bit challenging or if you’ve given it a shot, and would like assistance, I’ve got you covered. In the ‘<em>src/app/store</em>’ directory, create a new folder called ‘<em>cart</em>’. Within the ‘<em>cart</em>’ folder, create a new file, ‘<em>cart.reducer.ts</em>’.</p><pre>const initialState : ICart = {<br>  cartId : Date.now().toString(),<br>  cartItems : [],<br>};<br><br>export const cartReducer = createReducer(initialState);</pre><p>Following a similar approach as in <strong>Task 1</strong>, we create a reducer using the ‘<em>createReducer()</em>’ function from ‘<em>@ngrx/store</em>’ and pass an initial state to it. Subsequently, we add it to the store module within the ‘<em>imports</em>’ array in the app module</p><pre>  imports: [<br>    StoreModule.forRoot({<br>      product : productReducer,<br>      cart : cartReducer<br>    })<br>  ],</pre><p>Next, let’s retrieve the data in the navbar component, similar to how we did it earlier.</p><pre>export class NavBarComponent {<br><br>  cart$!: Observable&lt;ICart&gt;;<br><br>  constructor(private store : Store&lt;{cart: ICart}&gt;){<br>    this.cart$ = this.store.select(&#39;cart&#39;);<br>  }<br><br>}</pre><p>In this context, we use ‘<em>cart</em>’ because it was the key we used when adding ‘<em>cartReducer</em>’ to the store module and the reducer returns data of type ‘<em>ICart</em>’. Hence, we specify ‘<em>ICart</em>’ above. In the navbar html, we then display the count</p><pre>&lt;div *ngIf=&quot;(cart$ | async) as cart&quot;&gt;<br>  &lt;p&gt;Cart Item Count: {{cart.cartItems.length}}&lt;/p&gt;<br>&lt;/div&gt;</pre><p>The resulting view should look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XS3dp971sEwCDjr01IREA.png" /></figure><p>We’ve successfully displayed the list of products and the count of items in the cart.</p><p><strong>Task 3 : Display the Items in the Cart in the Cart Component</strong><br>We’ve set the foundation for this in <strong>Task 2</strong>. Let’s create a selector for this in the ‘<em>src/app/store/cart</em>’, directory by adding a file ‘<em>cart.selectors.ts</em>’</p><pre>export const selectCartItems = (state: {cart :ICart}) =&gt; state.cart.cartItems;</pre><p>Here, we are selecting the items from the cart.</p><p>In cart component</p><pre>export class CartComponent {<br><br>  cartItems$! : Observable&lt;ICartItems[]&gt;;<br><br>  constructor(private store: Store&lt;{cart : ICart}&gt;){<br>    this.cartItems$ = this.store.select(selectCartItems);<br>  }<br><br>}</pre><p>At this juncture, I assume everyone is familiar with the process. Now, let’s move on to displaying the items in the cart component</p><pre>&lt;div style=&quot;margin-top: 1rem;width: 700px;&quot;&gt;<br>&lt;h3&gt;Cart Items&lt;/h3&gt;<br>&lt;div style=&quot;display: flex;justify-content: space-between;&quot; <br>    *ngFor=&quot;let item of (cartItems$ | async)&quot;&gt;<br>  &lt;p&gt;{{item.productName}}&lt;/p&gt;<br>  &lt;p&gt;{{item.price}}&lt;/p&gt;<br>  &lt;p&gt;{{item.quantity}}&lt;/p&gt;<br>&lt;/div&gt;<br>&lt;/div&gt;</pre><p>Finally, add the cart component to the app component html as seen below</p><pre>&lt;app-nav-bar&gt;&lt;/app-nav-bar&gt;<br>&lt;app-product&gt;&lt;/app-product&gt;<br>&lt;app-cart&gt;&lt;/app-cart&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*yGP9IFtNbWbX9Gq0hvRuoA.png" /></figure><p>No items are displayed under the cart items since there are currently no items in the cart.</p><p><strong>Task 4: Add Item to Cart</strong><br>This task differs from reading data from the store, as we now want to modify data. To achieve this, we need to create an Action. In ‘<em>src/app/store/cart</em>’, directory, add a file called ‘<em>cart.actions.ts</em>’.</p><pre>export const addItem = createAction(); // from ngrx/store</pre><p>An error arise as the ‘<em>createAction()</em>’ method requires at least one argument which is the action type — the unique identifier for this action within your application. It is crucial to ensure that no two actions should have the same identifier.</p><pre>export const addItem = createAction(<br>  &#39;[Cart] Add Item&#39;<br>);</pre><p>Now, with the added identifier, it’s common practice to prefix it with the feature — in this case, ‘<em>[Cart]</em>’. However, we’re not done yet. We aim to add a cart item to our cart items, which means data of type ‘<em>ICartItem</em>’ will be passed down from somewhere. If this is unclear at the moment, don’t worry; it will become clearer as we proceed. To handle the data that will be passed, we add a second argument</p><pre>export const addItem = createAction(<br>  &#39;[Cart] Add Item&#39;,<br>  props&lt;{cartItem: ICartItem}&gt;()<br>);</pre><p>This is how we prepare an action when we want to pass data to it — by utilizing ‘<em>props</em>’ from ‘<em>ngrx/store</em>’. Now, let’s modify our reducer to execute a function when the action is dispatched.</p><pre>export const cartReducer = createReducer(<br>  initialState,<br>  on(addItem, (state, action) =&gt; {})<br>);</pre><p>We’ve introduced a second argument to the ‘<em>createReducer()</em>’ method, utilizing the ‘<em>on()</em>’ function from ‘<em>ngrx/store</em>’. This function associates an action with a given state function. The first argument it expects is the action. Recall that we previously created an action named, ‘<em>addItem</em>’ and we now pass that action as an argument here. Essentially, when the ‘<em>addItem</em>’ action is dispatched, the logic within this anonymous function will be executed and it must return the state.</p><p>Within the anonymous function, we get the <em>state </em>(our current cart) and the <em>action</em>. This <em>action </em>contains two properties, ‘<em>type</em>’ and ‘<em>cartItem</em>’. The ‘<em>type</em>’ property serves as the identifier we assigned earlier when creating the action; as a reminder, we used ‘<em>[Cart] Add Item</em>’ as the identifier. The ‘<em>cartItem</em>’ property holds the data passed down when the action is dispatched.</p><p>It’s important to note that we have the ‘<em>cartItem</em>’ property because when defining the action and utilizing the props, we specified ‘<em>cartItem</em>’ as seen below.</p><pre>export const addItem = createAction(<br>  &#39;[Cart] Add Item&#39;,<br>  props&lt;{cartItem: ICartItem}&gt;()<br>);</pre><p>If we were to change ‘<em>cartItem</em>’ to ‘<em>value</em>’, the two properties available on the action would be ‘<em>type</em>’ and ‘<em>value</em>’.</p><pre>export const addItem = createAction(<br>  &#39;[Cart] Add Item&#39;,<br>  props&lt;{value: ICartItem}&gt;()<br>);</pre><p>Now, let’s return to our reducer and implement the logic to add the item to the cart</p><pre>export const cartReducer = createReducer(<br>  initialState,<br>  on(addItem, (state, action) =&gt; {<br>    const cartItemExist = state.cartItems.find(x =&gt; x.productId == <br>        action.cartItem.productId);<br><br>    if (cartItemExist) {<br>      const updatedCartItems = state.cartItems.map((item) =&gt;<br>        item.productId === action.cartItem.productId<br>          ? { ...item, quantity: item.quantity + 1 }<br>          : item<br>      );<br>      return {<br>        ...state,<br>        cartItems: updatedCartItems,<br>      };<br>    } else {<br>      return {<br>        ...state,<br>        cartItems: [...state.cartItems, action.cartItem],<br>      };<br>    }<br>  })<br>  );</pre><p>In the code snippet above, we check if the product is already in the cart. Remember, the ‘<em>state</em>’ parameter represents our current cart. If the item exists, we increase the quantity of that item, then return an object where we spread our <em>state</em>, replacing the cart items with ‘<em>updatedCartItems</em>’. If the product does not exist, we simply add it. Additionally, the ‘<em>action</em>’, the second argument in the anonymous function is the data passed when we dispatch the ‘<em>addItem</em>’ action.</p><p>With the action and reducer set up, the next step is to dispatch this action.</p><p>In our product component, we define a function</p><pre> addCartItem(product: IProduct){<br>    const cartItem: ICartItem = {<br>      itemId: Date.now().toString(),<br>      productId: product.id,<br>      productName: product.name,<br>      quantity: 1,<br>      price: product.price<br>    }<br><br>    this.store.dispatch(addItem({cartItem: cartItem}));<br>  }</pre><p>We define a function that takes a product as a parameter. With this product we create a ‘<em>cartItem</em>’ of type ‘<em>ICartItem</em>’. Subsequently, we invoke the ‘<em>dispatch</em>’ method from the store. As a reminder, we injected ‘<em>store</em>’ earlier in the constructor. The ‘<em>dispatch()</em>’ method requires an action as an argument and we provide the ‘addItem’ action, executing it. To avoid confusion, note that the first ‘<em>cartItem</em>’ refers to when we initially defined the ‘<em>addItem</em>’ action.</p><pre>export const addItem = createAction(<br>  &#39;[Cart] Add Item&#39;,<br>  props&lt;{cartItem: ICartItem}&gt;() // this cart item<br>);</pre><p>The second ‘<em>cartItem</em>’ refers to the variable we defined. To resolve any confusion if there’s still any, let’s rename it</p><pre>  addCartItem(product: IProduct){<br>    const newCartItem: ICartItem = {<br>      itemId: Date.now().toString(),<br>      productId: product.id,<br>      productName: product.name,<br>      quantity: 1,<br>      price: product.price<br>    }<br><br>    this.store.dispatch(addItem({ cartItem: newCartItem }));<br>  }<br>}</pre><p>I believe any potential confusion has been cleared up. Now, let’s execute the ‘<em>addCartItem</em>’ function in the product component html</p><pre>&lt;div style=&quot;margin-top: 2rem;display: flex;flex-direction: column;width: 700px;&quot;&gt;<br>  &lt;div style=&quot;display: flex;justify-content: space-between;padding: 0 1rem;&quot;<br>    *ngFor=&quot;let product of (product$ | async)&quot;&gt;<br>    &lt;p&gt;{{product.name}}&lt;/p&gt;<br>    &lt;p&gt;{{product.price}}&lt;/p&gt;<br>    &lt;button style=&quot;margin: .5rem 0;&quot; (click)=&quot;addCartItem(product)&quot;&gt;<br>      Add To Cart&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*aJSALYelmlE4liAPDOgjmg.png" /></figure><p>The cart item count has now been updated to 3, reflecting the three(3) items in our cart. The cart items are displayed with their prices and quantities. In essence, what we’ve accomplished is creating an action named ‘<em>addItem</em>’, assigning it an identifier and props. In our cart reducer, we then link a function to this ‘<em>addItem</em>’ action and subsequently dispatch the action</p><p><strong>Task 5: Remove Item In Cart</strong><br>Similar to Task 4, we will create an action, associate the action with a function and then dispatch the action. You can attempt this on your own.</p><p>Have you given it a try? Did you encounter any difficulties? Regardless, let’s work on it together. First, we create an action in the ‘<em>cart.actions.ts</em>’ file</p><pre>export const removeItem = createAction(<br>  &#39;[Cart] Remove Item&#39;,<br>  props&lt;{productId: number}&gt;()<br>);</pre><p>We include the ‘<em>props</em>’ because we’ll need the product’s ID to determine which product to remove from the cart.</p><p>In our cart reducer</p><pre> export const cartReducer = createReducer(<br>  initialState,<br>  on(addItem, (state, action) =&gt; {<br>    const cartItemExist = state.cartItems.find(x =&gt; x.productId == action.cartItem.productId);<br><br>    if (cartItemExist) {<br>      const updatedCartItems = state.cartItems.map((item) =&gt;<br>        item.productId === action.cartItem.productId<br>          ? { ...item, quantity: item.quantity + 1 }<br>          : item<br>      );<br>      return {<br>        ...state,<br>        cartItems: updatedCartItems,<br>      };<br>    } else {<br>      return {<br>        ...state,<br>        cartItems: [...state.cartItems, action.cartItem],<br>      };<br>    }<br>  }),<br>// new code added below<br>  on(removeItem, (state, action) =&gt;<br>  ({...state, cartItems: state.cartItems.filter(x =&gt; x.productId !== action.productId)}))<br>  );</pre><p>It’s important to note that we can include any number of ‘<em>on()</em>’ methods in a reducer, depending on the number of actions we are listening for. In this case, we added a second ‘<em>on()</em>’ method that listens for the ‘<em>removeItem</em>’ action. We executed the function within it to return all items in the cart except the one that matches the ID of the product we are passing.</p><p>Now, let’s dispatch this action. In our cart component, we add a method</p><pre>  removeCartItem(productId: number){<br>    this.store.dispatch(removeItem({productId: productId}));<br>  }</pre><p>In the cart component html</p><pre>&lt;div style=&quot;margin-top: 1rem;width: 700px;&quot;&gt;<br>&lt;h3&gt;Cart Items&lt;/h3&gt;<br>&lt;div style=&quot;display: flex;justify-content: space-between;&quot; *ngFor=&quot;let item of (cartItems$ | async)&quot;&gt;<br>  &lt;p&gt;{{item.productName}}&lt;/p&gt;<br>  &lt;p&gt;{{item.price}}&lt;/p&gt;<br>  &lt;p&gt;{{item.quantity}}&lt;/p&gt;<br>  &lt;button style=&quot;margin: .5rem 0;&quot;  (click)=&quot;removeCartItem(item.productId)&quot;&gt;<br>    Remove Item&lt;/button&gt;<br>&lt;/div&gt;<br>&lt;/div&gt;</pre><p>Now, not only can we add items to our cart, but we can also remove them entirely.</p><p><strong>Task 6: Show Discount for Products and the Discounted Price</strong><br>First, we modify the ‘<em>IProduct</em>’ interface by introducing two additional properties.</p><pre>export interface IProduct{<br>  id: number;<br>  name: string;<br>  price: number;<br>  discount: number;<br>  discountPrice: number<br>}</pre><p>We also update the ‘<em>intialState</em>’ in the product reducer</p><pre>const initialState: IProduct[] = [<br><br>  {<br>    id: 1, name: &quot;Keyboard&quot;, price: 100, discount: 10, discountPrice: 0<br>  },<br>  {<br>    id: 2, name: &quot;Monitor&quot;, price: 300, discount: 5, discountPrice: 0<br>  },<br>  {<br>    id: 3, name: &quot;Mouse&quot;, price: 200, discount: 15, discountPrice: 0<br>  },<br>]</pre><p>In ‘<em>product.selectors.ts</em>’ file, we add a new selector</p><pre> export const selectProductsWithDiscount = createSelector(<br>    selectProducts,<br>    (state: IProduct[]) =&gt; state.map(item =&gt;<br>      { return {...item, discountPrice: item.price - <br>        (item.price * (item.discount / 100))}})<br>  );</pre><p>I’ve introduced a new method ‘<em>createSelector()</em>’ from ‘<em>ngrx/store</em>’. This method allows us to construct complex selectors by layering them on top of each other. Remember the ‘<em>selectProducts</em>’ selector we created earlier? Now we’ve utilized that selector as the first argument for this function. The second argument is a function that will automatically receive the result of the first selector. In this case, the first selector returns the list of products, which is passed as an argument to the anonymous functions, labelled as ‘<em>state</em>’. We can then calculate the discount price and return the updated list of products.</p><p>In the product component, we modify the constructor by replacing the selector passed as a parameter to the ‘<em>select()</em>’ method</p><pre> constructor(private store: Store&lt;{product: IProduct[]}&gt;){<br>    this.product$ = this.store.select(selectProductsWithDiscount);<br>  }</pre><p>In the product component html</p><pre>&lt;div style=&quot;margin-top: 2rem;display: flex;flex-direction: column;width: 700px;&quot;&gt;<br>  &lt;div style=&quot;display: flex;justify-content: space-between;padding: 0 1rem;&quot;<br>    *ngFor=&quot;let product of (product$ | async)&quot;&gt;<br>    &lt;p&gt;{{product.name}}&lt;/p&gt;<br>    &lt;p&gt;Price: {{product.price}}&lt;/p&gt;<br>    &lt;p&gt;Discount: {{product.discount}}%&lt;/p&gt;<br>    &lt;p&gt;Discount price: {{product.discountPrice}}&lt;/p&gt;<br>    &lt;button style=&quot;margin: .5rem 0;&quot; (click)=&quot;addCartItem(product)&quot;&gt;Add To Cart&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*IwTPArmn_VqrTEgJL3ppIQ.png" /></figure><p>As we conclude this article, I sincerely hope it has proven beneficial, providing a clearer understanding of the concepts discussed. Your feedback is immensely valuable; feel free to share comments and suggestions.</p><p>Thank you for your time and engagement.</p><h3>Stackademic</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=698c820ccde7" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/angular-state-management-beginners-guide-to-ngrx-698c820ccde7">Angular State Management: Beginners Guide to NgRx</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular: Sharing Data Between Parent Component and Child Components]]></title>
            <link>https://blog.stackademic.com/angular-sharing-data-between-parent-component-and-child-components-45a3c65f778a?source=rss-49c59b67c139------2</link>
            <guid isPermaLink="false">https://medium.com/p/45a3c65f778a</guid>
            <category><![CDATA[data-binding-in-angular]]></category>
            <category><![CDATA[angular-components]]></category>
            <category><![CDATA[angular-output]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-input]]></category>
            <dc:creator><![CDATA[Onafeso Olawale]]></dc:creator>
            <pubDate>Sun, 17 Dec 2023 09:52:48 GMT</pubDate>
            <atom:updated>2023-12-20T01:19:07.329Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*-0JtZWOXkX4SIor6NLgjdg.jpeg" /></figure><p>Are you exploring Angular and its component based architecture, curious about the mechanisms for sharing data between child and parent components? In this article, we’ll delve into this fundamental aspect. By the end, you’ll be adept at using using ‘<em>@Input</em>’ and ‘<em>@Output</em>’ decorators.</p><p>‘<em>@Input()</em>’ and ‘<em>@Output</em>’ decorators provide a communication bridge between a child component and its parent component. Before delving into the intricacies of these decorators, let’s take a moment to explore the concepts of parent and child components.</p><p><strong>Parent and Child Components</strong><br>Let’s use an illustrative example to describe the relationship between a parent and child component.</p><pre>ng g c product --skip-tests // this will create a product component<br>                            // in the current directory</pre><pre>export class ProductComponent {<br>  products: IProduct[] = [<br>    { id: 1, name: &#39;Shoe&#39;, description: &#39;A shoe&#39;, price: 9000 },<br>    { id: 2, name: &#39;Suit&#39;, description: &#39;A suit&#39;, price: 3000 },<br>    { id: 3, name: &#39;Laptop&#39;, description: &#39;A laptop&#39;, price: 12000 },<br>    { id: 4, name: &#39;Table&#39;, description: &#39;A Table&#39;, price: 1000 },<br>    { id: 5, name: &#39;Charger&#39;, description: &#39;A charger&#39;, price: 8000 },<br>    { id: 6, name: &#39;Airpods&#39;, description: &#39;Apple Airpods&#39;, price: 5000 },<br>  ];<br>}<br><br>  export interface IProduct {<br>    id: number;<br>    name: string;<br>    price: number;<br>    description: string;<br>  }</pre><p>Having created a ‘<em>ProductComponent</em>’ which also contains all our products, lets display this product on the user interface. In the ‘product.component.html’</p><pre>&lt;div *ngFor=&quot;let product of products&quot; style=&quot;width: 900px; padding: 0 5rem;&quot;&gt;<br>  &lt;div style=&quot;display: flex;align-items: center;justify-content: space-between;&quot;&gt;<br>    &lt;p&gt;{{product.name}}&lt;/p&gt;<br>    &lt;p&gt;{{product.description}}&lt;/p&gt;<br>    &lt;p&gt;{{product.price}}&lt;/p&gt;<br>  &lt;/div&gt;<br><br>&lt;/div&gt;</pre><p>In the html snippet above, we use the ‘*<em>ngFor</em>’ structural directive to iterate through the products and display them. Could we have done this better?</p><pre>ng g c product-item --skip-tests // create a product item component</pre><pre>&lt;div *ngFor=&quot;let product of products&quot; style=&quot;width: 900px; padding: 0 5rem;&quot;&gt;<br>  &lt;app-product-item&gt;&lt;/app-product-item&gt;<br>&lt;/div&gt;</pre><p>You can see the difference in the ‘<em>product.component.html</em>’ having introduced the ‘<em>ProductItemComponent</em>’. In the illustration above, ‘<em>ProductComponent</em>’ serves as the parent component while ‘<em>ProductItemComponent</em>’ assumes the role of a child component.</p><pre>// ProductItemComponent html<br><br>&lt;div style=&quot;display: flex;align-items: center;justify-content: space-between;&quot;&gt;<br>  &lt;p&gt;{{product.name}}&lt;/p&gt;<br>  &lt;p&gt;{{product.description}}&lt;/p&gt;<br>  &lt;p&gt;{{product.price}}&lt;/p&gt;<br>&lt;/div&gt;</pre><p>Presently, the child component, ‘<em>ProductItemComponent’ </em>solely defines the html structure for displaying each product but lacks the data from its parent. How do pass this data from the parent component to the child component. This is where the ‘<em>@Input()</em>’ decorator comes in play.</p><p><strong>@Input Decorator</strong><br>An ‘<em>@Input()</em>’ decorator in a child component or directive signifies that the property can receive its value from its parent component.</p><p>As a quick recap, we’ve created a ‘<em>ProductItemComponent</em>’ which is the child component to the ‘<em>ProductComponent</em>’. However, the data still resides in the parent, and we want to pass this data to the child.</p><pre>// Remember to import Input from @angular/core<br>export class ProductItemComponent {<br>  @Input() product!: IProduct<br>}</pre><p>In the provided code snippet, we define a ‘<em>product</em>’ variable of type ‘<em>IProduct</em>’ within the ‘<em>ProductItemComponent</em>’. The presence of ‘<em>@Input()</em>’ before the variable signifies that the data for this variable will be supplied by a parent component, in this case, the ‘<em>ProductComponent</em>’.</p><pre>&lt;div *ngFor=&quot;let product of products&quot; style=&quot;width: 900px; padding: 0 5rem;&quot;&gt;<br>  &lt;app-product-item [product]=&quot;product&quot;&gt;&lt;/app-product-item&gt;<br><br>&lt;/div&gt;</pre><p>In the template snippet above, we iterate over the ‘<em>products</em>’ array. For each ‘<em>product</em>’ in the iteration, we bind the current ‘<em>product</em>’ to the ‘<em>product</em>’ input property of ‘<em>ProductItemComponent</em>’. To avoid confusion, let’s introduce some clarity through renaming</p><pre>&lt;div *ngFor=&quot;let item of products&quot; style=&quot;width: 900px; padding: 0 5rem;&quot;&gt;<br>  &lt;app-product-item [product]=&quot;item&quot;&gt;&lt;/app-product-item&gt;<br><br>&lt;/div&gt;</pre><p>Here, ‘<em>item</em>’ is the individual product from the iteration, and it is passed to the ‘<em>product</em>’ input property of the ‘<em>ProductItemComponent</em>’..</p><p>With these adjustments, we have passed data from the parent component (‘<em>ProductComponent</em>’) to its child component (‘<em>ProductItemComponent</em>’) with the use of ‘<em>@Input()</em>’ decorator and property binding.</p><p><strong>Output Decorator<br></strong>Conceptually, ‘<em>@Output()</em>’ can be perceived as the counterpart to ‘<em>@Input()</em>’. While ‘<em>@Input()</em>’ is used to receive data from a parent component to a child component, ‘<em>@Output()</em>’ is used to send/emit data from a child component to its parent component.</p><p>Consider this scenario: when a button is clicked, we increase the price of a product by 50. Our ‘<em>ProductComponent</em>’ houses the product list, making it the ideal location for methods handling functionalities like price increment. However, the button triggering this action resides in the ‘<em>ProductItemComponent</em>’, which lacks direct access to the product list.</p><p>This presents a challenge: on button click, how does the parent component discern which product’s price to increment? The key lies in acquiring the ‘<em>id</em>’ of the relevant product.</p><p>In the ‘<em>ProductComponent</em>’,</p><pre>// method to increase product price by 50<br>incrementProductPrice(id: number) {<br>    let product = this.products.find(prd =&gt; prd.id === id);<br><br>    if (product) {<br>      product.price += 50;<br>    }<br>  }</pre><p>In the provided method, we retrieve a product from the product list (<em>this.products</em>) using the ‘<em>id</em>’ we get from the parameter. We then update the price of the product by ‘50’ if the product exists in the list. But the question still arises, how do we get the ‘<em>id</em>’ required by this method?</p><p>In the ‘<em>ProductComponentItem</em>’ component</p><pre>// Remember to import Output from @angular/core<br>@Output() productEmitter = new EventEmitter&lt;number&gt;();</pre><p>We introduce a variable ‘<em>productEmitter</em>’ and initialize it with an instance of ‘<em>EventEmitter</em>’. Event emitters serve the purpose of emitting events. The ‘<em>EventEmitter</em>’ takes a generic type parameter which could be a primitive data type — <em>string</em>, <em>number etc. </em>or a complex data type — <em>class etc</em>. In our case, we use a number because we want to emit the ‘<em>id</em>’ of the product which is of data type ‘<em>number</em>’.</p><pre> emitProduct(){<br>    this.productEmitter.emit(this.product.id);<br>  }</pre><p>In the same component — <em>ProductItemComponent </em>— we create a method, ‘<em>emitProduct()</em>’. In this method, we call the ‘<em>.emit()</em>’ on the ‘<em>productEmitter</em>’ and we emit the product id. Notably, as we have direct access to the individual product in this component, hence, why we can use ‘<em>this.product.id</em>’.</p><p>Now, let’s bind this method to a button in the ‘<em>product-item.component.html</em>’ file.</p><pre>&lt;div style=&quot;display: flex;align-items: center;justify-content: space-between;&quot;&gt;<br>  &lt;p&gt;{{product.name}}&lt;/p&gt;<br>  &lt;p&gt;{{product.description}}&lt;/p&gt;<br>  &lt;p&gt;{{product.price}}&lt;/p&gt;<br>  &lt;button (click)=&quot;emitProduct()&quot;&gt;Update Price&lt;/button&gt;<br>&lt;/div&gt;</pre><p>We added a button and on click of the button, we invoke the ‘<em>emitProduct()</em>’ method. As a remainder, this method emits the ‘<em>id</em>’ of the product. Now that our child component is configured to emit the product ‘<em>id</em>’, the next step is to understand how we can retrieve this ‘<em>id</em>’ so it can be used by the parent component.</p><pre>&lt;div *ngFor=&quot;let item of products&quot; style=&quot;width: 900px; padding: 0 5rem;&quot;&gt;<br>  &lt;app-product-item [product]=&quot;item&quot; <br>      (productEmitter)=&quot;incrementProductPrice($event)&quot;&gt;<br>  &lt;/app-product-item&gt;<br><br>&lt;/div&gt;</pre><p>In the provided code snippet, we bind the method ‘<em>incrementProductPrice()</em>’ to the ‘<em>output</em>’ property (‘<em>productEmitter</em>’). It is worth recalling that in the ‘<em>product-item-component.ts</em>’, we defined a variable ‘<em>productEmitter</em>’ and marked it with the ‘<em>@Output()</em>’ decorator.</p><p>The value emitted from ‘<em>productEmitter</em>’ will be contained in ‘<em>$event</em>’. To elaborate, if the emitter were emitting a string — let’s say ‘<em>productName</em>’ — ‘$event’ would represent that specific product name. However, in our case, as we emit the ‘<em>id</em>’ of the product, ‘<em>$event</em>’ corresponds to that particular ‘<em>id</em>’. This ‘<em>id</em>’ is subsequently passed to the ‘<em>incrementProductPrice()</em>’ method.</p><p>As we conclude this article, I sincerely hope it has proven beneficial, providing a clearer understanding of the concepts discussed. Your feedback is immensely valuable; feel free to share comments and suggestions.</p><p>Thank you for your time and engagement.</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45a3c65f778a" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/angular-sharing-data-between-parent-component-and-child-components-45a3c65f778a">Angular: Sharing Data Between Parent Component and Child Components</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular State Management: Exploring Subject, BehaviorSubject, ReplaySubject And AsyncSubject]]></title>
            <link>https://medium.com/@onafesowale/angular-state-management-exploring-subject-behaviorsubject-replaysubject-and-asyncsubject-f8987d2b1ab8?source=rss-49c59b67c139------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8987d2b1ab8</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[behaviorsubject]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[replaysubject]]></category>
            <category><![CDATA[rxjs]]></category>
            <dc:creator><![CDATA[Onafeso Olawale]]></dc:creator>
            <pubDate>Fri, 01 Dec 2023 05:52:39 GMT</pubDate>
            <atom:updated>2023-12-01T05:52:39.420Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*-0JtZWOXkX4SIor6NLgjdg.jpeg" /></figure><p>In this article, we will explore the concepts of state management within Angular. Our focus will be on utilizing the ‘Subject’ and its variants to effectively store and manage states in your Angular applications.</p><p>Essentially, state management involves managing the status of your application from a centralized point, enabling various components to access, and when needed, modify the state. RxJS provides ‘Subject’ and its variants as powerful tools for this purpose. To learn more about RxJS, you can visit this <a href="https://rxjs.dev/guide/overview">link</a>.</p><p>Let’s create an Angular application</p><pre>ng new subject // any name you want, doesn&#39;t have to be &#39;Subject&#39;</pre><p>In the ‘src/app’ directory, create two folders, ‘core’ and ‘student’. In the student directory, create a student component and a student service. This can be done with the command below</p><pre>ng g c student --skip-tests --flat // generate component<br>ng g s student --skip-tests --flat // generate service</pre><p>The initial command generates a student component, accompanied with its corresponding HTML and CSS files within the current directory (‘src/app/student’). By specifying ‘ — flat’, we ensure that a new folder is not created and ‘ — skip-tests’ prevents the generation of a test file. The subsequent command generates a student service file.</p><p>Similarly, replicate this process to create a nav-bar component within the ‘core’ folder. However, no service creation is required for this component. Keep in mind that adherence to the suggested folder structuring is not mandatory, if you prefer, you can create the nav-bar component in the ‘src/app’ directory.</p><p>Create a ‘shared’ folder in ‘src/app’ directory. In this folder, create a models folder, where we specify our models. Create a student interface and a class that implements it.</p><pre>export interface IStudent{<br>  id: number;<br>  name: string;<br>}<br><br>export class Student implements IStudent{<br>  constructor(id: number, name: string){<br>    this.id = id;<br>    this.name = name;<br>  }<br><br>  id: number;<br>  name: string;<br><br>}</pre><p>Within the student service, our goal is to retrieve a list of students and facilitate the addition of new students to the list. In a real-world project, these actions might involve making API calls to fetch and create data.</p><p>However, the challenge arises when we need to share this data, i.e. the list of students to other components. This is precisely where Subject and its variants prove invaluable.</p><p><strong>Subject</strong></p><p>A Subject is a special type of observable that allows values to be multicasted to many observers. Functioning as both an Observable and Observer, a Subject can be subscribed to, akin to any Observable. Simultaneously, it serves as an Observer enabling the pushing of values to the observers(subscribers) through its ‘<em>next()</em>’ method.</p><p>It’s noteworthy that multiple subscribers (Observers) can be linked to the same Subject. Consequently, when the Subject emits a new value, this value is broadcasted to all subscribed observers.</p><p>If your objective involves a straightforward event emitter for disseminating events or notifications to multiple subscribers, without the need for specialized features like replaying the last value or initializing with a specific value, utilizing a ‘Subject’ proves to be sufficient.</p><pre>numbersData = new Subject&lt;number&gt;();<br>textData = new Subject&lt;string&gt;();</pre><p>In the provided code snippet, a Subject is instantiated with the capability to emit number and string values to its subscribers. It’s worth noting that the generic type parameter allows for the utilization of complex data types as well.</p><pre>  students: IStudent[] = [{<br>    id: 1,<br>    name: &#39;Student 001&#39;<br>  },<br>  {<br>    id: 2,<br>    name: &#39;Student 002&#39;<br>  }<br>]<br><br>private studentSource = new Subject&lt;IStudent[]&gt;();<br>student$ = this.studentSource.asObservable();</pre><p>We’ve created a Subject with the generic type ‘<em>IStudent[]</em>’ and associated it with a variable named ‘<em>studentSource</em>’. To ensure that the ‘source’ (<em>studentSource</em>) remains unaltered outside this service, the ‘<em>studentSource</em>’ variable is designated as ‘<em>private</em>’. Additionally, an Observable named ‘student$’ has been created with the Subject(‘<em>studentSource</em>’) serving as its source. External components will subscribe to this Observable.</p><p>A ‘<em>student</em>’ variable is also defined and initialized with some initial data. Our next step involves creating methods within our service to retrieve the list and add items to it.</p><pre> getStudents() {<br>    return this.student$;<br>  }<br><br>  addStudents() {<br>    this.studentSource.next(this.students);<br><br>    const lastStudent = this.students[this.students.length - 1];<br><br>    const studentId = lastStudent.id + 1;<br>    const studentName = &#39;Student&#39; + `00${studentId}`;<br><br>    const newStudent = new Student(studentId, studentName);<br><br>    this.students.push(newStudent);<br><br>    this.studentSource.next(this.students);<br>  }</pre><p>In the provided code snippet, two methods have been outlined. The initial method, ‘<em>getStudents()</em>’, straightforwardly returns the observable ‘<em>student$</em>’ as defined earlier.</p><p>The subsequent method ‘<em>addStudents()</em>’ involves populating the student source with the initial data specified earlier. To add a new student to the list, we get the ‘<em>id</em>’ of the last student from the list, increment it by one, then create a new student with this updated ‘<em>id</em>’ and subsequently update the ‘<em>studentSource</em>’ through the ‘<em>next()</em>’method.</p><pre>this.studentSource.next(this.student);</pre><p>With these methods in place, our service is now set up to emit data to its subscribers. The next step involves subscribing to this data within our student component. Within the student component, we’ll inject our ‘<em>StudentService</em>’ and define two methods to invoke the methods defined in the service.</p><pre> students!: IStudent[];<br><br>  constructor(private studentService: StudentService){}<br><br>  ngOnInit(): void {<br>    this.getStudents();<br>  }<br><br>  getStudents(){<br>    this.studentService.getStudents().subscribe({<br>      next: students =&gt; this.students = students,<br>      error: err =&gt; console.log(err)<br>    });<br>  }<br><br>  addStudents(){<br>    this.studentService.addStudents()<br>  }</pre><p>In the provided code, we’ve defined a variable named ‘<em>students</em>’. Within our constructor, ‘<em>StudentService</em>’ is injected. The ‘<em>getStudents()</em>’ method, defined in our component, subscribes to the ‘getStudents’ method in our service. Upon receiving the data, it is assigned to the ‘<em>students</em>’ variable. Additionally, an ‘<em>addStudents()</em>’ method has been defined which invokes the ‘<em>addStudents()</em>’ method from our service.</p><p>In the student component hmtl, let’s bind the received data</p><pre>&lt;button (click)=&quot;addStudents()&quot;&gt;Add Student&lt;/button&gt;<br><br>&lt;div&gt;<br>  &lt;p *ngFor=&quot;let student of students&quot;&gt;<br>    Id: {{student.id}}  Name: {{student.name}}<br>  &lt;/p&gt;<br>&lt;/div&gt;</pre><p>In the HTML snippet above, a button is created with the ‘click’ event bound to the ‘<em>addStudents()</em>’ method. Additionally, the ‘<em>*ngFor</em>’ directive is used to iterate over the ‘students’ array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qj8_3l7AEe_cVAGuFqfIxQ.png" /></figure><p>Upon the clicking the button for the first time</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*meU00zJSzJV1-7XkgMGPxw.png" /></figure><p>After the initial click, our list has been populated with the initial data, and a new student with ID ‘3’ was added also. On click of the button 3 more times</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JLSuARr3EFN6CYyOmRN8Gg.png" /></figure><p>At this point, we now have a total of 6 students. Let’s recap the steps we have taken thus far. In the ‘<em>StudentService</em>’, a Subject with the type ‘<em>IStudent[]</em>’ was created. This subject named ‘s<em>tudentSource</em>’ serves as the source for an observable ‘<em>student$</em>’, which we exposed for external subscriptions. Additionally, two methods were defined in the service — one to return the observable ‘<em>student$</em>’ for external subscriptions and the other to create new students.</p><p>In the student component, we subscribed to the ‘<em>getStudents()</em>’ method from the ‘<em>StudentService</em>’. With these steps, we successfully shared data using our ‘<em>StudentService</em>’ as the exclusive source to other components.</p><p>Recall, we also created a ‘<em>nav-bar</em>’ component. In this component, our objective is to constantly display the current count of all students. This scenario can be likened to an e-commerce application, where you want to showcase the total items in the user’s shopping cart at all times.</p><pre>students: IStudent[] = [];<br><br>constructor(private studentService: StudentService){<br><br>}<br>  ngOnInit(): void {<br>    this.getStudents();<br>  }<br><br>getStudents(){<br>  this.studentService.getStudents().subscribe({<br>    next: students =&gt; this.students = students,<br>    error: err =&gt; console.log(err)<br>  })<br>}</pre><p>In our ‘nav-bar’ component, we’ve injected the ‘<em>ShopService</em>’, defined a variable named ‘<em>students</em>’ to receive the data from our service, and defined a method ‘<em>getStudents()</em>’ to retrieve the list of students.</p><p>Let’s bind it to the html</p><pre>&lt;div style=&quot;width: 100%; display: flex; justify-content: space-evenly;&quot;&gt;<br>&lt;p&gt;Nav bar&lt;/p&gt;<br>&lt;p&gt;Student count: {{students.length}}&lt;/p&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fsv5hJ3-0B_uTrIwtVH9uA.png" /></figure><p>As seen at the top we’ve achieved the display of ‘Student count: 7’ reflecting the total count of students in our list. Again, we’ve successfully shared data from our ‘<em>StudentService</em>’ to both the student component and the navbar component.</p><p><strong>BehaviorSubject</strong></p><p>‘BehaviorSubject’ holds the latest value and emits it to new subscribers immediately upon subscription. This variant of Subject proves valuable when there is a need to provide an initial value or the most recent emitted value to subscribers. A notable distinction between ‘Subject’ and ‘BehaviorSubject’ lies in their behavior at the time of subscription — ‘Subject’ does not emit an initial value while ‘BehaviorSubject’ does.</p><p>Recall that in the ‘<em>StudentService</em>’, we initialized a variable named ‘<em>students</em>’ of type ‘<em>IStudent[]</em>’ and added two items to it. This data(<em>students</em>) was then added to our source within the ‘<em>addStudents()</em>’ method.</p><pre>  students: IStudent[] = [<br>    {<br>      id: 1,<br>      name: &#39;Student 001&#39;,<br>    },<br>    {<br>      id: 2,<br>      name: &#39;Student 002&#39;,<br>    },<br>  ];<br><br>  addStudents() {<br>    this.studentSource.next(this.students);<br>    ...<br>  }</pre><p>Certainly, we can easily achieve this using a ‘BehaviorSubject’. Let’s proceed with refactoring the code to incorporate a ‘BehaviorSubject’.</p><pre>  private studentSource = new BehaviorSubject&lt;IStudent[]&gt;([<br>    {<br>      id: 1,<br>      name: &#39;Student 001&#39;,<br>    },<br>    {<br>      id: 2,<br>      name: &#39;Student 002&#39;,<br>    },<br>  ]);</pre><p>Upon reloading the webpage, you will notice that the initial data is now displayed without the need to press the ‘Add Student’ button. This behavior is as a result of utilizing the ‘BehaviorSubject’, which emits its initial value to subscribers immediately upon their subscription.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SzKGSasvpv88BDZeIfgfaA.png" /></figure><p><strong>ReplaySubject</strong></p><p>‘ReplaySubject’ has an internal buffer that stores a specified number of values it has observed, subsequently emitting them to new subscribers in the order they were received. This buffer can be configured using the arguments ‘bufferSize’ and ‘windowTime’. The former denotes the number of items retained in the buffer, while the latter signifies the duration for which values are stored in the buffer. Both arguments default to infinity if not explicitly specified.</p><p>Similar to ‘Subject’, ‘ReplaySubject’ utilizes the ‘<em>next()</em>’ method to observe and record new values. In essence, it maintains a record of multiple values in its buffer and emits to subscribers in a First-In-First-Out (FIFO) manner.</p><pre>private studentSource = new ReplaySubject&lt;IStudent&gt;(2);<br><br> addStudents() {<br><br>    const student1 = new Student(1, &quot;Paul&quot;);<br>    const student2 = new Student(2, &#39;Sanders&#39;);<br>    const student3 = new Student(3, &#39;Nial&#39;);<br><br>    this.studentSource.next(student1);<br>    this.studentSource.next(student2);<br>    this.studentSource.next(student3);<br><br>    this.student$.subscribe(val =&gt; {<br>      console.log(val)<br>    })<br>  }</pre><p>We instantiate a ‘ReplaySubject’ and set the buffer size to 2, indicating that the last two values will be conveyed to new subscribers. Within the ‘<em>addStudents()</em>’ method, three students are added to the student source. Subsequently, we subscribe to it and log the received value to the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tAvzsQx7GyEp1saGvl6KFg.png" /></figure><p>Upon examining the logged values, you’ll observe that only the last two students added are displayed. This outcome aligns with our configuration of a buffer size of two(2) during the initialization of the ‘ReplaySubject’.</p><p><strong>AsyncSubject</strong></p><p>‘AsyncSubject’ is a variant of ‘Subject’ that emits the last value emitted by the source observable, but it does so only after the observable has completed. This particular variant of ‘Subject’ proves beneficial when the focus is solely on the last value emitted by an observable. Let’s delve into some code samples to illustrate its usage</p><pre>private studentSource = new AsyncSubject&lt;IStudent&gt;();<br><br> addStudents() {<br><br>    const student1 = new Student(1, &#39;Paul&#39;);<br><br>    const student2 = new Student(2, &#39;Pauline&#39;);<br><br>    this.studentSource.next(student1);<br><br>    this.studentSource.next(student2);<br><br>    this.studentSource.subscribe((data) =&gt; console.log(data));<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RMMPMGQ5auZgRgxtno4kuQ.png" /></figure><p>Upon inspecting the result in the browser, it becomes evident that nothing is logged to the console despite subscribing to the observable. This behavior arises because ‘AsyncSubject’ only emits the latest value from the observable after the said observable has been completed. Let’s modify the code to address this</p><pre>addStudents() {<br>    const student1 = new Student(1, &#39;Paul&#39;);<br><br>    const student2 = new Student(2, &#39;Pauline&#39;);<br><br>    this.studentSource.next(student1);<br><br>    this.studentSource.next(student2);<br><br>    this.studentSource.subscribe((data) =&gt; console.log(data));<br><br>    this.studentSource.complete();<br>}</pre><p>By invoking the ‘<em>.complete()</em>’ method on the ‘Subject’, we are signaling the completion of the observable. Now, let’s inspect the result in the browser</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CuAZESbKjq3KSRYZCkuKTw.png" /></figure><p>We observe that the latest value (in this case, the ‘<em>student2</em>’ object) is successfully logged to the console. This outcome is a result of the observable being completed.</p><p>Now consider a scenario where new values are added to the observable after it has been completed, and then we subscribe to it and subsequently call the ‘<em>complete()</em>’ method. Let’s explore the behavior in this particular scenario</p><pre>addStudents() {<br>    const student1 = new Student(1, &#39;Paul&#39;);<br><br>    this.studentSource.next(student1);<br><br>    this.studentSource.subscribe((data) =&gt; console.log(data));<br><br>    this.studentSource.complete();<br><br>    const student2 = new Student(2, &#39;Pauline&#39;);<br><br>    this.studentSource.next(student2);<br><br>    this.studentSource.subscribe(data =&gt; {<br>      console.log(data);<br>    })<br><br>    this.studentSource.complete();<br>}</pre><p>After the initial call to ‘<em>complete()</em>’, subsequent emissions will be ignored. Referring to the provided code snippet, the logged data will consist of ‘<em>student1</em>’, and ‘<em>student2</em>’ will be disregarded because it was emitted after the ‘<em>complete()</em>’ method had been initially called. In this scenario, the ‘AsyncSubject’ exclusively emits the last value — in this case, ‘<em>student1</em>’ — to any subscribers when the source observable (here ‘<em>studentSource</em>’) completes.</p><p>As we conclude this article, I sincerely hope it has proven beneficial, providing a clearer understanding of the concepts discussed. Your feedback is immensely valuable; feel free to share comments and suggestions.</p><p>Thank you for your time and engagement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8987d2b1ab8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Delegates, Func, Action, Predicate And Lambda in C#: An overview]]></title>
            <link>https://medium.com/@onafesowale/delegates-func-action-predicate-and-lambda-in-c-an-overview-ea92adc0215f?source=rss-49c59b67c139------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea92adc0215f</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Onafeso Olawale]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 18:10:09 GMT</pubDate>
            <atom:updated>2023-11-16T06:57:06.995Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*I7N27KkWCXa-mmOu5jpbyA.jpeg" /></figure><p>As C# developers, we frequently encounter terms such as delegates, Func, lambda expression and so on. It’s highly likely that during our C# journey, we have employed one of these concepts. This article aims to provide a comprehensive discussion of these terms. By the end of this read, you should gain a deeper understanding of these concepts and feel more confident in utilizing them in your code.</p><p><strong>What are Delegates?</strong><br>A delegate is essentially a type that represents references to methods with a particular parameter list and return type, as stated by <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/">Microsoft</a> . In simple terms, it acts as a pointer to a method. When working with delegates, we delegate the responsibility of implementing a logic by assigning it to the delegate. If this concept seems a bit abstract, don’t worry, code samples will be provided soon.</p><p>Delegates are declared using the ‘delegate’ keyword in C#.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MdICIelx1wWVpER03ESpQg.png" /></figure><p>This specific delegate returns void and takes a string parameter. Any method from any accessible class or struct that matches this delegate type — meaning it returns void and accepts a string parameter — can be assigned to this delegate. In other words, ‘PrintMessage’ can reference any void method that takes a string parameter.</p><p>It’s important to note that the method assigned to our delegate doesn’t necessarily have to share the same name as the delegate; it only needs to match the signature. Let’s proceed to create a method that conforms to this delegate type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Wol-8sn2cG-L5Xe8qYQPg.png" /></figure><p>We’ve now defined a method called ‘ToUpper’ that returns void and takes a string parameter. Observe the similarity between this method and our delegate; they both share the same signature. Due to this, we can assign the ‘ToUpper’ method to our delegate ‘PrintMessage’. Let’s proceed to make this assignment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t9Krj19QoExbnw-KTdtpvg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YOPrPWJuPWF70G_BAmWQSw.png" /></figure><p>Both methods demonstrated above illustrate different ways to assign a method to a delegate. You can either assign the method directly to a variable of the delegate type without employing the ‘new’ keyword, or you can use the ‘new’ keyword.</p><p>Now, let’s proceed to invoke our delegate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5jPYELLoRAdj1Hr4tELTtQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PNYwO5HFjCtsIYrMc22ODw.png" /></figure><p>We invoke the delegate either by treating it as a method(printMessage(“”)) or by using the ‘Invoke’ keyword(printMessage.Invoke(“”)). As a reminder, our delegate takes a string parameter, hence the string argument passed during invocation.</p><p>Now let’s explore what happens when we attempt to assign a method that does not match the signature of our delegate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TSaFuLlliYkolFejAbY3yQ.png" /></figure><p>We have modified our ‘ToUpper()’ method to accept no parameters and you’ll notice that we are encountering an error. This is because it does not match the signature of the delegate.</p><p><strong>Delegate use cases</strong><br>Delegates are powerful tools for achieving extensibility in code. They provide a means to add or replace functionality within classes. Let’s delve into some code samples to illustrate how delegates can be used for this purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1LuP3yNQm4OwXuQNhfWn0g.png" /></figure><p>In this code sample, we’ve defined a delegate named ‘OnInitialized()’ and passed it as a parameter to the ‘Initialize()’ method. This approach allows us to introduce additional functionality to the ‘Initialize()’ method dynamically. It’s worth noting that, we could have defined the delegate outside the class and it will still be accessible to the ‘Initialize()’ method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hS7UgYWFi-kd7PLW_pg4rQ.png" /></figure><p>The ‘?’ before the ‘Invoke’ method ensures that Invoke is only called when it references a method. This way, we avoid a null reference exception. Let’s proceed to call this method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZVhapQlzvLebIg1MCtK9ZA.png" /></figure><p>Notice how we’ve extended our code to send a payment code via email to the user without modifying the class(‘PaymentProcessor’) itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*TVIj7aOclRkgVHJlZLRZaQ.png" /></figure><p>In the future, for some reason, it is decided that users be notified by SMS instead of email.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cJhxkw5-uefbWKsfIbiq_A.png" /></figure><p>Notice how we’ve achieved this without modifying our ‘PaymentProcessor’ class. All we needed to do was define a ‘SendPaymentCodeViaSms’ method and our code continues to function seamlessly. This exemplifies how delegates facilitate extensibility.</p><p>Delegates also play a crucial role in Events. When a publisher signals that an event has occurred, every subscriber is executed and act on it.</p><p>Before we go on to discuss on lambda expressions, let’s take a look at multi cast delegate.</p><p><strong>Multi cast Delegate</strong><br>A multi cast delegate is essentially a delegate variable that holds a reference to more than one function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ktWmry2b8oH5PpTrmTWe_w.png" /></figure><p>We have defined a delegate that returns a string and takes a string parameter. Let’s define methods with the same signature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDP5EsYloAirGHOst1z7Lw.png" /></figure><p>We have defined two methods with similar signatures with the ‘PrintMessage’ delegate. Now to assign both methods to our delegate, we can use the ‘+=’ operator with our delegate instance. This way we can add multiple methods to the delegate creating a multi cast delegate that can invoke all the methods when called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qlvIfyejrcFel11KIH-WPw.png" /></figure><p>When invoking the delegate, it’s essential to note that the methods execute sequentially in the order they are added. For instance, in the code above, the string will be converted to lowercase first before the first ten characters are stripped. There is no parallelism in this execution. Similarly, just as we chained methods using ‘+=’, we can also remove methods using ‘-=’.</p><p><strong>Lambda</strong><br>Lambda expressions or statements are concise ways of defining anonymous functions. It’s likely that as some point, you’ve used lambda expressions, even if you weren’t explicitly aware of it. The following is an example of a lambda expression</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0DEsQanPJ2BV3YY8rn-zw.png" /></figure><p>I’m confident that many of us have encountered LINQ and become familiar with syntax like this. It’s worth noting that this syntax below is a form of lambda expression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ccVs1499kPJg1b9saFMCJA.png" /></figure><p>In our ‘PaymentProcessor’ class, when calling the ‘Initialize’ method, we passed a named method to it (‘SendPaymentCodeViaSms’). Alternatively, we could use a lambda expression for the same purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*--Y9tUgPR4v9Z49C6Jv0cg.png" /></figure><p><strong>Is lambda expression the same with lambda statement?</strong></p><p>The provided example above is a lambda expression which is a concise way of defining a one-liner function. This particular lambda expression takes no parameters and returns void. When a method expects a delegate, we can use a lambda expression or statement as demonstrated in the method above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zMxCPPwuStFLWf9pHloi_Q.png" /></figure><p>Lambda statements are akin to method bodies. They are employed for more intricate lambdas. Specifically, for anonymous functions that don’t return anything, a lambda statement is used. This distinction arises because the core concept behind a lambda expression is that it returns a value. It’s advisable to keep anonymous functions as simple as possible to avoid complexity. If a situation becomes too complex, you can always extract portions of the code into separate methods, enhancing overall code readability.</p><p>During runtime, the compiler infers all types(both parameter and return types) used in a lambda expression. While you have the option to explicitly state the types, if the lambda serves as a pointer to a delegate, the types you explicitly state must match those of the delegate. Failure to do so will result in a compile time error.</p><p>Notably, lambdas and delegates play a significant role in the concept of .NET minimal APIs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bOpP4cABG62P59YIMl0NPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*ZOlVyjaDTJXtg_rpz-uLZw.png" /></figure><p><strong>Func</strong><br>A ‘Func’ is a generic delegate that allows you define a method with a specified number of parameters (up to 16) of any data type and a return type. Here is an example of a ‘Func’ delegate that takes two parameters and returns a result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*EpVS5YmeN-Rw6-lOGQhgRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mlUCqndy41Ee9vgf1YBmzg.png" /></figure><p>In this code sample, we’ve defined a ‘Func’ named ‘addFunc’ that takes two integer parameters and returns an integer result. Similarly to invoking any method in C#, we call the ‘addFunc’ function and provide two integers as arguments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*omlltqbeleXf1-NjCLp5hQ.png" /></figure><p>In the provided code snippet above, two methods are created to determine whether a number in a list is greater than a specified value and whether it is less than a specified value. The key observation is that the only distinction between these methods lies in the condition encapsulated within the ‘if’ block. This condition essentially represents a function that returns a boolean value. Is it possible to consolidate both methods into a single method that accommodates diverse conditions and similar scenarios?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IrJN2C1VN8vjGq9DEkUEfA.png" /></figure><p>In this revised code, the condition within the ‘if’ block has been replaced with a function, specifically a ‘Func&lt;int, bool&gt;’. By adopting this approach, the method ‘IsAny’ becomes versatile, allowing it to check condition such as greater than, les than, equal to, and so forth, for any given number in the list of integers. This demonstrated the flexibility achieved through the use of ‘Func’.</p><p><strong>Action</strong><br>An ‘Action’ is a generic delegate that can take a specified number of parameters (up to 16) and does not return a value, essentially representing a void delegate. The primary distinction between a ‘Func’ and ‘Action’ lies in the fact that a ‘Func’ returns a value, while an ‘Action’ does not return a value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pXAabXH_Eslo8S5afwMmhw.png" /></figure><p>In this code example, we’ve defined an ‘Action’ that takes two string parameters and returns void. The action, in this case, involves writing a string to console. This demonstrates how an ‘Action’ can be employed to encapsulate operations that don’t return a value but perform certain actions.</p><p><strong>Predicate</strong><br>A predicate is a generic delegate that accepts a single parameter and returns a boolean value. The key distinction between a ‘Func’ and a ‘Predicate’ lies in their usage: while a ‘Func’ can take multiple parameters and return any value, a ‘Predicate’ specifically takes a single parameter and produces a boolean result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SAmtXx47UtB4LkDB-pgazw.png" /></figure><p>In this code snippet, we define a predicate that takes an integer parameter and checks if that integer is greater than 10.</p><p>As we conclude this article, I sincerely hope it has proven helpful, providing a clearer understanding of the concepts discussed. Your feedback is immensely valuable; feel free to leave comments and suggestions for any topic you’d like me to explore in future articles.</p><p>Thank you for your time and engagement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea92adc0215f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>