<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[NullByte Tech Journals]]></title><description><![CDATA[NullByte Tech Journals]]></description><link>https://nullbyte.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Wed, 11 Nov 2026 05:49:39 GMT</lastBuildDate><atom:link href="https://nullbyte.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Azure App Services and Serverless Computing]]></title><description><![CDATA[Explore Azure App Services and Functions for scalable web, serverless apps. Learn about auto-scaling, cost optimization, and best practices]]></description><link>https://nullbyte.hashnode.dev/azure-app-services-and-serverless-computing</link><guid isPermaLink="true">https://nullbyte.hashnode.dev/azure-app-services-and-serverless-computing</guid><category><![CDATA[Azure]]></category><category><![CDATA[functions]]></category><category><![CDATA[Microsoft]]></category><category><![CDATA[Cloud]]></category><dc:creator><![CDATA[Nilay Barot]]></dc:creator><pubDate>Thu, 14 Aug 2025 15:53:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1755186708974/c165373b-b7f6-4abb-916f-90172d2181b4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome back to our Azure Compute series! After exploring Virtual Machines and Scale Sets, let's dive into Azure's Platform-as-a-Service (PaaS) offerings: <strong>Azure App Services</strong> and <strong>Azure Functions</strong>. These services enable you to build and deploy applications without managing the underlying infrastructure.</p>
<h2 id="heading-azure-app-services-web-apps-made-simple">Azure App Services: Web Apps Made Simple</h2>
<h3 id="heading-what-is-azure-app-service">What is Azure App Service?</h3>
<p>Azure App Service is a fully managed platform for building, deploying, and scaling web apps. It supports multiple programming languages and frameworks, allowing developers to focus on writing code rather than managing servers.</p>
<h3 id="heading-key-features">Key Features</h3>
<ul>
<li><strong>Multiple Language Support</strong>: ASP.NET, .NET Core, Java, Ruby, Node.js, PHP, Python</li>
<li><strong>Built-in DevOps</strong>: Continuous integration and deployment from GitHub, Azure DevOps, and more</li>
<li><strong>Auto-scaling</strong>: Automatically scale based on demand</li>
<li><strong>Global Scale</strong>: Deploy to multiple regions worldwide</li>
<li><strong>Security and Compliance</strong>: Built-in authentication, SSL certificates, and compliance certifications</li>
</ul>
<h3 id="heading-types-of-app-services">Types of App Services</h3>
<h4 id="heading-1-web-apps">1. Web Apps</h4>
<p>Host web applications and REST APIs:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Create a web app</span>
az webapp create \
  --resource-group myResourceGroup \
  --plan myAppServicePlan \
  --name myUniqueWebApp \
  --runtime <span class="hljs-string">"DOTNET|8.0"</span>
</code></pre>
<h4 id="heading-2-api-apps">2. API Apps</h4>
<p>Build and host RESTful APIs:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Deploy API app with continuous deployment</span>
az webapp deployment <span class="hljs-built_in">source</span> config \
  --name myApiApp \
  --resource-group myResourceGroup \
  --repo-url https://github.com/username/api-repo \
  --branch main \
  --manual-integration
</code></pre>
<h4 id="heading-3-mobile-apps">3. Mobile Apps</h4>
<p>Backend services for mobile applications:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Create mobile app backend</span>
az webapp create \
  --resource-group myResourceGroup \
  --plan myAppServicePlan \
  --name myMobileBackend \
  --runtime <span class="hljs-string">"DOTNETCORE|6.0"</span>
</code></pre>
<h3 id="heading-app-service-plans">App Service Plans</h3>
<p>App Service Plans define the compute resources for your apps:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Tier</td><td>Best For</td><td>Features</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Free/Shared</strong></td><td>Development, testing</td><td>Limited resources, no custom domains</td></tr>
<tr>
<td><strong>Basic</strong></td><td>Small production apps</td><td>Custom domains, SSL, manual scale</td></tr>
<tr>
<td><strong>Standard</strong></td><td>Production workloads</td><td>Auto-scale, staging slots, daily backups</td></tr>
<tr>
<td><strong>Premium</strong></td><td>High-performance apps</td><td>Advanced auto-scale, VNet integration</td></tr>
<tr>
<td><strong>Isolated</strong></td><td>Enterprise apps</td><td>Dedicated environment, advanced security</td></tr>
</tbody>
</table>
</div><h3 id="heading-deployment-slots">Deployment Slots</h3>
<p>Deployment slots enable zero-downtime deployments:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Create a staging slot</span>
az webapp deployment slot create \
  --name myWebApp \
  --resource-group myResourceGroup \
  --slot staging

<span class="hljs-comment"># Deploy to staging</span>
az webapp deployment <span class="hljs-built_in">source</span> config \
  --name myWebApp \
  --resource-group myResourceGroup \
  --slot staging \
  --repo-url https://github.com/username/app-repo

<span class="hljs-comment"># Swap staging to production</span>
az webapp deployment slot swap \
  --name myWebApp \
  --resource-group myResourceGroup \
  --slot staging \
  --target-slot production
