One of the fastest ways to deep copy an object is to serialize it to a binary stream and unserialize it to a new object, in that matter:
-
/// <summary>
-
/// Creates a deep copy of a serializable object
-
/// </summary>
-
/// <typeparam name="T">Any type</typeparam>
-
/// <param name="serializableObject">serializable object</param>
-
/// <returns>cloned object</returns>
-
public static T CloneOf<T>(T serializableObject)
-
{
-
object objCopy = null;
-
MemoryStream stream = new MemoryStream();
-
BinaryFormatter binFormatter = new BinaryFormatter();
-
binFormatter.Serialize(stream, serializableObject);
-
stream.Position = 0;
-
objCopy = (T) binFormatter.Deserialize(stream);
-
stream.Close();
-
return (T) objCopy;
-
}
-
This is a small hack class that adds a set color for input area borders (textbox, richtextbox, combos, etc.) Here is the result:

Screenshot
It all holds up in a single file:
-
-
/// <summary>
-
/// This class adds border to input elements similar to Chrome
-
/// </summary>
-
public class FormBorderizer
-
{
-
/** PRIVATE MEMBERS **/
-
private Label m_lblBorder; // label used for borders
-
private static Color BORDER_COLOR = Color.Gold; // Border color
-
private static int BORDER_WIDTH = 2; // Border width
-
private static Color BACK_COLOR = Color.AliceBlue; // Back color
-
-
/** CONTRUCTORS **/
-
/// <summary>
-
/// Constructor, adds borders to input areas
-
/// </summary>
-
/// <param name="Control.ControlCollection">collection of controls to parse</param>
-
public FormBorderizer(Control.ControlCollection controlCollection)
-
{
-
InitializeBorder(controlCollection);
-
AddBorder(controlCollection);
-
}
-
-
/** METHODS **/
-
-
/// <summary>
-
/// Initializes the border control
-
/// </summary>
-
/// <param name="controlCollection">collection</param>
-
private void InitializeBorder(Control.ControlCollection controlCollection)
-
{
-
m_lblBorder = new Label();
-
m_lblBorder.BackColor = Color.Gold;
-
m_lblBorder.Visible = false;
-
controlCollection.Add(m_lblBorder);
-
m_lblBorder.SendToBack();
-
}
-
-
/// <summary>
-
/// Adds a colored border to a collection of controls
-
/// </summary>
-
/// <param name="controlCollection">target collection</param>
-
private void AddBorder(Control.ControlCollection controlCollection)
-
{
-
foreach (Control c in controlCollection)
-
{
-
// generate event handlers for input areas
-
if (IsInputControl(c))
-
{
-
c.Enter += new EventHandler(c_Enter);
-
c.Leave += new EventHandler(c_Leave);
-
}
-
else if (c is Panel)
-
{
-
new FormBorderizer(c.Controls);
-
}
-
else if (c is TabControl)
-
{
-
TabControl tc = (TabControl)c;
-
foreach (TabPage tp in tc.TabPages)
-
{
-
new FormBorderizer(tp.Controls);
-
}
-
}
-
}
-
}
-
-
/// <summary>
-
/// Checks whether this control should hold a border or not
-
/// </summary>
-
/// <param name="c">target control</param>
-
/// <returns>true or false</returns>
-
private bool IsInputControl(Control c)
-
{
-
return (c is TextBox || c is ListBox || c is ComboBox || c is RichTextBox || c is MaskedTextBox);
-
}
-
-
/** EVENTS **/
-
/// <summary>
-
/// Event occuring when the user leaves an input control
-
/// </summary>
-
private void c_Leave(object sender, EventArgs e)
-
{
-
m_lblBorder.Visible = false;
-
Control ctrl = (Control)sender;
-
ctrl.BackColor = Color.White;
-
-
}
-
-
/// <summary>
-
/// Event occuring when the user enters an input control
-
/// </summary>
-
private void c_Enter(object sender, EventArgs e)
-
{
-
Control ctrl = (Control)sender;
-
WrapControl(ctrl);
-
m_lblBorder.Visible = true;
-
m_lblBorder.Anchor = ctrl.Anchor;
-
}
-
-
/// <summary>
-
/// Wraps the border around the control
-
/// </summary>
-
/// <param name="control"></param>
-
private void WrapControl(Control control)
-
{
-
m_lblBorder.Top = control.Top - BORDER_WIDTH;
-
m_lblBorder.Left = control.Left - BORDER_WIDTH;
-
m_lblBorder.Width = control.Width + 2 * BORDER_WIDTH;
-
m_lblBorder.Height = control.Height + 2 * BORDER_WIDTH;
-
control.BackColor = BACK_COLOR;
-
}
-
-
}
-
To call it, simply create an instance of FormBorderizer (such an awful name!!) and initialize it with a form / panel control collection.
Ex:
-
public partial class Form1 : Form
-
{
-
public Form1()
-
{
-
InitializeComponent();
-
new FormBorderizer(this.Controls);
-
}
-
-
}
-
-
Ever had those flickers in your 50+ component forms?
Trying to play with SuspendLayout / ResumeLayout didn’t help? That’s because it only suspends the automatic layout, triggered by the Anchor and Dock properties.
Setting double-buffering to true didn’t help either? That’s because it only suppresses flicker on individual controls: a label, a button and so on…
Setting the OptimizedDoubleBuffer flag to true? Nope, no changes…
After struggling for many hours trying to eliminate a flicker that was occuring on my application form, I finally found a solution on msdn:
It’s called compositing double-buffering and it’s simply 7 lines of code put in somewhere in your form code:
-
-
protected override CreateParams CreateParams {
-
get {
-
CreateParams cp = base.CreateParams;
-
cp.ExStyle |= 0×02000000;
-
return cp;
-
}
-
}
Explanation from nobugz:
I discovered a new Windows style in the SDK header files, available for Windows XP and (presumably) Vista: WS_EX_COMPOSITED. With that style turned on for your form, Windows XP does double-buffering on the form and all its child controls
nobugz is the man…
Java 5 got a bit closer to its twin C# by adding the possibility of directly accessing entities of a list or collection through its own “foreach” functionality :
C# :
-
foreach(type var in arr){
-
// implement body
-
}
Java :
-
for (type var : arr) {
-
// implement body
-
}
Delegates make it easier to find stuff in generic lists.
Let’s consider the following simple class:
-
Public Class Person{
-
private string m_name;
-
private int m_age;
-
-
// .Net3.0 syntax only.
-
public string Name{get;set}
-
public int Age{get;set}
-
-
public Person(string name, int age){
-
m_name = name;
-
m_age = age;
-
}
Instanciating :
-
List<Person> lstPpl = new List<Person>();
-
lstPpl.Add(new Person("Christian", 1));
-
lstPpl.Add(new Person("Noah", 0.3));
We can easily find Noah:
-
Person myson = lstPpl.Find(delegate(Person p) { return "Noah" == p.Name; });
For re-use: a small class that does encryption and binary serialization:
-
using System;
-
using System.Collections.Generic;
-
using System.Text;
-
using System.IO;
-
using System.Runtime.Serialization.Formatters.Binary;
-
using System.Security.Cryptography;
-
using System.Windows.Forms;
-
-
namespace MyNamespace
-
{
-
class Tools
-
{
-
// change me…
-
private static string m_encryptionKey = "password";
-
-
public static byte[] Encrypt(byte[] plainData, string sKey)
-
{
-
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
-
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
-
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
-
ICryptoTransform desencrypt = DES.CreateEncryptor();
-
byte[] encryptedData = desencrypt.TransformFinalBlock(plainData, 0, plainData.Length);
-
return encryptedData;
-
}
-
-
public static byte[] Decrypt(byte[] encryptedData, string sKey)
-
{
-
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
-
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
-
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
-
ICryptoTransform desDecrypt = DES.CreateDecryptor();
-
byte[] decryptedData = desDecrypt.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
-
return decryptedData;
-
}
-
-
public static void SaveObjectToFile(object obj, string path){
-
try
-
{
-
MemoryStream memStream = new MemoryStream();
-
BinaryFormatter binFormatter = new BinaryFormatter();
-
binFormatter.Serialize(memStream, obj);
-
byte[] encryptedBytes = Encrypt(memStream.ToArray(), m_encryptionKey);
-
memStream.Close();
-
Stream streamToFile = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
-
streamToFile.Write(encryptedBytes, 0, encryptedBytes.Length);
-
streamToFile.Flush();
-
streamToFile.Close();
-
}
-
catch (Exception e)
-
{
-
MessageBox.Show(e.Message);
-
}
-
}
-
-
public static object LoadObjectFromFile(string path)
-
{
-
try
-
{
-
-
Stream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
-
byte[] encryptedObj = new byte[fileStream.Length];
-
fileStream.Read(encryptedObj, 0, (int)encryptedObj.Length);
-
MemoryStream memStream = new MemoryStream(Decrypt(encryptedObj, m_encryptionKey));
-
BinaryFormatter binFormatter = new BinaryFormatter();
-
object decryptedObj = binFormatter.Deserialize(memStream);
-
memStream.Close();
-
fileStream.Close();
-
return decryptedObj;
-
}
-
catch (Exception e)
-
{
-
MessageBox.Show(e.Message);
-
}
-
return null;
-
}
-
}
-
}
Certains raccourcis peuvent parfois ralonger certaines routes. Par example, il est souvent requis d’échanger deux variables entre elles. Pour peu que cet échange doive avoir lieu au sein d’une boucle, disons pour un affichage fluide par ex., on va chercher à en optimiser l’échange.
De manière logique, on pense de suite à utiliser une variable intermédiaire :
-
void main()
-
{
-
int a = 0;
-
int b = 1;
-
int c;
-
-
// swap utilisant une 3e variable
-
c = a;
-
a = b;
-
b = c;
-
}
Cette méthode a beau avoir certains défauts, elle est en tout cas très clair.
Il y a pourtant plus court à écrire :
-
void main()
-
{
-
int a = 0;
-
int b = 1;
-
-
// en une ligne!
-
a+=b-=a=b-a;
-
}
Ou du moins c’est ce que l’on pourrait croire… Regardons le code assembleur généré par les deux corps de programmes précédents:
Swap à 3 variables :
-
push edi ; preparer de la place
-
push esi ; pour 3 variables
-
push ebx
-
cmp dword ptr ds:[00312E08h],0
-
je 00000011
-
call 78ACB4AF
-
xor esi,esi ; a = 0
-
xor edi,edi ; b = 0
-
xor ebx,ebx ; c = 0
-
xor esi,esi ; a = 0
-
mov edi,1 ; b = 1
-
mov ebx,esi ; c = a
-
mov esi,edi ; a = b
-
mov edi,ebx ; b = c
Swap en une ligne :
-
push edi ; preparer de la place
-
push esi ; pour 2 variables
-
cmp dword ptr ds:[003F2E08h],0
-
je 00000010
-
call 7963B4AF
-
xor esi,esi ; a = 0
-
xor edi,edi ; b = 0
-
xor esi,esi ; a = 0
-
mov edi,1 ; b = 1
-
mov eax,edi ; eax = reg. temporaire
-
sub eax,esi ; eax = b - a
-
mov esi,eax ; a = b - a
-
sub edi,esi ; b = b - a
-
add esi,edi ; a = a + b
On économise peut-être du tps en n’allouant pas de place pour une troisième variable, on le paye plus tard. Au final, le swap en une seule ligne prendra légèrement plus de temps que le swap sur 3 lignes. Plus important encore, le swap en une ligne est beaucoup moins lisible… Autant donc travailler clairement!!
Remarque :
Il existe une version optimale d’un échange de deux variables, détaillée ici : http://en.wikipedia.org/wiki/XOR_swap . Certains diront que cette version n’est pas entièrement portable… Mais ca reste à prouver, je l’ai vu tourner un peu partout… La technique consiste à utiliser la commande XOR qui est plus rapide que la commande MOV, comme ceci:
-
void main()
-
{
-
int a = 0;
-
int b = 1;
-
-
// avec des Xor :
-
a = a ^ b;
-
b = a ^ b;
-
a = a ^ b;
-
}
Ce qui donne :
-
push edi
-
push esi
-
cmp dword ptr ds:[00212E08h],0
-
je 00000010
-
call 7974B4AF
-
xor esi,esi
-
xor edi,edi
-
xor esi,esi
-
mov edi,1
-
xor esi,edi
-
xor edi,esi
-
xor esi,edi
Encore une fois, la lisibilité n’est pas optimale, à moins d’être habitué à faire des XOR!