Showing posts with label .NET Core. Show all posts
Showing posts with label .NET Core. Show all posts

Tuesday, March 3, 2020

Azure function to store csv data in Cosmos DB

This is a http trigger function written in C# - .NET Core 3.1. It processed a csv file and store the data on Cosmos DB

GitHub repo : https://github.com/hansamaligamage/fncsvdatastore

Technology stack

  • .NET Core 3.1 on Visual Studio 2019
  • Azure functions v3 and Azure Cosmos DB table API

Some code snippets


Retrieve the database storage account


public static CloudStorageAccount RetieveStorageAccount(string storageConnectionString) 

    CloudStorageAccount storageAccount; 
    try 
    { 
       storageAccount = CloudStorageAccount.Parse(storageConnectionString); 
    } 
    catch (FormatException) 
    { 
       Console.WriteLine("Invalid storage account information provided"); 
       throw; 
    } 
    catch (ArgumentException) 
    { 
       Console.WriteLine("Please check the storage account details"); 
       Console.ReadLine(); 
       throw; 
    } 
    catch(Exception ex) 
    { 
       throw ex; 
    } 
    return storageAccount; 
 }

Create a table in Cosmos DB


public static string LoadConnectionDetails() 

    return Environment.GetEnvironmentVariable("StorageConnectionString"); 
}

public static async Task<CloudTable> CreateTableAsync(string tableName)
{
    CloudTable table;
    string storageConnectionString = LoadConnectionDetails();
    CloudStorageAccount storageAccount = RetieveStorageAccount(storageConnectionString);
    CloudTableClient tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration());
    Console.WriteLine("Table client is created");
    try
    {
        table = tableClient.GetTableReference(tableName);
        if (await table.CreateIfNotExistsAsync())
        {
            Console.WriteLine("Table is created - {0}", tableName);
        }
        else
        {
            Console.WriteLine("Table {0} already exists", tableName);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    Console.WriteLine();
    return table;

}

Create a row in the Cosmos DB


public static async Task InsertOrUpdateEntityAsync(CloudTable table, Session session) 

   if (session == null) 
   { 
      throw new ArgumentNullException("Session is empty"); 
   } 
  try 
  { 
     TableOperation tableOperation = TableOperation.InsertOrMerge(session); 
     TableResult result = await table.ExecuteAsync(tableOperation); 
     Session newSession = result.Result as Session; 
     if (result.RequestCharge.HasValue) 
     { 
        Console.WriteLine("Request Charge of the operation: " + result.RequestCharge); 
     } 
     return newSession; 
 } 
 catch (StorageException e) 
 { 
    Console.WriteLine(e.Message); 
    Console.ReadLine(); 
    throw; 
 } 
 catch (Exception ex) 
 { 
    throw ex; 
 } 
}

Read a row in the Cosmos DB


public static async Task RetrieveEntityAsync(CloudTable table, string partitionKey, string rowKey) 

   try 
   { 
      TableOperation tableOperation = TableOperation.Retrieve(partitionKey, rowKey);
      TableResult result = await table.ExecuteAsync(tableOperation); 
      Session session = result.Result as Session; 
      if (session != null) 
      { 
         Console.WriteLine("\t{0}\t{1}\t{2}\t{3}", session.PartitionKey, session.RowKey,                               session.Points, session.IsWeekend); 
      } 
      if (result.RequestCharge.HasValue) 
      { 
         Console.WriteLine("Request Charge of Retrieve Operation: " +                                                     result.RequestCharge); 
      } 
      return session; 
  } 
  catch (StorageException e) 
  { 
     Console.WriteLine(e.Message); 
     Console.ReadLine(); 
     throw; 
  } 
 catch (Exception ex) 
 { 
    throw ex; 
 } 
}

Sunday, March 31, 2019

TechNet Guru Awards February 2019 - Miscellaneous

TechNet Guru Awards February 2019 - Miscellaneous - SILVER


I won the SILVER medal for one of my article on TechNet Guru competition


Source Code 
    TechNet Gallery : angular-zingchart-gauge
    GutHub : angular-zingchart




















Saturday, February 2, 2019

