<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Fabrício Marcondes Santos</title>
    <description>The latest articles on DEV Community by Fabrício Marcondes Santos (@fabrcio_marcondessantos).</description>
    <link>https://dev.to/fabrcio_marcondessantos</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1662584%2Fea7bce84-2de0-4ca1-a0db-12983b59b73f.jpg</url>
      <title>DEV Community: Fabrício Marcondes Santos</title>
      <link>https://dev.to/fabrcio_marcondessantos</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/fabrcio_marcondessantos"/>
    <language>en</language>
    <item>
      <title>Automating Deployments with GitHub Actions and Azure App Service</title>
      <dc:creator>Fabrício Marcondes Santos</dc:creator>
      <pubDate>Mon, 23 Sep 2024 23:37:12 +0000</pubDate>
      <link>https://dev.to/fabrcio_marcondessantos/automating-deployments-with-github-actions-and-azure-app-service-23e5</link>
      <guid>https://dev.to/fabrcio_marcondessantos/automating-deployments-with-github-actions-and-azure-app-service-23e5</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Keeping your applications up-to-date and running efficiently is crucial to your project’s success. But how do you ensure every new code is automatically tested, integrated, and deployed? The answer lies in automating deployments using CI/CD (Continuous Integration/Continuous Deployment). GitHub Actions and Azure App Service form a powerful combination that allows you to automate the deployment process for .NET applications, ensuring your updates are always consistent and secure.&lt;/p&gt;

&lt;p&gt;In this post, we’ll show you how to set up CI/CD pipelines using GitHub Actions to automate the deployment of .NET applications to Azure App Service.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is GitHub Actions?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;GitHub Actions is a workflow automation platform that allows you to create and run pipelines directly in your GitHub repositories. You can automate tasks such as testing, builds, and deployments whenever code is updated.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is CI/CD?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CI/CD&lt;/strong&gt; (Continuous Integration/Continuous Deployment) is a methodology that allows you to integrate and deliver code continuously. In practice, this means that every code change is automatically tested and deployed, ensuring your application is always up to date in production.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Before we begin, make sure you have:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Azure Account:&lt;/strong&gt; If you don’t have one yet, you can create one &lt;a href="https://azure.microsoft.com/free/" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;GitHub Account:&lt;/strong&gt; Go to &lt;a href="https://github.com/" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt; to create a repository for your code.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Azure App Service Created:&lt;/strong&gt; The application you want to deploy to Azure.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;ASP.NET Application in GitHub:&lt;/strong&gt; The .NET application is already in GitHub, and you want to automate its deployment.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step-by-Step: Automating Deployments with GitHub Actions&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Creating a Service Principal in Azure&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First, we need to configure a Service Principal in Azure, which is a security identity that GitHub Actions will use to authenticate and deploy to Azure App Service.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Open the &lt;strong&gt;Azure CLI&lt;/strong&gt; and run the following command to create a &lt;strong&gt;Service Principal&lt;/strong&gt;:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;az ad sp create-for-rbac --name "github-deploy" --role contributor \
  --scopes /subscriptions/{your-subscription-id}/resourceGroups/{your-resource-group} \
  --sdk-auth
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Replace {your-subscription-id} with your Azure subscription ID and {your-resource-group} with the name of your resource group.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The command will generate an output with the credentials for the Service Principal in the following format:&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "clientId": "YOUR_CLIENT_ID",
  "clientSecret": "YOUR_CLIENT_SECRET",
  "subscriptionId": "YOUR_SUBSCRIPTION_ID",
  "tenantId": "YOUR_TENANT_ID",
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Copy this output. We will use it to configure secrets in GitHub.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Adding Secrets to GitHub&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now, we will add the Azure credentials as secrets in GitHub.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;In GitHub, go to your application’s repository.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Click &lt;strong&gt;Settings&lt;/strong&gt; and then &lt;strong&gt;Secrets and Variables&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Add the following secrets:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;AZURE_CREDENTIALS:&lt;/strong&gt; Paste the full JSON generated by the 
Azure CLI.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;AZURE_WEBAPP_NAME:&lt;/strong&gt; The name of your application in Azure 
App Service.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Creating the GitHub Actions Workflow File&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Next, we will configure the GitHub Actions workflow file to deploy the application whenever new changes are pushed to the repository.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;In your GitHub repository, create a new folder called .github/workflows.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Inside this folder, create a YAML file called azure-deploy.yml with the following content:&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;name: Deploy ASP.NET Core App to Azure

on:
  push:
    branches:
      - main

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout code
      uses: actions/checkout@v2

    - name: Setup .NET Core
      uses: actions/setup-dotnet@v2
      with:
        dotnet-version: '6.0.x'

    - name: Build project
      run: dotnet build --configuration Release

    - name: Run tests
      run: dotnet test --no-build --verbosity normal

    - name: Publish project
      run: dotnet publish -c Release -o ./publish

    - name: 'Deploy to Azure Web App'
      uses: azure/webapps-deploy@v2
      with:
        app-name: ${{ secrets.AZURE_WEBAPP_NAME }}
        publish-profile: ${{ secrets.AZURE_CREDENTIALS }}
        package: ./publish
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Workflow Explanation:&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;on: push:&lt;/strong&gt; The pipeline will trigger whenever there’s a push to the main branch.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Setup .NET Core:&lt;/strong&gt; Configures the environment to use the .NET 6.0 version.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Build project:&lt;/strong&gt; Builds the application.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Run tests:&lt;/strong&gt; Runs unit tests.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Publish project:&lt;/strong&gt; Publishes the app to a ./publish folder.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Deploy to Azure Web App:&lt;/strong&gt; Deploys the app to Azure using the secrets set up earlier.&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Step 4: Testing the Pipeline&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now that the pipeline is set up, make a small change to your code and push it to the main branch. GitHub Actions will be triggered, and you can monitor the deployment process in the Actions tab of your repository.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Benefits of Using GitHub Actions with Azure&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Automating the deployment process with GitHub Actions brings several benefits:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Full Automation:&lt;/strong&gt; Ensure that every time new code is pushed to the repository, it is automatically tested and deployed, eliminating manual errors.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Deep Integration with Azure:&lt;/strong&gt; GitHub Actions offers native integrations with Azure services, making setup and deployment easier.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Scalability:&lt;/strong&gt; As your application grows, you can easily adjust the pipeline to include additional tests, build in multiple environments, and more.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Automating your deployments with GitHub Actions and Azure App Service is an efficient way to ensure your application is always up-to-date and in production with minimal manual effort. CI/CD pipelines allow you to focus on development while automation takes care of the rest.&lt;/p&gt;

