1 Kasım 2023

Rosyln Compiler - Memory Leak Free(Disposable)

Original Article: https://carljohansen.wordpress.com/2020/05/09/compiling-expression-trees-with-roslyn-without-memory-leaks-2/

I register handlebars helper for my codes that could be editable from text file.

Aim: Invoke public methods with TemplateHelper attribute.

Example Text File that contains C# Code:


using HandlebarsDotNet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RosylnCompilerDemo
{
    public class DigitalInsertHandlebarsHelpers
    {
        [TemplateHelper]
        public void RegisterPriceWhole(IHandlebars _handlebars)
        {
            _handlebars.RegisterHelper("Price.Whole", (writer, context, arguments) =>
            {
                if (!arguments.Any())
                {
                    throw new HandlebarsException("Correct Format: {{#Price.Whole decimalPrice seperator}}, {{Price.Whole decimalPrice}}");
                }
                var price = arguments.At<string>(0);
                if (!string.IsNullOrWhiteSpace(price))
                {
                    string seperator = ",";
                    if (arguments.Length == 2)
                    {
                        seperator = arguments.At<string>(1);
                    }
                    price = price.Split(seperator).FirstOrDefault();
                }
                writer.WriteSafeString($"{price}");
            });
        }

        [TemplateHelper]
        public void RegisterPriceFraction(IHandlebars _handlebars)
        {
            _handlebars.RegisterHelper("Price.Fraction", (writer, context, arguments) =>
            {
                if (!arguments.Any())
                {
                    throw new HandlebarsException("Correct Format: {{#Price.Fraction decimalPrice seperator}}, {{Price.Whole decimalPrice}}");
                }
                var price = arguments.At<string>(0);
                if (!string.IsNullOrWhiteSpace(price))
                {
                    string seperator = ",";
                    if (arguments.Length == 2)
                    {
                        seperator = arguments.At<string>(1);
                    }
                    price = price.Split(seperator).LastOrDefault();
                }
                writer.WriteSafeString($"{price}");
            });
        }
    }
}





Code File:

using HandlebarsDotNet;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System.Reflection;
using System.Runtime.Loader;

namespace RosylnCompilerDemo
{
    public class TemplateHelperOperations
    {
        private class CollectibleAssemblyLoadContext : AssemblyLoadContext, IDisposable
        {
            public CollectibleAssemblyLoadContext() : base(true)
            { }

            protected override Assembly Load(AssemblyName assemblyName)
            {
                return null;
            }

            public void Dispose()
            {
                Unload();
            }
        }

        public static void RegisterHelpers(string code, IHandlebars handlebars)
        {
            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            List<Assembly> assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();

            var references = assemblies.Where(q => !string.IsNullOrWhiteSpace(q.Location))
                .Select(q => MetadataReference.CreateFromFile(q.Location)).ToList();

            var syntaxTree = SyntaxFactory.ParseSyntaxTree(code);
            var assemblyName = $"TempAssembly{Guid.NewGuid()}";
            var compilation = CSharpCompilation.Create(assemblyName)
                                .WithOptions(compilationOptions)
                                .AddReferences(references)
                                .AddSyntaxTrees(syntaxTree);


            using (var assemblyLoadContext = new CollectibleAssemblyLoadContext())
            using (var ms = new MemoryStream())
            {
                var emitResult = compilation.Emit(ms);
                if (emitResult.Success)
                {
                    ms.Seek(0, SeekOrigin.Begin);

                    // Load the compiled assembly
                    var assembly = Assembly.Load(ms.ToArray());

                    // Execute the library code
                    var helperMethods = assembly.GetTypes()
                        .Where(q => q.IsClass && q.IsPublic)
                        .Select(q => new { ClassName = q.FullName, Methods = q.GetMethods().Where(m => m.IsPublic && m.GetCustomAttributes(typeof(TemplateHelperAttribute), false).FirstOrDefault() != null) })
                        .Where(q => q?.Methods?.Any() ?? false)
                        .ToList();


                    foreach (var cls in helperMethods.Where(q => q.Methods?.Any() ?? false).GroupBy(q => q.ClassName))
                    {
                        if (!string.IsNullOrWhiteSpace(cls.Key))
                        {
                            var libClassType = assembly.GetType(cls.Key);
                            var libraryInstance = Activator.CreateInstance(libClassType);
                            foreach (var item in cls)
                            {
                                foreach (var method in item.Methods)
                                {
                                    method.Invoke(libraryInstance, new object[] { handlebars });
                                }
                            }
                        }
                    }
                }
                else
                {
                    foreach (var diagnostic in emitResult.Diagnostics)
                    {
                        Console.WriteLine(diagnostic.ToString());
                    }
                }
            }
        }
    }

}

