resource: http://devdistrict.com/CodeDetails.aspx?A=54
using System.Security.Cryptography;
using System.IO;
using System.Data;
using System;
using System.Collections;
using System.ComponentModel;
public class PasswordEncryptor
{
private byte[] _keyBytes;
private byte[] _IVBytes;
private int _bufferSize=256;
private byte[] _hash;
public PasswordEncryptor(string password)
{
byte[] saltValueBytes = null;
PasswordDeriveBytes pdb = new PasswordDeriveBytes(password,saltValueBytes,"SHA1",50);
_keyBytes = pdb.GetBytes(32);
_IVBytes = pdb.GetBytes(16);
HashAlgorithm hasher = SHA256.Create();
_hash = hasher.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes("password"));
}
public void EncryptWithHash(Stream input, ref Stream output)
{
output.Write(_hash,0,_hash.Length);
RijndaelManaged rj = new System.Security.Cryptography.RijndaelManaged();
rj.Mode= CipherMode.CBC;
ICryptoTransform trans = rj.CreateEncryptor(_keyBytes, _IVBytes);
CryptoStream cs = new CryptoStream(output, trans, CryptoStreamMode.Write);
byte[] bytes = new byte[_bufferSize];
int byteCount;
while((byteCount = input.Read(bytes, 0, bytes.Length))!= 0)
{
cs.Write(bytes,0,byteCount);
}
cs.FlushFinalBlock();
//cs.Close();
}
public void DecryptWithHash(Stream input, ref Stream output)
{
byte[] inputHash = new byte[_hash.Length];
input.Read(inputHash,0,_hash.Length);
if (inputHash.Length!=_hash.Length) throw new Exception("Invalid Password");
for (int i=0;i<_hash.Length;i++)
{
if (_hash[i]!=inputHash[i]) throw new Exception("Invalid Password");
}
RijndaelManaged rj = new System.Security.Cryptography.RijndaelManaged();
rj.Mode= CipherMode.CBC;
ICryptoTransform trans = rj.CreateDecryptor(_keyBytes, _IVBytes);
CryptoStream cs = new CryptoStream(input, trans, CryptoStreamMode.Read);
byte[] bytes = new byte[_bufferSize];
int byteCount;
while((byteCount = cs.Read(bytes, 0, bytes.Length))!= 0)
{
output.Write(bytes,0,byteCount);
}
cs.Flush();
}
}
18 Ağustos 2007 Cumartesi
Encrypting data from one stream to another and attaching hash of the password
RC4 Encryption
author: Rick Sands, http://www.bytemycode.com/snippets/snippet/93/
// RC4 Encryption
/*
From RSA Security's website:
"RC4 is a stream cipher designed by Rivest for RSA Data
Security (now RSA Security). It is a variable key-size stream
cipher with byte-oriented operations. The algorithm is based on
the use of a random permutation. Analysis shows that the period
of the cipher is overwhelmingly likely to be greater than 10^100.
Eight to sixteen machine operations are required per output byte,
and the cipher can be expected to run very quickly in software.
Independent analysts have scrutinized the algorithm and it is
considered secure."
This implementation encodes the byte stream to be encrypted
"in-place".
------------
// Examples:
------------
Byte[] Key = new Byte[5] { 12, 34, 22, 12, 32 };
Byte[] B = new Byte[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Examine B array before and after this next call.
RC4(ref B, Key);
// Examine B array before and after this next call.
RC4(ref B, Key);
*/
public void RC4(ref Byte[] bytes, Byte[] key )
{
Byte[] s = new Byte[256];
Byte[] k = new Byte[256];
Byte temp;
int i, j, t;
int byteLen = bytes.GetLength(0);
int keyLen = key.GetLength(0);
// Generate "8x8 S-Box" and initialize key index
for (i = 0; i < 256; i++)
{
s[i] = (Byte) i;
k[i] = key[i % keyLen];
}
j = 0;
for (i = 0; i<256; i++)
{
j = (j + s[i] + k[i]) % 256;
// swap
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
i = j = 0;
for (int x = 0; x < byteLen; x++)
{
// The following is used to generate a random byte
i = (i + 1) % 256;
j = (j + s[i]) % 256;
temp = s[i];
s[i] = s[j];
s[j] = temp;
t = ((int)s[i] + s[j]) % 256;
// which is xor'd to the source
bytes[x] ^= s[t];
}
}
15 Ağustos 2007 Çarşamba
Use VB Component in C#
Imports System
Namespace hellovb
Public Class HelloString
Public Function GetString() As String
Console.WriteLine ("Hello World in Visual Basic Program")
End Function
End Class
End Namespace
' Compile it using vbc /t:library hellovb.vb
' This command will generate hellovb.dll
' Hello World program in C# (hellocs.cs)
using System;
namespace hellocs{
public class displayA
{
public void Displayhello()
{
Console.WriteLine("Hello in C# Program");
}
}
}
' Compile it using csc /t:library hellocs.cs
' This command will generate hellocs.dll
' Main program(in c#) in which we will use these libraries
Main Program in C# (maincs.cs)
using System;
using hellocs;
using hellovb;
class maincs
{
public static void Main()
{
hellovb.HelloString vb = new hellovb.HelloString(); // namespace.classname of hellovb.vb
vb.GetString(); //Calling vb function
hellocs.displayA cs = new hellocs.displayA(); // namespace.classname of hellocs.cs
cs.Displayhello(); //Calling vb function
}
}
' Compile it using command csc maincs.cs /r:hellocs.dll;hellovb.dll
' Output will be
' Hello World in Visual Basic Program
' Hello in C# Program
13 Ağustos 2007 Pazartesi
Read Excel files from ASP.NET
source: aspfree , http://www.aspfree.com/c/a/ASP.NET-Code/Read-Excel-files-from-ASPNET/
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data.OleDb" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System" %>
<script language="C#" runat="server">
protected void Page_Load(Object Src, EventArgs E)
{
string strConn;
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C:\\exceltest.xls;" +
"Extended Properties=Excel 8.0;";
//You must use the $ after the object you reference in the spreadsheet
OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [Sheet1$]",strConn);
DataSet myDataSet = new DataSet();
myCommand.Fill(myDataSet, "ExcelInfo");
DataGrid1.DataSource = myDataSet.Tables["ExcelInfo"].DefaultView;
DataGrid1.DataBind();
}
</script>
<html>
<head></head>
<body>
<p><asp:Label id=Label1 runat="server">SpreadSheetContents:</asp:Label></p>
<asp:DataGrid id=DataGrid1 runat="server"/>\
</body>
</html>
11 Ağustos 2007 Cumartesi
Send a SMTP E-Mail
using System;
using System.Web.Mail;
namespace DevDistrict.Sample
{
public class SendMail
{
public void Send(string serverName, string to, string from, string subject)
{
SmtpMail.SmtpServer = serverName;
MailMessage m = new MailMessage();
m.To = to;
m.From = from;
m.Subject = subject;
m.Body = body;
SmtpMail.Send(m);
}
}
}
How to Monitor a Process
using System;
using System.Windows.Forms;
namespace DevDistrict.MachineMonitor
{
public class Monitor
{
[STAThread()]
public static void Main()
{
System.Diagnostics.Process[] p = System.Diagnostics.Process.GetProcessesByName("Notepad");
if (p.Length<0)
{
Console.WriteLine("No process");
return;
}
if (p[0].HasExited)
{
Console.WriteLine("Process Exited");
return;
}
p[0].Exited+=new EventHandler(Startup_Exited);
while(!p[0].HasExited)
{
p[0].WaitForExit(30000);
Console.WriteLine("checking process health");
}
}
private static void Startup_Exited(object sender, EventArgs e)
{
Console.WriteLine("PROCESS EXIT CAUGHT");
}
}
}
Displaying HTML Help Files
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace DevDistrict
{
///
/// Summary description for Form1.
///
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.HelpProvider helpProvider1;
private System.Windows.Forms.Button btnShowContents;
private System.Windows.Forms.Button btnShowIndex;
private System.Windows.Forms.Button btnSearchHelp;
private System.ComponentModel.Container components = null;
public Form1()
{
InitializeComponent();
}
private void btnShowContents_Click(object sender, System.EventArgs e)
{
Help.ShowHelp(this, helpProvider1.HelpNamespace);
}
private void btnShowIndex_Click(object sender, System.EventArgs e)
{
Help.ShowHelpIndex(this, helpProvider1.HelpNamespace);
}
private void btnSearchHelp_Click(object sender, System.EventArgs e)
{
Help.ShowHelp(this, helpProvider1.HelpNamespace, HelpNavigator.Find, "");
}
#region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
private void InitializeComponent()
{
this.helpProvider1 = new System.Windows.Forms.HelpProvider();
this.btnShowContents = new System.Windows.Forms.Button();
this.btnShowIndex = new System.Windows.Forms.Button();
this.btnSearchHelp = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// helpProvider1
//
this.helpProvider1.HelpNamespace = "C:\\dev\\WindowsApplication40\\htmlhelp.chm";
//
// btnShowContents
//
this.btnShowContents.Location = new System.Drawing.Point(8, 8);
this.btnShowContents.Name = "btnShowContents";
this.btnShowContents.Size = new System.Drawing.Size(96, 23);
this.btnShowContents.TabIndex = 0;
this.btnShowContents.Text = "Show Contents";
this.btnShowContents.Click += new System.EventHandler(this.btnShowContents_Click);
//
// btnShowIndex
//
this.btnShowIndex.Location = new System.Drawing.Point(8, 48);
this.btnShowIndex.Name = "btnShowIndex";
this.btnShowIndex.Size = new System.Drawing.Size(96, 23);
this.btnShowIndex.TabIndex = 1;
this.btnShowIndex.Text = "Show Index";
this.btnShowIndex.Click += new System.EventHandler(this.btnShowIndex_Click);
//
// btnSearchHelp
//
this.btnSearchHelp.Location = new System.Drawing.Point(8, 88);
this.btnSearchHelp.Name = "btnSearchHelp";
this.btnSearchHelp.Size = new System.Drawing.Size(96, 23);
this.btnSearchHelp.TabIndex = 2;
this.btnSearchHelp.Text = "Search Help";
this.btnSearchHelp.Click += new System.EventHandler(this.btnSearchHelp_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(200, 174);
this.Controls.Add(this.btnSearchHelp);
this.Controls.Add(this.btnShowIndex);
this.Controls.Add(this.btnShowContents);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
}
}
Drawing a Gradient Background for a Control
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace DevDistrict.Sample
{
public class GradientPanel : System.Windows.Forms.Panel
{
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint (e);
Graphics g = e.Graphics;
g.SmoothingMode = SmoothingMode.HighQuality;
GraphicsPath gPath = new GraphicsPath();
Rectangle r = new Rectangle(0,0,this.Width,this.Height);
gPath.AddRectangle(r);
LinearGradientBrush lb = new LinearGradientBrush(r,Color.White,Color.Blue,LinearGradientMode.Vertical);
g.FillPath(lb,gPath);
}
}
}
Fast Greyscale using unsafe code in C#
/*
Fast Greyscale using unsafe code in C#
--
Insert this as a function anywere, I used it in a seperate DLL
to keep my form code clean. Just pass the Bitmap and the picture
box to show it in to the function
If anyone has tried using the .NET Graphics API, they know that
replacing pixel colors takes a long time to complete. I did some
research and found a good source. This code will adjust the color
to greyscale by Binary.
The page is http://www.navicosoft.com/software_articles/softwares_articles_index.html
for more information. It is under Basic Image Processing in the
list of articles.
*/
public void greyscale(Bitmap bmp, PictureBox picBox)
{
BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
unsafe
{
byte* imgPtr = (byte*)(data.Scan0);
byte red, green, blue;
for (int i = 0; i < data.Height; i++)
{
for (int j = 0; j < data.Width; j++)
{
blue = imgPtr[0];
green = imgPtr[1];
red = imgPtr[2];
imgPtr[0] = imgPtr[1] = imgPtr[2] =
(byte)(.299 * red
+ .587 * green
+ .114 * blue);
imgPtr += 3;
}
imgPtr += data.Stride - data.Width * 3;
}
}
bmp.UnlockBits(data);
picBox.Image = bmp;
}