Monday, October 20, 2025

๐Ÿง  Difference Between Functions, Stored Procedures, and Views in SQL Server

 ๐Ÿ“˜ Introduction

In SQL Server, Functions, Stored Procedures, and Views are three powerful components that simplify database programming and improve performance.
Although they look similar in some ways, their purpose, behavior, and execution are quite different.

Let’s understand each in detail with real-world examples and learn when to use them.


๐Ÿ”น What is a Function in SQL Server?

A Function in SQL Server is a reusable block of code that performs a specific task and returns a value. Functions are mainly used for calculations, data formatting, and reusable logic inside queries.

✅ Key Features:

  • Must return a value (scalar or table).

  • Cannot perform INSERT, UPDATE, or DELETE operations on database tables.

  • Can be called inside a SELECT statement.

  • Cannot use transactions.

๐Ÿงฉ Types of Functions:

  1. Scalar Function: Returns a single value.

  2. Table-Valued Function: Returns a table.

๐Ÿ’ก Real-Time Example:

Suppose your e-commerce database needs to calculate the total price including tax for each product.

CREATE FUNCTION dbo.fn_GetTotalPrice(@Price DECIMAL(10,2), @Tax DECIMAL(5,2)) RETURNS DECIMAL(10,2) AS BEGIN RETURN @Price + (@Price * @Tax / 100) END;

Now, you can call this function inside a query:

SELECT ProductName, dbo.fn_GetTotalPrice(Price, 18) AS TotalPrice FROM Products;

๐Ÿ‘‰ Use Case: Best used for reusable calculations and logic that needs to return a value in queries.


๐Ÿ”น What is a Stored Procedure in SQL Server?

A Stored Procedure is a precompiled collection of SQL statements that perform one or more database operations.
It can insert, update, delete, or retrieve data, and also handle complex business logic.

✅ Key Features:

  • Can return multiple result sets.

  • Supports transactions and error handling.

  • Can modify data in tables.

  • Can accept input, output, and return parameters.

  • Improves performance due to precompilation and execution plan reuse.

๐Ÿ’ก Real-Time Example:

Let’s say you want to add a new customer into your CRM database.

CREATE PROCEDURE dbo.sp_AddCustomer @CustomerName NVARCHAR(100), @Email NVARCHAR(100), @City NVARCHAR(50) AS BEGIN INSERT INTO Customers (CustomerName, Email, City) VALUES (@CustomerName, @Email, @City); SELECT 'Customer added successfully' AS Message; END;

Execute the stored procedure:

EXEC dbo.sp_AddCustomer 'John Doe', 'john@example.com', 'Hyderabad';

๐Ÿ‘‰ Use Case: Best for performing multiple DML operations (Insert, Update, Delete) or complex business transactions.


๐Ÿ”น What is a View in SQL Server?

A View is a virtual table that displays data from one or more tables through a SQL query.
It doesn’t store data physically — it simply saves a SQL query for easy reuse.

✅ Key Features:

  • Simplifies complex joins and queries.

  • Provides data security by restricting access to specific columns or rows.

  • Can be updated if it’s based on a single table.

  • Improves data abstraction.

๐Ÿ’ก Real-Time Example:

Suppose you have a Sales table and a Customer table. You can create a View to easily get the Customer Sales Summary.

CREATE VIEW vw_CustomerSales AS SELECT c.CustomerName, SUM(s.TotalAmount) AS TotalSales FROM Customers c JOIN Sales s ON c.CustomerID = s.CustomerID GROUP BY c.CustomerName;

Now, just query the View like a table:

SELECT * FROM vw_CustomerSales;

๐Ÿ‘‰ Use Case: Best for reporting, data analysis, and abstracting complex joins.


⚖️ Comparison Table: Functions vs Stored Procedures vs Views

FeatureFunctionStored ProcedureView
Returns ValueYes (Scalar/Table)OptionalActs as a virtual table
Can Modify Data❌ No✅ YesLimited (if single table)
Can Use Transactions❌ No✅ Yes❌ No
Used Inside SELECT✅ Yes❌ No✅ Yes
PerformanceHigh for calculationsHigh for large operationsMedium
ReusabilityHighHighHigh
CompilationCompiled each timePrecompiledNot compiled (query-based)

๐Ÿง  Real-World Scenario: E-Commerce Example

RequirementBest ChoiceReason
Calculate product discountFunctionReturns computed value
Insert new order & update stockStored ProcedurePerforms multiple DML operations
Generate monthly sales reportViewSimplifies query for reporting tools

