22 Kasım 2021

PostgreSQL Sequence Set


ERROR: duplicate key value violates unique constraint "pkey"

DETAIL: Key (id)=(1503) already exists. SQL state: 23505



SELECT MAX(the_primary_key) FROM the_table;   
SELECT nextval('the_primary_key_sequence');


Get Sequence Name

 select pg_get_serial_sequence('tableName','columnName')


Set Sequence Name
SELECT setval('the_primary_key_sequence', (SELECT MAX(the_primary_key) FROM the_table)+1);

VEYA
SELECT setval(pg_get_serial_sequence('tableName','columnName'), (SELECT MAX(columnName) FROM tableName)+1);




5 Kasım 2021

PHP - .NET Uyumlu AES Şifreleme

 C#

using System.Security.Cryptography;

using System.Text;


namespace ConsoleApp16

{

    public class Program

    {

        public static void Main()

        {

            var plain = "Lorem Ipsum";

            var encryptSettings = new EncryptSettings();

            var encryptTools = new EncryptTools(encryptSettings);

            var encrypted = encryptTools.AesEncrypt(plain);

            Console.WriteLine("Encrypted");

            Console.WriteLine(encrypted);

            Console.WriteLine();

            Console.WriteLine("Decrypted");

            var text = encryptTools.AesDecrypt(encrypted);

            Console.WriteLine(text);

        }

    }

    public class EncryptSettings

    {

        public string Key { get; set; }


        public EncryptSettings()

        {

            Key = "passwordstring";

        }

    }


    public class EncryptTools

    {

        private readonly EncryptSettings encryptSettings;


        public EncryptTools(EncryptSettings encryptSettings)

        {

            this.encryptSettings = encryptSettings;

        }


        private byte[] key => Sha256Byte(encryptSettings.Key);

        private byte[] iv => new byte[16] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };


        public string AesEncrypt(string plainText)

        {

            if (plainText == null || plainText.Length <= 0)

                throw new ArgumentNullException("plainText");

            if (key == null || key.Length <= 0)

                throw new ArgumentNullException("Key");

            if (iv == null || iv.Length <= 0)

                throw new ArgumentNullException("IV");

            byte[] encrypted;


            using (var aes = Aes.Create())

            {

                aes.Mode = CipherMode.CBC;

                aes.Key = key;

                aes.IV = iv;


                using (var ms = new MemoryStream())

                {

                    using (ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV))

                    using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))

                    using (StreamWriter swEncrypt = new StreamWriter(cs))

                    {

                        swEncrypt.Write(plainText);

                    }

                    encrypted = ms.ToArray();

                }

            }

            return Convert.ToBase64String(encrypted);

        }


        public string AesDecrypt(string encryptedText)

        {

            var cipherText = Convert.FromBase64String(encryptedText);


            if (cipherText == null || cipherText.Length <= 0)

                throw new ArgumentNullException("cipherText");

            if (key == null || key.Length <= 0)

                throw new ArgumentNullException("Key");

            if (iv == null || iv.Length <= 0)

                throw new ArgumentNullException("IV");


            string plaintext = null;


            using (Aes aes = Aes.Create())

            {

                aes.Mode = CipherMode.CBC;

                aes.Key = key;

                aes.IV = iv;


                using (MemoryStream msDecrypt = new MemoryStream(cipherText))

                using (ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV))

                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))

                using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                {

                    plaintext = srDecrypt.ReadToEnd();

                }

            }


            return plaintext;

        }


        public byte[] Sha256Byte(string plainText)

        {

            byte[] bytes = null;

            using (SHA256 sha256Hash = SHA256.Create())

            {

                bytes = sha256Hash.ComputeHash(Encoding.ASCII.GetBytes(plainText));

            }

            return bytes;

        }

    }


}

PHP

<?php

function encrypt_decrypt($string, $action = 'encrypt')
{
$encrypt_method = "aes-256-cbc";
$secret_key = 'passwordstring'; // user define private key
$key = substr(hash('sha256', $secret_key, true), 0, 32);
$iv = chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0);
if ($action == 'encrypt') {
$output = openssl_encrypt($string, $encrypt_method, $key, OPENSSL_RAW_DATA, $iv);
$output = base64_encode($output);
} else if ($action == 'decrypt') {
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, OPENSSL_RAW_DATA, $iv);
}
return $output;
}
echo encrypt_decrypt('CSBx7hQRszpDKM9Vfxy8qQ==', 'decrypt');