</code></pre>
<h2 id="heading-azure-functions-serverless-computing">Azure Functions: Serverless Computing</h2>
<h3 id="heading-what-are-azure-functions">What are Azure Functions?</h3>
<p>Azure Functions is a serverless compute service that lets you run event-driven code without managing infrastructure. You pay only for the time your code runs, making it cost-effective for sporadic workloads.</p>
<h3 id="heading-key-benefits">Key Benefits</h3>
<ul>
<li><strong>Event-Driven</strong>: Triggered by various events (HTTP requests, timers, storage changes)</li>
<li><strong>Pay-per-Execution</strong>: Only pay when your function runs</li>
<li><strong>Auto-Scaling</strong>: Automatically scales from zero to thousands of instances</li>
<li><strong>Multiple Languages</strong>: C#, JavaScript, Python, Java, PowerShell, and more</li>
</ul>
<h3 id="heading-function-triggers">Function Triggers</h3>
<h4 id="heading-http-trigger">HTTP Trigger</h4>
<pre><code class="lang-csharp">[<span class="hljs-meta">FunctionName(<span class="hljs-meta-string">"HttpTriggerCSharp"</span>)</span>]
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">async</span> Task&lt;IActionResult&gt; <span class="hljs-title">Run</span>(<span class="hljs-params">
    [HttpTrigger(AuthorizationLevel.Function, <span class="hljs-string">"get"</span>, <span class="hljs-string">"post"</span>, Route = <span class="hljs-literal">null</span></span>)] HttpRequest req,
    ILogger log)</span>
{
    log.LogInformation(<span class="hljs-string">"C# HTTP trigger function processed a request."</span>);

    <span class="hljs-keyword">string</span> name = req.Query[<span class="hljs-string">"name"</span>];

    <span class="hljs-keyword">string</span> requestBody = <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> StreamReader(req.Body).ReadToEndAsync();
    <span class="hljs-keyword">dynamic</span> data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

    <span class="hljs-keyword">string</span> responseMessage = <span class="hljs-keyword">string</span>.IsNullOrEmpty(name)
        ? <span class="hljs-string">"This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."</span>
        : <span class="hljs-string">$"Hello, <span class="hljs-subst">{name}</span>. This HTTP triggered function executed successfully."</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> OkObjectResult(responseMessage);
}
</code></pre>
<h4 id="heading-timer-trigger">Timer Trigger</h4>
<pre><code class="lang-csharp">[<span class="hljs-meta">FunctionName(<span class="hljs-meta-string">"TimerTriggerCSharp"</span>)</span>]
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Run</span>(<span class="hljs-params">[TimerTrigger(<span class="hljs-string">"0 */5 * * * *"</span></span>)]TimerInfo myTimer, ILogger log)</span>
{
    log.LogInformation(<span class="hljs-string">$"C# Timer trigger function executed at: <span class="hljs-subst">{DateTime.Now}</span>"</span>);
}
</code></pre>
<h4 id="heading-blob-storage-trigger">Blob Storage Trigger</h4>
<pre><code class="lang-csharp">[<span class="hljs-meta">FunctionName(<span class="hljs-meta-string">"BlobTriggerCSharp"</span>)</span>]
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Run</span>(<span class="hljs-params">
    [BlobTrigger(<span class="hljs-string">"samples-workitems/{name}"</span>, Connection = <span class="hljs-string">"AzureWebJobsStorage"</span></span>)] Stream myBlob,
    <span class="hljs-keyword">string</span> name,
    ILogger log)</span>
{
    log.LogInformation(<span class="hljs-string">$"C# Blob trigger function processed blob\n"</span>
                      <span class="hljs-string">$"Name: <span class="hljs-subst">{name}</span>\n"</span>
                      <span class="hljs-string">$"Blob Size: <span class="hljs-subst">{myBlob.Length}</span> bytes"</span>);

    <span class="hljs-comment">// Process the blob content</span>
    <span class="hljs-comment">// Example: Read blob content</span>
    <span class="hljs-keyword">using</span> (<span class="hljs-keyword">var</span> reader = <span class="hljs-keyword">new</span> StreamReader(myBlob))
    {
        <span class="hljs-keyword">string</span> content = reader.ReadToEnd();
        log.LogInformation(<span class="hljs-string">$"Blob content: <span class="hljs-subst">{content}</span>"</span>);
    }
}
</code></pre>
<h4 id="heading-service-bus-queue-trigger">Service Bus Queue Trigger</h4>
<pre><code class="lang-csharp">[<span class="hljs-meta">FunctionName(<span class="hljs-meta-string">"ServiceBusQueueTrigger"</span>)</span>]
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">Run</span>(<span class="hljs-params">
    [ServiceBusTrigger(<span class="hljs-string">"myqueue"</span>, Connection = <span class="hljs-string">"ServiceBusConnection"</span></span>)] <span class="hljs-keyword">string</span> myQueueItem,
    ILogger log)</span>
{
    log.LogInformation(<span class="hljs-string">$"C# ServiceBus queue trigger function processed message: <span class="hljs-subst">{myQueueItem}</span>"</span>);

    <span class="hljs-keyword">try</span>
    {
        <span class="hljs-comment">// Process the queue message</span>
        <span class="hljs-keyword">var</span> order = JsonConvert.DeserializeObject&lt;Order&gt;(myQueueItem);

        <span class="hljs-comment">// Business logic here</span>
        <span class="hljs-keyword">await</span> ProcessOrderAsync(order);

        log.LogInformation(<span class="hljs-string">$"Successfully processed order <span class="hljs-subst">{order.Id}</span>"</span>);
    }
    <span class="hljs-keyword">catch</span> (Exception ex)
    {
        log.LogError(ex, <span class="hljs-string">"Error processing queue message"</span>);
        <span class="hljs-keyword">throw</span>; <span class="hljs-comment">// Re-throw to handle poison messages</span>
    }
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">ProcessOrderAsync</span>(<span class="hljs-params">Order order</span>)</span>
{
    <span class="hljs-comment">// Implementation here</span>
    <span class="hljs-keyword">await</span> Task.CompletedTask;
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Order</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> CustomerId { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> Amount { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}
</code></pre>
<h4 id="heading-dependency-injection-example">Dependency Injection Example</h4>
<pre><code class="lang-csharp"><span class="hljs-comment">// Startup.cs</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Startup</span> : <span class="hljs-title">FunctionsStartup</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Configure</span>(<span class="hljs-params">IFunctionsHostBuilder builder</span>)</span>
    {
        builder.Services.AddHttpClient();
        builder.Services.AddScoped&lt;IOrderService, OrderService&gt;();
        builder.Services.AddSingleton&lt;IConfiguration&gt;(provider =&gt;
        {
            <span class="hljs-keyword">var</span> config = <span class="hljs-keyword">new</span> ConfigurationBuilder()
                .AddEnvironmentVariables()
                .Build();
            <span class="hljs-keyword">return</span> config;
        });
    }
}

<span class="hljs-comment">// Function with Dependency Injection</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">OrderFunction</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IOrderService _orderService;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> ILogger&lt;OrderFunction&gt; _logger;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">OrderFunction</span>(<span class="hljs-params">IOrderService orderService, ILogger&lt;OrderFunction&gt; logger</span>)</span>
    {
        _orderService = orderService;
        _logger = logger;
    }

    [<span class="hljs-meta">FunctionName(<span class="hljs-meta-string">"ProcessOrder"</span>)</span>]
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IActionResult&gt; <span class="hljs-title">Run</span>(<span class="hljs-params">
        [HttpTrigger(AuthorizationLevel.Function, <span class="hljs-string">"post"</span>, Route = <span class="hljs-string">"orders"</span></span>)] HttpRequest req)</span>
    {
        <span class="hljs-keyword">try</span>
        {
            <span class="hljs-keyword">string</span> requestBody = <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> StreamReader(req.Body).ReadToEndAsync();
            <span class="hljs-keyword">var</span> order = JsonConvert.DeserializeObject&lt;Order&gt;(requestBody);

            <span class="hljs-keyword">var</span> result = <span class="hljs-keyword">await</span> _orderService.ProcessOrderAsync(order);

            <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> OkObjectResult(result);
        }
        <span class="hljs-keyword">catch</span> (Exception ex)
        {
            _logger.LogError(ex, <span class="hljs-string">"Error processing order"</span>);
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> BadRequestObjectResult(<span class="hljs-string">"Failed to process order"</span>);
        }
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IOrderService</span>
{
    <span class="hljs-function">Task&lt;<span class="hljs-keyword">string</span>&gt; <span class="hljs-title">ProcessOrderAsync</span>(<span class="hljs-params">Order order</span>)</span>;
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">OrderService</span> : <span class="hljs-title">IOrderService</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;<span class="hljs-keyword">string</span>&gt; <span class="hljs-title">ProcessOrderAsync</span>(<span class="hljs-params">Order order</span>)</span>
    {
        <span class="hljs-comment">// Business logic implementation</span>
        <span class="hljs-keyword">await</span> Task.Delay(<span class="hljs-number">100</span>); <span class="hljs-comment">// Simulate processing</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">$"Order <span class="hljs-subst">{order.Id}</span> processed successfully"</span>;
    }
}
</code></pre>
<h3 id="heading-creating-azure-functions">Creating Azure Functions</h3>
<pre><code class="lang-bash"><span class="hljs-comment"># Create a function app</span>
az functionapp create \
  --resource-group myResourceGroup \
  --consumption-plan-location eastus \
  --runtime dotnet \
  --runtime-version 8 \
  --functions-version 4 \
  --name myFunctionApp \
  --storage-account mystorageaccount
</code></pre>
<h3 id="heading-hosting-plans">Hosting Plans</h3>
<h4 id="heading-1-consumption-plan">1. Consumption Plan</h4>
<ul>
<li>Pay-per-execution</li>
<li>Automatic scaling</li>
<li>5-minute execution timeout (default)</li>
</ul>
<h4 id="heading-2-premium-plan">2. Premium Plan</h4>
<ul>
<li>Pre-warmed instances</li>
<li>Unlimited execution duration</li>
<li>VNet connectivity</li>
</ul>
<h4 id="heading-3-dedicated-plan">3. Dedicated Plan</h4>
<ul>
<li>Run on App Service Plan</li>
<li>Predictable pricing</li>
<li>Full control over scaling</li>
</ul>
<h2 id="heading-durable-functions">Durable Functions</h2>
<p>For complex, stateful functions in serverless environments:</p>
<pre><code class="lang-csharp">[<span class="hljs-meta">FunctionName(<span class="hljs-meta-string">"OrderProcessing"</span>)</span>]
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">async</span> Task&lt;<span class="hljs-keyword">string</span>&gt; <span class="hljs-title">RunOrchestrator</span>(<span class="hljs-params">
    [OrchestrationTrigger] IDurableOrchestrationContext context</span>)</span>
{
    <span class="hljs-keyword">var</span> orderId = context.GetInput&lt;<span class="hljs-keyword">string</span>&gt;();

    <span class="hljs-comment">// Step 1: Validate order</span>
    <span class="hljs-keyword">await</span> context.CallActivityAsync(<span class="hljs-string">"ValidateOrder"</span>, orderId);

    <span class="hljs-comment">// Step 2: Process payment</span>
    <span class="hljs-keyword">await</span> context.CallActivityAsync(<span class="hljs-string">"ProcessPayment"</span>, orderId);

    <span class="hljs-comment">// Step 3: Ship order</span>
    <span class="hljs-keyword">await</span> context.CallActivityAsync(<span class="hljs-string">"ShipOrder"</span>, orderId);

    <span class="hljs-keyword">return</span> <span class="hljs-string">"Order processed successfully"</span>;
}
</code></pre>
<h2 id="heading-best-practices">Best Practices</h2>
<h3 id="heading-app-services">App Services</h3>
<ol>
<li><strong>Use Deployment Slots</strong>: Implement blue-green deployments</li>
<li><strong>Enable Application Insights</strong>: Monitor performance and errors</li>
<li><strong>Configure Auto-Scale</strong>: Handle traffic variations automatically</li>
<li><strong>Secure Your Apps</strong>: Use authentication providers and SSL certificates</li>
<li><strong>Optimize Performance</strong>: Use CDN for static content</li>
</ol>
<h3 id="heading-azure-functions-net-specific">Azure Functions (.NET Specific)</h3>
<ol>
<li><strong>Keep Functions Small</strong>: Single responsibility principle</li>
<li><strong>Handle Cold Starts</strong>: Use Premium plans for consistent performance</li>
<li><strong>Use Dependency Injection</strong>: Register services in <code>Startup.cs</code> for better testability</li>
<li><strong>Implement Proper Error Handling</strong>: Use try-catch and structured logging</li>
<li><strong>Async/Await Best Practices</strong>: Use <code>ConfigureAwait(false)</code> for better performance</li>
<li><strong>Secure Function Keys</strong>: Rotate keys regularly and use Azure Key Vault</li>
<li><strong>NuGet Package Management</strong>: Keep packages updated and minimize dependencies</li>
<li><strong>Monitor Costs</strong>: Watch execution counts and duration</li>
</ol>
<h2 id="heading-real-world-architecture-example">Real-World Architecture Example</h2>
<h3 id="heading-e-commerce-platform">E-commerce Platform</h3>
<pre><code>Frontend (React) → App Service
     ↓
API Gateway → Azure Functions
     ↓
┌─────────────────────────┐
│ • User Authentication  │
│ • Order Processing     │
│ • Inventory Updates    │
│ • Email Notifications  │
└─────────────────────────┘
     ↓
Azure Storage + Cosmos DB
</code></pre><h3 id="heading-implementation-steps">Implementation Steps</h3>
<ol>
<li><strong>Frontend</strong>: Deploy React app to App Service</li>
<li><strong>API Functions</strong>: Create HTTP-triggered functions for each API endpoint</li>
<li><strong>Background Processing</strong>: Use queue-triggered functions for async tasks</li>
<li><strong>Monitoring</strong>: Implement Application Insights across all services</li>
</ol>
<h2 id="heading-cost-optimization">Cost Optimization</h2>
<h3 id="heading-app-services-1">App Services</h3>
<ul>
<li><strong>Right-size your plan</strong>: Start small and scale up as needed</li>
<li><strong>Use shared plans</strong>: For development and testing</li>
<li><strong>Implement auto-shutdown</strong>: For non-production environments</li>
</ul>
<h3 id="heading-azure-functions">Azure Functions</h3>
<ul>
<li><strong>Optimize execution time</strong>: Reduce function duration</li>
<li><strong>Use appropriate hosting plans</strong>: Consumption for sporadic loads</li>
<li><strong>Implement efficient triggers</strong>: Avoid unnecessary executions</li>
</ul>
<h2 id="heading-monitoring-and-debugging">Monitoring and Debugging</h2>
<h3 id="heading-application-insights-integration">Application Insights Integration</h3>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Function1</span>
{
    [<span class="hljs-meta">FunctionName(<span class="hljs-meta-string">"Function1"</span>)</span>]
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">async</span> Task&lt;IActionResult&gt; <span class="hljs-title">Run</span>(<span class="hljs-params">
        [HttpTrigger(AuthorizationLevel.Function, <span class="hljs-string">"get"</span>, <span class="hljs-string">"post"</span>, Route = <span class="hljs-literal">null</span></span>)] HttpRequest req,
        ILogger log)</span>
    {
        log.LogInformation(<span class="hljs-string">"C# HTTP trigger function processed a request."</span>);

        <span class="hljs-comment">// Your function logic here</span>

        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> OkObjectResult(<span class="hljs-string">"Function executed successfully"</span>);
    }
}
</code></pre>
<h3 id="heading-log-analytics-queries">Log Analytics Queries</h3>
<pre><code class="lang-kusto">// Function execution times
requests
| where cloud_RoleName == "myFunctionApp"
| summarize avg(duration), count() by name
| order by avg_duration desc
</code></pre>
<h2 id="heading-common-pitfalls-to-avoid">Common Pitfalls to Avoid</h2>
<ol>
<li><strong>Over-provisioning App Service Plans</strong>: Choose the right tier for your needs</li>
<li><strong>Ignoring Cold Starts</strong>: Consider Premium functions for consistent performance</li>
<li><strong>Not implementing proper monitoring</strong>: Set up alerts and dashboards</li>
<li><strong>Security oversights</strong>: Always use HTTPS and implement authentication</li>
<li><strong>Lack of error handling</strong>: Implement comprehensive error handling and logging</li>
</ol>
<h2 id="heading-whats-next">What's Next?</h2>
<p>In our next post, we'll explore <strong>Container Services in Azure</strong>, covering:</p>
<ul>
<li>Azure Container Instances (ACI)</li>
<li>Azure Kubernetes Service (AKS)</li>
<li>Azure Container Registry</li>
<li>Container deployment strategies</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Azure App Services and Functions provide powerful platforms for building modern, scalable applications. App Services offer a managed environment for web applications, while Functions enable serverless architectures that can significantly reduce costs and complexity.</p>
<p>By combining these services, you can build robust, scalable applications that automatically adapt to demand while minimizing operational overhead.</p>
<p><strong>Key Takeaways:</strong></p>
<ul>
<li>App Services provide managed hosting for web applications and APIs</li>
<li>Azure Functions enable event-driven, serverless computing</li>
<li>Both services integrate seamlessly with other Azure services</li>
<li>Choose the right hosting plan based on your performance and cost requirements</li>
<li>Implement proper monitoring and security from the start</li>
</ul>
<hr />
<p><strong>Tags:</strong> Azure, App Services, Azure Functions, Serverless, PaaS, Web Applications</p>
<p><strong>Category:</strong> Azure Compute Series</p>
<p><strong>Estimated Reading Time:</strong> 12 minutes</p>
]]></content:encoded></item><item><title><![CDATA[Virtual Machines and Scale Sets]]></title><description><![CDATA[Explore Azure VMs and Scale Sets for flexible cloud solutions. Learn benefits, use cases, and optimization best practices]]></description><link>https://nullbyte.hashnode.dev/virtual-machines-and-scale-sets</link><guid isPermaLink="true">https://nullbyte.hashnode.dev/virtual-machines-and-scale-sets</guid><category><![CDATA[Azure]]></category><category><![CDATA[virtual machine]]></category><category><![CDATA[#virtual machine scale set]]></category><category><![CDATA[Microsoft]]></category><dc:creator><![CDATA[Nilay Barot]]></dc:creator><pubDate>Tue, 05 Aug 2025 16:27:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1754411693289/a9208051-a724-486a-918b-24cc9643f4ed.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome back to our Azure series! In the previous post, we introduced Azure Compute Services. Today, we'll explore two critical components of Azure Compute: <strong>Virtual Machines (VMs)</strong> and <strong>Virtual Machine Scale Sets</strong>.</p>
<h2 id="heading-understanding-virtual-machines">Understanding Virtual Machines</h2>
<h3 id="heading-what-are-virtual-machines">What are Virtual Machines?</h3>
<p>Virtual Machines (VMs) are virtualized computing environments that run on Microsoft's Azure cloud infrastructure. They allow you to run applications as if they were on a physical computer, with complete control over the operating system and hardware configurations.</p>
<h3 id="heading-why-use-vms">Why Use VMs?</h3>
<ul>
<li><strong>Customizability</strong>: Choose any OS and configure your VM according to your needs</li>
<li><strong>Flexibility</strong>: Scale resources like CPU, memory, and storage</li>
<li><strong>Compatibility</strong>: Support for a wide range of applications and frameworks</li>
</ul>
<h3 id="heading-common-use-cases">Common Use Cases</h3>
<ul>
<li><strong>Development and Testing</strong>: Spin up isolated environments quickly</li>
<li><strong>Legacy Application Migration</strong>: Move existing apps to the cloud without code changes</li>
<li><strong>Specialized Workloads</strong>: Run applications requiring specific OS setups</li>
</ul>
<h2 id="heading-introduction-to-virtual-machine-scale-sets">Introduction to Virtual Machine Scale Sets</h2>
<h3 id="heading-what-are-vm-scale-sets">What are VM Scale Sets?</h3>
<p>Virtual Machine Scale Sets let you deploy and manage a set of identical, auto-scaling VMs. They ensure your applications are highly available and capable of handling traffic spikes effectively.</p>
<h3 id="heading-key-benefits">Key Benefits</h3>
<ul>
<li><strong>Auto-Scaling</strong>: Automatically increase or decrease the number of VMs as demand changes</li>
<li><strong>Load Balancing</strong>: Evenly distribute incoming traffic across instances</li>
<li><strong>Cost Efficiency</strong>: Pay for only the compute instances you use</li>
</ul>
<h3 id="heading-common-use-cases-1">Common Use Cases</h3>
<ul>
<li><strong>Web Hosting</strong>: Handle varying traffic loads efficiently</li>
<li><strong>Batch Processing</strong>: Scale compute resources to process data faster</li>
<li><strong>Microservices Architectures</strong>: Continually adjust capacity based on workload</li>
</ul>
<h2 id="heading-getting-started-with-virtual-machines">Getting Started with Virtual Machines</h2>
<h3 id="heading-creating-a-virtual-machine">Creating a Virtual Machine</h3>
<p>Let's go through the steps to create a Linux VM using Azure CLI:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Login to Azure</span>
az login