๐Ÿš€ Best Practices

  1. Use Functions for small, reusable logic that doesn’t modify data.

  2. Use Stored Procedures for complex business workflows.

  3. Use Views to simplify data access and improve query readability.

  4. Avoid heavy logic inside Views — use Indexed Views for performance if needed.

  5. Combine all three effectively for a clean database architecture.


๐Ÿ Conclusion

Understanding the differences between Functions, Stored Procedures, and Views in SQL Server helps developers design efficient, modular, and maintainable databases.
Each component has its strengths — use them wisely to balance performance, reusability, and security.

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.”

๐Ÿงช Practical Example — Implementing Resilience in .NET Core Using Polly

 ๐Ÿ—️ Scenario

Let’s say we have a microservice called OrderService that needs to call another service — PaymentService — through an HTTP API.
We want to make sure our OrderService:

  • Retries if the call fails (Retry Pattern)

  • Stops repeated failing calls (Circuit Breaker Pattern)

  • Times out long requests (Timeout Pattern)

  • Returns fallback data if all else fails (Fallback Pattern)


๐Ÿงฐ Step 1: Install Required Package

Run this command in your OrderService project:

dotnet add package Polly dotnet add package Microsoft.Extensions.Http.Polly

⚙️ Step 2: Configure Resilience Policies in Program.cs

using Polly; using Polly.Extensions.Http; var builder = WebApplication.CreateBuilder(args); // Define resilience policies var retryPolicy = HttpPolicyExtensions .HandleTransientHttpError() .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))); // exponential backoff var circuitBreakerPolicy = HttpPolicyExtensions .HandleTransientHttpError() .CircuitBreakerAsync(5, TimeSpan.FromSeconds(30)); // break after 5 failures var timeoutPolicy = Policy.TimeoutAsync<HttpResponseMessage>(3); // 3-second timeout // Add HttpClient with resilience policies builder.Services.AddHttpClient("PaymentServiceClient", client => { client.BaseAddress = new Uri("https://payments.example.com/api/"); }) .AddPolicyHandler(retryPolicy) .AddPolicyHandler(circuitBreakerPolicy) .AddPolicyHandler(timeoutPolicy); builder.Services.AddControllers(); var app = builder.Build(); app.MapControllers(); app.Run();

๐Ÿ’ก Step 3: Use HttpClient in Controller

using Microsoft.AspNetCore.Mvc; [ApiController] [Route("api/[controller]")] public class OrderController : ControllerBase { private readonly HttpClient _httpClient; public OrderController(IHttpClientFactory httpClientFactory) { _httpClient = httpClientFactory.CreateClient("PaymentServiceClient"); } [HttpPost("create")] public async Task<IActionResult> CreateOrder([FromBody] object order) { try { var response = await _httpClient.PostAsJsonAsync("process", order); if (response.IsSuccessStatusCode) return Ok("Order placed successfully!"); return StatusCode((int)response.StatusCode, "Payment service failed."); } catch (BrokenCircuitException) { // Circuit breaker is open, fallback response return StatusCode(503, "Payment service temporarily unavailable. Try again later."); } catch (Exception ex) { // Fallback or logging return StatusCode(500, $"Unexpected error: {ex.Message}"); } } }

๐Ÿ” Step 4: Add Health Check for Kubernetes or Azure

Add in Program.cs:

builder.Services.AddHealthChecks(); app.MapHealthChecks("/health");

✅ This allows Kubernetes or Azure App Service to detect and restart unhealthy instances automatically.


๐Ÿ“Š Step 5: Add Observability (Optional)

Integrate Application Insights, Serilog, or ELK Stack to monitor:

  • Retry attempts

  • Circuit breaker states

  • Timeout events

This helps detect performance or availability issues early.


๐Ÿง  Output Behavior Summary

Failure TypePattern TriggeredSystem Reaction
Temporary network errorRetryAutomatically retries
Persistent downstream failureCircuit BreakerBlocks further calls temporarily
Long responseTimeoutCancels request after 3 seconds
Service completely downFallbackReturns cached/default message
Pod unhealthyHealth CheckAuto restarted by Kubernetes

๐Ÿš€ Result

With these configurations:

  • Your microservices become self-healing.

  • You prevent cascading failures.

  • The system delivers consistent performance and high availability.

Pro Tip: Combine Polly with Serilog for logging and OpenTelemetry for tracing to create a fully observable resilient microservice system.

Don't Copy

Protected by Copyscape Online Plagiarism Checker

Pages