?>

14 Ekim 2021

6 Karakterli Unique Key Üretme

 using System;

using System.Collections.Generic;
using System.Text;

namespace ConsoleApp14
{
    class Program
    {
       
        static void Main(string[] args)
        {
            var generatedKeys = new List<string>();
            for (int i = 0; i < 100000; i++)
            {
                var key = KeyGenerator.Generate(i);
                if (generatedKeys.Contains(key))
                    throw new Exception("Tekrar eden numaralar var");
                Console.WriteLine(key);
                generatedKeys.Add(key);
            }
        }
    }

    public static class KeyGenerator
    {
        // chars count must be prime number
        // (mine are 31 i also shuffled them you can re shuffle your letters)
        private static readonly char[] chars = {
                'C', 'V', 'M', 'J', '4', 'E', 'Y','L','R','N','9','5','Z','3','X',
                'D','8','G','T','6','K','W','P','B','S','U','F','H','A','2','7'
            };
        private static int Mod(int a, int b)
           => ((a % b) + b) % b;

        /// <summary>
        /// Generates Unique 6 Character Key By Id
        /// </summary>
        /// <param name="index"> Min 0 Max 887,503,680</param>
        /// <returns></returns>
        public static string Generate(int index)
        {
            // I am calculating 6 digit which means 31^6 = 887503681 possible number
            // I multiplied with 2 different very big prime numbers to prevent similar generated keys
            var number = Mod((index * 8969 * 10457), 887503681);
            var sb = new StringBuilder();
            while (number > 30)
            {
                var letter = chars[(number % 31)];
                sb.Append(letter);
                number = number / 31;
            }
            sb.Append(chars[number]);
            // if it's shorter than 6 character we add last character example (1 =>001)
            while (sb.Length < 6)
            {
                sb.Insert(0, chars[30]);
            }

            return sb.ToString();
        }
    } 
}


SQL User Defined Function

create function [dbo].[udf_GenerateSixCharacterKey] 
(@index int)
returns varchar(6)  as
begin 
declare @a int, 
@b int
set @a = @index * 8969 * 10457
set @b = 887503681

declare @number int
set @number = ((@a % @b) + @b) % @b

declare @chars varchar(31)
set @chars = 'CVMJ4EYLRN95Z3XD8GT6KWPBSUFHA27'

declare @key varchar(6)
set @key = ''

while @number > 30
begin 
set @key = @key + substring(@chars, (@number % 31) + 1, 1)
set @number = @number / 31
end

set @key = @key + substring(@chars, @number + 1, 1)

while len(@key) < 6
begin
set @key = substring(@chars, 31, 1) + @key
end

return @key

end

2 Eylül 2021

AES Encryption Quick Code