<span class="hljs-comment"># Create a resource group</span>
az group create --name myResourceGroup --location eastus

<span class="hljs-comment"># Create a virtual machine</span>
az vm create \
  --resource-group myResourceGroup \
  --name myVM \
  --image UbuntuLTS \
  --admin-username azureuser \
  --generate-ssh-keys
</code></pre>
<h3 id="heading-key-considerations">Key Considerations</h3>
<ul>
<li><strong>Choose the right size</strong>: Balance performance and cost</li>
<li><strong>Network Configuration</strong>: Ensure appropriate security groups and firewall rules</li>
<li><strong>Backup and Recovery</strong>: Implement a backup strategy using Azure Backup</li>
</ul>
<h2 id="heading-setting-up-virtual-machine-scale-sets">Setting Up Virtual Machine Scale Sets</h2>
<h3 id="heading-creating-a-vm-scale-set">Creating a VM Scale Set</h3>
<p>Easily create a scale set to manage multiple instances:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Create a scale set</span>
az vmss create \
  --resource-group myResourceGroup \
  --name myScaleSet \
  --image UbuntuLTS \
  --upgrade-policy-mode automatic \
  --admin-username azureuser \
  --generate-ssh-keys
</code></pre>
<h3 id="heading-key-capabilities">Key Capabilities</h3>
<ul>
<li><strong>Custom Autoscale Rules</strong>: Define how and when to scale based on metrics</li>
<li><strong>Integration with Load Balancer</strong>: Distribute traffic seamlessly</li>
<li><strong>Rolling Upgrades</strong>: Update VMs without downtime</li>
</ul>
<h2 id="heading-best-practices-for-vms-and-scale-sets">Best Practices for VMs and Scale Sets</h2>
<h3 id="heading-security">Security</h3>
<ul>
<li><strong>Use Network Security Groups</strong>: Control inbound and outbound traffic</li>
<li><strong>Regular Patching</strong>: Schedule updates for software and system</li>
<li><strong>Enable Disk Encryption</strong>: Protect sensitive data</li>
</ul>
<h3 id="heading-monitoring-and-maintenance">Monitoring and Maintenance</h3>
<ul>
<li><strong>Implement Azure Monitor</strong>: Gain insights into VM performance</li>
<li><strong>Use Log Analytics</strong>: Centralize logging and alerts</li>
<li><strong>Automate Management</strong>: Utilize scripts for common tasks</li>
</ul>
<h2 id="heading-cost-management">Cost Management</h2>
<ul>
<li><strong>Spot VMs</strong>: Use preemptible instances to save costs</li>
<li><strong>Optimize VM Sizes</strong>: Right-size VMs based on performance needs</li>
<li><strong>Reserved Instances</strong>: Commit to Azure for 1 or 3 years to reduce costs</li>
</ul>
<h2 id="heading-real-world-example-online-retail-platform">Real-World Example: Online Retail Platform</h2>
<p>Here's how a retail company can leverage VMs and Scale Sets:</p>
<ol>
<li><strong>Frontend Applications</strong>: Hosted on VMs for complete control</li>
<li><strong>Backend Processing</strong>: Use Scale Sets for managing order processing</li>
<li><strong>Seasonal Traffic Spikes</strong>: Scale easily during sales events with auto-scaling</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Whether you're running simple applications or complex architectures, Azure Virtual Machines and Scale Sets provide the flexibility and scalability needed to support your business needs. By selecting the appropriate configurations and implementing best practices, you can maximize performance while optimizing costs.</p>
<p>Stay tuned for our next post in the Azure series, where we'll explore Azure Networking capabilities, including Virtual Networks, Load Balancers, and more.</p>
<p><strong>Tags:</strong> Azure, Virtual Machines, Scale Sets, Cloud Computing, Microsoft</p>
<p><strong>Category:</strong> Azure Compute Series</p>
<p><strong>Estimated Reading Time:</strong> 10 minutes</p>
]]></content:encoded></item><item><title><![CDATA[Introduction to Azure Compute Services: The Foundation of Cloud Computing]]></title><description><![CDATA[Azure Compute Services offer scalable, reliable cloud options for modern applications, providing flexible, cost-effective infrastructure solutions]]></description><link>https://nullbyte.hashnode.dev/introduction-to-azure-compute-services-the-foundation-of-cloud-computing</link><guid isPermaLink="true">https://nullbyte.hashnode.dev/introduction-to-azure-compute-services-the-foundation-of-cloud-computing</guid><category><![CDATA[Azure]]></category><category><![CDATA[Cloud]]></category><category><![CDATA[Microsoft]]></category><category><![CDATA[Azure Functions]]></category><category><![CDATA[virtual machine]]></category><category><![CDATA[azure-compute]]></category><dc:creator><![CDATA[Nilay Barot]]></dc:creator><pubDate>Mon, 28 Jul 2025 18:09:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1753726062944/ecb8ebc4-3416-44c1-82ec-aae096c9e47e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to the first post in our comprehensive Azure series! Today, we'll dive deep into Azure Compute Services, the backbone of Microsoft's cloud platform that powers millions of applications worldwide.</p>
<h2 id="heading-what-is-azure-compute">What is Azure Compute?</h2>
<p>Azure Compute is a comprehensive suite of cloud computing services that provides on-demand access to computing resources. Think of it as your virtual data center in the cloud, where you can run applications, process data, and host services without the need to maintain physical hardware.</p>
<h3 id="heading-why-azure-compute-matters">Why Azure Compute Matters</h3>
<p>In today's digital landscape, businesses need:</p>
<ul>
<li><strong>Scale on demand</strong>: Handle traffic spikes without over-provisioning</li>
<li><strong>Cost efficiency</strong>: Pay only for what you use</li>
<li><strong>Global reach</strong>: Deploy applications close to your users</li>
<li><strong>Reliability</strong>: Built-in redundancy and disaster recovery</li>
</ul>
<h2 id="heading-core-azure-compute-services">Core Azure Compute Services</h2>
<h3 id="heading-1-virtual-machines-vms">1. Virtual Machines (VMs)</h3>
<p>Azure VMs are the most fundamental compute service, offering:</p>
<ul>
<li><strong>Full control</strong> over the operating system</li>
<li><strong>Wide OS support</strong> (Windows, Linux distributions)</li>
<li><strong>Flexible sizing</strong> from small development environments to high-performance computing</li>
</ul>
<p><strong>Use Cases:</strong></p>
<ul>
<li>Legacy application migration</li>
<li>Development and testing environments</li>
<li>Specialized workloads requiring specific OS configurations</li>
</ul>
<h3 id="heading-2-app-services">2. App Services</h3>
<p>Platform-as-a-Service (PaaS) offering for web applications:</p>
<ul>
<li><strong>Multiple frameworks</strong> (ASP.NET, Node.js, Python, PHP, Java)</li>
<li><strong>Built-in DevOps</strong> with continuous deployment</li>
<li><strong>Auto-scaling</strong> based on demand</li>
<li><strong>Integrated monitoring</strong> and diagnostics</li>
</ul>
<p><strong>Use Cases:</strong></p>
<ul>
<li>Web applications and APIs</li>
<li>Mobile app backends</li>
<li>Microservices architectures</li>
</ul>
<h3 id="heading-3-azure-functions">3. Azure Functions</h3>
<p>Serverless computing platform for event-driven applications:</p>
<ul>
<li><strong>Pay-per-execution</strong> pricing model</li>
<li><strong>Auto-scaling</strong> to zero when not in use</li>
<li><strong>Event triggers</strong> (HTTP, timers, storage events)</li>
<li><strong>Multiple language support</strong></li>
</ul>
<p><strong>Use Cases:</strong></p>
<ul>
<li>API backends</li>
<li>Data processing pipelines</li>
<li>IoT data handling</li>
<li>Scheduled tasks</li>
</ul>
<h3 id="heading-4-container-services">4. Container Services</h3>
<p>Modern application deployment with containers:</p>
<ul>
<li><strong>Azure Container Instances (ACI)</strong>: Simple container hosting</li>
<li><strong>Azure Kubernetes Service (AKS)</strong>: Managed Kubernetes orchestration</li>
<li><strong>Azure Container Apps</strong>: Serverless container platform</li>
</ul>
<p><strong>Use Cases:</strong></p>
<ul>
<li>Microservices applications</li>
<li>CI/CD pipelines</li>
<li>Batch processing jobs</li>
</ul>
<h3 id="heading-5-virtual-machine-scale-sets">5. Virtual Machine Scale Sets</h3>
<p>Automated scaling for VM-based applications:</p>
<ul>
<li><strong>Auto-scaling</strong> based on metrics</li>
<li><strong>Load balancing</strong> across instances</li>
<li><strong>Rolling updates</strong> for zero-downtime deployments</li>
</ul>
<p><strong>Use Cases:</strong></p>
<ul>
<li>High-traffic web applications</li>
<li>Batch processing workloads</li>
<li>Multi-tier applications</li>
</ul>
<h2 id="heading-choosing-the-right-compute-service">Choosing the Right Compute Service</h2>
<h3 id="heading-decision-framework">Decision Framework</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Service Type</td><td>Best For</td><td>Management Level</td><td>Scaling</td></tr>
</thead>
<tbody>
<tr>
<td>Virtual Machines</td><td>Full control, legacy apps</td><td>High</td><td>Manual/Scale Sets</td></tr>
<tr>
<td>App Services</td><td>Web apps, APIs</td><td>Low</td><td>Automatic</td></tr>
<tr>
<td>Azure Functions</td><td>Event-driven, serverless</td><td>Minimal</td><td>Automatic</td></tr>
<tr>
<td>Containers</td><td>Modern apps, microservices</td><td>Medium</td><td>Automatic</td></tr>
</tbody>
</table>
</div><h3 id="heading-cost-considerations">Cost Considerations</h3>
<ol>
<li><strong>Virtual Machines</strong>: Pay for allocated resources, even when idle</li>
<li><strong>App Services</strong>: Pay for the App Service Plan, regardless of usage</li>
<li><strong>Azure Functions</strong>: Pay per execution and resource consumption</li>
<li><strong>Containers</strong>: Pay for running container time</li>
</ol>
<h2 id="heading-getting-started-your-first-azure-compute-resource">Getting Started: Your First Azure Compute Resource</h2>
<h3 id="heading-prerequisites">Prerequisites</h3>
<ul>
<li>Azure subscription (free tier available)</li>
<li>Basic understanding of cloud concepts</li>
<li>Azure CLI or Azure Portal access</li>
</ul>
<h3 id="heading-quick-start-creating-a-virtual-machine">Quick Start: Creating a Virtual Machine</h3>
<pre><code class="lang-bash"><span class="hljs-comment"># Login to Azure CLI</span>
az login

