Socialize

Sunday, October 19, 2025

How IoT Works Using .NET Core Web API and SQL Server – Step by Step Guide

 Introduction to IoT (Internet of Things)

The Internet of Things (IoT) is a revolutionary technology that connects physical devices to the internet, allowing them to collect, transmit, and receive data. IoT enables automation, monitoring, and smarter decision-making in smart homes, healthcare, industrial automation, and more.

In this article, we will explore how IoT works and demonstrate a practical example using .NET Core Web API and SQL Server, which allows developers to build scalable IoT applications.


How IoT Works – Step by Step

IoT operates through a series of connected components:

1. Devices and Sensors

These are physical devices that monitor or measure conditions like temperature, humidity, motion, or light.

Example: A temperature sensor in a smart home detects 35°C in a room.

2. Connectivity

Devices transmit data to a server or cloud using protocols such as HTTP, MQTT, or CoAP. Wi-Fi, 4G/5G, and LoRaWAN are common connectivity options.

3. Data Storage and Processing

Servers, such as a .NET Core Web API connected to SQL Server, store and process the data. Analytics or automated actions can be performed based on this data.

4. Visualization and Action

The processed data is presented to users through web dashboards, mobile apps, or alerts. Actions can also be automated, such as switching on a fan if temperature exceeds a threshold.


IoT Architecture Example Using .NET Core and SQL Server

Here’s a simple smart home temperature monitoring system:

[Temperature Sensor] --> [IoT Device / Raspberry Pi] --> [Internet] --> [ASP.NET Core Web API] --> [SQL Server Database] --> [Web Dashboard / Mobile App]

Components:

  • Sensor: Collects temperature data.

  • IoT Device: Sends data to API.

  • Web API: Receives data and stores in SQL Server.

  • Database: Saves all readings for analytics.

  • Dashboard: Visualizes real-time data and triggers alerts.


Step 1: Setting Up SQL Server Database

Create a database named IoTDB with a table to store temperature readings:

CREATE TABLE TemperatureReadings ( Id INT IDENTITY(1,1) PRIMARY KEY, SensorId NVARCHAR(50), Temperature FLOAT, ReadingTime DATETIME DEFAULT GETDATE() );

Step 2: Creating .NET Core Web API Project

dotnet new webapi -n IoTWebApi cd IoTWebApi dotnet add package Microsoft.EntityFrameworkCore.SqlServer dotnet add package Microsoft.EntityFrameworkCore.Tools

Step 3: Define Entity and DbContext

public class TemperatureReading { public int Id { get; set; } public string SensorId { get; set; } public double Temperature { get; set; } public DateTime ReadingTime { get; set; } = DateTime.Now; } using Microsoft.EntityFrameworkCore; public class IoTDbContext : DbContext { public IoTDbContext(DbContextOptions<IoTDbContext> options) : base(options) { } public DbSet<TemperatureReading> TemperatureReadings { get; set; } }

Step 4: Configure Database Connection

appsettings.json

{ "ConnectionStrings": { "DefaultConnection": "Server=YOUR_SERVER_NAME;Database=IoTDB;Trusted_Connection=True;" }, "AllowedHosts": "*" }

Program.cs

builder.Services.AddDbContext<IoTDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); builder.Services.AddControllers();

Step 5: Create Temperature API Controller

[ApiController] [Route("api/[controller]")] public class TemperatureController : ControllerBase { private readonly IoTDbContext _context; public TemperatureController(IoTDbContext context) => _context = context; [HttpPost] public async Task<IActionResult> PostReading([FromBody] TemperatureReading reading) { _context.TemperatureReadings.Add(reading); await _context.SaveChangesAsync(); return Ok(reading); } [HttpGet] public async Task<IActionResult> GetReadings() { var readings = await _context.TemperatureReadings .OrderByDescending(r => r.ReadingTime) .ToListAsync(); return Ok(readings); } }

Step 6: Simulate IoT Sensor Data

POST Example (JSON)

{ "SensorId": "Room1", "Temperature": 35.5 }
  • This request stores the temperature reading in SQL Server.

  • GET api/temperature retrieves all readings for analytics and dashboard display.


Step 7: Visualizing Data

  • Use Angular, React, or Blazor to consume the API.

  • Display real-time graphs and trigger alerts if the temperature exceeds thresholds.


Benefits of This IoT Implementation

  1. Real-Time Monitoring: Track temperature changes instantly.

  2. Automation: Trigger devices or alerts automatically.

  3. Data Analytics: Store historical data for insights.

  4. Scalable: Multiple sensors and rooms can be integrated easily.


Conclusion

IoT bridges the physical world with the digital world. By combining .NET Core Web API and SQL Server, developers can create scalable, efficient, and real-time IoT systems for smart homes, industries, and more. With proper dashboards and analytics, businesses and users can make informed decisions and improve automation.

Saturday, October 18, 2025

🚀 Deployment Slots in CI/CD Pipelines — Complete Guide

 🌐 What Are Deployment Slots?

