Use ediFabric to read/publish edi transactions

          

Scenario: Create plugin to read/publish edi transactions

Solution:

Per ediFabric documentaion

EdiFabric is Lightning-fast and easy-to-use developer SDK and API to parse, generate, validate, split, acknowledge, represent, view, and document EDI files.

Below are the steps to convert edi document to XML. This is for X12 format of edi.
  1. Register & download the EdiFabric package. It had DLL targeting different .net versions. Add appropriate to the project.
  2. Include the EDI templates in the project, which come with the package. These are based on edi format/ version. ex X12/002040. These have POCO classes for each edi transaction, e.g. EDI 832 [Catalog]/ EDI 846[Inventory] etc.
  3. Use EdiFabric.X12Reader to read the edi files. They could be serialized using XMLSerializer or DataContractSerilizer per above classes.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    
    namespace MyCoreSolution
    {
        public class EdiPlugin
        {
            public void ConvertEdidocumentoXML()
            {
                EdiFabric.SerialKey.Set();
    
                var ediData = "";
                //var ediData  = File.OpenRead(@"");
    
                var dataStream = new MemoryStream(Encoding.UTF8.GetBytes(ediData));
    
                var ediItems = new List<IEdiItem>();
    
                using (var reader = new X12Reader(dataStream, "namespace",
                    new X12ReaderSettings { ContinueOnError = false }))
                {
                    ediItems = reader.ReadToEnd().ToList();
                }
    
                var transactions = ediItems.OfType<TS832>();
                foreach (var transaction in transactions)
                {
                    var xml = transaction.Serialize();
                }
            }
        }
    }

FTP operations using FluentFTP

           

Scenario: Implement FTP solution using FluentFTP library

Solution:

Per fluentFTP documentation

FluentFTP is a fully managed FTP and FTPS library for .NET & .NET Standard, optimized for speed. It provides extensive FTP commands, File uploads/downloads, SSL/TLS connections, Automatic directory listing parsing, File hashing/checksums, File permissions/CHMOD, FTP proxies, FXP transfers, UTF-8 support, Async/await support, Powershell support and more.
  1. Add latest FluentFTP nuget package to the project
  2. Create FluentFtp class to download/upload to FTP

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    using System;
    using System.IO;
    using System.Net;
    using FluentFTP;
    
    namespace TestApp
    {
        public class FluentFTPUtils
        {
            public void Download(Context context)
            {
                var ftpClient = new FtpClient
                {
                    Host = _host,
                    Credentials = new NetworkCredential { UserName = "{user}", Password = "{pass}" },
                    Port = _port,
                    DataConnectionType = _connectionType,
                    DownloadDataType = FtpDataType.Binary,
                    UploadDataType = FtpDataType.Binary,
                    ConnectTimeout = _timeout,
                    ReadTimeout = _rimeout,
                    DataConnectionConnectTimeout = _dcTimeout,
                    DataConnectionReadTimeout = _drTimeout
                }; ;
    
                ftpClient.Connect();
    
                ftpClient.SetWorkingDirectory(_workingDirectory);
    
                foreach (
                    var file in
                    ftpClient.GetListing(ftpClient.GetWorkingDirectory())
                        .Where(f => f.Type == FtpFileSystemObjectType.File && f.Name == "fileName")
                        .OrderBy(f => f.Modified))
                {
                    Stream destStream = null;
                    try
                    {
                        ftpClient.Download(destStream, file.Name);
                    }
                    finally
                    {
                        destStream?.Close();
                    }
    
                    if (delete)
                    {
                        ftpClient.DeleteFile(file.Name);
                    }
                    else if (rename)
                    {
                        ftpClient.MoveFile(file.Name, newFilename);
    
                    }
                }
    
                CloseFtpConnection(ftpClient);
            }
    
            public void Upload(Context context)
            {
    
                var ftpClient = new FtpClient
                {
                    Host = _host,
                    Credentials = new NetworkCredential { UserName = "{user}", Password = "{pass}" },
                    Port = _port,
                    DataConnectionType = _connectionType,
                    DownloadDataType = FtpDataType.Binary,
                    UploadDataType = FtpDataType.Binary,
                    ConnectTimeout = _timeout,
                    ReadTimeout = _rimeout,
                    DataConnectionConnectTimeout = _dcTimeout,
                    DataConnectionReadTimeout = _drTimeout
                }; ;
    
                ftpClient.Connect();
    
                Stream inputStream = null;
                try
                {
                    inputStream = document.CreateStream();
                    ftpClient.Upload(inputStream, "fileName");
                }
                finally
                {
                    inputStream?.Close();
                }
                CloseFtpConnection(ftpClient);
            }
    
            private void CloseFtpConnection(FtpClient ftpConnection)
            {
                if (ftpConnection != null)
                {
                    ftpConnection.Dispose();
                }
            }
        }
    }