using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace AesSample
{
    class Program
    {
        static void Main(string[] args)
        {
            //appsettings üzerinden okunduğunu varsayalım.
            var encryptSettings = new EncryptSettings()
            {
                IV = "LoremIpsum",
                Key = "DolorSitAmet",
            };

            IEncryptTools encryptTools = new EncryptTools(encryptSettings);

            var sampleText = "Knowing is not enough; we must apply. Willing is not enough; we must do";

            var encrypted = encryptTools.AesEncrypt(sampleText);

            Console.WriteLine("Encrypted:");
            Console.WriteLine(encrypted);
            Console.WriteLine();

            var decrypted = encryptTools.AesDecrypt(encrypted);
            Console.WriteLine("Decrypted");
            Console.WriteLine(decrypted);

        }
    }

    public interface IEncryptTools
    {
        string AesEncrypt(string plainText);
        string AesDecrypt(string encryptedText);
        byte[] Sha256Byte(string plainText);
        string Sha256String(string plainText);
        string Sha256String(byte[] bytes);
    }

    public class EncryptSettings
    {
        public string Key { get; set; }
        public string IV { get; set; }

    }

    public class EncryptTools : IEncryptTools
    {
        private readonly EncryptSettings encryptSettings;

        public EncryptTools(EncryptSettings encryptSettings)
        {
            this.encryptSettings = encryptSettings;
        }


        private byte[] key => Sha256Byte(encryptSettings.Key);
        private byte[] iv => new List<byte>(Sha256Byte(encryptSettings.IV))
            .GetRange(0, 16).ToArray();
        public string AesEncrypt(string plainText)
        {
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");
            if (key == null || key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (iv == null || iv.Length <= 0)
                throw new ArgumentNullException("IV");
            byte[] encrypted;

            using (var aes = Aes.Create())
            {
                aes.Key = key;
                aes.IV = iv;

                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                using (var ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(cs))
                        {
                            swEncrypt.Write(plainText);
                        }
                        encrypted = ms.ToArray();
                    }
                }
            }
            return Convert.ToBase64String(encrypted);
        }

        public string AesDecrypt(string encryptedText)
        {
            var cipherText = Convert.FromBase64String(encryptedText);

            if (cipherText == null || cipherText.Length <= 0)
                throw new ArgumentNullException("cipherText");
            if (key == null || key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (iv == null || iv.Length <= 0)
                throw new ArgumentNullException("IV");

            string plaintext = null;

            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = key;
                aesAlg.IV = iv;

                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }

            return plaintext;
        }

        public byte[] Sha256Byte(string plainText)
        {
            byte[] bytes = null;
            using (SHA256 sha256Hash = SHA256.Create())
            {
                bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(plainText));
            }
            return bytes;
        }

        public string Sha256String(byte[] bytes)
        {
            var builder = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                builder.Append(bytes[i].ToString("x2"));
            }
            return builder.ToString();
        }

        public string Sha256String(string plainText)
        {
            var bytes = Sha256Byte(plainText);
            return Sha256String(bytes);
        }
    }
}
 

23 Ağustos 2021

ASP.NET Core Middleware Response Body Değiştirme

using Sample.Settings;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Threading.Tasks;

namespace Sample.Middlewares
{
    public class ContentModifyMiddleware
    {
        private readonly RequestDelegate next;
        private readonly MySettings mySettings;
        public ContentModifyMiddleware(RequestDelegate next,
            MySettings mySettings)
        {
            this.next = next;
            this.mySettings = mySettings;
        }

        public async Task Invoke(HttpContext context)
        {
            // Başlangıç: Hangi Koşullarda Değiştireceğim (Opsiyonel)
            var modifyBody = false;
            object controllerName = null;
            modifyBody = (context.Request.RouteValues != null
                && context.Request.RouteValues.TryGetValue("controller", out controllerName)
                && mySettings.ReplaceTexts != null
                && mySettings.ReplaceTexts.Count > 0);
            modifyBody &= (controllerName != null && controllerName.ToString() == "Home");
            // Bitiş: Hangi Koşullarda Değiştireceğim (Opsiyonel)
          
            // Başlangıç: İçerik Değiştirilsin
            if (modifyBody)
            {
                // Orjinal Body Yedekle
                var originalBody = context.Response.Body;
               
                // Değişikliklerin Yapılacağı Yeni Body
                var newBody = new MemoryStream();
                context.Response.Body = newBody;

                // Response'u al
                await next(context);

                // Responsu string olarak oku
                newBody.Position = 0;
                var newContent = await new StreamReader(newBody).ReadToEndAsync();

                // Başlangıç: Response Üzerinde Değişiklikeri Yap
                // (Replace alanlarını appsettings.json dan okuyorum - siz gömülü kod kullanabilirsiniz.)
                foreach (var item in mySettings.ReplaceTexts)
                {
                    newContent = newContent.Replace(item.Old, item.New);
                }
                // Başlangıç: Response Üzerinde Değişiklikeri Bitiş
               
                //String üzerinde yapılan değişiklikler tekrar stream'a dönüştürülüyor. Ve değiştirilmiş stream original body ile değiştiriliyor.
                using (var stream = new MemoryStream())
                {
                    var writer = new StreamWriter(stream);
                    writer.Write(newContent);
                    writer.Flush();
                    stream.Position = 0;
                    await stream.CopyToAsync(originalBody);
                }
                newBody.DisposeAsync();
                context.Response.Body = originalBody;
            }
            // Bitiş: İçerik Değiştirilsin
            // Başlangıç: İçerik Değiştirilmeden Geç
            else
            {
                await next(context);
            }
            // Bitiş: İçerik Değiştirilmeden Geç
        }
    }
}
 

