Archive for Maggio, 2008
List To Generic List Converter
CodeKeep C# Feed Maggio 29th, 2008
->
Description: Converts a non-typed collection into a strongly typed collection
Credits: http://weblogs.asp.net/bsimser/archive/2007/05/08/generic-list-converter-snippet.aspx
Link: http://www.codekeep.net/snippets/f3658f93-d7c7-44c0-8431-6a826a2678ba.aspx
/// <summary>
/// Converts a non-typed collection into a strongly typed collection. This will fail if
/// the non-typed collection contains anything that cannot be casted to type of T.
/// </summary>
/// <param name="listOfObjects">A <see cref="ICollection"/> of objects that will
/// be converted to a strongly typed collection.</param>
/// <returns>Always returns a valid collection - never returns null.</returns>
public List<T> ConvertToGenericList(IList listOfObjects){
ArrayList notStronglyTypedList = new ArrayList(listOfObjects);
return new List<T>(notStronglyTypedList.ToArray(typeof(T)) as T[]);
}
Human readable file sizes (25 MB, 2 GB) from file size inbytes
CodeKeep C# Feed Maggio 28th, 2008
Description: Human readable file sizes (25 MB, 2 GB) from file size inbytes
Link: http://www.codekeep.net/snippets/b9dcda3e-5454-4ee7-b816-bf111c56c193.aspx
string GetReadableFileSize(long fileSize) {
long s = size;
string[] format = new string[] { "{0} bytes", "{0} KB", "{0} MB", "{0} GB", "{0} TB", "{0} PB", "{0} EB", "{0} ZB", "{0} YB" };
int i = 0;
while (i < format.Length - 1 && s >= 1024) {
s = (long)((long)100 * s / (long)1024) / (long)100.0;
i++;
}
return string.Format(format[i], s.ToString("###,###,###.##"));
}
Using ZIPLIB
CodeKeep C# Feed Maggio 27th, 2008
Description: How to use the ziplib on the fly
Link: http://www.codekeep.net/snippets/dc6c17a3-4d8d-4fb9-9e08-7592b2a8c377.aspx
using System;
using System.IO;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
class MainClass
{
public static void Main(string[] args)
{
string[] filenames = Directory.GetFiles(args[0]);
byte[] buffer = new byte[4096];
using ( ZipOutputStream s = new ZipOutputStream(File.Create(args[1])) ) {
s.SetLevel(9); // 0 - store only to 9 - means best compression
foreach (string file in filenames) {
ZipEntry entry = new ZipEntry(file);
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file)) {
StreamUtils.Copy(fs, s, buffer);
}
}
}
}
}
Button Event handler
CodeKeep C# Feed Maggio 27th, 2008
Description: change the name
Link: http://www.codekeep.net/snippets/22f612e6-79b2-449b-8987-2df154c1e48c.aspx
#region event handlers
protected void ButtonEventHandler(object sender, EventArgs e)
{
}
#endregion event handlers
Exception handling inititlization
CodeKeep C# Feed Maggio 27th, 2008
Description: Exception handling inititlization
Link: http://www.codekeep.net/snippets/ba986589-dd21-4056-80ff-273d418331f7.aspx
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(ExceptionHandler);
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
Start External Application
CodeKeep C# Feed Maggio 26th, 2008
Description: A simple method of starting an external application
Link: http://www.codekeep.net/snippets/f915fc5b-a717-4f2e-a21e-fdf3cfe95947.aspx
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClass, string lpTitle);
/// <summary>
/// Starts a specified app if not running
/// </summary>
/// <param name="appName">The name of the app</param>
/// <param name="pathToYourExe">The path to the app exe</param>
void StartSpp(string appName, string pathToYourExe)
{
if (FindWindow(null, appName) == System.IntPtr.Zero)
{
Process.Start(pathToYourExe);
}
}
Serialize Code
CodeKeep C# Feed Maggio 26th, 2008
Description: Stuff
Link: http://www.codekeep.net/snippets/b66bcc9e-3fa7-4d49-b173-0cfded008ce0.aspx
/// <summary>
/// Cache the gpEncounter to DB
/// </summary>
private void SaveToCache()
{
// Serialize to a memory stream
MemoryStream stream = new MemoryStream();
DataContractSerializer serializer = new DataContractSerializer(typeof(GpEncounter));
serializer.WriteObject(stream, _gpEncounter);
// Just make sure we're pointing at the beginning of the stream
stream.Seek(0, SeekOrigin.Begin);
// Save stream to the DB
CachingDataAccess.CacheGpEncounter(_guid, stream);
//Clean up
}
/// <summary>
/// Retrieve the GpEncounter from the DB
/// </summary>
private void RetrieveFromCache()
{
byte[] rawdata = CachingDataAccess.UnCacheGpEncounter(_guid);
MemoryStream stream = new MemoryStream(rawdata);
DataContractSerializer serializer = new DataContractSerializer(typeof(GpEncounter));
stream.Seek(0, SeekOrigin.Begin);
_gpEncounter = (GpEncounter) serializer.ReadObject(stream);
}
public static bool CacheGpEncounter(Guid guid, MemoryStream gpEncounterMemoryStream)
{
Database db = DatabaseFactory.CreateDatabase("StatConnection");
byte[] bytes = gpEncounterMemoryStream.ToArray();//NB Do Not use GetBuffer()
string sqlCommand = @"Delete from Cache where CacheGUID = @guid;
INSERT INTO Cache (CacheGUID, Blob) VALUES (@guid, @data )";
DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand);
db.AddInParameter(dbCommand, "guid", DbType.Guid, guid);
db.AddInParameter(dbCommand, "data", DbType.Binary, bytes);
db.ExecuteNonQuery(dbCommand);
return true;
}
public static Byte[] UnCacheGpEncounter(Guid guid)
{
Database db = DatabaseFactory.CreateDatabase("StatConnection");
string sqlCommand = @"SELECT Blob FROM Cache WHERE CacheGUID = @guid";
DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand);
db.AddInParameter(dbCommand, "guid", DbType.Guid, guid);
DataTable table = new DataTable();
byte[] bytes = (byte[]) db.ExecuteScalar(dbCommand);
return bytes;
}
MultiBinding
CodeKeep C# Feed Maggio 25th, 2008
Description: WPF MultiBinding with Converter
Link: http://www.codekeep.net/snippets/e1d1225a-a857-452d-9136-27c47980cb5f.aspx
<Rectangle Name="rtColor" Margin="25">
<Rectangle.Fill>
<SolidColorBrush>
<SolidColorBrush.Color>
<MultiBinding Converter="{StaticResource convertColor}">
<MultiBinding.Bindings>
<Binding ElementName="slAlpha" Path="Value" />
<Binding ElementName="slRed" Path="Value" />
<Binding ElementName="slGreen" Path="Value" />
<Binding ElementName="slBlue" Path="Value" />
</MultiBinding.Bindings>
</MultiBinding>
</SolidColorBrush.Color>
</SolidColorBrush>
</Rectangle.Fill>
</Rectangle>
<Window.Resources>
<local:ConvertColor x:Key="convertColor" />
<ImageBrush x:Key="newtelligencelogo" TileMode="Tile" Viewport="0,0,240,51" ViewportUnits="Absolute" ImageSource= "newtelligencelogo.bmp"/>
</Window.Resources>
public class ConvertColor : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
float alpha = (float)(double)(values[0]);
float red = (float)(double)(values[1]);
float green = (float)(double)(values[2]);
float blue = (float)(double)(values[3]);
return Color.FromScRgb(alpha, red, green, blue);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException("Not supported");
}
}
Ejecutar un programa externo
CodeKeep C# Feed Maggio 25th, 2008
Description: Ejecutar un programa externo
Link: http://www.codekeep.net/snippets/f2f35277-cff6-487a-a3fa-76ab693d9f42.aspx
class Program
{
static void Main(string[] args) {
System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
myProcess.EnableRaisingEvents = false;
System.Diagnostics.ProcessStartInfo myStarInfo = new System.Diagnostics.ProcessStartInfo("C:\\Archivos de programa\\Notepad 2rc\\Notepad2.exe", "");
myProcess.StartInfo = myStarInfo;
myProcess.Start();
}
}