TechNet Guru Awards December 2018 - ASP.NET

TechNet Guru Awards  December 2018 - ASP.NET - SILVER medal

I won the SILVER medal for my ASP.NET article on TechNet Guru competition


Source Code 
    TechNet Gallery : ng-input-restrictions
    GutHub : ng-input-restrictions


Saturday, December 1, 2018

Global Office 365 Developer Bootcamp - Colombo 2018

Graph API to read Outlook mail


Session Abstract : In a big organization there will be hundreds maybe thousands of mails a day. Within those you might find plenty of invoices sent. Lets use the power of Graph Api and read those invoices and at the end of the month, send a invoice summary from azure function app

Thursday, November 1, 2018

TechNet Guru Awards September 2018 - ASP.NET

TechNet Guru Awards  September 2018 - ASP.NET - BRONZE medal

I won the BRONZE medal for my ASP.NET article on TechNet Guru competition


Source Code 
    TechNet Gallery : ASP.NET Core : loading a partial view
    GutHub : ajax-partialview



Tuesday, October 23, 2018

aOSKL Malaysia 2018

Using Graph API to read Outlook mail for Accounting



Session Abstract : What if you have hundreds of invoices landed in your Outlook as in the email. And you need a way of processing them into real invoices or maybe store in a database. Lets discuss how to do this using Microsoft Graph API, Outlook and Azure functions.


Source Code
    GitHub : trackmailboxchanges


Related Blogs :

Saturday, October 20, 2018

Input validations in a form with Angular 6

Introduction


This article is going to explain how to apply input validations to a form. We have used Angular 6 directive to perform that using Visual Studio Code. Let's see how we can do that with step by step instructions.


Background


Create Angluar application


You can go through the previous blog post to know how to create Front end and back end solution from the beginning Angular 6 - Input restrictions in a form
You can see the sample web page in the browser like this,






















You can see app.component.html file as below, it has a form to get input values, it's going to check for mandatory fields like First name, Last name, Email, SSN and Gender. 
All of these fields have required attribute, angular directive is used to check whether input values are given in correct format with the help of a regular expression.  



























We are going to use directives to apply the validation, so directives are added to app.module component as below. PhoneVaidator, EmailValidator and SSNValidator.





































import {PhoneValidator} from './directives/input-validators/phone-validator.directive'; 
import {EmailValidator} from './directives/input-validators/email-validator.directive'; 
import {SSNValidator} from './directives/input-validators/ssn-validator.directive';

@NgModule({ 
  declarations: [ 
    AppComponent, 
    PhoneValidator,
    EmailValidator, 
    SSNValidator 
], 
imports: [ 
   BrowserModule, 
   FormsModule, 
   NgSelectModule, 
   HttpClientModule 
], 
providers: [], 
bootstrap: [AppComponent] 
})

You can see the directive to apply email validation as follows, It's going to use a regular expression to parse the input text in the email field.







































//validate email 
import { NG_VALIDATORS, FormControl, ValidatorFn, Validator } from '@angular/forms'; 
import { Directive } from '@angular/core'; 

@Directive({ 
  selector: '[emailvalidator][ngModel]', 
  providers: [ 
    { 
      provide: NG_VALIDATORS, 
      useExisting: EmailValidator, 
      multi: true 
    } 
 ] 
}) 

export class EmailValidator implements Validator { 
  
  validator: ValidatorFn; 

  constructor() { 
    this.validator = this.emailValidator(); 
  } 

  validate(c: FormControl) { 
    return this.validator(c); 
  } 

  emailValidator(): ValidatorFn { 
     return (c: FormControl) => { 
       if(c.value == "") { 
          return null; 
       } 
       let isValid = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/                      .test(c.value); //email 
       if (isValid) { 
          return null; 
       } else { 
          return { 
             emailvalidator: { 
                valid: false 
               } 
              }; 
            } 
          } 
        } 
      }

We can validate Phone no field using this regular expression, It allows to enter phone no in +11111111111 format.




















































//validate phone no 
import { NG_VALIDATORS, FormControl, ValidatorFn, Validator } from '@angular/forms'; 
import { Directive } from '@angular/core'; 

