до этого были: http://seregaborzov.wordpress.com/2008/01/26/quick-samples-csharp/
http://seregaborzov.wordpress.com/2008/01/01/links-prichem-useful/
http://seregaborzov.wordpress.com/2007/12/05/quick-samples-in-csharp/
http://seregaborzov.wordpress.com/2007/10/24/csharp-links/
Эксепшн одной строкой:
string GetSingleLineExceptionText(Exception ex)
{
if (ex != null)
{
return ex.Message + ” — ” + ex.StackTrace.Replace(”\r”, ” “).Replace(”\n”, ” “);
}
return string.Empty;
}
Одиночка (а вы еще хотите про паттерны?)
using System;
namespace DoFactory.GangOfFour.Singleton.Structural
{
// MainApp test application
class MainApp
{
static void Main()
{
// Constructor is protected — cannot use new
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();
if (s1 == s2)
{
Console.WriteLine(”Objects are the same instance”);
}
// Wait for user
Console.Read();
}
}
// “Singleton”
class Singleton
{
private static Singleton instance;
// Note: Constructor is ‘protected’
protected Singleton()
{
}
public static Singleton Instance()
{
// Use ‘Lazy initialization’
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
Сохранение байтного массива
public static bool BytesToFile(byte[] pData, string pFilePath)
{
System.IO.FileStream oStream;
System.IO.BinaryWriter oWriter;
oStream = new System.IO.FileStream(pFilePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
oWriter = new System.IO.BinaryWriter(oStream);
try
{
for (int i = 0; i <= pData.GetLength(0) - 1; i++)
{
oWriter.Write(pData[i]);
if ((i % 1000) == 0) { oWriter.Flush(); } //Flush every 1000 bytes
}
oWriter.Flush(); //Perform final flush
return true;
}
catch (Exception oE)
{
return false;
}
finally
{
//Make sure to do house keeping
oWriter.Close();
oStream.Close();
}
}
Шлем мыло с SMTP аутентификацией
using System.Net.Mail;
MailMessage oMsg = new MailMessage();
// Set the message sender
oMsg.From = new MailAddress(”xavier@devel.oping.net”, “Xavier Larrea”);
// The .To property is a generic collection,
// so we can add as many recipients as we like.
oMsg.To.Add(new MailAddress(”fox@foxcorp.org”,”John Doe”));
// Set the content
oMsg.Subject = “My First .NET email”;
oMsg.Body = “Test body - .NET Rocks!”;
oMsg.IsBodyHtml = true;
SmtpClient oSmtp = new SmtpClient(”smtp.myserver.com”);
//You can choose several delivery methods.
//Here we will use direct network delivery.
oSmtp.DeliveryMethod = SmtpDeliveryMethod.Network;
//Some SMTP server will require that you first
//authenticate against the server.
NetworkCredential oCredential = new NetworkCredential(”myusername”,”mypassword”);
oSmtp.UseDefaultCredentials = false;
oSmtp.Credentials = oCredential;
//Let’s send it already
oSmtp.Send(oMsg);
Сравнить две даты:
DateTime startDate = new DateTime (2008, 1, 1);
DateTime endDate = new DateTime (2008, 1, 5);
TimeSpan ts = endDate - startDate;
long days = ts.Days;
long hours = ts.TotalHours;
long mins = ts.TotalMinutes;
long secs = ts.TotalSeconds;
Небольшой примерчик коллекции с событиями:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
public class NotificationList<T> : Collection<T>{
public event EventHandler<ItemInsertedArgs<T>> ItemAdded;
protected override void InsertItem(int index, T item){
EventHandler<ItemInsertedArgs<T>> handler = ItemAdded;
if (handler != null){
handler(this, new ItemInsertedArgs<T>(index, item));
}
base.InsertItem(index, item);
}
}
public class ItemInsertedArgs<T> : EventArgs{
public int Index;
public T Item;
public ItemInsertedArgs(int index, T item)
{
this.Index = index;
this.Item = item;
}
}
public class MainClass
{
public static void Main()
{
NotificationList<int> list = new NotificationList<int>();
list.ItemAdded += delegate(object o, ItemInsertedArgs<int> args) {
Console.WriteLine(”A new item was added to the list: {0} at index {1}”,args.Item, args.Index);
};
for (int i = 0; i < 10; i++)
{
list.Add(i);
}
}
}
Обработчик горячих клавиш на CSharp:
private void Any_KeyDownPreview(object sender, PreviewKeyDownEventArgs e)
{
#region KEY = Right Arrow (Rotate Right)
if (e.KeyCode == Keys.Right)
ShiftLCDRightWithRotate();
#endregion
#region KEY = Left Arrow (Rotate Left)
else if (e.KeyCode == Keys.Left)
ShiftLCDLeftWithRotate();
#endregion
#region KEY = Up Arrow (Rotate Up)
else if (e.KeyCode == Keys.Up)
ShiftLCDUpWithRotate();
#endregion
#region KEY = Down Arrow (Rotate Down)
else if (e.KeyCode == Keys.Down)
ShiftLCDDownWithRotate();
#endregion
#region Key = Enter || ESC (Editing Frame Flag==true) Finish Editing
else if (MainForm.EditingFrameFlag == true)
{
#region Key = ENTER (Accept Edit)
if (e.KeyCode == Keys.Enter) //Finish Editing-Save it
{
int[][] mfCCnList = new int[8][];
for (int index = 0; index < 8; index++)
mfCCnList[index] = MainForm.CC[index].GetCharacterArray();
LF.Enabled = true;
LF.FinishEditingFrame(8, MainForm.EditFrameNumber, mfCCnList);
LF.label1.Visible = false;
this.Text = FormTextHeader;
MainForm.EditingFrameFlag = false;
}
#endregion
#region Key = ESC (Cancel Edit)
else if (MainForm.EditingFrameFlag == true)
if (e.KeyCode == Keys.Escape) //Finish Editing-Esape it
{
LF.Enabled = true;
LF.label1.Visible = false;
this.Text = FormTextHeader;
MainForm.EditingFrameFlag = false;
}
#endregion
}
#endregion
#region Key = CTRL+< (Mainform Zooming Out)
else if (e.Control == true & e.KeyCode == Keys.Oemcomma)
{
MainForm.CurrentZoomLevel–;
if (CurrentZoomLevel < 1)
CurrentZoomLevel = 4;
ZoomTo();
}
#endregion
#region Key = CTRL+> (Mainform Zooming In)
else if (e.Control == true & e.KeyCode == Keys.OemPeriod)
{
MainForm.CurrentZoomLevel++;
if (CurrentZoomLevel > 4)
CurrentZoomLevel = 1;
ZoomTo();
}
#endregion
#region Key = CTRL+A (Save Library As)
else if (e.Control == true & e.KeyCode == Keys.A)
LibraryForm.SaveAsFlag = true;
#endregion
#region Key = CTRL+N (New Library)
else if (e.Control == true & e.KeyCode == Keys.N)
LibraryForm.NewLibraryFlag = true;
#endregion
#region Key = CTRL+O (Open Library)
else if (e.Control == true & e.KeyCode == Keys.O)
LibraryForm.OpenLibraryFlag = true;
#endregion
#region Key = CTRL+S (Save Mainform to Library)
else if (e.Control == true & e.KeyCode == Keys.S)
CopyFrameToLibrary();
#endregion
#region Key = CTRL+I (Invert All CCs)
else if (e.Control == true & e.KeyCode == Keys.I)
MainForm_InvertAll();
#endregion
#region Key = CTRL+C (Clear All CCs)
else if (e.Control == true & e.KeyCode == Keys.C)
MainForm_ClearAll();
#endregion
#region Key = CTRL+1 (4×2 LCD Configuration)
else if (e.Control == true & e.KeyCode == Keys.D1)
MainForm_MiddleBottomConfig_Click();
#endregion
#region Key = CTRL+2 (2×4 LCD Configuration)
else if (e.Control == true & e.KeyCode == Keys.D2)
MainForm_MiddleTopConfig_Click();
#endregion
#region Key = CTRL+3 (1×8 LCD Configuration)
else if (e.Control == true & e.KeyCode == Keys.D3)
MainForm_TopConfig_Click();
#endregion
}