Tuesday, May 24, 2022

Mongo db query

 Query

> use s27_events


  1. SELECT * FROM Profile

    db.Profile.find ({})

  2. SELECT * FROM Profile WHERE Name = "Chamith"

    db.Profile.find({Name:"Chamith"})

  3. SELECT * FROM Profile WHERE Name = "Chamith" AND Dob = "1988-01-24" AND Setting.Security._2fa = false

    db.Profile.find({Name:"Chamith",Dob:"1988-01-24",Setting:{Security:{_2fa:false}}})



Update

update/add a new field to the collection


db.Profile.update({},{$set:{ProfileImage:"chamith.png"}})

db.Profile.update({},{$unset:{ProfileImage:"chamith.png"}})

db.Profile.update({},{$set:{ProfileImage:[{Url:"chamith1",IsDefault:false},{Url:"chamith2",IsDefault:true}]}})

db.Profile.update({},{$set:{Setting:{Security:{ _2fa:false}}}})

db.Profile.update({_id:ObjectId('628cae92a72e5e4316a8a8a5')},{$set:{Setting:{Preferences:{Country:"Sri Lanka",Currency:"LKR"},Security:{_2fa:true}}}})




Wednesday, February 24, 2021

Digital signature apply to http request body

 public CheckValiedContent (HttpRequest request){

          string xeroPrivateKey = Environment.GetEnvironmentVariable("XEROKEY");

          var signatureHeader = request.Headers["x-xero-signature"];
          var requestBody = request.Body;

         var resultSignature = GenarateSignature(requestBody,xeroPrivateKey);

         if (signatureHeader != resultSignature){
            return 401
        }

 }


 public string GenerateSignature(string dataToHash, string xeroKey)
        {
            using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(xeroKey)))
            {
                var messageBytes = Encoding.UTF8.GetBytes(dataToHash);
                var hash = hmac.ComputeHash(messageBytes);
                return Convert.ToBase64String(hash);
            }
        }

Wednesday, February 10, 2021

Backend best practices

 Select praticulr coloms from database (EF)


https://git.itelasoft.com.au/chamith.saranga/broker-service/blob/master/Application/Services/BankStatementService.cs#L544

return await DataContext.BankStatements
                .Where(s => bankStatementIds.Contains(s.RequestId))
                .Include(s => s.Applicant).Include(s => s.Lender)
                .Select(m => new BankStatementModel
                {
                    RequestId = m.RequestId,
                    ApplicantId = m.ApplicantId,
                    ApplicantName = $"{m.Applicant.FirstName} {m.Applicant.LastName}",
                    IsPrimaryApplicant = m.Applicant.PrimaryApplicant,
                    LenderId = m.LenderId,
                    LenderName = m.Lender != null?m.Lender.Name : m.LenderName,
                    LenderLogo = m.Lender.Logo,
                    Deprecated = m.Deprecated,
                    Provider = m.Provider,
                    RequestVersion = m.RequestVersion
                }).ToListAsync();

EF.Function
https://git.itelasoft.com.au/chamith.saranga/broker-service/blob/master/Application/Services/ProductService.cs#L134
           if (!string.IsNullOrWhiteSpace(name))           
                query = query
                    .Where(p => EF.Functions.Like(p.Name, $@"%{name}%"));          

Monday, February 8, 2021

.Net Core Utilities

 Audit Filter 

 public class AuditFilter : IAsyncActionFilter
    {
        /// <summary>
        /// The Logger
        /// </summary>
        private readonly ILogger<AuditFilter> logger;


        /// <summary>
        /// Constructs an Audit Filter
        /// </summary>
        /// <param name="logger"></param>
        public AuditFilter(ILogger<AuditFilter> logger)
        {
            this.logger = logger;
        }


        /// <summary>
        /// This method is called just before an action is invoked
        /// </summary>
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            LogRequest(context);
            await next();
        }


        /// <summary>
        /// Logs the request information about the request 
        /// </summary>
        /// <param name="context">The Action Executing Context</param>
        private void LogRequest(ActionExecutingContext context)
        {
            Dictionary<string, object> routeData = null;

            if (context.HttpContext.Request.ContentType == null
                || !context.HttpContext.Request.ContentType.Contains("multipart/form-data"))
                routeData = context.ActionArguments?.ToDictionary(kv => kv.Key, kv => kv.Value);

            var request = new
            {
                RequestId = context.HttpContext.TraceIdentifier, // Request identifier ({ConnectionId:RequestNumber}) generated by Kestrel
                RouteData = routeData, // Route parameters (including anything taken from request body)
                UserId = context.HttpContext.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value, // User Id
                Name = context.HttpContext.User?.FindFirst(ClaimTypes.Name)?.Value, // User Name
                Date = DateTime.UtcNow, // Date and time in UTC
                Operation = $"{context.HttpContext.Request.Path}-{context.HttpContext.Request.Method}", // Endpoint - HTTP verb
            };

            logger.LogInformation(JsonConvert.SerializeObject(request));
        }
    }

Thursday, February 27, 2020

Run CMD From C sharp

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DockerRunner
{
    delegate void SetMergerTextCallback(string text);
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Process _Process;
        private void Button1_Click(object sender, EventArgs e)
        {
            Execute("echo chamith");
        }
        private Process ConfigureFfmpeg()
        {
            _Process = new Process();
            _Process.StartInfo.FileName = "cmd";
            _Process.StartInfo.UseShellExecute = false;
            _Process.StartInfo.RedirectStandardOutput = true;
            _Process.StartInfo.RedirectStandardInput = true;
            _Process.StartInfo.CreateNoWindow = true;
            return _Process;
        }

        private void Execute(string argument)
        {

            var process = ConfigureFfmpeg();
           process.OutputDataReceived += p_OutputDataReceived;
            process.Start();
            process.StandardInput.WriteLine(argument);
            process.BeginOutputReadLine();
        }
        StringBuilder sb = new StringBuilder();
        private void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            sb.Append(e.Data + Environment.NewLine);
            SetText(sb.ToString());
        }

        private void SetText(string text)
        {
            if (this.richTextBox1.InvokeRequired)
            {
                SetMergerTextCallback d = new SetMergerTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.richTextBox1.Text = text;
            }
        }
    }
}

Sql server row level policy