</description>
      <category>azure</category>
      <category>github</category>
      <category>cicd</category>
    </item>
    <item>
      <title>Step-by-Step: Deploying a .NET Web App to Azure</title>
      <dc:creator>Fabrício Marcondes Santos</dc:creator>
      <pubDate>Thu, 19 Sep 2024 22:02:30 +0000</pubDate>
      <link>https://dev.to/fabrcio_marcondessantos/step-by-step-deploying-a-net-web-app-to-azure-2553</link>
      <guid>https://dev.to/fabrcio_marcondessantos/step-by-step-deploying-a-net-web-app-to-azure-2553</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Imagine you've developed an amazing web application in .NET, and now you want to make it accessible to the world. One of the most efficient and scalable ways to do this is by deploying your application to Azure App Service. Azure provides a complete solution for hosting your applications without the need to manage servers, allowing you to focus on what really matters: development.&lt;/p&gt;

&lt;p&gt;In this tutorial, we'll walk you through the process of deploying an ASP.NET application to Azure App Service, from creating the resource to deploying the application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Azure App Service?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Azure App Service is a managed hosting platform that allows you to easily create and deploy web applications, APIs, and even mobile apps. It offers automatic scaling, built-in security, and support for multiple programming languages such as .NET, Java, Node.js, Python, and more.&lt;/p&gt;

&lt;p&gt;For .NET developers, Azure App Service is the natural choice for hosting applications securely and at scale.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Before starting, make sure you have the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Azure Account:&lt;/strong&gt; If you don’t have one yet, you can create one &lt;a href="https://azure.microsoft.com/free/" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Visual Studio 2019/2022 or Visual Studio Code:&lt;/strong&gt; Installed on your computer.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;.NET Core SDK:&lt;/strong&gt; Ensure the latest version of the .NET SDK is installed.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step-by-Step Guide to Deploy Your Web App to Azure&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Creating the Web App in Visual Studio&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Open Visual Studio and create a new ASP.NET Core Web Application project.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;ul&gt;
&lt;li&gt;Select the ASP.NET Core Web App (Model-View-Controller) option.&lt;/li&gt;
&lt;li&gt;Choose the latest version of .NET Core and configure the project 
name.&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Build your application by adding controllers, views, and necessary logic.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Run the project locally to ensure everything works correctly.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Creating the App Service in Azure&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now that your application is ready, let’s set it up on Azure.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Go to the Azure portal and sign in.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Navigate to "App Services" in the portal menu and click "Create".&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Fill in the required details:&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Resource Group:&lt;/strong&gt; Create a new one or select an existing &lt;br&gt;
   one.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;App Name:&lt;/strong&gt; Choose a unique name for your app.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Publish:&lt;/strong&gt; Select "Code".&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Runtime Stack:&lt;/strong&gt; Select the .NET version your app is using &lt;br&gt;
   (e.g., ".NET 6").&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Region:&lt;/strong&gt; Choose the nearest region for better latency.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Hosting Plan: Choose the Service Plan that best suits your needs. To start, the free plan (F1) is a great option for small projects.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Review and Create: Click "Review + Create", and after reviewing, click "Create" to provision the resource.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Deploying the Web App to Azure&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;In Visual Studio, right-click your project and select Publish.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose Azure as the deployment target and click Next.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Sign in to your Azure account directly from Visual Studio if you haven’t already.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Select the App Service you just created as the deployment target.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Configure the deployment options, review the settings, and click Publish.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Visual Studio will now automatically deploy your application to Azure App Service. Once completed, the URL of your published application will be displayed.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 4: Verifying the Deployed Application&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Once the deployment process is complete, your application will be available at the App Service URL.&lt;/p&gt;

&lt;blockquote&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Visit the provided URL to see your application live.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Test the application online to ensure everything works as &lt;br&gt;
expected.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Additional Tips&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Auto Scaling:&lt;/strong&gt; Azure App Service allows you to configure automatic scaling based on traffic, ensuring your app can handle spikes in usage without issues.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Monitoring:&lt;/strong&gt; Use Application Insights in Azure to monitor your app’s performance and identify bottlenecks.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Automated Deployments:&lt;/strong&gt; For larger projects, you can configure GitHub Actions or Azure DevOps for continuous deployments whenever code changes are made.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Deploying an ASP.NET application to Azure App Service is a straightforward and efficient process. With just a few steps, you can make your application accessible to the world with scalable, secure infrastructure managed by Azure. If you’re new to Azure, App Service is a great starting point for hosting your .NET applications.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Unveiling Azure: The Future of Cloud for .NET Developers</title>
      <dc:creator>Fabrício Marcondes Santos</dc:creator>
      <pubDate>Sun, 15 Sep 2024 22:38:51 +0000</pubDate>
      <link>https://dev.to/fabrcio_marcondessantos/unveiling-azure-the-future-of-cloud-for-net-developers-bml</link>
      <guid>https://dev.to/fabrcio_marcondessantos/unveiling-azure-the-future-of-cloud-for-net-developers-bml</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Imagine Azure as a vast toolbox in the cloud that offers scalable and flexible solutions for your .NET applications. Azure, Microsoft’s cloud platform, not only provides computational power and storage but also a complete ecosystem for developing, managing, and monitoring your applications efficiently and securely.&lt;/p&gt;