8 Şubat 2023

SQL Cloning Database

dbbackup.bat

sqlcmd -S SERVERNAME\SQLEXPRESS -E -i backupdb.sql


-------------------------------------------------------------------------------------------

backupdb.sql
 
declare     @backupDB nvarchar(128),
    @restoreDB nvarchar(128),
    @backupFolder nvarchar(512),
    @dataFolder nvarchar(512);

set @backupDB = 'SampleDB';
set @restoreDB = 'SampleDBX';
set @backupFolder = 'C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\Backup\';
set @dataFolder = 'C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\DATA\';

declare @diskName nvarchar(512);
set @diskName = @backupDB + '-' +REPLACE(REPLACE(CONVERT(VARCHAR(128),GETDATE(),20),' ','-'),':','-') + '.bak';
set @diskName = @backupFolder + @diskName;

backup database @backupDB to disk = @diskName

declare @sql nvarchar(max)
set @sql = 'alter database ' + @restoreDB + ' set single_user with rollback immediate';
exec(@sql);

set @sql = 'restore database ' + @restoreDB + ' from disk = N'''+ @diskName +''''
+ ' with file = 1, '
+ ' move N'''+@backupDB+''' to N''' + @dataFolder + @restoreDB + '.mdf'', '
+ ' move N'''+@backupDB+'_log'' to N''' + @dataFolder + @restoreDB + '_log.ldf'', '
+ ' KEEP_REPLICATION,  NOUNLOAD,  REPLACE,  STATS = 5'
exec(@sql);

set @sql = 'alter database ' + @restoreDB + ' set MULTI_USER';
exec(@sql);

8 Aralık 2022

Basit Encrpytion C# and JS

!Don't use it for important data.

I use it to prevent search engines from collecting data.


.C#


 public static class EasyCrypt

    {

        public static string Encrypt(string input, int shft)

        {

            if (string.IsNullOrEmpty(input))

                return string.Empty;

            return Convert.ToHexString(input.Select(c => Convert.ToByte((((int)c) + shft) % 255)).ToArray());

        }


        public static string Decrypt(string input, int shft)

        {

            if (string.IsNullOrEmpty(input))

                return string.Empty;

            return System.Text.ASCIIEncoding.ASCII.GetString(

                Convert.FromHexString(input).Select(b => Convert.ToByte(((int)b + 255 - shft) % 255)).ToArray());

        }

    }


JS


const cardNo = '321321312';


function encrypt(text, shft = 83) {

    if (text == null ||

        typeof (text) == 'undefined' ||

        text.length < 1)

        return '';

    let encrypted = '';

    for (let i = 0; i < text.length; i += 1) {

        const  charCode = text.charCodeAt(i);

        let shiftedChar = (charCode + shft) % 255;

        encrypted += shiftedChar.toString(16);

    }

    return encrypted;

}


function decrypt(text, shft = 83) {

    if (text == null ||

        typeof (text) == 'undefined' ||

        text.length < 1)

        return '';

    let decrypted = '';

    for (let i = 0; i < text.length; i += 2) {

        const hex = text.substring(i, i + 2);

        const charCode = parseInt(hex,16);        

        let shiftedChar = (255 +(charCode - shft)) % 255;

        decrypted += String.fromCharCode(shiftedChar);

    }

    return decrypted;

}


const encryptedCardNo = encrypt(cardNo);

const decryptedCardNo = decrypt(encryptedCardNo);

console.log(cardNo);