<span class="hljs-comment"># Create a resource group</span>
az group create --name myResourceGroup --location eastus

<span class="hljs-comment"># Create a virtual machine</span>
az vm create \
  --resource-group myResourceGroup \
  --name myVM \
  --image Ubuntu2204 \
  --admin-username azureuser \
  --generate-ssh-keys
</code></pre>
<h2 id="heading-best-practices-for-azure-compute">Best Practices for Azure Compute</h2>
<h3 id="heading-1-resource-management">1. Resource Management</h3>
<ul>
<li><strong>Use Resource Groups</strong> to organize related resources</li>
<li><strong>Apply tags</strong> for cost tracking and management</li>
<li><strong>Implement naming conventions</strong> for consistency</li>
</ul>
<h3 id="heading-2-security">2. Security</h3>
<ul>
<li><strong>Enable Azure Security Center</strong> for threat protection</li>
<li><strong>Use Azure Key Vault</strong> for secrets management</li>
<li><strong>Implement network security groups</strong> for traffic control</li>
</ul>
<h3 id="heading-3-cost-optimization">3. Cost Optimization</h3>
<ul>
<li><strong>Right-size resources</strong> based on actual usage</li>
<li><strong>Use reserved instances</strong> for predictable workloads</li>
<li><strong>Implement auto-shutdown</strong> for development environments</li>
<li><strong>Monitor with Azure Cost Management</strong></li>
</ul>
<h3 id="heading-4-performance">4. Performance</h3>
<ul>
<li><strong>Choose appropriate regions</strong> for low latency</li>
<li><strong>Use SSD storage</strong> for better performance</li>
<li><strong>Implement caching strategies</strong> where applicable</li>
</ul>
<h2 id="heading-monitoring-and-management">Monitoring and Management</h2>
<h3 id="heading-azure-monitor">Azure Monitor</h3>
<ul>
<li><strong>Application Insights</strong> for application performance monitoring</li>
<li><strong>Log Analytics</strong> for centralized logging</li>
<li><strong>Metrics and alerts</strong> for proactive monitoring</li>
</ul>
<h3 id="heading-azure-resource-manager-arm">Azure Resource Manager (ARM)</h3>
<ul>
<li><strong>Infrastructure as Code</strong> with ARM templates</li>
<li><strong>Consistent deployments</strong> across environments</li>
<li><strong>Version control</strong> for infrastructure changes</li>
</ul>
<h2 id="heading-real-world-example-e-commerce-platform">Real-World Example: E-commerce Platform</h2>
<p>Let's consider how different Azure Compute services work together:</p>
<ol>
<li><strong>Frontend</strong>: App Services hosting the web application</li>
<li><strong>API Layer</strong>: Azure Functions handling order processing</li>
<li><strong>Background Jobs</strong>: Virtual Machines running inventory updates</li>
<li><strong>Microservices</strong>: AKS managing containerized services</li>
<li><strong>Scaling</strong>: VM Scale Sets handling traffic spikes during sales</li>
</ol>
<h2 id="heading-common-pitfalls-to-avoid">Common Pitfalls to Avoid</h2>
<ol>
<li><strong>Over-provisioning</strong>: Don't allocate more resources than needed</li>
<li><strong>Ignoring regions</strong>: Choose regions close to your users</li>
<li><strong>Security oversights</strong>: Always follow security best practices</li>
<li><strong>Lack of monitoring</strong>: Implement comprehensive monitoring from the start</li>
<li><strong>No backup strategy</strong>: Plan for disaster recovery</li>
</ol>
<h2 id="heading-whats-next">What's Next?</h2>
<p>In our next post, we'll dive deep into <strong>Virtual Machines and Scale Sets</strong>, exploring:</p>
<ul>
<li>VM sizing and selection</li>
<li>Setting up scale sets for high availability</li>
<li>Advanced networking configurations</li>
<li>Performance optimization techniques</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Azure Compute Services provide the foundation for building scalable, reliable, and cost-effective cloud applications. By understanding the different service options and their use cases, you can make informed decisions about your cloud architecture.</p>
<p>Whether you're migrating existing applications or building new cloud-native solutions, Azure Compute offers the flexibility and power you need to succeed in the cloud.</p>
<p><strong>Key Takeaways:</strong></p>
<ul>
<li>Azure offers multiple compute options for different use cases</li>
<li>Choose services based on your control requirements and scaling needs</li>
<li>Implement best practices for security, cost optimization, and performance</li>
<li>Start with simple deployments and evolve your architecture over time</li>
</ul>
<hr />
<p><strong>Tags:</strong> Azure, Cloud Computing, Virtual Machines, App Services, Serverless, Containers</p>
<p><strong>Category:</strong> Azure Compute Series</p>
<p><strong>Estimated Reading Time:</strong> 8 minutes</p>
]]></content:encoded></item><item><title><![CDATA[Building an AI-Powered Translator Using Svelte, TypeScript, and GenAI: A Journey in Innovation]]></title><description><![CDATA[Create an AI-powered translator using Svelte and TypeScript, leveraging GenAI to eliminate third-party APIs and innovate web translation]]></description><link>https://nullbyte.hashnode.dev/building-an-ai-powered-translator-using-svelte-typescript-and-genai-a-journey-in-innovation</link><guid isPermaLink="true">https://nullbyte.hashnode.dev/building-an-ai-powered-translator-using-svelte-typescript-and-genai-a-journey-in-innovation</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[Svelte]]></category><category><![CDATA[Google]]></category><category><![CDATA[gemini]]></category><category><![CDATA[AI]]></category><category><![CDATA[genai]]></category><category><![CDATA[generative ai]]></category><category><![CDATA[Google Gemini AI]]></category><category><![CDATA[GPT 3]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[js]]></category><category><![CDATA[ts]]></category><dc:creator><![CDATA[Nilay Barot]]></dc:creator><pubDate>Sun, 10 Nov 2024 14:46:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1731249589767/2000ca74-903c-44d3-acf9-d326f65aebfe.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Recently, I had the opportunity to work on a project, <a target="_blank" href="https://ai-powered-translator.netlify.app/">you can check it</a> out that combined modern web technologies with the power of GenAI, resulting in a fully AI-powered translation application. This project was built using <strong>Svelte</strong> and <strong>TypeScript</strong>, and it leverages <strong>Gemini AI</strong> to handle translations — all without relying on any third-party APIs.</p>
<h3 id="heading-the-problem">The Problem</h3>
<p>Most translation apps depend heavily on third-party translation APIs, but what if we could bypass that entirely? Using <strong>GenAI prompting</strong>, I was able to retrieve all the supported languages in an array format. These languages were displayed in a dynamic <strong>combo box</strong> in the UI. The actual translation process also happened within GenAI itself, eliminating the need for any external API calls.</p>
<h3 id="heading-why-svelte-and-typescript">Why Svelte and TypeScript?</h3>
<p>Choosing <strong>Svelte</strong> for this project was an easy decision, and here’s why:</p>
<p>- <strong>Reactivity</strong>: Svelte's reactivity model makes state management seamless. This helped in dynamically updating language selections and translation results.</p>
<p>- <strong>Lightweight</strong>: Svelte compiles down to pure JavaScript at build time, resulting in faster load times and smaller bundle sizes.</p>
<p>- <strong>Type Safety</strong>: With <strong>TypeScript</strong>, I ensured that the app had robust type-checking, making development smoother and reducing the risk of runtime errors.</p>
<p>Here is the example, how to effectively use prompting and fetch the data as required:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> response = <span class="hljs-keyword">await</span> GetResponse(
          <span class="hljs-string">"Fetch me all the languages used for translation with comma separated. Just return me this information and nothing else"</span>
        );
