Pages

Advertisement

Wednesday, November 8, 2023

Azure Functions: Sending Email via SendGrid

 In this blog post, I will show you how to create an Azure Functions app that can send emails via SendGrid. SendGrid is a cloud-based email service that provides reliable and scalable email delivery. Azure Functions is a serverless compute service that lets you run code without managing servers or infrastructure. By combining these two services, you can easily send emails from your Azure Functions app without worrying about the underlying email infrastructure.


To get started, you will need the following:

- An Azure account with an active subscription. If you don't have one, you can create one for free here.
- A SendGrid account with an API key. If you don't have one, you can sign up for free here and follow the instructions to create an API key.
- Visual Studio Code with the Azure Functions extension installed. You can download Visual Studio Code here and install the extension from here.
- The Azure Functions Core Tools. You can install them from here.

Once you have everything set up, follow these steps to create and deploy your Azure Functions app:

1. Open Visual Studio Code and create a new folder for your project. Name it whatever you like, such as `EmailSender`.
2. In Visual Studio Code, press `Ctrl+Shift+P` to open the command palette and select `Azure Functions: Create New Project...`. Choose the folder you created in the previous step as the location for your project.
3. Select `C#` as the language for your project and `.NET Core 3.1` as the runtime version.
4. Select `HTTP trigger` as the template for your first function and name it `SendEmail`. Choose `Anonymous` as the authorization level for your function.
5. A new file named `SendEmail.cs` will be created in your project folder with some boilerplate code for your function. Replace the code in this file with the following:

6. In Visual Studio Code, open the `local.settings.json` file in your project folder and add a new setting named `SENDGRID_API_KEY` with the value of your SendGrid API key. This file is used to store app settings for local development and testing. Make sure not to commit this file to source control as it contains sensitive information.
7. In Visual Studio Code, press `F5` to run your function app locally. You should see a message in the terminal window that says `Http Functions: SendEmail: [POST] http://localhost:7071/api/SendEmail`.
8. To test your function, you can use a tool like Postman or curl to send a POST request to the function URL with a JSON body that contains the email parameters. For example, you can use the following curl command:

//csharp
using System;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SendGrid;
using SendGrid.Helpers.Mail;

namespace EmailSender
{
    public static class SendEmail
    {
        [FunctionName("SendEmail")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            // Parse the request body
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);

            // Get the email parameters from the request body
            string fromEmail = data?.fromEmail;
            string fromName = data?.fromName;
            string toEmail = data?.toEmail;
            string toName = data?.toName;
            string subject = data?.subject;
            string body = data?.body;

            // Validate the email parameters
            if (string.IsNullOrEmpty(fromEmail) || string.IsNullOrEmpty(toEmail) || string.IsNullOrEmpty(subject) || string.IsNullOrEmpty(body))
            {
                return new BadRequestObjectResult("Please provide valid email parameters in the request body.");
            }

            try
            {
                // Create a SendGrid client with your API key
                var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
                var client = new SendGridClient(apiKey);

                // Create a SendGrid message object with the email parameters
                var from = new EmailAddress(fromEmail, fromName);
                var to = new EmailAddress(toEmail, toName);
                var msg = MailHelper.CreateSingleEmail(from, to, subject, body, body);

                // Send the email using the SendGrid client
                var response = await client.SendEmailAsync(msg);

                // Check the response status code and return accordingly
                if (response.StatusCode == HttpStatusCode.Accepted)
                {
                    return new OkObjectResult("Email sent successfully.");
                }
                else
                {
                    return new BadRequestObjectResult($"Email failed to send. Status code: {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                // Log and return any exception that occurs
                log.LogError(ex, "An error occurred while sending email.");
                return new StatusCodeResult(StatusCodes.Status500InternalServerError);
            }
        }
    }
}


Best Practices of Software Development in C#

Software development is a complex and creative process that requires careful planning, design, implementation, testing, and maintenance. Software developers need to follow some best practices to ensure that their code is consistent, readable, understandable, and maintainable. In this article, we will discuss some of the best practices of software development in C#, a popular and powerful programming language.

1. Follow Consistent Naming Conventions

In C#, it is important to follow consistent naming conventions for variables, methods, classes, interfaces, and other elements. Naming conventions help to avoid naming conflicts, improve code readability, and make it easier for developers to understand and navigate the code. Some of the common naming conventions in C# are:

  • Use Pascal case for class names, struct names, method names, property names, constant field names, and interface names. Pascal case means that the first letter of each word in the name is capitalized, and there are no underscores or hyphens between words. For example: Customer, OrderService, GetTotalPrice, FirstName, MaxValue, IComparable.
  • Use camel case for parameter names, local variable names, and private field names. Camel case means that the first letter of the first word in the name is lowercase, and the first letter of each subsequent word is capitalized. There are no underscores or hyphens between words. For example: firstName, orderService, totalPrice, maxValue, _customer.
  • Use underscore prefix for private field names. This helps to distinguish them from local variables and parameters, and to avoid naming collisions with property names. For example: _firstName, _orderService, _totalPrice, _maxValue.
  • Use descriptive and meaningful names for variables, methods, classes, and other elements. Avoid using vague, generic, or abbreviated names that do not convey the purpose or functionality of the element. For example: Customer, OrderService, GetTotalPrice, FirstName, MaxValue are better than C, OS, GTP, FN, MV.
  • Use singular names for classes, structs, enums, and interfaces. Use plural names for collections, arrays, and lists. For example: Customer, Order, Product, Customers, Orders, Products.
  • Use I prefix for interface names. This helps to identify them as interfaces, and to avoid naming conflicts with classes that implement them. For example: IComparable, IDisposable, IEnumerable.
  • Use generic type parameters that start with T, followed by a descriptive name. For example: TKey, TValue, TEntity, TResult.

2. Use Proper Code Organization

Code organization is another important aspect of software development in C#. Code organization refers to how the code is structured, grouped, and formatted in a logical and consistent way. Code organization helps to improve code readability, maintainability, and modularity. Some of the best practices for code organization in C# are:

  • Use namespaces to group related classes, structs, enums, interfaces, and delegates. Namespaces help to avoid naming conflicts, and to provide a logical hierarchy for the code. For example: System, System.IO, System.Collections.Generic, System.Linq.
  • Use access modifiers to specify the visibility and accessibility of classes, methods, properties, fields, and other elements. Access modifiers help to control the scope and encapsulation of the code, and to prevent unauthorized or unintended access. For example: public, private, protected, internal, protected internal, private protected.
  • Use regions to group related code blocks within a class or a method. Regions help to collapse and expand the code, and to provide a descriptive label for the code. For example: #region Fields, #region Properties, #region Constructors, #region Methods, #endregion.
  • Use indentation to align the code blocks and statements within a class or a method. Indentation helps to show the structure and hierarchy of the code, and to improve code readability. For example: use four spaces or one tab for each level of indentation.
  • Use whitespace to separate the code blocks and statements within a class or a method. Whitespace helps to create a clear and consistent layout for the code, and to improve code readability. For example: use one blank line between methods, properties, fields, and other elements; use one space before and after operators, commas, semicolons, and parentheses; use one space after keywords, such as if, for, while, switch, catch.
  • Use comments to explain the purpose, functionality, logic, or algorithm of the code. Comments help to document the code, and to make it easier for developers to understand and maintain the code. For example: use // for single-line comments, and /* */ for multi-line comments.

3. Avoid Magic Numbers and Strings

Magic numbers and strings are literal values that are hard-coded in the code, and that have no obvious meaning or significance. Magic numbers and strings make the code difficult to understand, maintain, and modify. They also introduce potential errors and bugs, and reduce the flexibility and reusability of the code. Some of the best practices to avoid magic numbers and strings in C# are:

  • Use constants to declare and assign meaningful names to magic numbers and strings. Constants are immutable values that can be used throughout the code, and that can be easily changed in one place if needed. For example: const int MaxLength = 10;, const string ConnectionString = \"Data Source=localhost;Initial Catalog=TestDB;Integrated Security=True\";.
  • Use enumerations to declare and assign meaningful names to a set of related magic numbers. Enumerations are named constants that represent a group of values, and that can be used to improve code readability and type safety. For example: enum DayOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };, enum Color { Red, Green, Blue, Yellow, Black, White };.
  • Use configuration files to store and retrieve magic numbers and strings that are related to the application settings, such as connection strings, app settings, user preferences, etc. Configuration files are external files that can be easily edited and updated without recompiling the code, and that can be used to provide different values for different environments, such as development, testing, and production. For example: appsettings.json, web.config, app.config.

4. Handle Exceptions Properly

Exceptions are unexpected or abnormal events that occur during the execution of the code, and that disrupt the normal flow of the program. Exceptions can be caused by various reasons, such as invalid input, network failure, file not found, division by zero, etc. Exceptions can result in undesirable outcomes, such as data loss, memory leak, security breach, or application crash. Therefore, it is essential to handle exceptions properly in C#. Some of the best practices for exception handling in C# are:

  • Use try-catch-finally blocks to enclose the code that may throw an exception, and to provide appropriate actions for handling the exception. The try block contains the code that may cause an exception; the catch block contains the code that executes when an exception occurs; the finally block contains the code that always executes, regardless of whether an exception occurs or not. For example:
try { //code that may throw an exception } catch (Exception ex) { //code that handles the exception } finally { //code that always executes }
  • Use specific exception types to catch and handle different kinds of exceptions. Specific exception types help to provide more information and context about the exception, and to handle the exception more appropriately and accurately. For example: FileNotFoundException, InvalidOperationException, ArgumentNullException, DivideByZeroException.
  • Use multiple catch blocks to catch and handle different kinds of exceptions separately. Multiple catch blocks help to provide different actions for different exceptions, and to handle the exceptions in the order of specificity. For example:
try { //code that may throw an exception } catch (FileNotFoundException ex) { //code that handles file not found exception } catch (DivideByZeroException ex) { //code that handles division by zero exception } catch (Exception ex) { //code that handles any other exception }
  • Use throw keyword to rethrow an exception, or to throw a new exception. The throw keyword helps to propagate the exception to the caller, or to create a custom exception with a specific message or inner exception. For example:
try { //code that may throw an exception } catch (Exception ex) { //code that handles the exception throw; //rethrow the exception //or throw new CustomException(\"Custom message\", ex); //throw a new exception }
  • Use finally block to release any resources that are acquired in the try block, such as files, streams, sockets, database connections, etc. The finally block helps to ensure that the resources are properly disposed and freed, regardless of whether an exception occurs or not. For example:
FileStream fs = null; try { fs = new FileStream(\"test.txt\", FileMode.Open); //code that may throw an exception } catch (Exception ex) { //code that handles the exception

Tuesday, November 15, 2022

[SOLVED] Portronics Sound Drum turns off every 10 mins

Sound Drum switches off automatically after 10 mins of playing. There's a glitch in the software for power saving feature. 

Due to the glitch, device turns off even if you're connect to bluetooth and playing music.

This can be fixed by upgrading the software of the device. Step by step process has been mentioned below for the upgrade.


Steps.

  1. Download this zip file (Download)
  2. Extract and copy the files on the root of an empty USB drive (formatted as exFat)
  3. Power on the speaker
  4. Input USB drive on the back of the speaker
  5. The speaker will update itself, and power off by itself (usually takes 1-3 secs)
  6. Remove the USB, and power on,
  7. Check running your device for more than 10 mins now... it won't turn off automatically now.


 

[Solved] Identity Server 4 caching not working issue

 

Hey guys, I've gone through some of the issue created on IdentityServer4 which were closed without proper solution.


"Issue: Identity Server 4 Caching is not working"

In simple words, it works like charm. If you know how the DI works then you even get this issue.


Here's a simple solution:

Make sure you add the below 4 store caching API at the end of identity store configurations.

What's the cause: If the cache DI is added before any other configuration then the Cache DI would be overwritten with the new DI.

.AddInMemoryCaching()
                .AddClientStoreCache<ClientStore>()
                .AddResourceStoreCache<ResourceStore>()
                .AddConfigurationStoreCache()
                .AddCorsPolicyCache<CorsPolicyService>();


Complete solutions:

Hope this solves your issue. 

Issues::: 

https://github.com/IdentityServer/IdentityServer4/issues/2191

https://stackoverflow.com/questions/51560620/caching-does-not-appear-to-work-in-identity-server-4

https://stackoverflow.com/questions/43858231/how-to-implement-caching-on-identityserver4

https://github.com/IdentityServer/IdentityServer4/issues/5007

Monday, December 6, 2010

Auto .Net code Generation based on SQL Table

It has always been a heck for programmers to start form scratch when developing Asp.Net pages with some common functionality like Add / Delete/ Update record & Design Html. Well there’s no doubt that all programmers are lazy. Lazy in the sense, who believe in Smart work & minimizing there work & rework. Definitely, I’m also one of them.

Alright, lets start with the main topic. While developing Any Asp.net Page what we need & how much time it takes ??

Here’s the answer… :

  1. HTML Page with Server Controls, (Appx. 20 mins.)
  2. Code Behind File to handle Events, (Appx. 20 mins.)
  3. A DB Class which contains methods for Adding/ Updating & Deleting Records from DB Tables. (Appx. 20 mins)
  4. Stored Procedures to perform DB Actions (Appx. Time 60 mins.)

For Creating all these things this usually takes approximately 2-8 Hrs depending on the complexity of your DB Tables.

But, what if you get all the above thing in JUST A CLICK. That sounds Cool ! isn’t it ?

At first, I tried searching for application that can perform this activity. But was unable to get any result for this. So After digging up Google, I made my final decision to Create Such Application By My Own. And here’s what I have “Express.NetArchitect”.

image

image

 

image

image

Complete Downloadable Source Code Available Below:

(RapidShare) Download Source (Size : 107 KB)

(RapidShare) Download Executable(Size : 32 KB)

If you like my post kindly leave your comments & suggestion below.

If you believe that this application needs to have additional features and this can be experimented then we can take it CodePlex.com and your suggestion we can make it a boon for .Net programmers.

Thanks Good luck.