&lt;p&gt;For .NET developers, Azure is the natural extension of their skills, enabling the creation of robust solutions in the cloud with full integration into the Microsoft stack.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Azure?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Azure is Microsoft’s cloud computing platform, offering a wide range of services to help businesses and developers build, test, deploy, and manage applications. Whether creating a simple web app or a complex machine learning solution, Azure has the infrastructure and tools needed to take your idea from concept to production.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why Use Azure for .NET Applications?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For developers using .NET, Azure offers a series of benefits that make cloud development simpler and more integrated:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Full Integration with .NET:&lt;/strong&gt; Azure is optimized to work with .NET, allowing you to use your existing knowledge to build powerful cloud solutions without needing to learn a new ecosystem.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;On-Demand Scalability&lt;/strong&gt;: With Azure, you can start small and scale as your application grows. Whether increasing processing power or storage, Azure makes it easy to scale without complications.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Automation Tools:&lt;/strong&gt; Azure offers tools like Azure DevOps and GitHub Actions to help automate the development lifecycle, including CI/CD (Continuous Integration and Delivery).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Managed Services:&lt;/strong&gt; Azure provides a range of managed services, such as databases, storage, authentication, and AI APIs, making it easier to build complete applications without managing complex infrastructure.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Security:&lt;/strong&gt; With a focus on security, Azure provides encryption at rest, integrated network security, and compliance with industry standards like GDPR.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Key Azure Services for .NET Developers&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here are some of the most commonly used Azure services by .NET developers:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Azure App Service:&lt;/strong&gt; A fully managed service for hosting web apps, APIs, and mobile apps. With native .NET support, it's a great choice for hosting your applications securely and at scale.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Azure Functions:&lt;/strong&gt; A serverless platform that lets you run small pieces of code on-demand, without managing servers. Ideal for automation and background tasks.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Azure SQL Database:&lt;/strong&gt; A fully managed relational database service optimized for use with .NET, with support for transactions, automatic backups, and recovery.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Azure Blob Storage:&lt;/strong&gt; A scalable storage solution for any type of unstructured data, such as files, images, or backups.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Azure Service Bus:&lt;/strong&gt; A messaging service that facilitates communication between different components and services of your application.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Practical Example of .NET Integration with Azure&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s consider a practical example: you're developing a web application in ASP.NET Core. With Azure App Service, you can easily host this application in the cloud, configure automatic backups, monitor performance with Application Insights, and automate deployments using GitHub Actions. The entire development and operations cycle can be managed with ease and efficiency.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Azure is one of the most powerful cloud platforms available, especially for .NET developers. With a wide range of services, built-in security, and on-demand scalability, it enables you to build, test, and deploy robust solutions quickly and efficiently. If you haven't explored Azure yet, now is the time to start!&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>azure</category>
    </item>
    <item>
      <title>Encrypting Columns in .NET Without Third-Party Dependencies</title>
      <dc:creator>Fabrício Marcondes Santos</dc:creator>
      <pubDate>Sat, 17 Aug 2024 17:14:15 +0000</pubDate>
      <link>https://dev.to/fabrcio_marcondessantos/encrypting-columns-in-net-without-third-party-dependencies-fm2</link>
      <guid>https://dev.to/fabrcio_marcondessantos/encrypting-columns-in-net-without-third-party-dependencies-fm2</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;br&gt;
Imagine you have a vault where you store confidential information. To ensure that no one else has access, you need a secure key that encrypts and decrypts this data. In programming, this concept is implemented using encryption, and ensuring your information is secure is essential.&lt;/p&gt;