</code></pre>
<p>Using this approach, I created a user-friendly interface that allowed for real-time translation while showing the remaining character count. The language list fetched using GenAI was displayed in a <strong>combo box</strong>, making the UI highly interactive.</p>
<hr />
<h3 id="heading-leveraging-genai-for-creative-applications">Leveraging GenAI for Creative Applications</h3>
<p>This project opened my eyes to the wide array of possibilities that <strong>GenAI</strong> offers beyond just translation. We can leverage it to build all sorts of useful tools. Here are a few ideas:</p>
<p>- <strong>JSON to Class Converters</strong>: Prompting GenAI to generate C#, Java, or other language classes based on a given JSON structure.</p>
<p>- <strong>CSS to SCSS/SASS Converters</strong>: Automatically convert vanilla CSS into SCSS, SASS, or even Tailwind utility classes, making the switch between styling frameworks more seamless.</p>
<p>- <strong>Tailwind to Bootstrap Converter</strong>: If you’ve ever wanted to switch between CSS frameworks, imagine converting Tailwind classes into Bootstrap classes using the power of AI.</p>
<p>These types of GenAI-powered tools are not just cool experiments but could significantly enhance productivity for developers working across different stacks and languages.</p>
<hr />
<p>This project really demonstrated how powerful and flexible <strong>Svelte</strong> and <strong>TypeScript</strong> are, and how <strong>GenAI</strong> can remove the need for external APIs. It also sparked new ideas for leveraging GenAI to create developer tools that save time and effort across various domains. There might be some issues while translating but this will depend on GenAI model used.</p>
<p>Feel free to check out the full source code for this AI-powered translator on my GitHub: <a target="_blank" href="https://github.com/nullbyte01/AI-Translator">Click here</a>.</p>
<hr />
<p>Let’s continue exploring how AI can drive innovation in web development!</p>
<p>If you’re building something cool with AI or web technologies, I’d love to hear about it!</p>
<p>#ArtificialIntelligence #GenAI #Svelte #TypeScript</p>
]]></content:encoded></item><item><title><![CDATA[Custom URL Protocols: The Secret to Opening Desktop Apps from the Web]]></title><description><![CDATA[Custom URL Protocols integrate websites and desktop apps via unique identifiers in the Windows Registry]]></description><link>https://nullbyte.hashnode.dev/custom-url-protocols-the-secret-to-opening-desktop-apps-from-the-web</link><guid isPermaLink="true">https://nullbyte.hashnode.dev/custom-url-protocols-the-secret-to-opening-desktop-apps-from-the-web</guid><category><![CDATA[Web Development]]></category><category><![CDATA[protocols]]></category><category><![CDATA[desktop]]></category><category><![CDATA[Applications]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Productivity]]></category><category><![CDATA[infrastructure]]></category><category><![CDATA[Information]]></category><category><![CDATA[System Design]]></category><category><![CDATA[architecture]]></category><category><![CDATA[System Architecture]]></category><dc:creator><![CDATA[Nilay Barot]]></dc:creator><pubDate>Mon, 30 Sep 2024 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1731254843066/32839924-6494-4da9-94b9-e65f3cd4ae2f.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Ever wondered how websites can open desktop applications like Notion, Steam, or others directly from the browser? The magic lies in <strong>Custom URL Protocols</strong>. This method is widely used by popular apps to provide seamless transitions between web and desktop environments, ensuring a smooth user experience. In this article, I’ll walk you through how <strong>Custom URL Protocols</strong> work and show you how to set one up for your own application using Windows Registry.</p>
<h3 id="heading-what-are-custom-url-protocols">What Are Custom URL Protocols?</h3>
<p>A Custom URL Protocol is a unique identifier registered in the system’s registry. When a web browser encounters a link starting with a registered protocol (e.g., <code>notion://</code>), it can invoke a dialog to open the specified desktop application, if installed. This approach is ideal for launching desktop applications directly from web pages, enhancing user interaction across platforms.</p>
<p>Here are a few examples of commonly registered URL protocols:</p>
<ul>
<li><p><strong>Notion</strong>: <code>notion://</code></p>
</li>
<li><p><strong>Calculator</strong>: <code>ms-calculator://</code></p>
</li>
<li><p><strong>Notepad</strong>: <code>ms-notepad://</code></p>
</li>
</ul>
<p>These protocols are recognized by Windows (and other operating systems) and can be launched by simply clicking a corresponding link in the browser. Now, let's dive into the process of creating your own Custom URL Protocol.</p>
<h3 id="heading-registering-a-custom-url-protocol-in-windows">Registering a Custom URL Protocol in Windows</h3>
<p>To register a Custom URL Protocol in Windows, we’ll work with the Windows Registry. Here’s a step-by-step guide to creating your own protocol.</p>
<h3 id="heading-steps-to-register-your-custom-url-protocol">Steps to Register Your Custom URL Protocol</h3>
<ol>
<li><p><strong>Open the Registry Editor</strong></p>
<ul>
<li>Press <code>Win + R</code>, type <code>regedit</code>, and press Enter to open the Windows Registry Editor.</li>
</ul>
</li>
<li><p><strong>Navigate to HKEY_CLASSES_ROOT</strong></p>
<ul>
<li>In the Registry Editor, go to <code>HKEY_CLASSES_ROOT</code>. This location stores all the registered protocols and file associations.</li>
</ul>
</li>
<li><p><strong>Create a New Key for Your Protocol</strong></p>
<ul>
<li>Under <code>HKEY_CLASSES_ROOT</code>, create a new key with the name of your protocol. For this example, let’s call it <code>my-custprotocol</code>.</li>
</ul>
</li>
<li><p><strong>Add a</strong> <code>URL Protocol</code> String Value</p>
<ul>
<li>Inside the <code>my-custprotocol</code> key, create a new <code>String Value</code> named <code>URL Protocol</code>. This value doesn’t require any specific data; simply leave it blank. Adding this key informs Windows that this entry is a protocol handler.</li>
</ul>
</li>
<li><p><strong>Define the Launch Command</strong></p>
<ul>
<li><p>Inside the <code>my-custprotocol</code> key, create a subkey named <code>shell</code>.</p>
</li>
<li><p>Under <code>shell</code>, create another subkey named <code>open</code>.</p>
</li>
<li><p>Under <code>open</code>, create a final subkey called <code>command</code>.</p>
</li>
<li><p>Set the <code>(Default)</code> value of <code>command</code> to the path of the executable you want to open, with the following format:</p>
<pre><code class="lang-javascript">  <span class="hljs-string">"path\to\your\application.exe"</span> <span class="hljs-string">"%1"</span>
</code></pre>
</li>
<li><p>For example, if your application is located at <code>D:\TestApp\CustomProtocol.Tester.exe</code>, you would enter:</p>
<pre><code class="lang-javascript">  <span class="hljs-string">"D:\TestApp\CustomProtocol.Tester.exe"</span> <span class="hljs-string">"%1"</span>
</code></pre>
</li>
</ul>
</li>
</ol>
<p>    The <code>%1</code> argument allows the protocol to pass any query string data from the browser to your application, enabling custom handling based on the URL parameters.</p>
<p>    Now, when you or any user navigates to <code>my-custprotocol://example</code>, the browser will prompt to open your application, passing along any query strings as arguments.</p>
<h3 id="heading-handling-url-arguments-in-your-application">Handling URL Arguments in Your Application</h3>
<p>In most frameworks, such as Electron, WPF, Tkinter, or JavaFX, you can access command-line arguments in the application startup process. You can then parse the <code>%1</code> argument to extract parameters from the query string, allowing you to implement custom logic based on the URL.</p>
<p>For instance, if you navigate to <code>my-custprotocol://open?doc=123</code>, the query <code>doc=123</code> will be passed to your application, and you could handle this in your app to open a specific document.</p>
<hr />
<h2 id="heading-automating-the-registry-key-creation">Automating the Registry Key Creation</h2>
<p>Adding a Custom URL Protocol manually can be tedious, especially if you want this protocol to register on each installation. The registration process can be automated using scripts in various programming languages, such as PowerShell, C#, or Python.</p>
<p>Here's a simple PowerShell script to automate the registry addition for <code>my-custprotocol</code>:</p>
<pre><code class="lang-powershell"><span class="hljs-variable">$protocolName</span> = <span class="hljs-string">"my-custprotocol"</span>
<span class="hljs-variable">$exePath</span> = <span class="hljs-string">"D:\TestApp\CustomProtocol.Tester.exe"</span>

<span class="hljs-built_in">New-Item</span> <span class="hljs-literal">-Path</span> <span class="hljs-string">"HKCR:\<span class="hljs-variable">$protocolName</span>"</span> | <span class="hljs-built_in">Out-Null</span>
<span class="hljs-built_in">New-ItemProperty</span> <span class="hljs-literal">-Path</span> <span class="hljs-string">"HKCR:\<span class="hljs-variable">$protocolName</span>"</span> <span class="hljs-literal">-Name</span> <span class="hljs-string">"URL Protocol"</span> <span class="hljs-literal">-Value</span> <span class="hljs-string">""</span> | <span class="hljs-built_in">Out-Null</span>
<span class="hljs-built_in">New-Item</span> <span class="hljs-literal">-Path</span> <span class="hljs-string">"HKCR:\<span class="hljs-variable">$protocolName</span>\shell"</span> | <span class="hljs-built_in">Out-Null</span>
<span class="hljs-built_in">New-Item</span> <span class="hljs-literal">-Path</span> <span class="hljs-string">"HKCR:\<span class="hljs-variable">$protocolName</span>\shell\open"</span> | <span class="hljs-built_in">Out-Null</span>
<span class="hljs-built_in">New-Item</span> <span class="hljs-literal">-Path</span> <span class="hljs-string">"HKCR:\<span class="hljs-variable">$protocolName</span>\shell\open\command"</span> | <span class="hljs-built_in">Out-Null</span>
<span class="hljs-built_in">Set-ItemProperty</span> <span class="hljs-literal">-Path</span> <span class="hljs-string">"HKCR:\<span class="hljs-variable">$protocolName</span>\shell\open\command"</span> <span class="hljs-literal">-Name</span> <span class="hljs-string">"(Default)"</span> <span class="hljs-literal">-Value</span> <span class="hljs-string">"`"<span class="hljs-variable">$exePath</span>`" `"%1`""</span>
</code></pre>
<p>Run this script as part of your application installation process to register the protocol automatically.</p>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>Custom URL Protocols offer a powerful way to bridge the web and desktop application worlds, creating a smooth and integrated experience for users. By following these steps, you can create and register your own Custom URL Protocol, enabling you to launch your desktop applications directly from the web. With the ability to pass arguments through URL query strings, this approach can add significant functionality to your application, making it highly responsive to user actions initiated from a browser.</p>
<p>So, the next time you need to invoke an app from the web, remember that setting up a Custom URL Protocol might be the key!</p>
]]></content:encoded></item><item><title><![CDATA[Incorporating .NET Functionality into JavaScript using WebAssembly]]></title><description><![CDATA[Harness .NET power in the browser with WebAssembly. Learn to integrate .NET functionality into JavaScript for efficient web development]]></description><link>https://nullbyte.hashnode.dev/incorporating-net-functionality-into-javascript-using-webassembly</link><guid isPermaLink="true">https://nullbyte.hashnode.dev/incorporating-net-functionality-into-javascript-using-webassembly</guid><category><![CDATA[wasm]]></category><category><![CDATA[dotnet]]></category><category><![CDATA[WebAssembly]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[# csharp  # beginners  # dotnet  # programming]]></category><category><![CDATA[C#]]></category><category><![CDATA[js]]></category><dc:creator><![CDATA[Nilay Barot]]></dc:creator><pubDate>Sun, 12 May 2024 19:44:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1715456297529/310c99e6-7793-47f9-b111-8043ed76c2f7.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-what-is-webassembly">What is WebAssembly?</h2>
<p>WebAssembly or popularly known as WASM is an open web standard that allows efficient code execution in a binary format, similar to native code execution. It can be used with various languages like <strong>C, C++, Go, and C# .NET</strong>, enabling developers to compile their code into WASM files that can be downloaded and run in the browser.</p>
<h2 id="heading-why-consider-net-in-the-browser">Why Consider .NET in the Browser?</h2>
<p>JavaScript undoubtedly reigns supreme in client-side development. However, what if your project demands server-side processing, such as file conversions or complex computations, that are more efficiently handled with .NET using C#? Simply making calls to the backend server might not be the most optimal solution. What if you could execute these operations directly within the browser using .NET? This is where WebAssembly comes into play, enabling you to harness the capabilities of .NET right in the client's browser environment. In this article, we delve into the potential of leveraging .NET with WebAssembly, revolutionizing the way we approach web development.</p>
<h2 id="heading-lets-get-started">Lets get started</h2>
<p>To unleash the power of .NET in your browser, you'll need to ensure you have the <strong>.NET 7</strong> or latest, installed on your system. Additionally, make sure to equip your environment with the necessary tools, such as the <strong>wasm-tools</strong> workload, to seamlessly integrate WebAssembly into your development workflow.</p>
<p><strong>wasm-tools</strong> can be installed with following commands</p>
<pre><code class="lang-powershell">dotnet workload install wasm<span class="hljs-literal">-tools</span>
</code></pre>
<p>Create a new dotnet console application</p>
<pre><code class="lang-powershell">dotnet new console
</code></pre>
<p>Now to convert our console application to build WebAssembly bindings on compilation we need to below tags in <strong>&lt;PropertyGroup&gt;</strong> tag in <strong>csproj</strong> file, also we need to create a <strong><em>main.js</em></strong> file in the same project.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">RuntimeIdentifier</span>&gt;</span>browser-wasm<span class="hljs-tag">&lt;/<span class="hljs-name">RuntimeIdentifier</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">AllowUnsafeBlocks</span>&gt;</span>true<span class="hljs-tag">&lt;/<span class="hljs-name">AllowUnsafeBlocks</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">WasmMainJSPath</span>&gt;</span>main.js<span class="hljs-tag">&lt;/<span class="hljs-name">WasmMainJSPath</span>&gt;</span>
</code></pre>
<p>In <strong><em>Program.cs</em></strong>, add the following code</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> System.Runtime.InteropServices.JavaScript;
<span class="hljs-keyword">using</span> System.Text.Json;
<span class="hljs-keyword">using</span> System.Text.Json.Serialization;