console.log(encryptedCardNo);

console.log(decryptedCardNo);

23 Kasım 2022

CIDR (Classless Inter-Domain Routing) Notation


{8Bits}. {8Bits}. {8Bits}. {8Bits} / {Allocated Bits}

00000000 = 0

11111111 = 255

 Example: 102.123.149.240 / 24

 

Allocated Bits To Address         Allocated For Range

102.123.149                                .240 / 24                       => 102.123.149.000 - 102.123.149.255

102.123                                       .149.240 / 16                => 102.123.000.000 - 102.123.255.255

102.123                                       .149.240 / 20                => 102.123.144.000 - 102.123.159.255 

 

Algorithm For 102.123.149/20

102.123 => 8+8 => 16 Bits Used Remained 4

149 => 1 0 0 1 0 1 0 1 => 1 + 4 + 16 +128 

First 4 are allocated we will use remained ones

1 0 0 1 0 0 0 0  to 1 0 0 1 1 1 1 1

=> 128+16 to 128+16+8+4+2+1

=> 144 to 159

Thus =>

102.123.144.000 - 102.123.159.255  

 

3 Kasım 2022

RSA C#

  internal class Program

    {

        static void Main(string[] args)

        {

            

            IRSAEncryption rsa = new RSAEncryption();

            // Use only one time for generating keys

            //rsa.GenerateKeys("mx.pub","px.pem");


            var text = "Fıstıkçı Şahap 2";

            var encryptedText = rsa.Encrypt(text, "mx.pub");

            Console.WriteLine($"Encrpyted: {encryptedText}");

            //var decryptedText = rsa.Decrypt(encryptedText, "mx.pem");

            //Console.WriteLine($"Decrypted: {decryptedText}");



        }


    }


public interface IRSAEncryption

    {

        public void GenerateKeys(string pathPublicKey, string pathPrivateKey);

        public string Encrypt(string plainText, string pathPublicKey);

        public string Decrypt(string encrpyedText, string pathPrivateKey);

    }


public class RSAEncryption : IRSAEncryption

    {

        private string ByteArrayToString(byte[] bytes)

        {

            var sb = new StringBuilder(bytes.Length * 2);

            foreach (var b in bytes)

            {

                sb.AppendFormat("{0:x2}", b);

            }

            return sb.ToString();

        }


        public static byte[] StringToByteArray(String hex)

        {

            int NumberChars = hex.Length;

            byte[] bytes = new byte[NumberChars / 2];

            for (int i = 0; i < NumberChars; i += 2)

                bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);

            return bytes;

        }


        private RSAParameters ImportKey(string path)

        {

            var serializer = new XmlSerializer(typeof(RSAParameters));

            using (var fs = new FileStream(path, FileMode.Open))

            {

                return (RSAParameters)serializer.Deserialize(fs);

            }

        }


        private void ExportKey(RSAParameters parameters, string path)

        {

            var serializer = new XmlSerializer(typeof(RSAParameters));

            using (var fs = new FileStream(path, FileMode.CreateNew))

            using (var sw = new StreamWriter(fs, Encoding.UTF8))

            {

                serializer.Serialize(sw, parameters);

            }

        }



        public string Decrypt(string encrpyedText, string pathPrivateKey)

        {

            using (var rsa = new RSACryptoServiceProvider())

            {

                var pubKey = ImportKey(pathPrivateKey);

                rsa.ImportParameters(pubKey);

                var data = StringToByteArray(encrpyedText);

                var cypher = rsa.Decrypt(data, false);

                return Encoding.UTF8.GetString(cypher);

            }

        }


        public string Encrypt(string plainText, string pathPublicKey)

        {

            using (var rsa = new RSACryptoServiceProvider())

            {

                var pubKey = ImportKey(pathPublicKey);

                rsa.ImportParameters(pubKey);

                var data = Encoding.UTF8.GetBytes(plainText);

                var cypher = rsa.Encrypt(data, false);

                return ByteArrayToString(cypher);

            }

        }


        public void GenerateKeys(string pathPublicKey, string pathPrivateKey)

        {

            using (var rsa = new RSACryptoServiceProvider(2048))

            {

                var pem = rsa.ExportParameters(true);

                var pub = rsa.ExportParameters(false);

                ExportKey(pem, "mx.pem");

                ExportKey(pub, "mx.pub");

            }

        }

    }