&lt;p&gt;In my recent .NET project, after upgrading to .NET 8, I realized that the 'EntityFrameworkCore.EncryptColumn' NuGet package was no longer compatible. Instead of being tied to a potentially abandoned package, I decided to create my own encryption solution. I'll share with you how I implemented this functionality to protect sensitive data without relying on third-party packages.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why Create Your Own Solution?&lt;/strong&gt;&lt;br&gt;
Relying on third-party packages can be risky, especially if those packages are no longer maintained or regularly updated. Creating your own solution offers several advantages:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Total Control:&lt;/strong&gt; You have complete control over how the data is encrypted and decrypted.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Flexibility:&lt;/strong&gt; You can adjust the implementation as needed without waiting for external updates.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Security:&lt;/strong&gt; Ensures that the libraries and methods used are secure and compatible with the latest version of .NET.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Implementing Column Encryption&lt;/strong&gt;&lt;br&gt;
Here's how you can implement column encryption in Entity Framework Core using a custom approach:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Create the 'EncryptColumnAttribute'&lt;/strong&gt;&lt;br&gt;
This attribute will be used to mark the properties that need to be encrypted.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public sealed class EncryptColumnAttribute : System.Attribute
{
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Create the Encryption Converter&lt;/strong&gt;&lt;br&gt;
The 'EncryptionConverter' converts property values for encryption and decryption.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;internal sealed class EncryptionConverter : ValueConverter&amp;lt;string, string&amp;gt;
{
    public EncryptionConverter(IEncryptionProvider encryptionProvider, ConverterMappingHints mappingHints = null) 
        : base(x =&amp;gt; encryptionProvider.Encrypt(x), x =&amp;gt; encryptionProvider.Decrypt(x), mappingHints)
    {
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Extension for Configuring the ModelBuilder&lt;/strong&gt;&lt;br&gt;
This extension allows you to configure the 'ModelBuilder' to apply encryption to properties marked with the 'EncryptColumn' attribute.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static class ModelBuilderExtension
{
    public static void UseEncryption(this ModelBuilder modelBuilder, IEncryptionProvider encryptionProvider)
    {
        if (modelBuilder is null)
            throw new ArgumentNullException(nameof(modelBuilder));
        if (encryptionProvider is null)
            throw new ArgumentNullException(nameof(encryptionProvider));

        var encryptionConverter = new EncryptionConverter(encryptionProvider);
        foreach (IMutableEntityType entityType in modelBuilder.Model.GetEntityTypes())
        {
            foreach (IMutableProperty property in entityType.GetProperties())
            {
                if(property.ClrType == typeof(string) &amp;amp;&amp;amp; !IsDiscriminator(property))
                {
                    object[] attributes = property.PropertyInfo.GetCustomAttributes(typeof(EncryptColumnAttribute), false);
                    if(attributes.Any())
                        property.SetValueConverter(encryptionConverter);
                }
            }
        }
    }

    private static bool IsDiscriminator(IMutableProperty property) 
        =&amp;gt; property.Name == "Discriminator" || property.PropertyInfo == null;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Interface for the Encryption Provider
This interface defines the methods for encrypting and decrypting values.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface IEncryptionProvider
{
    string Encrypt(string value);
    string Decrypt(string value);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;5. Implement the Custom Encryption Provider&lt;/strong&gt;&lt;br&gt;
The 'CustomEncryptionProvider' class implements the 'IEncryptionProvider' interface using the AES algorithm for encryption.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class CustomEncryptionProvider : IEncryptionProvider
{
    private readonly byte[] _key;
    private readonly byte[] _iv;

    public CustomEncryptionProvider(IOptions&amp;lt;EncryptionOptions&amp;gt; options)
    {
        var key = options.Value.Key;
        if (string.IsNullOrEmpty(key))
        {
            throw new ArgumentNullException(nameof(key));
        }

        _key = Encoding.UTF8.GetBytes(key);
        _iv = new byte[16];
    }

    public string Encrypt(string value)
    {
        if (string.IsNullOrEmpty(value))
            return string.Empty;

        byte[] array; 

        using (Aes aes = Aes.Create())
        {
            aes.Key = _key;
            aes.IV = _iv;

            ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream))
                    {
                        streamWriter.Write(value);
                    }
                    array = memoryStream.ToArray();
                }
            }
        }
        return Convert.ToBase64String(array);
    }

    public string Decrypt(string value)
    {
        if (string.IsNullOrEmpty(value))
            return string.Empty;

        using (Aes aes = Aes.Create())
        {
            aes.Key = _key;
            aes.IV = _iv;
            ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

            var buffer = Convert.FromBase64String(value);
            using (MemoryStream memoryStream = new MemoryStream(buffer))
            {
                using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader streamReader = new StreamReader((Stream)cryptoStream))
                    {
                        return streamReader.ReadToEnd();
                    }
                }
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;6. Configuration in the 'DbContext'&lt;/strong&gt;&lt;br&gt;
In your 'DbContext', configure the 'ModelBuilder' to use encryption.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Context : DbContext
{
    private readonly IConfiguration _config;
    private readonly IEncryptionProvider _provider;

    public Context(IConfiguration config, IEncryptionProvider encryptionProvider)
    {
        _config = config;
        _provider = encryptionProvider;
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.UseEncryption(_provider);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;7. AppSettings and Startup Configuration&lt;/strong&gt;&lt;br&gt;
Add the encryption settings in 'appsettings.json' and configure the service in 'Startup'.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"Encryption": {
    "Key": "Insert your key here"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;services.Configure&amp;lt;EncryptionOptions&amp;gt;(Configuration.GetSection("Encryption"));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;8. Marking Properties for Encryption&lt;/strong&gt;&lt;br&gt;
Now you can mark the properties you want to encrypt with the '[EncryptColumn]' attribute.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Message
{
    public Guid Id { get; set; }
    [EncryptColumn]
    public string Message { get; set; }
}

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
By creating your own encryption solution, you no longer rely on third-party libraries that may be outdated or abandoned. This implementation not only solves the compatibility issue with .NET 8 but also strengthens your application's security by avoiding external dependencies.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Using Redis with .NET</title>
      <dc:creator>Fabrício Marcondes Santos</dc:creator>
      <pubDate>Fri, 02 Aug 2024 21:57:54 +0000</pubDate>
      <link>https://dev.to/fabrcio_marcondessantos/using-redis-with-net-4404</link>
      <guid>https://dev.to/fabrcio_marcondessantos/using-redis-with-net-4404</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Imagine you have a very busy library and need an efficient system to store and retrieve information quickly. Redis is like a super-fast librarian who knows exactly where each book is and can fetch it in the blink of an eye.&lt;/p&gt;

&lt;p&gt;In today’s post, we’ll explore how to use Redis with .NET to improve the performance and scalability of your applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Redis?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Redis is an in-memory data structure store, used as a database, cache, and message broker. It is known for its speed and support for various data structures such as strings, hashes, lists, sets, and more.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why Use Redis with .NET?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Integrating Redis into your .NET applications can bring several benefits:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Performance:&lt;/strong&gt; Storing data in memory makes data retrieval extremely fast.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Scalability:&lt;/strong&gt; Redis can handle large volumes of data and concurrent accesses.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Flexibility:&lt;/strong&gt; Support for multiple data structures allows a wide range of use cases.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Setting Up Redis with .NET&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Step 1: Install Redis&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Before you begin, you need to have Redis installed and running. You can install Redis locally or use a cloud Redis service like Azure Redis Cache or Amazon ElastiCache.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Add NuGet Package&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Add the StackExchange.Redis package to your .NET project. This is the most popular Redis client for .NET.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet add package StackExchange.Redis
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3: Configure the Redis Connection&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In your .NET code, configure the connection to Redis. Here’s an example of how to do this in an ASP.NET Core application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using StackExchange.Redis;

public class RedisCacheService
{
    private readonly ConnectionMultiplexer _redis;
    private readonly IDatabase _db;

    public RedisCacheService()
    {
        _redis = ConnectionMultiplexer.Connect("localhost");
        _db = _redis.GetDatabase();
    }

    public void SetValue(string key, string value)
    {
        _db.StringSet(key, value);
    }

    public string GetValue(string key)
    {
        return _db.StringGet(key);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 4: Use Redis in Your Application&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now, you can use the RedisCacheService to store and retrieve data in your application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class HomeController : Controller
{
    private readonly RedisCacheService _cacheService;

    public HomeController(RedisCacheService cacheService)
    {
        _cacheService = cacheService;
    }

    public IActionResult Index()
    {
        _cacheService.SetValue("greeting", "Hello, Redis!");
        var value = _cacheService.GetValue("greeting");

        ViewBag.Message = value;
        return View();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Practical Example: Data Caching&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s look at a practical example of using Redis for data caching. Suppose you have an application that fetches data from an external API. Using Redis as a cache can reduce latency and load on the external API.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class DataService
{
    private readonly HttpClient _httpClient;
    private readonly RedisCacheService _cacheService;

    public DataService(HttpClient httpClient, RedisCacheService cacheService)
    {
        _httpClient = httpClient;
        _cacheService = cacheService;
    }

    public async Task&amp;lt;string&amp;gt; GetDataAsync(string url)
    {
        var cachedData = _cacheService.GetValue(url);
        if (!string.IsNullOrEmpty(cachedData))
        {
            return cachedData;
        }

        var response = await _httpClient.GetStringAsync(url);
        _cacheService.SetValue(url, response);

        return response;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Using Redis with .NET is like having a super-efficient librarian who can store and retrieve information in record time. By integrating Redis into your application, you can significantly improve performance and scalability.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Authentication and Authorization: Best Practices for Your Application</title>
      <dc:creator>Fabrício Marcondes Santos</dc:creator>
      <pubDate>Wed, 24 Jul 2024 21:20:19 +0000</pubDate>
      <link>https://dev.to/fabrcio_marcondessantos/authentication-and-authorization-best-practices-for-your-application-lbe</link>
      <guid>https://dev.to/fabrcio_marcondessantos/authentication-and-authorization-best-practices-for-your-application-lbe</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Security is like a game of chess: every move must be well thought out. Similarly, when implementing authentication and authorization in your .NET applications, it’s crucial to follow best practices to ensure your data and users are protected.&lt;/p&gt;

&lt;p&gt;In today’s post, we’ll share tips and recommended practices to ensure the security of your .NET applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Importance of Security&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Authentication and authorization are critical processes to ensure that only authorized users can access specific resources in your application. Implementing these practices correctly is essential to protect sensitive data and prevent unauthorized access.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Best Practices for Authentication and Authorization&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Use Strong Passwords and Secure Hashing&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Always require users to create strong passwords and use secure hashing algorithms to store these passwords. ASP.NET Core Identity, for example, uses the PBKDF2 hashing algorithm by default.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;services.AddIdentity&amp;lt;IdentityUser, IdentityRole&amp;gt;(options =&amp;gt;
{
    options.Password.RequireDigit = true;
    options.Password.RequiredLength = 8;
    options.Password.RequireNonAlphanumeric = false;
    options.Password.RequireUppercase = true;
    options.Password.RequireLowercase = false;
})
.AddEntityFrameworkStores&amp;lt;ApplicationDbContext&amp;gt;()
.AddDefaultTokenProviders();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Implement Multi-Factor Authentication (MFA)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Multi-factor authentication adds an extra layer of security by requiring users to provide two or more forms of verification before accessing the application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;services.Configure&amp;lt;IdentityOptions&amp;gt;(options =&amp;gt;
{
    options.SignIn.RequireConfirmedEmail = true;
    options.Tokens.EmailConfirmationTokenProvider = "emailconfirmation";
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Manage User Sessions with Secure Cookies&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Use secure cookies to manage user sessions, ensuring that authentication information is protected.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;services.ConfigureApplicationCookie(options =&amp;gt;
{
    options.Cookie.HttpOnly = true;
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    options.Cookie.SameSite = SameSiteMode.Strict;
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. Limit Login Attempts&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Implement limits for login attempts to prevent brute force attacks. ASP.NET Core Identity allows you to configure this behavior easily.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;services.Configure&amp;lt;IdentityOptions&amp;gt;(options =&amp;gt;
{
    options.Lockout.MaxFailedAccessAttempts = 5;
    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
    options.Lockout.AllowedForNewUsers = true;
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;5. Use Claims and Roles for Authorization&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Use claims and roles to control access to different parts of the application based on user permissions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[Authorize(Roles = "Admin")]
public IActionResult AdminOnly()
{
    return View();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;6. Validate Input Data&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Always validate input data to prevent injection attacks and other common vulnerabilities.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[HttpPost]
public IActionResult Create([FromBody] CreateModel model)
{
    if (ModelState.IsValid)
    {
        // Process the data
    }
    return BadRequest(ModelState);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Security is a game of chess: every move must be well thought out. Implementing these best practices in authentication and authorization will ensure that your .NET application is well protected against threats and unauthorized access.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Step by Step: Implementing Authentication with Identity</title>
      <dc:creator>Fabrício Marcondes Santos</dc:creator>
      <pubDate>Tue, 23 Jul 2024 19:29:19 +0000</pubDate>
      <link>https://dev.to/fabrcio_marcondessantos/step-by-step-implementing-authentication-with-identity-1l4i</link>
      <guid>https://dev.to/fabrcio_marcondessantos/step-by-step-implementing-authentication-with-identity-1l4i</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Imagine you have a building and need to ensure that only authorized people can enter. You hire an electronic doorman to verify users' identities at the entrance. ASP.NET Core Identity works similarly, acting as this electronic doorman that controls access to your application.&lt;/p&gt;

&lt;p&gt;In today’s post, we’ll create a practical tutorial on how to set up and use ASP.NET Core Identity for authentication.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is ASP.NET Core Identity?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;ASP.NET Core Identity is a library that simplifies the implementation of authentication and authorization in .NET applications. It provides ready-to-use functionalities to manage users, passwords, roles, and claims.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step-by-Step Guide to Set Up ASP.NET Core Identity&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Add NuGet Packages&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First, add the necessary packages to your project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2: Configure DbContext and Identity&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create an ApplicationDbContext class that inherits from IdentityDbContext:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ApplicationDbContext : IdentityDbContext&amp;lt;IdentityUser&amp;gt;
{
    public ApplicationDbContext(DbContextOptions&amp;lt;ApplicationDbContext&amp;gt; options)
        : base(options)
    {
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the Startup.cs file, configure the Identity service:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext&amp;lt;ApplicationDbContext&amp;gt;(options =&amp;gt;
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity&amp;lt;IdentityUser, IdentityRole&amp;gt;()
        .AddEntityFrameworkStores&amp;lt;ApplicationDbContext&amp;gt;()
        .AddDefaultTokenProviders();

    services.AddControllersWithViews();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3: Configure Authentication Middleware&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In the Configure method of Startup.cs, add the authentication and authorization middlewares:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =&amp;gt;
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
        endpoints.MapRazorPages();
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 4: Create Registration and Login Pages&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create controllers and views to allow users to register, log in, and log out. ASP.NET Core Identity provides scaffolding to make this task easier:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet aspnet-codegenerator identity -dc ApplicationDbContext
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will create the basic authentication pages for your application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;ASP.NET Core Identity is like an electronic doorman that verifies users' identities, ensuring that only authorized people have access to your application. By following these steps, you can implement authentication efficiently and securely in your .NET applications.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Security in Focus: Authentication in .NET</title>
      <dc:creator>Fabrício Marcondes Santos</dc:creator>
      <pubDate>Mon, 22 Jul 2024 21:27:57 +0000</pubDate>
      <link>https://dev.to/fabrcio_marcondessantos/security-in-focus-authentication-in-net-16a7</link>
      <guid>https://dev.to/fabrcio_marcondessantos/security-in-focus-authentication-in-net-16a7</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Imagine you have a house with several doors. To ensure only authorized people can enter, you distribute keys to those who have permission. Similarly, authentication in web applications is like these keys: only authorized users can access certain areas of the application.&lt;/p&gt;

&lt;p&gt;In today’s post, we’ll explore the importance of authentication in web applications and how .NET makes this process easier.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Importance of Authentication&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Authentication is a critical process in any web application. It ensures that only legitimate users can access sensitive resources and information. Without proper authentication, your applications are vulnerable to unauthorized access, compromising data security.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Authentication in .NET&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;.NET offers various tools and libraries to implement authentication simply and securely. One of the main libraries is ASP.NET Core Identity, which provides a comprehensive solution for managing users, passwords, and roles.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Setting Up ASP.NET Core Identity&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s see how to set up ASP.NET Core Identity in a .NET application:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Add NuGet Packages&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Add the necessary packages to your project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2: Configure DbContext and Identity&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create an ApplicationDbContext class that inherits from IdentityDbContext:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ApplicationDbContext : IdentityDbContext&amp;lt;IdentityUser&amp;gt;
{
    public ApplicationDbContext(DbContextOptions&amp;lt;ApplicationDbContext&amp;gt; options)
        : base(options)
    {
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the Startup.cs file, configure the Identity service:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext&amp;lt;ApplicationDbContext&amp;gt;(options =&amp;gt;
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity&amp;lt;IdentityUser, IdentityRole&amp;gt;()
        .AddEntityFrameworkStores&amp;lt;ApplicationDbContext&amp;gt;()
        .AddDefaultTokenProviders();

    services.AddControllersWithViews();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3: Configure Authentication Middleware&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In the Configure method of Startup.cs, add the authentication and authorization middleware:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =&amp;gt;
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
        endpoints.MapRazorPages();
    });
}

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 4: Create Registration and Login Pages&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create controllers and views to allow users to register, log in, and log out. ASP.NET Core Identity provides scaffolding to make this task easier:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet aspnet-codegenerator identity -dc ApplicationDbContext

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Authentication is like the key to a door: only authorized people can enter. In .NET, we implement this with ASP.NET Core Identity, which simplifies user management and secure authentication implementation.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Protecting Your Applications: Error Middlewares</title>
      <dc:creator>Fabrício Marcondes Santos</dc:creator>
      <pubDate>Sat, 20 Jul 2024 19:35:35 +0000</pubDate>
      <link>https://dev.to/fabrcio_marcondessantos/protecting-your-applications-error-middlewares-5338</link>
      <guid>https://dev.to/fabrcio_marcondessantos/protecting-your-applications-error-middlewares-5338</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;br&gt;
Imagine you are driving a car and, suddenly, something unexpected happens. Airbags deploy to protect you and your passengers. Implementing error middlewares in your .NET application is like having those airbags: they protect your application when something goes wrong, ensuring resilience and security.&lt;/p&gt;

&lt;p&gt;In today’s post, we’ll explore how to implement error middlewares to improve the resilience and security of your .NET application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What Are Error Middlewares?&lt;/strong&gt;&lt;br&gt;
Error middlewares are components that intercept unhandled exceptions in the application, allowing you to log, handle, and respond to these errors appropriately. They are essential to ensure that the application continues to function safely and that users receive friendly error messages.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementing an Error Middleware&lt;/strong&gt;&lt;br&gt;
Let’s create a simple middleware to capture exceptions and log the error details:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Creating the Middleware&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ErrorHandlingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger&amp;lt;ErrorHandlingMiddleware&amp;gt; _logger;

    public ErrorHandlingMiddleware(RequestDelegate next, ILogger&amp;lt;ErrorHandlingMiddleware&amp;gt; logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "An unexpected error occurred!");
            await HandleExceptionAsync(context, ex);
        }
    }

    private static Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

        var response = new { message = "Internal Server Error. Please try again later." };
        var jsonResponse = JsonSerializer.Serialize(response);

        return context.Response.WriteAsync(jsonResponse);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2: Registering the Middleware&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now, let’s register the middleware in the application’s request pipeline:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMiddleware&amp;lt;ErrorHandlingMiddleware&amp;gt;();

    // Other middlewares...
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =&amp;gt;
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Enhancing Resilience and Security&lt;/strong&gt;&lt;br&gt;
Implementing error middlewares brings several benefits:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Resilience: Ensures the application continues running even after an unexpected error.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Security: Prevents exposing sensitive error details to end users.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Maintenance: Makes it easier to identify and fix issues through detailed exception logging.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Implementing error middlewares is like having airbags in a car: they protect your application when something goes wrong, ensuring it continues to operate safely and efficiently. By capturing and handling exceptions appropriately, you improve the resilience and security of your .NET application.&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>csharp</category>
    </item>
    <item>
      <title>Unraveling Middlewares in .NET</title>
      <dc:creator>Fabrício Marcondes Santos</dc:creator>
      <pubDate>Fri, 19 Jul 2024 21:51:30 +0000</pubDate>
      <link>https://dev.to/fabrcio_marcondessantos/unraveling-middlewares-in-net-2jgk</link>
      <guid>https://dev.to/fabrcio_marcondessantos/unraveling-middlewares-in-net-2jgk</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;br&gt;
Imagine driving in a busy city. Traffic officers are strategically positioned to direct and control the flow of vehicles, ensuring everyone reaches their destination safely and efficiently. Similarly, middlewares in .NET act like these traffic officers, directing and controlling the flow of data in an application.&lt;/p&gt;

&lt;p&gt;In today's post, we'll explore the concept of middlewares, understand how they work, and discover why they are fundamental to the architecture of .NET applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What Are Middlewares?&lt;/strong&gt;&lt;br&gt;
Middlewares are software components that form a request and response processing pipeline in a web application. Each middleware can perform operations before and after passing the request to the next middleware in the pipeline. They are essential for tasks like authentication, logging, error handling, and more.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How Do Middlewares Work?&lt;/strong&gt;&lt;br&gt;
When a request arrives at the server, it passes through a series of middlewares, each performing a specific action. Think of it as a processing chain where each link can modify the request or response.&lt;/p&gt;

&lt;p&gt;Here's a simple example of how to configure middlewares in .NET:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =&amp;gt;
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we have several middlewares configured in the pipeline, including HTTP redirection, static files, routing, authentication, and authorization.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why Are They Important?&lt;/strong&gt;&lt;br&gt;
Middlewares are crucial to the architecture of .NET applications for several reasons:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Modularity: They allow functionalities to be broken down into small, reusable components.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Flexibility: You can easily add, remove, or reorder middlewares to change the application's behavior.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Maintainability: They simplify maintenance and evolution of the application by isolating responsibilities.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Practical Example&lt;/strong&gt;&lt;br&gt;
Let's create a simple middleware that logs the processing time of each request:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class RequestTimingMiddleware
{
    private readonly RequestDelegate _next;

    public RequestTimingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var watch = Stopwatch.StartNew();
        await _next(context);
        watch.Stop();
        var elapsedMs = watch.ElapsedMilliseconds;
        Console.WriteLine($"Request took {elapsedMs} ms");
    }
}

public static class RequestTimingMiddlewareExtensions
{
    public static IApplicationBuilder UseRequestTiming(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware&amp;lt;RequestTimingMiddleware&amp;gt;();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And to register this middleware in the pipeline:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseRequestTiming();
    // Other middlewares...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
Just as traffic officers control and direct the flow of vehicles, middlewares in .NET manage the flow of data, ensuring your application runs efficiently and securely. Understanding and utilizing middlewares is essential for developing robust and scalable web applications.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Advanced Entity Framework: Mapping and Queries</title>
      <dc:creator>Fabrício Marcondes Santos</dc:creator>
      <pubDate>Thu, 18 Jul 2024 20:30:13 +0000</pubDate>
      <link>https://dev.to/fabrcio_marcondessantos/advanced-entity-framework-mapping-and-queries-lgm</link>
      <guid>https://dev.to/fabrcio_marcondessantos/advanced-entity-framework-mapping-and-queries-lgm</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;br&gt;
Imagine you are organizing a large closet. Each shelf needs to be well-categorized and each item in its proper place so you can find everything easily. Similarly, mapping in Entity Framework (EF) helps keep our data well-structured and accessible.&lt;/p&gt;

&lt;p&gt;Today’s post will explore more advanced Entity Framework concepts, focusing on relationship mapping and creating complex queries.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Relationship Mapping&lt;/strong&gt;&lt;br&gt;
In Entity Framework, relationships between entities are mapped using navigation properties. Let’s see how to map different types of relationships:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;One-to-Many Relationship&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;An author can have many books, but each book has only one author. Let’s map this relationship:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Author
{
    public int AuthorId { get; set; }
    public string Name { get; set; }
    public ICollection&amp;lt;Book&amp;gt; Books { get; set; }
}

public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public int AuthorId { get; set; }
    public Author Author { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Many-to-Many Relationship&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Imagine a book can have multiple authors and an author can have written multiple books. This is a many-to-many relationship:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public ICollection&amp;lt;BookAuthor&amp;gt; BookAuthors { get; set; }
}

public class Author
{
    public int AuthorId { get; set; }
    public string Name { get; set; }
    public ICollection&amp;lt;BookAuthor&amp;gt; BookAuthors { get; set; }
}

public class BookAuthor
{
    public int BookId { get; set; }
    public Book Book { get; set; }

    public int AuthorId { get; set; }
    public Author Author { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;One-to-One Relationship&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A book can have one specific detail, and that detail belongs to only one book. Here’s how to map this relationship:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public BookDetail BookDetail { get; set; }
}

public class BookDetail
{
    public int BookDetailId { get; set; }
    public string Summary { get; set; }
    public int BookId { get; set; }
    public Book Book { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Complex Queries&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Querying data using LINQ is one of EF’s most powerful features. Let’s look at some examples of complex queries:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Query with Filters and Sorting&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s fetch books by a specific author, sorted by title:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using (var context = new LibraryContext())
{
    var authorBooks = context.Books
        .Include(b =&amp;gt; b.Author)
        .Where(b =&amp;gt; b.Author.Name == "Example Author")
        .OrderBy(b =&amp;gt; b.Title)
        .ToList();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Query with Grouping&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s group books by author and count how many books each author has written:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using (var context = new LibraryContext())
{
    var authorGroups = context.Books
        .GroupBy(b =&amp;gt; b.Author.Name)
        .Select(g =&amp;gt; new 
        {
            Author = g.Key,
            BookCount = g.Count()
        })
        .ToList();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Query with Joins&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s fetch book details along with author information:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using (var context = new LibraryContext())
{
    var booksWithDetails = context.Books
        .Include(b =&amp;gt; b.BookDetail)
        .Include(b =&amp;gt; b.Author)
        .ToList();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
Just like organizing a closet helps us find everything easily, mapping and queries in Entity Framework allow us to keep our data well-structured and accessible. Mastering these advanced concepts makes development with .NET more efficient and powerful.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Fundamentals of Entity Framework: Simplifying Data Access in .NET</title>
      <dc:creator>Fabrício Marcondes Santos</dc:creator>
      <pubDate>Wed, 17 Jul 2024 22:31:44 +0000</pubDate>
      <link>https://dev.to/fabrcio_marcondessantos/fundamentals-of-entity-framework-simplifying-data-access-in-net-2a2b</link>
      <guid>https://dev.to/fabrcio_marcondessantos/fundamentals-of-entity-framework-simplifying-data-access-in-net-2a2b</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;br&gt;
Imagine you are building a large library of books. Organizing, cataloging, and finding information quickly can be a challenge. Now, think of Entity Framework (EF) as an intelligent librarian that makes this process easy for your .NET applications.&lt;/p&gt;

&lt;p&gt;Entity Framework is an Object-Relational Mapper (ORM) that allows developers to work with a database using .NET objects, eliminating the need to write most of the data access code. Let's explore the fundamentals of Entity Framework and understand why it is such a powerful tool.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Entity Framework?&lt;/strong&gt;&lt;br&gt;
Entity Framework is a Microsoft technology for .NET that automates the mapping between domain objects and relational database tables. With it, you can:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Define the data model as C# classes.&lt;/li&gt;
&lt;li&gt;Query and manipulate data using LINQ (Language Integrated Query).&lt;/li&gt;
&lt;li&gt;Manage database versioning through migrations.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Key Components of Entity Framework&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;DbContext: It is the main point of interaction with Entity Framework. It manages the connection to the database and is used to query and save data.
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class LibraryContext : DbContext
{
    public DbSet&amp;lt;Book&amp;gt; Books { get; set; }
    public DbSet&amp;lt;Author&amp;gt; Authors { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ol&gt;
&lt;li&gt;DbSet: Represents a collection of entities in the context, i.e., a table in the database.
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public int AuthorId { get; set; }
    public Author Author { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ol&gt;
&lt;li&gt;Entity Models: These are classes that represent database tables. They are mapped to columns in the database.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Basic Configuration&lt;/strong&gt;&lt;br&gt;
To start using Entity Framework, you need to configure the DbContext. Here is an example of how to configure the database connection:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class LibraryContext : DbContext
{
    public LibraryContext(DbContextOptions&amp;lt;LibraryContext&amp;gt; options)
        : base(options)
    {
    }

    public DbSet&amp;lt;Book&amp;gt; Books { get; set; }
    public DbSet&amp;lt;Author&amp;gt; Authors { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And in the configuration file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "ConnectionStrings": {
    "LibraryDatabase": "Server=(localdb)\\mssqllocaldb;Database=LibraryDb;Trusted_Connection=True;"
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Querying Data&lt;/strong&gt;&lt;br&gt;
With Entity Framework, you can query data using LINQ, which is a powerful and expressive way to write queries:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using (var context = new LibraryContext())
{
    var books = context.Books
        .Include(b =&amp;gt; b.Author)
        .Where(b =&amp;gt; b.Title.Contains("C#"))
        .ToList();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Migrations&lt;/strong&gt;&lt;br&gt;
Migrations allow you to manage changes to the database schema over time. You can create a migration using the command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet ef migrations add InitialCreate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And then apply the migrations to the database:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet ef database update
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
Entity Framework is an essential tool for .NET developers who want to simplify data access and focus more on the business logic of their applications. With its mapping power, LINQ queries, and database migrations, it transforms application development into a more efficient and enjoyable task.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