26 Mayıs 2021

MVC JQuery Validate Unobtrusive Boostrap Class

<script src="jquery.js"></script> 

<script src="jquery.validate.js"></script> 

<script src="jquery.validate.min.js"></script> 

 <script>
        var validationSettings = {
            validClass: "is-valid",
            errorClass: "is-invalid"
        };
        $.validator.setDefaults(validationSettings);
        $.validator.unobtrusive.options = validationSettings;
    </script>

22 Nisan 2021

Javascript ile HTML i PDF'e çevirme (html-to-pdfmake, pdfmake)

jsPDF düzgün bir görüntü vermediği için pdfmake ve html-to-pdfmake kullanılmıştır.

Eğer bu kütüphaneleri kullanacaksanız iki kütüphaneye de github üzerinden yıldız vermeyi unutmayın. 

Kullanılan Kütüphaneler

https://pdfmake.github.io/docs/0.1/

https://github.com/Aymkdn/html-to-pdfmake

<!doctype html>
<html lang='en'>
    <head>
        <meta charset='utf-8'>
        <title>my example</title>
        <style>
        /*Hide style for print screen*/
        
            @media print {
            .noPrint {
                display: none;
            }
        }
        </style>
    </head>
    <body>
        <div class="noPrint">
            <button type="button" onclick="downloadPdf()">PDF(HtmlToPdfMaker)</button>
            <!--Print doesn't come with pdf download option on mobile phones, but it has save as pdf option on web browsers in Windows-->
            <button type="button" onclick="window.print()">Print(Vanilla JS)</button>
        </div>
        <div id="pdfContent">
            <h1>Some Html Codes</h1>
        </div>

        <script src='https://cdn.jsdelivr.net/npm/pdfmake@latest/build/pdfmake.min.js'></script>
        <script src='https://cdn.jsdelivr.net/npm/pdfmake@latest/build/vfs_fonts.min.js'></script>
        <script src="https://cdn.jsdelivr.net/npm/html-to-pdfmake/browser.js"></script>
        <script>
            function downloadPdf() {
                var val = new htmlToPdfmake(document.getElementById('pdfContent').innerHTML);
                var dd = { content: val };
                pdfMake.createPdf(dd).download('FileName.pdf');                
            }
        </script>
    </body>
</html>

 

4 Mart 2021

Image Resize For Javascript

 //index.html

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <form>
        <button id="addNewImage" type="button">Yeni Resim Ekle</button>
        <img id="preview" width="100">
    </form>

    <script src="index.js"></script>
</body>
</html>

 

// index.js 

var btnAddNewImage = document.getElementById('addNewImage');
var imgPreview = document.getElementById('preview');
var inputInvoicePhoto = document.getElementById('invoicePhoto');

var MaxSize = 1024;

function dataURLToBlob(dataURL) {
    var BASE64_MARKER = ';base64,';
    if (dataURL.indexOf(BASE64_MARKER) == -1) {
        var parts = dataURL.split(',');
        var contentType = parts[0].split(':')[1];
        var raw = parts[1];

        return new Blob([raw], {type: contentType});
    }

    var parts = dataURL.split(BASE64_MARKER);
    var contentType = parts[0].split(':')[1];
    var raw = window.atob(parts[1]);
    var rawLength = raw.length;

    var uInt8Array = new Uint8Array(rawLength);

    for (var i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
    }

    return new Blob([uInt8Array], {type: contentType});
}

// func delegateAfterResizedImage(imageName, blob)
function resizeImage(file, delegateAfterResizedImage){
    if(file.type=="image/jpeg"){
        var reader = new FileReader();
        reader.onload = function(readerEvent){
            var image = new Image();
            image.onload = function(imageEvent){
                var canvas = document.createElement('canvas'),
                width = image.width,
                height = image.height;
                if (width > height) {
                    if (width > MaxSize) {
                        height *= MaxSize / width;
                        width = MaxSize;
                    }
                } else {
                    if (height > MaxSize) {
                        width *= MaxSize / height;
                        height = MaxSize;
                    }
                }
                canvas.width = width;
                canvas.height = height;
                canvas.getContext('2d').drawImage(image, 0, 0, width, height);
                var dataUrl = canvas.toDataURL('image/jpeg');
                console.log('dataUrl '+ dataUrl );
                var resizedImage = dataURLToBlob(dataUrl);    
                delegateAfterResizedImage(resizedImage, file.name)            
                
            }
            image.src = readerEvent.target.result;
        }
        reader.readAsDataURL(file);
    }
}