Deployment Slots are live environments within an Azure App Service (Web App) that let you deploy, test, and swap applications without downtime.

Think of them as separate versions of your app running under the same App Service Plan — for example:

  • Production Slot – your live application

  • Staging Slot – where new code is deployed and tested

  • Testing / QA Slot – for internal validation

💡 In short: Deployment slots allow safe, zero-downtime deployments by letting you deploy new versions to a staging environment first and then swap them into production.


🧩 Example Slot Setup

Slot NamePurposeURL Example
ProductionLive user traffichttps://myapp.azurewebsites.net
StagingTest new releases before going livehttps://myapp-staging.azurewebsites.net
QAInternal testinghttps://myapp-qa.azurewebsites.net

Each slot:

  • Has its own configuration (connection strings, app settings)

  • Runs under the same compute resources

  • Can be swapped instantly


⚙️ How Deployment Slots Work in CI/CD

In a CI/CD pipeline, deployment slots are used between the Build and Release stages.

Let’s visualize the flow:

🔁 Pipeline Flow Example

Developer Commit → Build Pipeline → Create Artifact → Deploy to Staging Slot → Validate Tests → Swap to Production Slot

🔹 Step-by-Step Explanation

  1. Build Stage

    • Your code is compiled and tested.

    • Output is packaged as an artifact.

  2. Release Stage

    • The artifact is deployed to the staging slot (not production yet).

    • Automated smoke tests or manual validations are performed.

  3. Slot Swap

    • Once validated, the staging slot is swapped with the production slot.

    • The swap is instantaneous, so users experience zero downtime.

  4. Rollback (if needed)

    • If something goes wrong, simply swap back — instant rollback.


🧱 Example: YAML CI/CD Pipeline Using Deployment Slots

trigger: - main stages: - stage: Build jobs: - job: BuildApp steps: - task: DotNetCoreCLI@2 inputs: command: 'publish' projects: '**/*.csproj' arguments: '--output $(Build.ArtifactStagingDirectory)' - publish: $(Build.ArtifactStagingDirectory) artifact: drop - stage: Deploy dependsOn: Build jobs: - deployment: DeployToStaging environment: 'staging' strategy: runOnce: deploy: steps: - download: current artifact: drop - task: AzureWebApp@1 inputs: azureSubscription: 'MyAzureConnection' appName: 'myapp-service' package: '$(Pipeline.Workspace)/drop/**/*.zip' slotName: 'staging' - deployment: SwapToProduction dependsOn: DeployToStaging steps: - task: AzureAppServiceManage@0 inputs: azureSubscription: 'MyAzureConnection' Action: 'Swap Slots' WebAppName: 'myapp-service' SourceSlot: 'staging' ResourceGroupName: 'MyResourceGroup'

✅ In this pipeline:

  • The Build stage publishes artifacts.

  • The Deploy stage deploys to staging.

  • The Swap step promotes the app to production after verification.


🧠 Key Benefits of Deployment Slots

BenefitDescription
Zero-Downtime DeploymentSwap instantly between slots with no downtime.
Safe TestingTest new versions in staging with production-like settings.
Instant RollbackSwap back to previous slot in seconds if issues occur.
Configuration IsolationDifferent connection strings or keys per slot.
Warm-Up Before ReleaseStaging slot can “preload” your app before swap.

🔍 Use Cases

  1. Blue-Green Deployments
    Deploy new code to blue (staging), swap with green (production) once validated.

  2. Canary Releases
    Gradually route small portions of traffic to the staging slot to monitor impact.

  3. Testing in Production Environment
    Test the latest build in a real environment before it goes live.

  4. Instant Rollback Scenarios
    When a new release fails, swap back to restore the previous version.


⚠️ Things to Keep in Mind

  • Slots share App Service Plan (CPU/RAM).

  • App settings marked as “Slot specific” won’t transfer on swap.

  • Swapping doesn’t move custom domain or SSL settings (they stay on production).

  • Limit: Free and Shared App Service Plans do not support slots.


🧰 Integration with Azure DevOps

In Azure DevOps, you can use:

  • Azure Web App Deploy Task to deploy to specific slots

  • Azure App Service Manage Task to perform swap operations

  • Environments for approvals before swapping to production

This allows controlled, automated deployments without affecting live traffic.


🏁 Summary Table

FeatureDescription
Deployment SlotSeparate environment within App Service
Common SlotsProduction, Staging, QA
Supported PlansStandard, Premium, Isolated
Swap OperationMoves staging → production instantly
CI/CD IntegrationAzure DevOps Pipelines, GitHub Actions, or CLI

💬 Final Thought

Deployment slots are one of the most effective DevOps strategies for achieving:

  • Zero downtime

  • Safe testing in production

  • Quick rollback in case of failure

🗣️ “If you’re deploying to Azure App Service, deployment slots are your safety net for continuous delivery.”

Blog Archive

Don't Copy

Protected by Copyscape Online Plagiarism Checker

Pages