15 Ekim 2022

PostgreSql PgAdmin Docker Çalıştırma

 docker-compose.yaml dosyası aşağıdaki gibidir.

services:
  pgadmin:
    environment:
      PGADMIN_DEFAULT_EMAIL: PGAdminMail@mail.com
      PGADMIN_DEFAULT_PASSWORD: PGAdminPassword
    image: dpage/pgadmin4
    ports:
    - published: 5080
      target: 80
  postgres:
    environment:
      POSTGRES_DB: PostgresDefaultDB
      POSTGRES_PASSWORD: PostgresDefaultPassword
      POSTGRES_USER: PostgresDefaultUsername
    image: postgres
    ports:
    - published: 5432
      target: 5432
version: '3.9'

 

docker-compose config ile config kontrol edilir hata varsa güncel bilgilere göre google dan aratıp düzeltin.

docker compose up --build ile çalıştırılır

 

http://localhost:5080/ adresinden yaml da yazdığınız kullanıcı adı ve şifre ile PG Amin'e giriş yapınız.

terminal de
docker ps 

yazarak postgres in ContainerID sini alalım benim örnekte  44b778e8e612

daha sonra docker inspect 44b yazarak işlemin IP adresini bulalım

Benim örnek te

"IPAddress": "172.19.0.3",

IP adres ve YAML a girilen bilgilerdeki kullanıcı adı şifre ile Postgres e bağlanabilirsiniz.




19 Eylül 2022

Types Of Cloud Services and Types of Clouds

 

Types of Cloud Services

IaaS

Infrastructure as a Service

The cloud provides the underlying platforms

  • Compute

  • Networking

  • Storage

The client handles and is responsible for all the rest. In other words, the cloud provides minimum infrastructure and we the clients of cloud are expected to take care of all the rest.

The most common example of IaaS is Virtual Machines.

The clouds provide the host machine, networking and disks.

The client creates the virtual machine, installs software on it, patches it, maintains it etc. So it is the responsibility of the client to make sure that the virtual machine is up and running, and the cloud has nothing to do with it.



PaaS

Platform as a Service

The cloud provides a platform for running apps.

Including Compute, networking, storage, runtime environment, scaling redundancy, security, updates, patching, maintenance etc.

The client just needs to bring the code to run

As a developer we just write the codes and upload it to cloud and the cloud takes care of all the rest.

Most common examples: Web Apps

The cloud provides the runtime for running web apps

The client uploads the code, and it just runs

The client has no access to the underlying virtual machines





SaaS

Software as a Service

A software running completely in the cloud.

The user doesn’t need to install anything on premises or on his machine

The provider of the software takes care of updates, patches, redundancy, scalability etc.

Common Examples: Office 365, SalesForce

We have no idea what is the infrastructure that Office 365 and Salesforce are running on

What are the virtual machines, what language are they developed in, what is a database and so on.



Types of Clouds

Public Cloud

The cloud is set up in the public network

Managed by large companies

Accessible through the internet

Available to all clients and users

Clients have no access to underlying infrastructure

Examples: AWS, Azure, Google Clouds, IBM Clouds



Private Cloud

A cloud set up in an organization’s premises

Managed by the organization’s IT team

Accessible only in the organization’s network

Available to users from the organizations

Uses private cloud infrastructure and engines

Contains a subset of the public cloud’s capabilities

Examples VMWare Cloud, Red Hat OpenShift Container Platform, Azure Stack

Used for privacy and security issues





Hybrid Cloud

A cloud set up in organization’s premises but also connected to the public cloud

Workload can be separated between the two clouds. For instance, sensitive data in the organization’s premises, public data in the public cloud.

So, for example, the organization can decide that the usernames, passwords and credit cards of its users will be stored inside the organization’s premises, but for example the professional profile of its users, such as the ones in LinkedIn will be stored in the public cloud.

