3 Ekim 2024

JS Parse Excel From Clipboard

 <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table,
        th,
        td {
            border: 1px solid black;
        }
    </style>
</head>

<body>
    <textarea id="txtData" style="width: 100%;height: 300px;">

    </textarea>
    <hr>
    <table id="tblData">
        <thead>
            <tr>
                <th>E-Mail</th>
                <th>Name</th>
                <th>Surname</th>
                <th>Reference</th>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>

    <script>
        function parseData(rawText) {
            var tblData = document.querySelector('#tblData tbody');
            tblData.innerHTML = '';
            rawText = rawText.trim();
            var trs = rawText.split('\n');
            if (trs != null && trs.length > 0) {
                for (var i = 0; i < trs.length; i++) {
                    var tds = trs[i].trim().split('\t');
                    if (tds.length == 4) {
                        let tr = document.createElement('tr');

                        for (var j = 0; j < tds.length; j++) {
                            let td = document.createElement('td');
                            td.innerText = tds[j];
                            tr.appendChild(td);
                        }
                        tblData.appendChild(tr);
                    }
                }
            }
            console.log(rawText);
        }
        document.getElementById("txtData").addEventListener('change', function (e) {
            parseData(e.target.value);
        }, false);
    </script>
</body>

</html>

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