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;
}
13 Aralık 2011 Salı
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)
{
return dirtyString.Split(stringsToRemove, StringSplitOptions.None)
.Aggregate((sentence, next) => sentence + next)
}
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);
}
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();
}
{
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;
}
}
}
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;
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){
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);
}
}
}
{
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;
}
}
21 Temmuz 2011 Perşembe
Convert String to 64bit Integer
static Int64 GetInt64HashCode(string strText)
{
Int64 hashCode = 0;
if (!string.IsNullOrEmpty(strText))
{
byte[] byteContents = Encoding.Unicode.GetBytes(strText);
System.Security.Cryptography.SHA256 hash =
new System.Security.Cryptography.SHA256CryptoServiceProvider();
byte[] hashText = hash.ComputeHash(byteContents);
Int64 hashCodeStart = BitConverter.ToInt64(hashText, 0);
Int64 hashCodeMedium = BitConverter.ToInt64(hashText, 8);
Int64 hashCodeEnd = BitConverter.ToInt64(hashText, 24);
hashCode = hashCodeStart ^ hashCodeMedium ^ hashCodeEnd;
}
return (hashCode);
}
Itextsharp swf view methods
Itextsharp dll i kullanarak oluşturduğumuz pdf te istenilen swf dosyaları oynatmak için yazmış olduğum method örneği
public void PdfFlash(string file)
{
string day = DateTime.Now.ToString("dd/MM/yyyy");
Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(file, FileMode.Create));
writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);
writer.AddDeveloperExtension(PdfDeveloperExtension.ADOBE_1_7_EXTENSIONLEVEL3);
document.Open();
RichMediaAnnotation richMedia = new RichMediaAnnotation(writer, new Rectangle(36, 400, 559, 806));
PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(writer, @"C:\1.swf", "1.swf", null);
PdfIndirectReference asset = richMedia.AddAsset("1.swf", fs);
RichMediaConfiguration configuration = new RichMediaConfiguration(PdfName.FLASH);
RichMediaInstance instance = new RichMediaInstance(PdfName.FLASH);
RichMediaParams flashVars = new RichMediaParams();
String vars = day;
flashVars.FlashVars = vars;
instance.Params = flashVars;
instance.Asset = asset;
configuration.AddInstance(instance);
PdfIndirectReference configurationRef = richMedia.AddConfiguration(configuration);
RichMediaActivation activation = new RichMediaActivation();
activation.Configuration = configurationRef;
richMedia.Activation = activation;
PdfAnnotation richMediaAnnotation = richMedia.CreateAnnotation();
richMediaAnnotation.Flags = PdfAnnotation.FLAGS_PRINT;
writer.AddAnnotation(richMediaAnnotation);
document.Close();
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text;
using iTextSharp.text.xml;
using System.IO;
using System.Xml;
using iTextSharp.text.pdf.codec;
using iTextSharp.text.pdf.parser;
using iTextSharp.text.pdf.richmedia;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text;
using iTextSharp.text.xml;
using System.IO;
using System.Xml;
using iTextSharp.text.pdf.codec;
using iTextSharp.text.pdf.parser;
using iTextSharp.text.pdf.richmedia;
{
string day = DateTime.Now.ToString("dd/MM/yyyy");
Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(file, FileMode.Create));
writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);
writer.AddDeveloperExtension(PdfDeveloperExtension.ADOBE_1_7_EXTENSIONLEVEL3);
document.Open();
RichMediaAnnotation richMedia = new RichMediaAnnotation(writer, new Rectangle(36, 400, 559, 806));
PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(writer, @"C:\1.swf", "1.swf", null);
PdfIndirectReference asset = richMedia.AddAsset("1.swf", fs);
RichMediaConfiguration configuration = new RichMediaConfiguration(PdfName.FLASH);
RichMediaInstance instance = new RichMediaInstance(PdfName.FLASH);
RichMediaParams flashVars = new RichMediaParams();
String vars = day;
flashVars.FlashVars = vars;
instance.Params = flashVars;
instance.Asset = asset;
configuration.AddInstance(instance);
PdfIndirectReference configurationRef = richMedia.AddConfiguration(configuration);
RichMediaActivation activation = new RichMediaActivation();
activation.Configuration = configurationRef;
richMedia.Activation = activation;
PdfAnnotation richMediaAnnotation = richMedia.CreateAnnotation();
richMediaAnnotation.Flags = PdfAnnotation.FLAGS_PRINT;
writer.AddAnnotation(richMediaAnnotation);
document.Close();
}
Rijndael Extensions Methods
Rijndael şifreleme tekniniğinin kullanımı için extensions method haline getirilmiş hali...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace EncryptionExtensions
{
public class EncryptionExtensions
{
private byte[] Encrypt(byte[] inputData, byte[] pwd, byte[] value)
{
MemoryStream stream = new MemoryStream();
Rijndael rij = Rijndael.Create();
rij.Key = pwd;
rij.IV = value;
CryptoStream cStream = new CryptoStream(stream, rij.CreateEncryptor(), CryptoStreamMode.Write);
cStream.Write(inputData, 0, inputData.Length);
cStream.Close();
byte[] encryptedData = stream.ToArray();
return encryptedData;
}
public string Encrypt(string inputData, string pwd, int bits)
{
byte[] Bytes = System.Text.Encoding.Unicode.GetBytes(inputData);
PasswordDeriveBytes pwdBytes = new PasswordDeriveBytes(pwd, new byte[] { 0x10, 0x40, 0x00, 0x34, 0x1A, 0x70, 0x01, 0x34, 0x56, 0xFF, 0x99, 0x77, 0x4C, 0x22, 0x49 });
if (bits == 128)
{
byte[] encryptedData = Encrypt(Bytes, pwdBytes.GetBytes(16), pwdBytes.GetBytes(16));
return Convert.ToBase64String(encryptedData);
}
else if (bits == 192)
{
byte[] encryptedData = Encrypt(Bytes, pwdBytes.GetBytes(24), pwdBytes.GetBytes(16));
return Convert.ToBase64String(encryptedData);
}
else if (bits == 256)
{
byte[] encryptedData = Encrypt(Bytes, pwdBytes.GetBytes(32), pwdBytes.GetBytes(16));
return Convert.ToBase64String(encryptedData);
}
else
{
// append all bits
return string.Concat(bits);
}
}
private byte[] Decrypt(byte[] outputData, byte[] pwd, byte[] value)
{
MemoryStream stream = new MemoryStream();
Rijndael rij = Rijndael.Create();
rij.Key = pwd;
rij.IV = value;
CryptoStream cStream = new CryptoStream(stream, rij.CreateDecryptor(), CryptoStreamMode.Write);
cStream.Write(outputData, 0, outputData.Length);
cStream.Close();
byte[] decryptedData = stream.ToArray();
return decryptedData;
}
public string Decrypt(string str, string pwd, int bits)
{
byte[] Bytes = Convert.FromBase64String(str);
PasswordDeriveBytes pwdBytes = new PasswordDeriveBytes(pwd,
new byte[] { 0x10, 0x40, 0x00, 0x34, 0x1A, 0x70, 0x01, 0x34, 0x56, 0xFF, 0x99, 0x77, 0x4C, 0x22, 0x49 });
if (bits == 128)
{
byte[] decryptedData = Decrypt(Bytes, pwdBytes.GetBytes(16), pwdBytes.GetBytes(16));
return System.Text.Encoding.Unicode.GetString(decryptedData);
}
else if (bits == 192)
{
byte[] decryptedData = Decrypt(Bytes, pwdBytes.GetBytes(24), pwdBytes.GetBytes(16));
return System.Text.Encoding.Unicode.GetString(decryptedData);
}
else if (bits == 256)
{
byte[] decryptedData = Decrypt(Bytes, pwdBytes.GetBytes(32), pwdBytes.GetBytes(16));
return System.Text.Encoding.Unicode.GetString(decryptedData);
}
else
{
return string.Concat(bits);
}
}
}
}
Windows Service Extensions Methods
Windows service lerinde yaptığımız işlemleri extensions method halinde yazdım iyi günlerde kullanmanız dileğiyle...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
{
public class WindowsServices
{
#region Start Service
public static void StartService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
try
{
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
catch
{
throw;
}
}
#endregion
#region Shutdown Service
public static void ShutdownService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
try
{
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Close();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
}
catch (Exception)
{
throw;
}
}
#endregion
#region Stop Service
public static void StopService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
try
{
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
}
catch
{
throw;
}
}
#endregion
#region Restart Service
public static void RestartService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
try
{
int millisec1= Environment.TickCount;
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
int millisec2 = Environment.TickCount;
timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1));
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
catch
{
throw;
}
}
#endregion
#region Get List of Windows Services
public static bool IsServiceInstalled(string serviceName)
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController service in services)
{
if (service.ServiceName == serviceName)
return true;
}
return false;
}
#endregion
}
}
5 Temmuz 2011 Salı
Itextsharp'da 3d işlemleri
u3d dosya türlerini itextsharp kütüphanesini kullanarak açmamıza yarayan yazmış olduğum bir class güle güle kullanmanız dileğiyle.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;
{
Document doc = new Document();
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(filePath,FileMode.Create));
doc.Open();
Rectangle rect = new Rectangle(100, 400, 500, 800);
rect.Border = Rectangle.BOX;
rect.BorderWidth = 0.5F;
rect.BorderColor = new BaseColor(0xFF, 0x00, 0x00);
doc.Add(rect);
PdfStream stream3D = new PdfStream(new FileStream(Files3D, FileMode.Open), writer);
stream3D.Put(PdfName.TYPE, new PdfName("3D"));
stream3D.Put(PdfName.SUBTYPE, new PdfName("U3D"));
stream3D.FlateCompress();
PdfIndirectObject streamObject = writer.AddToBody(stream3D);
stream3D.WriteLength();
PdfDictionary dict3D = new PdfDictionary();
dict3D.Put(PdfName.TYPE, new PdfName("3DView"));
dict3D.Put(new PdfName("XN"), new PdfString("Default"));
dict3D.Put(new PdfName("IN"), new PdfString("Unnamed"));
dict3D.Put(new PdfName("MS"), PdfName.M);
dict3D.Put(new PdfName("C2W"),
new PdfArray(new float[] { 1, 0, 0, 0, 0, -1, 0, 1, 0, 3, -235, 28 }));
dict3D.Put(PdfName.CO, new PdfNumber(235));
PdfIndirectObject dictObject = writer.AddToBody(dict3D);
PdfAnnotation annot = new PdfAnnotation(writer, rect);
annot.Put(PdfName.CONTENTS, new PdfString("3D Model"));
annot.Put(PdfName.SUBTYPE, new PdfName("3D"));
annot.Put(PdfName.TYPE, PdfName.ANNOT);
annot.Put(new PdfName("3DD"), streamObject.IndirectReference);
annot.Put(new PdfName("3DV"), dictObject.IndirectReference);
PdfAppearance ap = writer.DirectContent.CreateAppearance(rect.Width, rect.Height);
annot.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, ap);
annot.SetPage();
writer.AddAnnotation(annot);
// step 5
doc.Close();
}
Kullanımı :
Pdf3D pdf3d = new Pdf3D();pdf3d.ThreeDPdf("C:\\3d.pdf", "c:\\teapot.u3d");
29 Haziran 2011 Çarşamba
Itextsharp PageNumber Method
Itextsharp'da yapmış olduğunuz sayfaların footer kısmına sayfa numarası eklemek için yazmış olduğum method örneği. İyi günlerde kullanmanız dileğiyle
namespace Methods
{
public class PageNumber
{
public void NumberPage(string Path,int PageNumber)
{
Document doc = new Document();
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(Path, FileMode.Create));
doc.Open();
PdfContentByte cb = writer.DirectContent;
PdfTemplate template = cb.CreateTemplate(50, 50);
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
for (int i = 0; i < PageNumber; i++)
{
String PageText = "Page " + writer.PageNumber + " of ";
float len = bf.GetWidthPoint(PageText, 12);
cb.BeginText();
cb.SetFontAndSize(bf, 12);
cb.SetTextMatrix(280, 40);
cb.ShowText(PageText);
cb.EndText();
cb.AddTemplate(template, 280 + len, 40);
doc.NewPage();
}
template.BeginText();
template.SetFontAndSize(bf, 12);
template.ShowText((writer.PageNumber - 1).ToString());
template.EndText();
doc.Close();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;
{
public class PageNumber
{
public void NumberPage(string Path,int PageNumber)
{
Document doc = new Document();
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(Path, FileMode.Create));
doc.Open();
PdfContentByte cb = writer.DirectContent;
PdfTemplate template = cb.CreateTemplate(50, 50);
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
for (int i = 0; i < PageNumber; i++)
{
String PageText = "Page " + writer.PageNumber + " of ";
float len = bf.GetWidthPoint(PageText, 12);
cb.BeginText();
cb.SetFontAndSize(bf, 12);
cb.SetTextMatrix(280, 40);
cb.ShowText(PageText);
cb.EndText();
cb.AddTemplate(template, 280 + len, 40);
doc.NewPage();
}
template.BeginText();
template.SetFontAndSize(bf, 12);
template.ShowText((writer.PageNumber - 1).ToString());
template.EndText();
doc.Close();
}
}
}
30 Mayıs 2011 Pazartesi
Convert to Unix Epoch Time
private string ConvertUnixEpochTime(long epoch)
{
try
{
long baseTicks = 621355968000000000;
long tickResolution = 10000000;
long epochNegative = 1000000000;
long epochTicks = (epoch - epochNegative * tickResolution) + baseTicks; string date = new DateTime(epochTicks, DateTimeKind.Utc).ToString();
return date;
}
catch (Exception exp)
{
}
return string.Empty;
}
Kullanımı :
private void button1_Click(object sender, EventArgs e)
{
txtMesaj.Text = ConvertUnixEpochTime(epoch format);
}
9 Mayıs 2011 Pazartesi
DeflateStream ile Compress ve Decompress
Byte türündeki dataları sıkıştırmaya yarayan DeflateStream ile yazılan Compress ve Decompress Methodları...
using System.IO;
using System.IO.Compression;
using System;
public static class Deflate
{
public static byte[] Compress(byte[] Bytes)
{
if (Bytes == null)
throw new ArgumentNullException("Bytes");
using (MemoryStream Stream = new MemoryStream())
{
using (DeflateStream ZipStream = new DeflateStream(Stream, CompressionMode.Compress, true))
{
ZipStream.Write(Bytes, 0, Bytes.Length);
ZipStream.Close();
return Stream.ToArray();
}
}
}
public static byte[] Decompress(byte[] Bytes)
{
if (Bytes == null)
throw new ArgumentNullException("Bytes");
using (MemoryStream Stream = new MemoryStream())
{
using (DeflateStream ZipStream = new DeflateStream(new MemoryStream(Bytes), CompressionMode.Decompress, true))
{
byte[] Buffer = new byte[4096];
while (true)
{
int Size = ZipStream.Read(Buffer, 0, Buffer.Length);
if (Size > 0) Stream.Write(Buffer, 0, Size);
else break;
}
ZipStream.Close();
return Stream.ToArray();
}
}
}
6 Mayıs 2011 Cuma
Verman Encryption-Decryption
One-time pad belirli usullerle karıştırılmış harflerden oluşturulan tek kullanımlık şifreleme yöntemidir. Bir diğer adı ise Vernam şifreleme yöntemidir.
public static class VernamEncryption
{
public static string Encrypt(string Input, string Key)
{
return Process(Input, Key);
}
public static string Decrypt(string Input, string Key)
{
return Process(Input, Key);
}
private static string Process(string Input, string Key)
{
if (string.IsNullOrEmpty(Input))
throw new ArgumentNullException("Input");
if (string.IsNullOrEmpty(Key))
throw new ArgumentNullException("Key");
if (Input.Length != Key.Length)
{
throw new ArgumentException("Key is not the same length as the input string");
}
ASCIIEncoding Encoding = new ASCIIEncoding();
byte[] InputArray = Encoding.GetBytes(Input);
byte[] KeyArray = Encoding.GetBytes(Key);
byte[] OutputArray = new byte[InputArray.Length];
for (int x = 0; x < InputArray.Length; ++x)
{
OutputArray[x] = (byte)(InputArray[x] ^ Key[x]);
}
return Encoding.GetString(OutputArray);
}
}
{
public static string Encrypt(string Input, string Key)
{
return Process(Input, Key);
}
public static string Decrypt(string Input, string Key)
{
return Process(Input, Key);
}
private static string Process(string Input, string Key)
{
if (string.IsNullOrEmpty(Input))
throw new ArgumentNullException("Input");
if (string.IsNullOrEmpty(Key))
throw new ArgumentNullException("Key");
if (Input.Length != Key.Length)
{
throw new ArgumentException("Key is not the same length as the input string");
}
ASCIIEncoding Encoding = new ASCIIEncoding();
byte[] InputArray = Encoding.GetBytes(Input);
byte[] KeyArray = Encoding.GetBytes(Key);
byte[] OutputArray = new byte[InputArray.Length];
for (int x = 0; x < InputArray.Length; ++x)
{
OutputArray[x] = (byte)(InputArray[x] ^ Key[x]);
}
return Encoding.GetString(OutputArray);
}
}
Screenshot Class
Projelerinizde kullanabileceğiniz klavyedeki PrintScreen tuşunun görevini yapan class örneği...
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System;
public static class Screenshot
{
public static void TakeScreenShot(string FileName)
{
if (string.IsNullOrEmpty(FileName))
throw new ArgumentNullException("FileName");
using (Bitmap TempBitmap = Screenshot.TakeScreenShot())
{
TempBitmap.Save(FileName);
}
}
public static Bitmap TakeScreenShot()
{
Rectangle TotalScreenRect = Rectangle.Empty;
foreach (Screen CurrentScreen in Screen.AllScreens)
{
TotalScreenRect = Rectangle.Union(TotalScreenRect, CurrentScreen.Bounds);
}
Bitmap TempBitmap = new Bitmap(TotalScreenRect.Width, TotalScreenRect.Height, PixelFormat.Format32bppArgb);
using (Graphics TempGraphics = Graphics.FromImage(TempBitmap))
{
TempGraphics.CopyFromScreen(TotalScreenRect.X, TotalScreenRect.Y, 0, 0, TotalScreenRect.Size, CopyPixelOperation.SourceCopy);
}
return TempBitmap;
}
}
2 Mayıs 2011 Pazartesi
ItextSharp ConcetenatePDF
Var olan bir pdf deki verileri yeniden oluşturacağımız bir pdf e kopyalamak için yazmış olduğum bir method iyi günlerde kullanmanız dileğiyle...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text;
public void ConcetenatePDF(String sourcePdf, String[] destinationPdf)
{
Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, new FileStream(sourcePdf, FileMode.Create));
doc.Open();
PdfReader reader;
int n;
for (int i = 0; i < destinationPdf.Length; i++)
{
reader = new PdfReader(destinationPdf[i]);
n = reader.NumberOfPages;
for (int page = 0; page < n; )
{
copy.AddPage(copy.GetImportedPage(reader, ++page));
}
copy.FreeReader(reader);
}
doc.Close();
}
26 Nisan 2011 Salı
ITextSharp Create Barcode Image
Itextsharp'da barkod image yaratmanız için yazmış olduğum method...
Reference lardan System.Drawing'i eklemeyi unutmayın...
public static Image CreateBarcodeImage(string barcodeText)
{
Barcode39 code39 = new Barcode39();
code39.BarHeight = 5;
code39.Code = barcodeText;
System.Drawing.Bitmap bm = new System.Drawing.Bitmap(code39.CreateDrawingImage(System.Drawing.Color.Black, System.Drawing.Color.White));
MemoryStream ms = new MemoryStream();
bm.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
Image img = iTextSharp.text.Image.GetInstance(ms.ToArray());
return img;
}
{
Barcode39 code39 = new Barcode39();
code39.BarHeight = 5;
code39.Code = barcodeText;
System.Drawing.Bitmap bm = new System.Drawing.Bitmap(code39.CreateDrawingImage(System.Drawing.Color.Black, System.Drawing.Color.White));
MemoryStream ms = new MemoryStream();
bm.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
Image img = iTextSharp.text.Image.GetInstance(ms.ToArray());
return img;
}
HL7 To XML Converter
Günümüz teknolojisinde ASTM(American Society For Testing And Materials) yani enerji endüstrisinde kullanılan birçok standart yöntemlerden sorumlu olan kuruluş. yerini HL7 teknolojisi aldı ve gayri ihtiyari bunun içinde hl7 kodlama standartlarını xml e dönüştürme methodları yazılmak durumunda kalındı. Size Method örneklerinden bulduğum ve sizinle paylaşmak istediğim bizzat test edip işe yaradığını gördüğüm methodu paylaşmak istedim... İyi kodlamalar...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Text.RegularExpressions;
public static class HL7ToXmlConverter
{
private static XmlDocument _xmlDoc;
public static string ConvertToXml(string sHL7)
{
// Go and create the base XML
_xmlDoc = CreateXmlDoc();
// HL7 message segments are terminated by carriage returns,
// so to get an array of the message segments, split on carriage return
string[] sHL7Lines = sHL7.Split('\r');
// Now we want to replace any other unprintable control
// characters with whitespace otherwise they'll break the XML
for (int i = 0; i < sHL7Lines.Length; i++)
{
sHL7Lines[i] = Regex.Replace(sHL7Lines[i], @"[^ -~]", "");
}
{
private static XmlDocument _xmlDoc;
public static string ConvertToXml(string sHL7)
{
// Go and create the base XML
_xmlDoc = CreateXmlDoc();
// HL7 message segments are terminated by carriage returns,
// so to get an array of the message segments, split on carriage return
string[] sHL7Lines = sHL7.Split('\r');
// Now we want to replace any other unprintable control
// characters with whitespace otherwise they'll break the XML
for (int i = 0; i < sHL7Lines.Length; i++)
{
sHL7Lines[i] = Regex.Replace(sHL7Lines[i], @"[^ -~]", "");
}
/// Go through each segment in the message
/// and first get the fields, separated by pipe (|),
/// then for each of those, get the field components,
/// separated by carat (^), and check for
/// repetition (~) and also check each component
/// for subcomponents, and repetition within them too.
for (int i = 0; i < sHL7Lines.Length; i++)
{
// Don't care about empty lines
if (sHL7Lines[i] != string.Empty)
{
// Get the line and get the line's segments
string sHL7Line = sHL7Lines[i];
string[] sFields = HL7ToXmlConverter.GetMessgeFields(sHL7Line);
// Create a new element in the XML for the line
XmlElement el = _xmlDoc.CreateElement(sFields[0]);
_xmlDoc.DocumentElement.AppendChild(el);
// For each field in the line of HL7
for (int a = 0; a < sFields.Length; a++)
{
// Create a new element
XmlElement fieldEl = _xmlDoc.CreateElement(sFields[0] +
"." + a.ToString());
/// Part of the HL7 specification is that part
/// of the message header defines which characters
/// are going to be used to delimit the message
/// and since we want to capture the field that
/// contains those characters we need
/// to just capture them and stick them in an element.
if (sFields[a] != @"^~\&")
{
/// Get the components within this field, separated by carats (^)
/// If there are more than one, go through and create an element for
/// each, then check for subcomponents, and repetition in both.
string[] sComponents = HL7ToXmlConverter.GetComponents(sFields[a]);
if (sComponents.Length > 1)
{
for (int b = 0; b < sComponents.Length; b++)
{
XmlElement componentEl = _xmlDoc.CreateElement(sFields[0] +
"." + a.ToString() +
"." + b.ToString());
string[] subComponents = GetSubComponents(sComponents[b]);
if (subComponents.Length > 1)
// There were subcomponents
{
for (int c = 0; c < subComponents.Length; c++)
{
// Check for repetition
string[] subComponentRepetitions =
GetRepetitions(subComponents[c]);
if (subComponentRepetitions.Length > 1)
{
for (int d = 0;
d < subComponentRepetitions.Length;
d++)
{
XmlElement subComponentRepEl =
_xmlDoc.CreateElement(sFields[0] +
"." + a.ToString() +
"." + b.ToString() +
"." + c.ToString() +
"." + d.ToString());
subComponentRepEl.InnerText =
subComponentRepetitions[d];
componentEl.AppendChild(subComponentRepEl);
}
}
else
{
XmlElement subComponentEl =
_xmlDoc.CreateElement(sFields[0] +
"." + a.ToString() + "." +
b.ToString() + "." + c.ToString());
subComponentEl.InnerText = subComponents[c];
componentEl.AppendChild(subComponentEl);
}
}
fieldEl.AppendChild(componentEl);
}
else // There were no subcomponents
{
string[] sRepetitions =
HL7ToXmlConverter.GetRepetitions(sComponents[b]);
if (sRepetitions.Length > 1)
{
XmlElement repetitionEl = null;
for (int c = 0; c < sRepetitions.Length; c++)
{
repetitionEl =
_xmlDoc.CreateElement(sFields[0] + "." +
a.ToString() + "." + b.ToString() +
"." + c.ToString());
repetitionEl.InnerText = sRepetitions[c];
componentEl.AppendChild(repetitionEl);
}
fieldEl.AppendChild(componentEl);
el.AppendChild(fieldEl);
}
else
{
componentEl.InnerText = sComponents[b];
fieldEl.AppendChild(componentEl);
el.AppendChild(fieldEl);
}
}
}
el.AppendChild(fieldEl);
}
else
{
fieldEl.InnerText = sFields[a];
el.AppendChild(fieldEl);
}
}
else
{
fieldEl.InnerText = sFields[a];
el.AppendChild(fieldEl);
}
}
}
}
return _xmlDoc.OuterXml;
}
/// <summary>
/// Split a line into its component parts based on pipe.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
private static string[] GetMessgeFields(string s)
{
return s.Split('|');
}
/// <summary>
/// Get the components of a string by splitting based on carat.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
private static string[] GetComponents(string s)
{
return s.Split('^');
}
/// <summary>
/// Get the subcomponents of a string by splitting on ampersand.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
private static string[] GetSubComponents(string s)
{
return s.Split('&');
}
/// <summary>
/// Get the repetitions within a string based on tilde.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
private static string[] GetRepetitions(string s)
{
return s.Split('~');
}
/// <summary>
/// Create the basic XML document that represents the HL7 message
/// </summary>
/// <returns></returns>
private static XmlDocument CreateXmlDoc()
{
XmlDocument output = new XmlDocument();
XmlElement rootNode = output.CreateElement("HL7Message");
output.AppendChild(rootNode);
return output;
}
}
Kullanımı:
string myHL7string = @"MSH|^~\&|||||20080925161613||ADT^A05||P|2.6";
txtHL7.Text = myHL7string;
txtConvertHL7.Text = HL7ToXmlConverter.ConvertToXml(myHL7string);
txtHL7.Text = myHL7string;
txtConvertHL7.Text = HL7ToXmlConverter.ConvertToXml(myHL7string);
Kaydol:
Kayıtlar (Atom)