Examples: Azure Arc, AWS Outposts

23 Mayıs 2022

Python PyJWT Equivelent in C#

using System.Security.Cryptography; using System.Text; public class PyJwt { public static string Encode(string clientId, string secret) { var algorithm = "{\"typ\":\"JWT\",\"alg\":\"HS256\"}"; var data = "{\"clientID\":\"" + clientId + "\"}"; var header = Convert.ToBase64String(Encoding.UTF8.GetBytes(algorithm)); var payload = Convert.ToBase64String(Encoding.UTF8.GetBytes(data)); var key = Convert.ToBase64String(Encoding.UTF8.GetBytes(secret)); string signature = string.Empty; using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key))) { var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes($"{header}.{payload}")); signature = Convert.ToBase64String(hash) .Replace("+", "-") .Replace("/", "_") .Replace("=", ""); } return $"{header}.{payload}.{signature}"; } }

31 Mart 2022

Online Base64 Encoder





24 Mart 2022

SignedString Sınıfı

 Dışarıya açık dosya paylaşmada URL i zaman bazlı kısıtlamak için oluşturulmuş kod parçaları.

EncryptTool.cs

using System;

using System.Security.Cryptography;

using System.Text;


namespace SampleSigner

{

    public static class EncryptTool 

    {

        public static byte[] EncryptSha5126(string plainText)

        {

            if (string.IsNullOrEmpty(plainText))

            {

                throw new ArgumentNullException(nameof(plainText));


            }

            using (var sha = SHA512.Create())

                return sha.ComputeHash(Encoding.UTF8.GetBytes(plainText));

        }


        /// <summary>

        /// 

        /// </summary>

        /// <param name="plainText"> Not Null</param>

        /// <param name="key">byte[64] random bytes</param>

        /// <returns></returns>

        public static byte[] HmacSha256(string plainText, byte[] key)

        {

            if (key == null)

                throw new ArgumentNullException(nameof(key));

            if (key.Length != 64)

                throw new ArgumentException("key.length must be 64");

            if (string.IsNullOrEmpty(plainText))

                throw new ArgumentNullException(nameof(plainText));


            using (HMACSHA256 hmac = new HMACSHA256(key))

            {

                return hmac.ComputeHash(Encoding.UTF8.GetBytes(plainText));

            }

        } 

    }

}



// SignedStringSettings.cs

using System;

namespace SampleSigner
{
    public class SignedStringSettings
    {
        /// <summary>
        /// Key olarak proje her başlatıldığında key değişsin diye dinamik guid üretilmiştir.
        /// İsteyen gömülü key kullanabilir. 
        /// Ben dosya paylaşım süresini uzun tutmayacağım için Guid benim için sorun değil
        /// </summary>
        private SignedStringSettings()
            :this(Guid.NewGuid().ToString())
        {

        }
        private SignedStringSettings(string key)
        {
            var bytes = EncryptTool.EncryptSha5126(key);
            byte[] data = new byte[64];
            Array.Copy(bytes, 0, data, 0, 64);
            Key = data;
        }

        public static readonly Lazy<SignedStringSettings> _instance
            = new Lazy<SignedStringSettings>(() => new SignedStringSettings());

        public static SignedStringSettings Instance => _instance.Value;

        public byte[] Key { get; private set; }

    }
}


// SignedString.cs

using System;
using System.Security.Cryptography;
using System.Text;

namespace SampleSigner
{
    public class SignedString
    {
        private string _text { get; set; }
        private long _validUntil { get; set; }

        private SignedString(string text, DateTimeOffset validUntil)
        {
            _validUntil = validUntil.ToUnixTimeSeconds();
            _text = Sign(text, _validUntil);
        }

        private SignedString(string text)
        {
            _text = text;
        }



        public static SignedString CreateNew(string text, DateTimeOffset to)
        {
            return new SignedString(text, to);
        }
        public static SignedString CreateNew(string text, TimeSpan time)
        {
            return new SignedString(text, DateTimeOffset.UtcNow.Add(time));
        }

        public static SignedString Load(string text)
        {
            return new SignedString(text);
        }