btnAddNewImage.addEventListener('click', function () {
    console.log('clicked');
    var inputSelectFile = document.createElement('input');
    inputSelectFile.type = "file";
    inputSelectFile.accept = "image/jpeg";

    inputSelectFile.addEventListener('change', function(e){
        var files = e.target.files;
        if(files!=null && files.length > 0){
            for(var i = 0; i < files.length; i++){
                var file = files[i];
                resizeImage(file, (blob, name)=>{
                    console.log(name);
                    var objectURL = URL.createObjectURL(blob);
                    imgPreview.src = objectURL;
                });
            }
        }
        inputSelectFile = null;
    })
    inputSelectFile.click();       
}, false);

7 Şubat 2021

Sudoku Çözme Algoritması

AMS de yazılan sudoku çözme algoritmasının C# a uyarlanmasıdır.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SudokuSolver
{
class Program
{
static void Main(string[] args)
{
var game = SudokuGame.NewGame();
Console.WriteLine(game.ToString());
game.Crook();
Console.WriteLine(game.ToString());
}
}

public class SudokuGame
{
public List<Cell> Cells { get; set; }
public SudokuGame()
{
Cells = new List<Cell>();
for (int m = 1; m <= 9; m++)
{
for (int n = 1; n <= 9; n++)
{
Cells.Add(new Cell(m, n));
}
}

}
public Cell this[int m, int n]
{
get { return Cells.SingleOrDefault(q => q.M == m && q.N == n); }
set
{
var cell = Cells.SingleOrDefault(q => q.M == m && q.N == n);
cell = value;
}
}

public static SudokuGame NewGame()
{
var game = new SudokuGame();
game[1, 2].Value = 9;
game[1, 4].Value = 7;
game[1, 7].Value = 8;
game[1, 8].Value = 6;
game[2, 2].Value = 3;
game[2, 3].Value = 1;
game[2, 6].Value = 5;
game[2, 8].Value = 2;
game[3, 1].Value = 8;
game[3, 3].Value = 6;
game[4, 3].Value = 7;
game[4, 5].Value = 5;
game[4, 9].Value = 6;
game[5, 4].Value = 3;
game[5, 6].Value = 7;
game[6, 1].Value = 5;
game[6, 5].Value = 1;
game[6, 7].Value = 7;
game[7, 7].Value = 1;
game[7, 9].Value = 9;
game[8, 2].Value = 2;
game[8, 4].Value = 6;
game[8, 7].Value = 3;
game[8, 8].Value = 5;
game[9, 2].Value = 5;
game[9, 3].Value = 4;
game[9, 6].Value = 8;
game[9, 8].Value = 7;
return game;
}

public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine();
sb.AppendLine(new string('-', 19));
for (int m = 1; m <= 9; m++)
{
sb.Append('|');
for (int n = 1; n <= 9; n++)
{
sb.Append(this[m, n].Value == 0 ? " " : this[m, n].Value.ToString());
sb.Append('|');
}
sb.AppendLine();
sb.AppendLine(new string('-', 19));
}

return sb.ToString();

}

public void RemovePossibilities()
{
var firstText = this.ToString();
for (int m = 1; m <= 9; m++)
{
for (int n = 1; n <= 9; n++)
{
var cell = this[m, n];

if (cell.Value == 0)
{
// remove row
for (int i = 1; i <= 9; i++)
{
if (cell == this[m, i])
continue;
var r = this[m, i].Value;
cell.Possibilities.RemoveAll(q => q == r);
}
// remove column
for (int i = 1; i <= 9; i++)
{
if (cell == this[i, n])
continue;
var c = this[i, n].Value;
cell.Possibilities.RemoveAll(q => q == c);
}

// remove small square
var startM = 1;
if (m > 6)
startM = 7;
else if (m > 3)
startM = 4;

var startN = 1;
if (n > 6)
startN = 7;
else if (n > 3)
startN = 4;

for (int i = startM; i < startM + 3; i++)
{
for (int j = startN; j < startN + 3; j++)
{
if (cell == this[i, j])
continue;
if (this[i, j].Value > 0)
cell.Possibilities.RemoveAll(q => q == this[i, j].Value);
}
}

if (cell.Possibilities.Count == 1)
cell.Value = cell.Possibilities[0];
}
}
}
if (firstText != ToString())
RemovePossibilities();
}

public void Crook()
{
var firstText = this.ToString();
RemovePossibilities();
for (int m = 1; m <= 9; m++)
{
for (int n = 1; n <= 9; n++)
{
var cell = this[m, n];

if (cell.Value == 0)
{
for (int p = 0; p < cell.Possibilities.Count; p++)
{
var possibility = cell.Possibilities[p];

var possibilityCount = 0;
// row
for (int i = 1; i <= 9; i++)
{
if (this[m, i] != cell && this[i, n].Possibilities.Exists(q => q == possibility))
possibilityCount++;
}
if (possibilityCount == 1)
{
cell.Value = possibility;
Crook();
}
possibilityCount = 0;
// column
for (int i = 1; i <= 9; i++)
{
if (this[i, n] != cell && this[i, n].Possibilities.Exists(q => q == possibility))
possibilityCount++;
}
if (possibilityCount == 1)
{
cell.Value = possibility;
Crook(); ;
}

var startM = 1;
if (m > 6)
startM = 7;
else if (m > 3)
startM = 4;

var startN = 1;
if (n > 6)
startN = 7;
else if (n > 3)
startN = 4;
possibilityCount = 0;
for (int i = startM; i < startM + 3; i++)
{
for (int j = startN; j < startN + 3; j++)
{
if (cell == this[i, j])
continue;
if (this[i, j].Possibilities.Exists(q => q == possibility))
possibilityCount++;
}
}

if (possibilityCount == 1)
{
cell.Value = possibility;
Crook(); ;
}
}

}
}
}
if (firstText != ToString())
RemovePossibilities();
}
}

