13 Aralık 2011 Salı

Datatable ve çift dizili matris örneği

Datatable dan dönen değerleri çift dizili matrise çeviren method örneği.     

private static string[][] ConvertToArray(DataTable veri, int dizi)
        {
            string[][] veriler = new string[veri.Rows.Count][];

            int k = 0;
            foreach (DataRow r in veri.Rows)
            {
                veriler[k] = new string[dizi];

                for (int j = 0; j < veri.Columns.Count; j++)
                {
                    veriler[k][j] = ToolKit.ToString(r[j]);
                }
                k++;
            }
            return veriler;
        }

18 Ekim 2011 Salı

String.RemoveMany (Extension Method)

public static string RemoveMany(this string dirtyString, params string[] stringsToRemove)
{
            return dirtyString.Split(stringsToRemove, StringSplitOptions.None)
           .Aggregate((sentence, next) => sentence + next)
}

Kullanımı:
string dirty = "This is ABCa st)r(ing.";
string dirty2 = "tDEFes.t-";
string[] delims = new string[] { "ABC", "(", ")" };
Console.WriteLine(dirty.RemoveMany(delims));
Console.WriteLine(dirty2.RemoveMany("DEF", ".", "-"));
//output
"This is a string."
"test"

14 Ekim 2011 Cuma

Sql Data Source Enumerator Extensions

Mevcut ağ üzerindeki tüm kullanılabilir SQL sunucu örnekleri bir liste halinde alan method örneği.

 public static IEnumerable<string> GetAvailableSqlServers(this SqlDataSourceEnumerator sqlDataSourceEnumerator)
        {
            return from row in SqlDataSourceEnumerator.Instance.GetDataSources().AsEnumerable()
                   orderby row.Field<string>("ServerName"), row.Field<string>("InstanceName")
                   select string.Concat(
                        row.Field<string>("ServerName"),
                        row.Field<string>("InstanceName") != string.Empty
                            ? string.Concat("\\", row.Field<string>("InstanceName"))
                            : string.Empty);
        }

HTML Document Extensions Methods

        public static void AddScript(this HtmlDocument htmlDocument, string javaScript)
        {
            HtmlElement head = htmlDocument.GetElementsByTagName("head")[0];
            HtmlElement scriptElement = htmlDocument.CreateElement("script");
            IHTMLScriptElement element = (IHTMLScriptElement)scriptElement.DomElement;
            element.text = javaScript;
            head.AppendChild(scriptElement);
        }

        public static void AddCSS(this HtmlDocument htmlDocument, string cssFileName)
        {
            IHTMLDocument2 currentDocument = (IHTMLDocument2)htmlDocument.DomDocument;
            int length = currentDocument.styleSheets.length;
            IHTMLStyleSheet styleSheet = currentDocument.createStyleSheet(@"", length + 1);
            using (TextReader reader = new StreamReader(cssFileName))
            {
                styleSheet.cssText = reader.ReadToEnd();
            }
        }

        public static void DoPostBack(this HtmlDocument document)
        {
            document.InvokeScript("__doPostBack");
        }

        public static void DoPostBack(this HtmlDocument document, string eventTarget, string eventArgument)
        {
            document.InvokeScript("__doPostBack", new object[] { eventTarget, eventArgument });
        }

        public static HtmlElement GetElementByTitle(this HtmlDocument document, string title)
        {
            return (from x in document.All.Cast<HtmlElement>()
                    where x.GetAttribute("title") == title
                    select x).SingleOrDefault();
        }

26 Temmuz 2011 Salı

Itextsharp File Attachment Event

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text;
using iTextSharp.text.xml;
using iTextSharp.text.pdf.events;
using System.IO;