        private string Sign(string text, long validUntil)
        {
            var plainText = Convert.ToBase64String(Encoding.UTF8.GetBytes(text));
            plainText += $".{validUntil}";
            var computedHash = EncryptTool.HmacSha256(plainText, SignedStringSettings.Instance.Key);
            return $"{plainText}.{Convert.ToBase64String(computedHash)}";
        }

        private bool Verify(string signedText, byte[] key)
        {
            if (string.IsNullOrWhiteSpace(signedText))
                throw new ArgumentNullException(nameof(signedText));

            var parts = signedText.Split('.');

            if (parts.Length != 3
                || string.IsNullOrWhiteSpace(parts[0])
                || string.IsNullOrWhiteSpace(parts[1])
                || string.IsNullOrWhiteSpace(parts[2]))
                throw new ArgumentException("Invalid String");

            
           

            byte[] computedBytes = null;
            using (HMACSHA256 hmac = new HMACSHA256(key))
            {
                var checkText = signedText.Substring(0, signedText.LastIndexOf("."));
                computedBytes = EncryptTool.HmacSha256(checkText, SignedStringSettings.Instance.Key);
            }
            var signBytes = Convert.FromBase64String(parts[2]);

            if (computedBytes == null
                || (computedBytes.Length != signBytes.Length))
                return false;

            for (int i = 0; i < computedBytes.Length; i++)
            {
                if (computedBytes[i] != signBytes[i])
                {
                    return false;
                };
            }
            var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
            var until = Convert.ToInt64(parts[1]);

            return now < until;
        }

        public override string ToString()
        {
            return _text;
        }

        public bool IsValid => Verify(_text, SignedStringSettings.Instance.Key);

        public string ToUnsignedString()
        {
            if (IsValid)
            {
                var parts = _text.Split(".");
                var byteText = Convert.FromBase64String(parts[0]);
                return Encoding.UTF8.GetString(byteText);
            }
            else return string.Empty;
        }
    }
}

// Program.cs

using System;
using System.Threading;

namespace SampleSigner
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var plainUrl = "https://www.muharrembarkin.com/";
            var sample = SignedString.CreateNew(plainUrl, TimeSpan.FromSeconds(5));
            // Url is valid 5 seconds
            var signedUrl = sample.ToString();
            Console.WriteLine($"Signed Url: {sample}");

            Console.WriteLine();

            //  1 second later  valid
            Thread.Sleep(1000);
            var sample2 = SignedString.Load(signedUrl);
            Console.WriteLine($"Is Valid after 1 seconds: {sample2.IsValid}");
            Console.WriteLine();
            Console.WriteLine("1 Second later Unsigned Url: " + sample2.ToUnsignedString());
            Console.WriteLine();
            //  6 second later not valid
            Thread.Sleep(5000);
            Console.WriteLine($"Is Valid after 6 seconds: {sample2.IsValid}");
            Console.WriteLine();
            Console.WriteLine("6 Second later Unsigned Url: " + sample2.ToUnsignedString());

            Console.WriteLine();
            var sample3 = SignedString.CreateNew(plainUrl, TimeSpan.FromSeconds(30));
            Console.WriteLine($"Signed Url: {sample3}");
            Console.WriteLine();
            Console.WriteLine("lets change one character of signed url");
            var signedUrl2 = sample3.ToString();
            signedUrl2 = signedUrl2.Substring(0, signedUrl2.Length - 1) + "a";
            Console.WriteLine("Changed Url: " + signedUrl2);
            Console.WriteLine();
            var sample4 = SignedString.Load(signedUrl2);
            Console.WriteLine($"Is valid changed url: {sample4.IsValid}");
            Console.WriteLine();
            Console.WriteLine($"UnsignedString changed url: {sample4.ToUnsignedString()}");
            Console.WriteLine();
            Console.WriteLine("Re test original url");
            var sample5 = SignedString.Load(sample3.ToString());
            Console.WriteLine($"IsValid: {sample5.IsValid}");
            Console.WriteLine($"UnsignedString: {sample5.ToUnsignedString()}");

        }
    }
}