You can find it for free at GitHub:
https://github.com/QubeX2/gstickies
//QubeX2
Visar inlägg med etikett c#. Visa alla inlägg
Visar inlägg med etikett c#. Visa alla inlägg
torsdag 29 september 2011
onsdag 28 september 2011
Problem #1 How to encrypt data between PHP and C#
One important note. When you want to encrypt the data on the
C# side you have to pad the iv to length of 32.
In PHP encrypt data like this:
In C# decrypt data like this:
//QubeX2
C# side you have to pad the iv to length of 32.
In PHP encrypt data like this:
<?php
$iv= "01234567890123456789012345678901";
$key= "this is they key";
$text= "This text will be encrypted...";
$bsize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$pad= $bsize - (strlen($text) % $bsize);
$text .= str_repeat(chr($pad), $pad);
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv);
$enc_text = base64_encode($encrypted);
echo "
$enc_text";
/* the output
* MCfBJe4H7U+9Qb48RkHlXUt1/it10mx+TG7lrCUjO4w=
*/
?>
In C# decrypt data like this:
using System; using System.Text; using System.Security.Cryptography; using System.IO; namespace Encryption { class MainClass { public static void Main (string[] args) { string enc_text = @"MCfBJe4H7U+9Qb48RkHlXUt1/it10mx+TG7lrCUjO4w="; string iv = "01234567890123456789012345678901"; string key = "this is they key"; byte[] bytes = Base64_Decode(enc_text); Console.WriteLine(Decrypt(bytes, key, iv)); } public static byte[] Base64_Decode (string str) { return Convert.FromBase64String (str); } public static string Decrypt (byte[] cipher, string key, string iv) { string retVal = ""; UTF8Encoding encoding = new UTF8Encoding (); byte[] Key = encoding.GetBytes (key); byte[] IV = encoding.GetBytes (iv); using (RijndaelManaged rj = new RijndaelManaged ()) { try { rj.Padding = PaddingMode.PKCS7; rj.Mode = CipherMode.CBC; rj.KeySize = 256; rj.BlockSize = 256; rj.Key = Key; rj.IV = IV; using (MemoryStream ms = new MemoryStream (cipher)) { using (CryptoStream cs = new CryptoStream (ms, rj.CreateDecryptor (Key, IV), CryptoStreamMode.Read)) { using (StreamReader sr = new StreamReader (cs)) { retVal = sr.ReadLine (); } } } } finally { rj.Clear (); } } return retVal; } } }
//QubeX2
torsdag 24 februari 2011
Att använda Javascript i Windows Forms
Ett litet exempel på hur man kan använda Javascript i Windows Forms
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MSScriptControl;
namespace Blog.Script
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
ScriptControlClass script = new ScriptControlClass();
script.Language = "JScript";
script.AddCode("var v = 10;");
StringBuilder js = new StringBuilder();
js.AppendLine("function max(x,y){ return x > y ? x : y; }");
js.AppendLine("max(v,3);");
string result = "";
try
{
result = script.Eval(js.ToString()).ToString();
}
catch
{
result = script.Error.Line + "," + script.Error.Column + " " + script.Error.Description;
}
MessageBox.Show(result);
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MSScriptControl;
namespace Blog.Script
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
ScriptControlClass script = new ScriptControlClass();
script.Language = "JScript";
script.AddCode("var v = 10;");
StringBuilder js = new StringBuilder();
js.AppendLine("function max(x,y){ return x > y ? x : y; }");
js.AppendLine("max(v,3);");
string result = "";
try
{
result = script.Eval(js.ToString()).ToString();
}
catch
{
result = script.Error.Line + "," + script.Error.Column + " " + script.Error.Description;
}
MessageBox.Show(result);
}
}
}
onsdag 15 juli 2009
DEVTIPS #17 Sortera med LINQ
public class Node
{
public Node[] children;
public string name;
}
var nodes = from nd in node.children.AsEnumerable()
orderby
nd.name ascending
select nd;
nodes kommer att innehålla en array av Node object som är sorterad efter Node.name.
onsdag 8 april 2009
DEVTIPS #16 Göra Syntax Highlight med RichTextBox utan flicker!