Console.WriteLine(<span class="hljs-string">""</span>); <span class="hljs-comment">//work around for main is not defined error on code compilation </span>

<span class="hljs-keyword">public</span> <span class="hljs-keyword">partial</span> <span class="hljs-keyword">class</span> <span class="hljs-title">JSBridge</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Employee employee { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    [<span class="hljs-meta">JSImport(<span class="hljs-meta-string">"globalThis.console.log"</span>)</span>]
    <span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">partial</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Log</span>(<span class="hljs-params">[JSMarshalAs&lt;JSType.String&gt;] <span class="hljs-keyword">string</span> message</span>)</span>;

    [<span class="hljs-meta">JSExport</span>]
    <span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">string</span> <span class="hljs-title">GetEmployee</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">string</span> jsonString = JsonSerializer.Serialize(employee, SourceGenerationContext.Default.Employee);
        Log(jsonString);<span class="hljs-comment">//Logging message log to console</span>
        <span class="hljs-keyword">return</span> jsonString;
    }

    [<span class="hljs-meta">JSExport</span>]
    <span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">SetEmployee</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> _id, <span class="hljs-keyword">string</span> _name, <span class="hljs-keyword">int</span> _age, <span class="hljs-keyword">bool</span> _isActive</span>)</span>
    {
        Log(<span class="hljs-string">$"<span class="hljs-subst">{<span class="hljs-keyword">nameof</span>(Employee.EmployeeId)}</span>: <span class="hljs-subst">{_id}</span>, <span class="hljs-subst">{<span class="hljs-keyword">nameof</span>(Employee.EmployeeName)}</span>: <span class="hljs-subst">{_name}</span>, <span class="hljs-subst">{<span class="hljs-keyword">nameof</span>(Employee.EmployeeAge)}</span>: <span class="hljs-subst">{_age}</span>, <span class="hljs-subst">{<span class="hljs-keyword">nameof</span>(Employee.IsActive)}</span>: <span class="hljs-subst">{_isActive}</span>,"</span>);
        employee = <span class="hljs-keyword">new</span> Employee() { EmployeeId = _id, EmployeeName = _name, EmployeeAge = _age, IsActive = _isActive };
    }
}

[<span class="hljs-meta">JsonSourceGenerationOptions(WriteIndented = true)</span>]
[<span class="hljs-meta">JsonSerializable(typeof(Employee))</span>]
<span class="hljs-keyword">internal</span> <span class="hljs-keyword">partial</span> <span class="hljs-keyword">class</span> <span class="hljs-title">SourceGenerationContext</span> : <span class="hljs-title">JsonSerializerContext</span>
{

}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> EmployeeId { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> EmployeeName { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> EmployeeAge { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> IsActive { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}
</code></pre>
<p>Information related to JSExport and JSImport can be found <a target="_blank" href="https://learn.microsoft.com/en-us/aspnet/core/client-side/dotnet-interop?view=aspnetcore-8.0">here</a> and in <strong><em>main.js</em></strong> we need to create a wrapper to access the .NET code using JavaScript.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { dotnet } <span class="hljs-keyword">from</span> <span class="hljs-string">"./_framework/dotnet.js"</span>;
<span class="hljs-keyword">let</span> exportsPromise = <span class="hljs-literal">null</span>;

<span class="hljs-keyword">const</span> createRuntimeAndGetExports = <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> { getAssemblyExports, getConfig } = <span class="hljs-keyword">await</span> dotnet.create();
    <span class="hljs-keyword">const</span> config = getConfig();
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> getAssemblyExports(config.mainAssemblyName);
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getEmployee</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">if</span> (!exportsPromise) {
        exportsPromise = createRuntimeAndGetExports();
    }
    <span class="hljs-keyword">const</span> <span class="hljs-built_in">exports</span> = <span class="hljs-keyword">await</span> exportsPromise;
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">exports</span>.JSBridge.GetEmployee();
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setEmployee</span>(<span class="hljs-params">id, name, age, isActive</span>) </span>{
    <span class="hljs-keyword">if</span> (!exportsPromise) {
        exportsPromise = createRuntimeAndGetExports();
    }
    <span class="hljs-keyword">const</span> <span class="hljs-built_in">exports</span> = <span class="hljs-keyword">await</span> exportsPromise;
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">exports</span>.JSBridge.SetEmployee(id,name,age,isActive);
}
</code></pre>
<p>Now our C# code and JavaScript wrapper is ready to publish, it can be done from Visual Studio itself by Publish or running below command.</p>
<pre><code class="lang-powershell">dotnet publish <span class="hljs-literal">-c</span> Release
</code></pre>
<p>On invoking the command .NET code will be converted to WebAssembly binding which can be triggered by our main.js exports. AppBundle folder will be created with the similar files. Package.json file can be created if we need to use it as npm module.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715540392680/4ecdbc9b-dc40-4975-b999-947f84d0b9f7.png" alt class="image--center mx-auto" /></p>
<p>Now well be using the .NET code in a JavaScript, for it we can create a basic Node.js application which uses express serving static HTML file.</p>
<p>Add the following code to the <strong><em>index.js</em></strong> file, also create a new folder public and subfolder dotnet and copy the contents of <strong>AppBundle</strong> folder which were generated on publishing .NET wasm project.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);
<span class="hljs-keyword">const</span> path=<span class="hljs-built_in">require</span>(<span class="hljs-string">"path"</span>);
<span class="hljs-keyword">const</span> app = express();

app.use(express.static(path.join(__dirname, <span class="hljs-string">'public'</span>)));

app.get(<span class="hljs-string">"/"</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
  res.sendFile(<span class="hljs-string">"index.html"</span>,{<span class="hljs-attr">root</span>:__dirname});
});