public class FileAttachmentEvent : PdfPCellEventForwarder
    {
        protected PdfWriter writer;
        protected PdfFileSpecification fs;
        protected String description;

        public FileAttachmentEvent(PdfWriter Writer, PdfFileSpecification Fs, String Description)
        {
            this.writer = Writer;
            this.fs = Fs;
            this.description = Description;
        }

        public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases)
        {
            try
            {
                PdfAnnotation annonation = PdfAnnotation.CreateFileAttachment(writer, new Rectangle(position.GetLeft(20f), position.GetTop(15f),
                    position.GetLeft(5f), position.GetTop(5f)), description, fs);
                annonation.Name = description;
                writer.AddAnnotation(annonation);
            }
            catch (IOException)
            {
                throw;
            }
        }
    }

Compress JSON Decompress JSON

using System.Text;
using System.IO;
using System.IO.Compression;

  public static void CompressJson(string json, string path)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(json);

            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                using (GZipStream gzs = new GZipStream(fs, CompressionMode.Compress))
                {
                    gzs.Write(bytes, 0, bytes.Length);
                }
            }
        }
 
 public static string DecompressJson(string path)
        {
            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                using (GZipStream gzs = new GZipStream(fs, CompressionMode.Decompress))
                {
                    return gzs.GetString(Encoding.UTF8);
                }
            }
        }

TripleDES Encryption Methods

TripleDES de şifreleme ve deşifreleme yapmak için yazmış olduğum method...

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


public static class TripleDESEncryption
    {
        public static string Encrypt(string Input, string Key)
        {
            if (string.IsNullOrEmpty(Input) || string.IsNullOrEmpty(Key))
            {
                throw new ArgumentNullException("The input/key string can not be empty.");
            }
            ASCIIEncoding Encoding = new ASCIIEncoding();
            byte[] Hash = Encoding.GetBytes(Key);
            byte[] KeyArray = new byte[24];
            byte[] Key2Array = new byte[8];
            for (int x = 0; x < 24; ++x)
            {
                KeyArray[x] = Hash[x];
            }
            for (int x = 0; x < 8; ++x)
            {
                Key2Array[x] = Hash[x + 8];
            }
            byte[] Text = null;
            TripleDESCryptoServiceProvider Encryptor = new TripleDESCryptoServiceProvider();
            using (MemoryStream Stream = new MemoryStream())
            {
                using (CryptoStream DESStream = new CryptoStream(Stream, Encryptor.CreateEncryptor(KeyArray, Key2Array), CryptoStreamMode.Write))
                {
                    using (StreamWriter Writer = new StreamWriter(DESStream))
                    {
                        Writer.Write(Input);
                        Writer.Flush();
                        DESStream.FlushFinalBlock();
                        Writer.Flush();
                        Text = Stream.GetBuffer();
                    }
                }
            }
            Encryptor.Clear();
            return Convert.ToBase64String(Text, 0, (int)Text.Length);
        }
 

        public static string Decrypt(string Input, string Key)
        {
            if (string.IsNullOrEmpty(Input) || string.IsNullOrEmpty(Key))
            {
                throw new ArgumentNullException("The input/key string can not be empty.");
            }
            ASCIIEncoding Encoding = new ASCIIEncoding();
            byte[] Hash = Encoding.GetBytes(Key);
            byte[] KeyArray = new byte[24];
            byte[] Key2Array = new byte[8];
            for (int x = 0; x < 24; ++x)
            {
                KeyArray[x] = Hash[x];
            }
            for (int x = 0; x < 8; ++x)
            {
                Key2Array[x] = Hash[x + 8];
            }
            string Text = "";
            TripleDESCryptoServiceProvider Decryptor = new TripleDESCryptoServiceProvider();
            using (MemoryStream Stream = new MemoryStream(Convert.FromBase64String(Input)))
            {
                using (CryptoStream DESStream = new CryptoStream(Stream, Decryptor.CreateDecryptor(KeyArray, Key2Array), CryptoStreamMode.Read))
                {
                    using (StreamReader Reader = new StreamReader(DESStream))
                    {
                        Text = Reader.ReadToEnd();
                    }
                }
            }
            Decryptor.Clear();
            return Text;
        }
    }