1) Skapa en klass som ärver av RichTextBox overrida WndProc för att äta en del paint messages (Hemligheten för att slippa flicker). I OnTextChanged eventet kan vi då styra när kontrollen skall ritas om genom att sätta m_bPaint.
public class SyntaxRichTextBox : System.Windows.Forms.RichTextBox {
private bool m_bDoEvents = true;
private static bool m_bPaint = true;
private string[] m_Keywords = new string[] {
"require", "and", "break", "false",
"in", "local", "nil", "not", "or",
"return", "true", "do", "else", "elseif",
"end", "for", "function", "if", "repeat",
"then", "until", "while"
};
protected override void WndProc(ref System.Windows.Forms.Message m) {
// Tar bort flicker från RichTextBox
if (m.Msg == 0x00f) {
if (m_bPaint)
base.WndProc(ref m);
else
m.Result = IntPtr.Zero;
} else
base.WndProc(ref m);
}
public SyntaxRichTextBox() {
}
protected override void OnKeyDown(KeyEventArgs e) {
base.OnKeyDown(e);
}
protected override void OnTextChanged(EventArgs e) {
if (m_bDoEvents == true) {
m_bPaint = false;
try {
int iCharIndex = GetFirstCharIndexOfCurrentLine();
int iLine = GetLineFromCharIndex(iCharIndex);
int iLength = Lines[iLine].Length;
SyntaxHighlight(iCharIndex, iLength);
} catch {
}
m_bPaint = true;
}
base.OnTextChanged(e);
}
private void FindKeyWord(string sKeyword, Color oColor, int iCharIndex, int iLength) {
int iIndex = Find(sKeyword, iCharIndex, (iCharIndex + iLength), RichTextBoxFinds.MatchCase | RichTextBoxFinds.WholeWord);
while (iIndex >= 0) {
SelectionColor = oColor;
if ((iIndex + sKeyword.Length) < (iCharIndex + iLength)) {
iIndex = Find(sKeyword, iIndex + sKeyword.Length, (iCharIndex + iLength), RichTextBoxFinds.MatchCase | RichTextBoxFinds.WholeWord);
} else {
break;
}
}
}
public void Initialize() {
m_bDoEvents = false;
for (int i = 0; i <>
int chfi = GetFirstCharIndexFromLine(i);
SyntaxHighlight(chfi, Lines[i].Length);
}
m_bDoEvents = true;
}
private void SyntaxHighlight(int iCharIndex, int iLength) {
int index = iCharIndex;
int length = iLength;
int iCursorPos = SelectionStart;
SelectionStart = iCharIndex;
SelectionLength = iLength;
SelectionColor = Color.Black;
foreach (string sKeyword in m_Keywords) {
FindKeyWord(sKeyword, Color.Blue, iCharIndex, iLength);
}
SelectionStart = index;
SelectionLength = length;
// find numbers
Regex rNum = new Regex("[0-9]*");
Match mNum = rNum.Match(SelectedText);
while (mNum.Success) {
if (mNum.Captures.Count > 0) {
string sExp = mNum.Captures[0].Value;
FindKeyWord(sExp, Color.DarkOrchid, iCharIndex, iLength);
}
mNum = mNum.NextMatch();
}
SelectionStart = index;
SelectionLength = length;
// find xml
Regex rXml = new Regex("<[^>]*>");
Match mXml = rXml.Match(SelectedText);
while (mXml.Success) {
if (mXml.Captures.Count > 0) {
string sExp = mXml.Captures[0].Value;
FindKeyWord(sExp, Color.MediumSlateBlue, iCharIndex, iLength);
}
mXml = mXml.NextMatch();
}
// reset
SelectionStart = iCursorPos;
SelectionLength = 0;
SelectionColor = Color.Black;
}
}
2) Användning:
SyntaxRichTextBox srt = new SyntaxRichTextBox();
this.Controls.Add(srt);
srt.Dock = DockStyle.Fill;
tisdag 7 april 2009
DEVTIPS #15 Extensions: utöka befintliga klasser med egna metoder
I .NET 3.5 går det att använda Extensions för att utöka befintliga klasser med egna metoder.
Exempel:
string s = "42";
int num = s.ToNumber() * 8;
Så här skapar man en extension.
1) Skapa en statisk klass
2) En statisk metod med argumentet (this string)
Exempel:
public static class QubeExtensions {
public static int ToNumber(this string s) {
try { return int.Parse(s); } catch { } return 0;
}
}
måndag 6 april 2009
DEVTIPS #14 Köra Stored Procedures enklare
För att få lite enklare hantering av ett datalager med en massa "Stored Procedures" kan man skapa en basklass som stänger connection i dispose.
public class DbBase : IDisposable {
protected SqlCommand mCommand = null;
protected SqlConnection mConnection = null;
protected SqlDataReader mReader = null;
protected DbBase() {
try {
mConnection = new SqlConnection("connectionString goes here");
mConnection.Open();
mCommand = new SqlCommand();
mCommand.Connection = mConnection;
mCommand.CommandType = CommandType.StoredProcedure;
} catch (Exception ex) {
Dispose();
throw ex;
}
}
~DbBase() {
Dispose();
}
public void Dispose() {
if (mConnection != null)
mConnection.Close();
if (mReader != null)
mReader.Close();
}
}
Sedan skapar vi en klass som ärver av denna klass DbBase. Fördelen här är att vi inte behöver öppna och stänga connection hela tiden, det sköter basklassen DbBase om. Smidigt!
public class DbDirectory : DbBase {
public void pSerializedAdd(Guid EntryGUID, byte[] Data, string Name) {
mCommand.CommandText = "Directory.pSerializedAdd";
mCommand.Parameters.Clear();
mCommand.Parameters.Add("@EntryGUID", SqlDbType.UniqueIdentifier).Value = EntryGUID;
mCommand.Parameters.Add("@Data", SqlDbType.VarBinary).Value = Data;
mCommand.Parameters.Add("@Name", SqlDbType.VarChar, 50).Value = Name;
mCommand.ExecuteNonQuery();
}
public void pSerializedDelete(Guid EntryGUID, string Name) {
mCommand.CommandText = "Directory.pSerializedDelete";
mCommand.Parameters.Clear();
mCommand.Parameters.Add("@EntryGUID", SqlDbType.UniqueIdentifier).Value = EntryGUID;
mCommand.Parameters.Add("@Name", SqlDbType.VarChar, 50).Value = Name;
mCommand.ExecuteNonQuery();
}
}
För att köra DbDirectory funktioner kör vi sedan med using som säkerställer att dispose i basklassen DbBase körs.
using (DbDirectory dbDir = new DbDirectory()) {
dbDir.pSerializedAdd(Guid.Empty, new byte[0], "test");
}
torsdag 2 april 2009
DEVTIPS #12 ASP.NET Plugins
Att skapa plugins för ASP.NET sidor:
1) Fixa till ett Interface:
public interface IPlugin {
string Name {get; set;}
void RenderContent(Control parent);
}
2) Skapa en plugin som bygger på Interfacet från steg 1)
public class MyPlugin : IPlugin {
private string _name = "MyPlugin";
public string Name {
get {
return _name;
}
set {
_name = value;
}
}
public void RenderContent(Control parent) {
Label label = new Label();
label.Text = "MyPlugin";
parent.Controls.Add(label);
}
}
3) Kör pluginen dynamiskt på hemsidan:
protected void Page_Load(object sender, EventArgs e)
{
string typeName = "myplugin.MyPlugin, myplugin, Version=0.0.0.0";
Type type = Type.GetType(typeName);
object o = Activator.CreateInstance(type);
IPlugin plugin = (IPlugin)o;
plugin.RenderContent(pnlMain);
}
DEVTIPS #11 ASP.NET Confirm
För att göra en liten extra check kan man lägga till eventet onclick via attributes.
javascripts confirm returnar true eller false, trycker man på avbryt så körs aldrig btnTest_Click eventet.
protected void Page_Load(object sender, EventArgs e)
{
btnTest.Attributes.Add("onclick", "return confirm('Är du säker?');");
}
protected void btnTest_Click(object sender, EventArgs e) {
// do your stuff here
}
onsdag 1 april 2009
DEVTIPS #9 IsNull
Om en variabel är null och man vill snabbt sätta ett standardvärde
använd dubbla frågetecken ??:
string message = null;
MessageBox.Show(message ?? "NULL");
DEVTIPS #7 JSON Message
Class defenitions for serialization:
[Serializable]
public class JsonQuery
{
public string licenseKey;
public string layoutName;
public List<JsonQueryItem> items;
}
[Serializable]
public class JsonQueryItem
{
public string fieldRef;
public string comparison;
public string value;
}
Javascript JSON Message:
var query = {
licenseKey: "3c67897",
layoutName: "hemma",
items: [
{
fieldRef: "PRODUCT_CODE",
comparison: "Contains",
value: "hepa"
}
]
};
DEVTIPS #6 JSON Serialization with .NET
.NET 3.5 Has JSON serialization built-in.
Include these references:
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
Make a serializable object defenition (class):
[Serializable]
public class JsonQuery
{
public string licenseKey;
public string layoutName;
public List items;
}
Make two generic functions for serialize and deserialize JSON Message:
private object JsonDeserialize(string json, Type type)
{
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DataContractJsonSerializer dcjs = new DataContractJsonSerializer(type);
object o = dcjs.ReadObject(ms);
ms.Close();
return o;
}
private string JsonSerialize(object obj, Type type, string callback)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(type);
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, obj);
string json = Encoding.Default.GetString(ms.ToArray());
ms.Close();
return callback + "(" + json + ")";
}
Prenumerera på:
Inlägg (Atom)