ASP.NET core security headers

          

Scenario: Add remove security headers as per security scan

Solution:

  1. securityheaders.io scans the website and make suggestions on any vunerability and any HTTP response headers to be added to improve security.
  2. These headers can be added through middleware or web.config
  3. Below is the way to addheader through middleware which needs to be added before UseEndpoints & UseMvc

  1. securityheaders.io scans the website and make suggestions on any vunerability and any HTTP response headers to be added to improve security.
  2. These headers can be added through middleware or web.config
  3. Below is the way to addheader through middleware which needs to be added before UseEndpoints & UseMvc

    //middleware
    if (!context.Response.Headers.ContainsKey("headerName"))
    {        
                app.Use(async (context, next) =>
                {
                    context.Response.Headers.Add("headerName", "headerValue");
                    await next();
                };
    }
    
    //Web.config
    
      <system.webServer>
        <httpProtocol>
          <customHeaders>
            <add name="Header-Name" value="Header-Value" />
          </customHeaders>
        </httpProtocol>
      </system.webServer>

     4. Some of the common security headers to add/remove

    //server
    <system.webServer>
    <security>
      <requestFiltering removeServerHeader="true" />
    </security>
    </system.webServer>
    
    //X-Powered-By
    <system.webServer>
    <httpProtocol>
      <customHeaders>
    	<remove name="X-Powered-By" />
      </customHeaders>
    </httpProtocol>
    </system.webServer>
    
    
    //X-Frame-Options
    context.Response.Headers.Add("X-Frame-Options", "DENY");
    
    //X-Xss-Protection [Against Crosssite scripting
    context.Response.Headers.Add("X-Xss-Protection", "1; mode=block");]
    
    //X-Content-Type-Options [sniffing]
    
    //middleware
    context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
    
    //web.config
    <system.webServer>
        <httpProtocol>
          <customHeaders>
            <add name="X-Content-Type-Options" value="nosniff" />
          </customHeaders>
        </httpProtocol>
    </system.webServer>

Azure - CL & Commands

          

Scenario: Use Azure CLI to execute commands & perform operations.

Solution:

Per Azure docs:

The Azure Command-Line Interface (CLI) is a cross-platform command-line tool that can be installed locally on Windows computers. You can use the Azure CLI for Windows to connect to Azure and execute administrative commands on Azure resources.
  1. To install Azure CLI -> https://aka.ms/installazurecliwindows
  2. Below are some of common commands.

    Commands
    Login -  az login
    Resource group -  az group
    Keyvault - az keyvault
    Find commands - az find

Azure - Managed Identity

         

Scenario: Use Azure Managed Identity to access Azure vault secrets

Solution:

Per Azure docs:

Azure Key Vault provides a way to store credentials and other secrets with increased security. But your code needs to authenticate to Key Vault to retrieve them. Managed identities for Azure resources help to solve this problem by giving Azure services an automatically managed identity in Azure Active Directory (Azure AD). You can use this identity to authenticate to any service that supports Azure AD authentication, including Key Vault, without having to display credentials in your code.
  1. Create and assign a managed identity. Navigate to Azure CLI and execute below command

     az webapp identity assign --name "<webappName>" --resource-group "resourceGroup"

     2. On success we should get back below JSON in response. 

     {
    "principalId": "xxxx", "tenantId": "xxxxx", "type": "SystemAssigned" }

     3. To give your web app permission to do get and list operations on your key vault,                       execute below command

    az keyvault set-policy --name "<keyvaultName>" --object-id "<principalId>" --secret-permissions get list

      4. In the Startup.cs file of the project add below

    using Azure.Identity;
    using Azure.Security.KeyVault.Secrets;
    using Azure.Core;
    var options = new SecretClientOptions()
        {
            Retry =
            {
                Delay= TimeSpan.FromSeconds(2),
                MaxDelay = TimeSpan.FromSeconds(16),
                MaxRetries = 5,
                Mode = RetryMode.Exponential
             }
        };
    var client = new SecretClient(new Uri("https://keyVaultName.vault.azure.net/"), new DefaultAzureCredential(),options);
    
    KeyVaultSecret secret = client.GetSecret("secretName");
    
    string secretValue = secret.Value;
5. Deploy the app to Azure.

Git - Clear history

          

Scenario: Start afresh for your Git repository

Solution:

1. Git Bash -> navigate to your repository and execute below command line commands.

    -- Remove the history from
    rm -rf .git
    -- recreate the repository from the current content only
    git init
    git add .
    git commit -m "Initial commit"
    -- push to the github remote repository [overwrite history]
    git remote add origin git@github.com:<Account>/<Repository>.git
    git push -u --force origin master

  

Move Github Sub Repository back to main repo

 -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...