app.listen(<span class="hljs-number">8000</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Server started on http://localhost:8000/"</span>);
});
</code></pre>
<p>and the last step is to create an <strong><em>index.html</em></strong> file which will invoke the .NET code.</p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Document<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
      <span class="hljs-selector-class">.form-container</span> {
        <span class="hljs-attribute">display</span>: flex;
      }
      <span class="hljs-selector-class">.btn</span> {
        <span class="hljs-attribute">display</span>: inline-block;
        <span class="hljs-attribute">padding</span>: <span class="hljs-number">2%</span>;
        <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
        <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">5px</span>;
      }
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Employee Information<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">table</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">tbody</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Employee Id<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"txtEmployeeId"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Employee Name<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"txtEmployeeName"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Employee Age<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"txtEmployeeAge"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Is Active<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"chkIsActive"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn"</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"btnSetEmployee_Click()"</span>&gt;</span>
              Set Employee
            <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn"</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"btnGetEmployee_Click()"</span>&gt;</span>
              Get Employee
            <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">tbody</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">table</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">const</span> btnSetEmployee_Click = <span class="hljs-keyword">async</span> () =&gt; {
        <span class="hljs-keyword">let</span> employeeId = <span class="hljs-built_in">Number</span>(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"txtEmployeeId"</span>).value);
        <span class="hljs-keyword">let</span> employeeName = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"txtEmployeeName"</span>).value;
        <span class="hljs-keyword">let</span> employeeAge = <span class="hljs-built_in">Number</span>(
          <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"txtEmployeeAge"</span>).value
        );
        <span class="hljs-keyword">let</span> isActive = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"chkIsActive"</span>).checked;

        <span class="hljs-keyword">if</span> (employeeId &amp;&amp; employeeName &amp;&amp; employeeAge &amp;&amp; isActive) {
          <span class="hljs-keyword">import</span>(<span class="hljs-string">"/dotnet/main.js"</span>).then(<span class="hljs-function">(<span class="hljs-params">{ setEmployee }</span>) =&gt;</span> {
            setEmployee(employeeId, employeeName, employeeAge, isActive).then(<span class="hljs-function">()=&gt;</span>{
              alert(<span class="hljs-string">'Success'</span>);
            })
          });
        } <span class="hljs-keyword">else</span> {
          alert(<span class="hljs-string">"Invalid data entered"</span>);
        }
      };

      <span class="hljs-keyword">const</span> btnGetEmployee_Click = <span class="hljs-keyword">async</span> () =&gt; {
        <span class="hljs-keyword">import</span>(<span class="hljs-string">"/dotnet/main.js"</span>).then(<span class="hljs-function">(<span class="hljs-params">{ getEmployee }</span>) =&gt;</span> {
          getEmployee().then(<span class="hljs-function">(<span class="hljs-params">result</span>)=&gt;</span>{
            <span class="hljs-keyword">if</span>(result===<span class="hljs-literal">null</span>){
              alert(<span class="hljs-string">'no data present'</span>);
              <span class="hljs-keyword">return</span>;
            }
            alert(result);
          });
        });
      };
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>on running the node.js code html file will be displayed, on Setting employee data we are invoking the C# code which internally log data to console in browser as we have imported <strong>console.log</strong> functionality using <strong>JSImport</strong>, similarly on getting employee data we are reading serialized string data from the <strong>Employee</strong> class object we have created earlier in the code.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715541101667/bad53597-454b-4fd2-9857-cf942120e830.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715541251541/867192ee-eaf2-4f4a-959f-ce569f6a21c7.png" alt class="image--center mx-auto" /></p>
<p>You can find the code used in this blog on my Github <a target="_blank" href="https://github.com/nullbyte01/Dotnet-wasm-blog"><strong>here</strong></a> and do check out my other projects and connect with on <strong>LinkedIn</strong>.</p>
<p><a target="_blank" href="https://www.linkedin.com/in/nilaybarot/">https://www.linkedin.com/in/nilaybarot/</a></p>
<h3 id="heading-additional-resources">Additional Resources</h3>
<p><a target="_blank" href="https://learn.microsoft.com/en-us/aspnet/core/client-side/dotnet-interop?view=aspnetcore-8.0">https://learn.microsoft.com/en-us/aspnet/core/client-side/dotnet-interop?view=aspnetcore-8.0</a></p>
<p><a target="_blank" href="https://github.com/maraf/dotnet-wasm-react">https://github.com/maraf/dotnet-wasm-react</a></p>
]]></content:encoded></item><item><title><![CDATA[Unveiling the Power of OpenCV]]></title><description><![CDATA[Optimize computer vision with OpenCV. Choose between C++ and Python for superior performance. Uncover real-world applications with expert insights]]></description><link>https://nullbyte.hashnode.dev/unveiling-the-power-of-opencv</link><guid isPermaLink="true">https://nullbyte.hashnode.dev/unveiling-the-power-of-opencv</guid><category><![CDATA[opencv]]></category><category><![CDATA[Computer Vision]]></category><category><![CDATA[C++]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Nilay Barot]]></dc:creator><pubDate>Sat, 09 Mar 2024 09:00:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/zNRITe8NPqY/upload/5e8b5141fd9f9f80d32a5d9eb2b47714.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>OpenCV, or the Open Source Computer Vision Library, stands as a beacon in the realm of real-time computer vision. Developed by Intel in 1999, it has garnered widespread adoption from tech giants like Google, Facebook, and Microsoft. The library, available in various languages such as C++, Python, and Java, boasts a plethora of algorithms catering to diverse applications like facial recognition, object detection, and feature extraction.</p>
<h3 id="heading-pythons-dominance-in-tutorials-a-practical-approach">Python's Dominance in Tutorials: A Practical Approach?</h3>
<p>A scroll through YouTube tutorials reveals a prevalent trend – OpenCV projects showcased predominantly in Python. But, is this inclination a practical one?</p>
<p>Python, being an interpreted language, often carries the stigma of slower performance compared to its compiled counterparts. Yet, its unparalleled efficiency and speed in code development cannot be overlooked. Notably, when utilizing OpenCV's API in Python, the underlying C++ API and performance-optimized Python modules like NumPy come into play. While leveraging the core functionality of OpenCV API, Python showcases commendable performance. However, when custom Python code comes into play, a potential slowdown might manifest.</p>
<h3 id="heading-real-world-implications-pythons-sweet-spot-and-c-precision">Real-world Implications: Python's Sweet Spot and C++ Precision</h3>
<p>Consider a scenario where a product employs OpenCV for Advanced Driver Assistance Systems (ADAS), requiring real-time processing. Here, Python might take a back seat due to its slower execution compared to C++. The inherent performance optimization in the C++ API and Python modules might not suffice for applications demanding robust performance.</p>
<h3 id="heading-pythons-playground-and-cs-realm-of-robustness">Python's Playground and C++'s Realm of Robustness</h3>
<p>Where does each language shine? Python thrives in scenarios where rapid prototyping is paramount, and performance is a secondary concern. It becomes an invaluable asset for proof of concepts and prototype applications.</p>
<p>On the flip side, when crafting a robust application demanding performance, real-time processing, and meticulous memory management, C++ emerges as the undisputed champion. Most production-ready applications harnessing the prowess of OpenCV are meticulously crafted in C++.</p>
<h3 id="heading-key-takeaways-the-synergy-of-c-and-python">Key Takeaways: The Synergy of C++ and Python</h3>
<p>Ultimately, the true potential lies in mastering both languages. Python's agility facilitates swift prototyping, while C++ steps in for the production-ready heavyweight. This synergistic approach allows developers to harness the unique strengths of both, ensuring a seamless journey from conceptualization to implementation. Embrace the power of both C++ and Python to unlock the full spectrum of OpenCV's capabilities.</p>
<p>Thank you for reading! Connect with me on <a target="_blank" href="https://www.linkedin.com/in/nilaybarot/">LinkedIn</a> for more insights on OpenCV, computer vision, and software development.</p>
]]></content:encoded></item><item><title><![CDATA[C# and C++ Interops: Combining the Best of Both Worlds]]></title><description><![CDATA[Discover the benefits of combining C# and C++ interops for powerful programming. Learn how to leverage the strengths of each language for optimal results.]]></description><link>https://nullbyte.hashnode.dev/c-and-c-interops-combining-the-best-of-both-worlds</link><guid isPermaLink="true">https://nullbyte.hashnode.dev/c-and-c-interops-combining-the-best-of-both-worlds</guid><category><![CDATA[C#]]></category><category><![CDATA[C++]]></category><category><![CDATA[C]]></category><category><![CDATA[interoperability]]></category><category><![CDATA[interop]]></category><dc:creator><![CDATA[Nilay Barot]]></dc:creator><pubDate>Tue, 04 Apr 2023 04:19:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680581960292/9503f4d5-c39e-4666-b94f-f9f174def6c5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-what-are-c-interops">What are C++ Interops?</h3>
<p>C++ Interop enables calling C++ code from C# code by utilizing various techniques and libraries provided by the .NET Framework, including Platform Invocation Services (P/Invoke), COM Interop, and C++/CLI.</p>
<h3 id="heading-what-are-the-benefits-of-c-interops-in-c">What are the benefits of C++ Interops in C#?</h3>
<p>There are several benefits of using C++ Interops functionality in C# code, they are described below.</p>
<ol>
<li><p>By reusing existing C++ code that is already available, we can avoid the need to develop the same functionality from scratch for C#, resulting in significant time and effort savings.</p>
</li>
<li><p>C++ Interop in C# allows us to leverage the low-level hardware and memory manipulation capabilities of C++, enabling us to access them directly from our C# application.</p>
</li>
<li><p>When performance is crucial and there is a need to optimize code, C++ Interop in C# can be utilized to leverage the power of C++ and improve the application's performance.</p>
</li>
<li><p>C++ Interop in C# allows for seamless integration of third-party C++ libraries into your C# application. Additionally, it enables access to system-specific libraries, such as User32.dll and system32.dll.</p>
</li>
</ol>
<h3 id="heading-how-to-use-c-interop-functionality-in-c-and-how-we-can-create-interop-dll-in-c">How to use C++ Interop functionality in C# and how we can create Interop DLL in C++?</h3>
<p>Create a C++ dll project and add the following code to the header file, I have added it as <strong>CustomClass.h.</strong></p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> once</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">ifdef</span> CPPDEMOLIB_EXPORTS</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> DemoLib __declspec(dllexport)</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">else</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> DemoLib __declspec(dllimport)</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">endif</span> <span class="hljs-comment">// CPPDEMOLIB_EXPORTS</span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

DemoLib <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomClassLib</span>
{</span>
<span class="hljs-keyword">public</span>:
    CustomClassLib();
    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">AddNumbers</span><span class="hljs-params">(<span class="hljs-keyword">int</span> num1, <span class="hljs-keyword">int</span> num2)</span></span>;
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">DisplayMessage</span><span class="hljs-params">(<span class="hljs-keyword">char</span>* message, <span class="hljs-keyword">char</span>* buffer)</span></span>;
    ~CustomClassLib();
};

<span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function">DemoLib CustomClassLib * <span class="hljs-title">Initialize</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> CustomClassLib(); }
<span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function">DemoLib <span class="hljs-keyword">int</span> <span class="hljs-title">AddNumbers</span><span class="hljs-params">(CustomClassLib classObj, <span class="hljs-keyword">int</span> num1, <span class="hljs-keyword">int</span> num2)</span> </span>{ <span class="hljs-keyword">return</span> classObj.AddNumbers(num1, num2); }
<span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function">DemoLib <span class="hljs-keyword">void</span> <span class="hljs-title">DisplayMessage</span><span class="hljs-params">(CustomClassLib classObj, <span class="hljs-keyword">char</span>* message, <span class="hljs-keyword">char</span>* buffer)</span> </span>{ classObj.DisplayMessage(message, buffer); }
<span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function">DemoLib <span class="hljs-keyword">void</span> <span class="hljs-title">DeleteObj</span><span class="hljs-params">(CustomClassLib * classObj)</span> </span>{ <span class="hljs-keyword">delete</span> classObj; }
</code></pre>
<p>This code defines a C++ class called CustomClassLib that is intended to be used in a C# project via a DLL. The code includes the standard input/output stream library, defines a header guard, and uses a preprocessor directive to check whether the DLL is being exported or imported.</p>
<p>The CustomClassLib class has three member functions: a constructor, an addition function, and a message display function, as well as a destructor. The DemoLib attribute is used to indicate whether the class is being compiled as a DLL or an executable.</p>
<p>External functions are defined using the "extern C" keyword to ensure they are exported with C-style naming, which makes it easier for the C# wrapper to access them. Overall, this code is designed to be compiled into a DLL that can be used in a C# project via a wrapper.</p>
<p>The add following code to the Source file, i.e. <strong>CustomClass.cpp.</strong></p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"CustomClass.h"</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;string&gt;</span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

CustomClassLib::CustomClassLib() {
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Intialize Library"</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">CustomClassLib::AddNumbers</span><span class="hljs-params">(<span class="hljs-keyword">int</span> num1, <span class="hljs-keyword">int</span> num2)</span> </span>{
    <span class="hljs-keyword">try</span>
    {
        <span class="hljs-keyword">int</span> _sum = num1 + num2;
        <span class="hljs-keyword">return</span> _sum;
    }
    <span class="hljs-keyword">catch</span> (<span class="hljs-keyword">const</span> <span class="hljs-built_in">std</span>::exception&amp; e)
    {
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Error:"</span> &lt;&lt; e.what() &lt;&lt; <span class="hljs-built_in">endl</span>;
        <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;
    }
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">CustomClassLib::DisplayMessage</span><span class="hljs-params">(<span class="hljs-keyword">char</span>* message, <span class="hljs-keyword">char</span>* buffer)</span> </span>{
    <span class="hljs-keyword">try</span>
    {
        <span class="hljs-keyword">char</span> cArray[<span class="hljs-number">255</span>];
        sprintf_s(cArray, <span class="hljs-string">"Hello, %s"</span>, message);
        strcpy_s(buffer, <span class="hljs-keyword">sizeof</span>(cArray), cArray);
    }
    <span class="hljs-keyword">catch</span> (<span class="hljs-keyword">const</span> <span class="hljs-built_in">std</span>::exception&amp; e)
    {
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Error:"</span> &lt;&lt; e.what() &lt;&lt; <span class="hljs-built_in">endl</span>;
    }
}

CustomClassLib::~CustomClassLib() {
}
</code></pre>
<p>This code defines the member functions of a C++ class called CustomClassLib, which can be used in a C# project via a DLL.</p>
<p>The constructor function CustomClassLib() simply outputs a message to the console when the class is initialized.</p>
<p>The AddNumbers() function takes two integer arguments, adds them together, and returns their sum. It also includes error handling in case an exception is thrown.</p>
<p>The DisplayMessage() function takes a character array argument and writes a message to it, which is then copied to another character array buffer. Again, error handling is included.</p>
<p>The destructor function ~CustomClassLib() is empty.</p>
<p>Overall, this code provides basic functionality for the CustomClassLib class, allowing it to be used in a C# project via a DLL.</p>
<p>Now we need to use these Interop functions in a C# program for it, we can add the following code</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> System;
<span class="hljs-keyword">using</span> System.Collections.Generic;
<span class="hljs-keyword">using</span> System.Linq;
<span class="hljs-keyword">using</span> System.Runtime.InteropServices;
<span class="hljs-keyword">using</span> System.Text;
<span class="hljs-keyword">using</span> System.Threading.Tasks;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">InteropDemo</span>
{
    <span class="hljs-keyword">internal</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
        {
            IntPtr _myClassObj = ExternHelpers.Initialize();

            <span class="hljs-keyword">int</span> sum = ExternHelpers.AddNumbers(_myClassObj, <span class="hljs-number">100</span>, <span class="hljs-number">56</span>);
            Console.WriteLine(<span class="hljs-string">"From CPP -&gt; AddNumbers :"</span> + sum);

            StringBuilder sb=<span class="hljs-keyword">new</span> StringBuilder(<span class="hljs-number">255</span>);
            ExternHelpers.DisplayMessage(_myClassObj, <span class="hljs-string">"Have a wonderful day, keep learning."</span>,sb);
            Console.WriteLine(<span class="hljs-string">"From CPP -&gt; Display Message: "</span> + sb.ToString());


            ExternHelpers.DeleteObj(_myClassObj);

            Console.Read();
        }
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ExternHelpers</span>
    {
        <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> dllName = <span class="hljs-string">"CppDemoLib.dll"</span>;

        [<span class="hljs-meta">DllImport(dllName)</span>]
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">extern</span> IntPtr <span class="hljs-title">Initialize</span>(<span class="hljs-params"></span>)</span>;

        [<span class="hljs-meta">DllImport(dllName)</span>]
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">extern</span> <span class="hljs-keyword">int</span> <span class="hljs-title">AddNumbers</span>(<span class="hljs-params">IntPtr myClassObj, <span class="hljs-keyword">int</span> num1, <span class="hljs-keyword">int</span> num2</span>)</span>;

        [<span class="hljs-meta">DllImport(dllName)</span>]
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">extern</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DisplayMessage</span>(<span class="hljs-params">IntPtr myClassObj, <span class="hljs-keyword">string</span> message,StringBuilder responseMessage</span>)</span>;

        [<span class="hljs-meta">DllImport(dllName)</span>]
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">extern</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DeleteObj</span>(<span class="hljs-params">IntPtr myClassObj</span>)</span>;
    }
}
</code></pre>
<p>This is a C# code that demonstrates how to use a C++ DLL in a C# project using interop. The C# program defines a class called "Program" with a Main method that calls several functions from a C++ DLL called "CppDemoLib.dll".</p>
<p>The program first initializes the DLL by calling the "Initialize" method from the DLL through the "ExternHelpers" class. Then it calls the "AddNumbers" method, which takes two integers as arguments and returns their sum. It also calls the "DisplayMessage" method, which takes a string message and a StringBuilder as arguments and writes the message to the StringBuilder.</p>
<p>Finally, it calls the "DeleteObj" method to clean up the instance of the C++ class. The interop is facilitated by the [DllImport] attribute which allows the C# program to access the functions in the C++ DLL.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Integrating C++ code in a C# project can seem daunting at first, but with the right tools and knowledge, it can be a powerful way to enhance your application's performance and functionality. By following the steps outlined in this blog post, you can get started with integrating C++ code in your C# project using DLLs.</p>
]]></content:encoded></item><item><title><![CDATA[SOLID Principles]]></title><description><![CDATA[Learn SOLID principles in C#: write clean and maintainable code with SRP, OCP, LSP, ISP, and DIP. Improve your coding skills and create high-quality code.]]></description><link>https://nullbyte.hashnode.dev/solid-principles</link><guid isPermaLink="true">https://nullbyte.hashnode.dev/solid-principles</guid><category><![CDATA[C#]]></category><category><![CDATA[SOLID principles]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Programming Tips]]></category><category><![CDATA[Basic of c#]]></category><dc:creator><![CDATA[Nilay Barot]]></dc:creator><pubDate>Thu, 30 Mar 2023 04:30:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/q10VITrVYUM/upload/89395f26ace521a959aa94ebb312bbff.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Solid principles provide a foundation for writing high-quality code. By adhering to these principles, developers can create code that is efficient, maintainable, clean and scalable. Rather than delving into theory, let's examine how these principles can be applied in practice.</p>
<h3 id="heading-s-single-responsibility-principle-srp"><strong>S - Single Responsibility Principle (SRP)</strong></h3>
<p>The Single Responsibility Principle states that a class or module should have only one reason to change. In simple words, a class or library should be responsible for only one functionality or task.</p>
<p>Let's understand it with code, here we have a class it has implementation as shown in code.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Users</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> UserId { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Username { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Password { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> ProductId { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> ProductName { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> ProductDescription { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">AuthenticateUser</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> _username, <span class="hljs-keyword">string</span> _password</span>)</span>
    {
        <span class="hljs-comment">//Code implementation to authenticate user</span>
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">AddProduct</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> _productId, <span class="hljs-keyword">string</span> _productName, <span class="hljs-keyword">string</span>         _productDescription</span>)</span>
    {
        <span class="hljs-comment">//Code implementation to add product</span>
    }
}
</code></pre>
<p>Here the class <strong>User</strong> contains functionality as well as properties of <strong>User</strong> as well as of <strong>Product</strong>, which is not a scalable and maintainable approach.</p>
<p>As per SRP, we divide the functionality of <strong>User</strong> and <strong>Product</strong> so they do not interfere with each other's functionality, and also the class with have only reason to change when there is an addition or any modification related to it.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Users</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> UserId { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Username { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Password { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">AuthenticateUser</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> _username, <span class="hljs-keyword">string</span> _password</span>)</span>
    {
        <span class="hljs-comment">//Code implementation to authenticate user</span>
    }
}
</code></pre>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Products</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> ProductId { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> ProductName { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> ProductDescription { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">AddProduct</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> _productId, <span class="hljs-keyword">string</span> _productName, <span class="hljs-keyword">string</span> _productDescription</span>)</span>
    {
        <span class="hljs-comment">//Code implementation to add product</span>
    }
}
</code></pre>
<h3 id="heading-o-openclosed-principle-ocp"><strong>O - Open/Closed Principle (OCP)</strong></h3>
<p>The Open/Closed Principle states that classes or modules should be open for extension but closed for modification. In other words, once a class or module is created, it should not be modified directly. Instead, new functionality should be added through new code that extends the existing code.</p>
<p>Let us check an example of how OCP works.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ExtensionClass</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">bool</span> <span class="hljs-title">Rename</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> FileInfo fileInfo, <span class="hljs-keyword">string</span> newName</span>)</span>
    {
        <span class="hljs-keyword">try</span>
        {
            fileInfo.MoveTo(newName);
        }
        <span class="hljs-keyword">catch</span> (Exception)
        {
            <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
        }

        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
}
</code></pre>
<p>We have added an extension method to <strong>FileInfo</strong> class which is available in the <strong>System.IO</strong> namespace, and it does not contain any method named <strong>Rename</strong>, so we have extended the <strong>FileInfo</strong> class.</p>
<pre><code class="lang-csharp">FileInfo file = <span class="hljs-keyword">new</span> FileInfo(<span class="hljs-string">"test.txt"</span>);
file.Rename(<span class="hljs-string">"newname.txt"</span>);
</code></pre>
<p>Now, <strong>Rename</strong> method can be accessed by creating an object of <strong>FileInfo.</strong></p>
<h3 id="heading-l-liskov-substitution-principle-lsp"><strong>L - Liskov Substitution Principle (LSP)</strong></h3>
<p>Liskov's Substitution Principle states that objects of a superclass should be able to be replaced with objects of a subclass without any problem.</p>
<p>The idea behind the LSP is to make code more flexible and easier to maintain. By ensuring that subclasses can be used interchangeably with their parent classes, we can write code that is more modular and easier to extend.</p>
<p>Let us understand it with a simple example</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">SuperHero</span>
{
    <span class="hljs-comment">//Implementation of SuperHero</span>
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Batman</span> : <span class="hljs-title">SuperHero</span>
{
    <span class="hljs-comment">//Implementation of Batman</span>
}
</code></pre>
<p>Here we have a <strong>SuperHero</strong> and <strong>Batman,</strong> where <strong>SuperHero</strong> is the base class and <strong>Batman</strong> is inheriting properties of <strong>SuperHero</strong>. As per Liskov Substitution Principle, we can initialize <strong>SuperHero</strong> with an instance of <strong>Batman</strong>.</p>
<pre><code class="lang-csharp">SuperHero super = <span class="hljs-keyword">new</span> Batman();
</code></pre>
<h3 id="heading-i-interface-segregation-principle-isp"><strong>I - Interface Segregation Principle (ISP)</strong></h3>
<p>The Interface Segregation Principle states that no client should be forced to depend on methods it does not use. Segregation in simple words means separation.</p>
<p>In simpler words, this means that when creating <strong>interfaces</strong>, we should make sure that they are focused on specific functionality and only include methods that are relevant to that functionality. <strong>Classes</strong> that implement the <strong>interface</strong> should not be required to implement methods that they don't need or use.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IDemoInterface</span>
{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">AddUser</span>(<span class="hljs-params"></span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">DeleteUser</span>(<span class="hljs-params"></span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">string</span> <span class="hljs-title">GetUser</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> UserId</span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">AddProduct</span>(<span class="hljs-params"></span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">DeleteProduct</span>(<span class="hljs-params"></span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">string</span> <span class="hljs-title">GetProduct</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> ProductId</span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">GetPrice</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> ProductId</span>)</span>;
}
</code></pre>
<p>Here in the above code if we want to implement <strong>IDemoInterface</strong> into our class that has user management functionality, we only require some implementation, rather than other unnecessary methods related to product management. So we can separate/segregate the interface, so we implement relevant functionality.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IUser</span>
{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">AddUser</span>(<span class="hljs-params"></span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">DeleteUser</span>(<span class="hljs-params"></span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">string</span> <span class="hljs-title">GetUser</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> UserId</span>)</span>;
}
</code></pre>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IProduct</span>
{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">AddProduct</span>(<span class="hljs-params"></span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">DeleteProduct</span>(<span class="hljs-params"></span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">string</span> <span class="hljs-title">GetProduct</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> ProductId</span>)</span>;
    <span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">GetPrice</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> ProductId</span>)</span>;
}
</code></pre>
<h3 id="heading-d-dependency-inversion-principle-dip"><strong>D - Dependency Inversion Principle (DIP)</strong></h3>
<p>The Dependency Inversion Principle suggests that high-level modules should not depend on low-level modules directly, but instead, both should depend on abstractions.</p>
<p>In simpler terms, DIP is about designing software in a way that allows for easy changes in the future. By abstracting away the implementation details of low-level components, changes to those components will not affect the high-level components that depend on them. This makes it easier to make changes to the system without causing unintended consequences.</p>
<p>Let's understand it using a simple example.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">interface</span> <span class="hljs-title">IDirectory</span>
{
    <span class="hljs-function">List&lt;<span class="hljs-keyword">string</span>&gt; <span class="hljs-title">GetDirectories</span>(<span class="hljs-params"></span>)</span>;
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">FTPDirectory</span> : <span class="hljs-title">IDirectory</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> List&lt;<span class="hljs-keyword">string</span>&gt; <span class="hljs-title">GetDirectories</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-comment">//Implementation to get FTP Directories</span>
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">LocalDriveDirectory</span> : <span class="hljs-title">IDirectory</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> List&lt;<span class="hljs-keyword">string</span>&gt; <span class="hljs-title">GetDirectories</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-comment">//Implementation to get Local drive Directories</span>
    }
}
</code></pre>
<p>Here we have an interface, which is being implemented by two classes <strong>FTPDirectory</strong> and <strong>LocalDriveDirectory</strong>. In the below code, we are injecting dependency using a constructor and accessing methods of Interface <strong>IDirectory,</strong> which is an abstraction for low-level classes <strong>FTPDirectory</strong> and <strong>LocalDriveDirectory</strong>.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">DirectoryExplorer</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> idirectory _directory;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">directoryexplorer</span>(<span class="hljs-params">idirectory directory</span>)</span>
    {
        _directory = directory;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> list&lt;<span class="hljs-keyword">string</span>&gt; <span class="hljs-title">listdirectories</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">return</span> _directory.getdirectories();
    }
}
</code></pre>
<p>By using Dependency Inversion Principle, our high-level class is not directly dependent on low-level classes but depends on abstraction. This ensures decoupled, flexible and modular code. We can create instances of Directory Explorer in the following ways, based on our requirements.</p>
<pre><code class="lang-csharp">DirectoryExplorer directoryExplorer = <span class="hljs-keyword">new</span> DirectoryExplorer(<span class="hljs-keyword">new</span> FTPDirectory());
</code></pre>
<pre><code class="lang-csharp">DirectoryExplorer directoryExplorer = <span class="hljs-keyword">new</span> DirectoryExplorer(<span class="hljs-keyword">new</span> LocalDriveDirectory());
</code></pre>
<p>Thank you for taking the time to read our first blog post on writing clean code.</p>
<p>If you have any thoughts or suggestions on how we can improve our blog posts, please don't hesitate to let us know. We're always looking for ways to enhance our content and make it more engaging for our readers. If there's a topic you'd like us to cover in a future blog post, we'd love to hear your ideas.</p>
<p>You can leave a comment below or contact us directly through our website to share your thoughts. We look forward to hearing from you and continuing to provide valuable content for our readers.</p>
]]></content:encoded></item></channel></rss>