@Directive({ 
   selector: '[phonevalidator][ngModel]', 
   providers: [ 
      { 
         provide: NG_VALIDATORS, 
         useExisting: PhoneValidator, 
         multi: true 
       } 
 ] 
}) 

export class PhoneValidator implements Validator { 
   validator: ValidatorFn; 
  
   constructor() { 
      this.validator = this.phoneValidator(); 
    } 

   validate(c: FormControl) { 
      return this.validator(c); 
   } 
   
   phoneValidator(): ValidatorFn { 
      return (c: FormControl) => { 
         if(c.value == "") { 
            return null; 
          } 
      
      let isValid = /^\+[0-9]{11}$/.test(c.value); 
      if (isValid) { 
         return null; 
      } else { 
         return { 
            phonevalidator: { 
               valid: false 
            } 
          }; 
        } 
      } 
    } 
  }

We want to validate SSN field in Norway, so have to install npm package to validate ssn field as below,

npm install --save norwegian-national-id-validator

You can find the following directive has used installed npm package to validate norwegian ssn no































































//validate ssn 
import { NG_VALIDATORS, FormControl, ValidatorFn, Validator } from '@angular/forms'; 
import { Directive } from '@angular/core'; 
import { validateNorwegianIdNumber } from 'norwegian-national-id-validator'; 

@Directive({ 
   selector: '[ssnvalidator][ngModel]', 
   providers: [ 
      { 
         provide: NG_VALIDATORS, 
         useExisting: SSNValidator, 
         multi: true 
      } 
   ] 
}) 

export class SSNValidator implements Validator { 
   validator: ValidatorFn; 

   constructor() { 
      this.validator = this.ssnValidator(); 
   } 

   validate(c: FormControl) { 
      return this.validator(c); 
   } 

   ssnValidator(): ValidatorFn { 
      return (c: FormControl) => { 
         if(c.value == "") { 
            return null; 
         } 
      
         let isValid = /^[0-9]{6}( )[0-9]{5}$/g.test(c.value); 
         if (isValid) { 
            var format = validateNorwegianIdNumber(c.value.replace(/ /g,'')); 
            if(format){ 
               return null; 
            } 
            else{ 
               return { 
                  ssnvalidator: { 
                     valid: false 
                  } 
                }; 
              } 
            } else { 
                return { 
                   ssnvalidator: { 
                      valid: false 
                    } 
                  }; 
                } 
              } 
           } 
         }

You can see package.json file like this after installing npm package to validate ssn field























When you run the application, you can see Create Student form as below, Save button is disabled since the form is not dirty yet.




















When you hit on the Save button after entering some values, You can see all the required field error messages as follows, It shows SSN and Email fields as invalid as well.
It doesn't show Phone as invalid since we haven't added any value to it and Phone is not a mandatory field.






















You can see Gender dropdown field has turned into red border as above, we have to add some styling to achieve that.














.invalid-feedback-select { width: 100%; font-size: 80%; color: #dc3545; }

We have to add style file in angular.json file












"styles": [ 
   "./node_modules/bootstrap/dist/css/bootstrap.min.css", 
   "src/styles.css", 
   "src/assets/css/common.scss" 
 ], 

Let's input data to required fields and check what happens, still shows invalid fields as below for phone no, email and ssn























After entering correct values for Phone, Email and SSN form look like this.























Download


TechNet Gallery


You can download the sample code from here, ng-input-validations

GitHub


You can clone this repo from GitHub, ng-input-validations


Conclusion


In this article, it describes how to apply input validations to form controls using Angular 6. The sample code has used .NET Core Web API project to develop the service layer. We used Angular 6 directives to achieve this.


References

Thursday, October 11, 2018

Sri Lanka .NET Forum - October Meetup - 2018

A real-world example with Microsoft Graph API and Outlook.



Session Abstract : What if you have hundreds of invoices landed in your Outlook as in the email. And you need a way of processing them into real invoices or maybe store in a database. Lets discuss how to do this using Microsoft Graph API, Outlook and Azure functions.


Source Code
    GitHub : trackmailboxchanges


Related Blogs :