public class Cell
{
public Cell(int m, int n, int value = 0)
{
M = m;
N = n;
Value = value;
Possibilities = new List<int>();
if (Value == 0)
{
for (int i = 1; i <= 9; i++)
{
Possibilities.Add(i);
}
}
}
public int M { get; set; }
public int N { get; set; }
private int value = 0;
public int Value
{
get
{
return value;
}
set
{
this.value = value;
if (value != 0)
Possibilities.Clear();
}
}
public List<int> Possibilities { get; set; }
}

}

 

 

 

 Kaynak: https://www.ams.org/notices/200904/rtx090400460p.pdf

10 Aralık 2020

Pdf Türünde Dosya Kontrolü İçin Attribute

public class IsPdfFileAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
try
{
if (value != null)
{
var files = (List<IFormFile>)value;
if (files.Count > 0)
{
var areAllFilesZip = true;
foreach (var file in files)
{
if (file.FileName.EndsWith(".pdf") && file.ContentType == "application/pdf"
)
{
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
var byteArray = ms.ToArray();
var content = System.Text.Encoding.UTF8.GetString(byteArray);
if (Regex.IsMatch(content, @"<script|<html|<head|<title|<body|<pre|<table|<a\s+href|<img|<plaintext|<cross\-domain\-policy",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline))
{
areAllFilesZip = false;
break;
}

if (!content.StartsWith("%PDF"))
{
areAllFilesZip = false;
break;
}
}
}
else
{
areAllFilesZip = false;
break;
}
}
if (areAllFilesZip)
return ValidationResult.Success;
}
}
}
catch (Exception ex)
{

}
return new ValidationResult("Sadece PDF dosya yükleyebilirsiniz!");
}

public class SampleModel
{
[IsPdfFile]
public List<IFormFile> SamplePdfFile { get; set; }
}

// HomeController.cs
   public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}

[HttpPost]
[Consumes("multipart/form-data")]
public IActionResult Index([FromForm] SampleModel model)
{
return View(model);
}


//Index.cshtml
@{
@model WebApplication1.Models.SampleModel
}

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="SamplePdfFile" accept="application/pdf" required>
<input type="submit" />
if (!Html.ViewData.ModelState.IsValid)
{
<hr />
<div asp-validation-summary="All"></div>
}