Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Edgardo Rossetto

« Newer Snippets
Older Snippets »
Showing 1-8 of 8 total  RSS 

Add consolas to cmd.exe

// description of your code here

reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont" /v 00 /d Consolas


logoff

Read image metadata withWPF

// description of your code here

FileStream fs = new FileStream("image.jpg", FileMode.Open, FileAccess.Read, FileShare.Read);
BitmapDecoder decoder = BitmapDecoder.Create(fs, BitmapCreateOptions.None, BitmapCacheOption.Default);
BitmapFrame frame = decoder.Frames[0];
BitmapMetadata metadata = frame.Metadata as BitmapMetadata;

Calculate MD5 hash

// description of your code here
http://blogs.msdn.com/csharpfaq/archive/2006/10/09/How-do-I-calculate-a-MD5-hash-from-a-string_3F00_.aspx

public string CalculateMD5Hash(string input)
{
    // step 1, calculate MD5 hash from input
    MD5 md5 = System.Security.Cryptography.MD5.Create();
    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
    byte[] hash = md5.ComputeHash(inputBytes);
 
    // step 2, convert byte array to hex string
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < hash.Length; i++)
    {
        sb.Append(hash[i].ToString("X2"));
    }
    return sb.ToString();
}

Calculate age in C#

using System;
using System.Data;

public static class Snippets
{
    public static int CalculateAge(DateTime birthdate)
    {
        // get the difference in years
        int years = DateTime.Now.Year - birthdate.Year;
        // subtract another year if we're before the
        // birth day in the current year
        if (DateTime.Now.Month < birthdate.Month || (DateTime.Now.Month == birthdate.Month && DateTime.Now.Day < birthdate.Day))
            years--;

        return years;
    }
}

Resize image with .NET

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

public static byte[] ResizeImageFile(byte[] imageFile, int targetSize)
{
    Image original = Image.FromStream(new MemoryStream(imageFile));
    int targetH, targetW;
    if (original.Height > original.Width)
    {
        targetH = targetSize;
        targetW = (int)(original.Width * ((float)targetSize / (float)original.Height));
    }
    else
    {
        targetW = targetSize;
        targetH = (int)(original.Height * ((float)targetSize / (float)original.Width));
    }
    Image imgPhoto = Image.FromStream(new MemoryStream(imageFile));
    // Create a new blank canvas.  The resized image will be drawn on this canvas.
    Bitmap bmPhoto = new Bitmap(targetW, targetH, PixelFormat.Format24bppRgb);
    bmPhoto.SetResolution(72, 72);
    Graphics grPhoto = Graphics.FromImage(bmPhoto);
    grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
    grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
    grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
    grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, targetW, targetH), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel);
    // Save out to memory and then to a file.  We dispose of all objects to make sure the files don't stay locked.
    MemoryStream mm = new MemoryStream();
    bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
    original.Dispose();
    imgPhoto.Dispose();
    bmPhoto.Dispose();
    grPhoto.Dispose();
    return mm.GetBuffer();
}

Crop image with .NET

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

public static byte[] CropImageFile(byte[] imageFile, int targetW, int targetH, int targetX, int targetY)
{
    Image imgPhoto = Image.FromStream(new MemoryStream(imageFile));
    Bitmap bmPhoto = new Bitmap(targetW, targetH, PixelFormat.Format24bppRgb);
    bmPhoto.SetResolution(72, 72);
    Graphics grPhoto = Graphics.FromImage(bmPhoto);
    grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
    grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
    grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
    grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, targetW, targetH), targetX, targetY, targetW, targetH, GraphicsUnit.Pixel);
    // Save out to memory and then to a file.  We dispose of all objects to make sure the files don't stay locked.
    MemoryStream mm = new MemoryStream();
    bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
    imgPhoto.Dispose();
    bmPhoto.Dispose();
    grPhoto.Dispose();
    return mm.GetBuffer();
}

Autenticando por UserName o Email

protected void Login1_LoggingIn(object sender, LoginCancelEventArgs e)
{
    Regex r = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.Compiled);
 
    // sólo si el usuario ingreso un email
    if (r.IsMatch(Login1.UserName))
    {
        string username = Membership.GetUserNameByEmail(Login1.UserName);
 
        // esto significa que el usuario ingresó un email que no existe
        if (String.IsNullOrEmpty(username))
        {
            // mostramos un mensaje de error amigable y cancelamos la autenticación
            Literal error = Login1.FindControl("FailureText") as Literal;
            error.Text = "La dirección de email no se encuentra en nuestros registros.";
            e.Cancel = true;
        }
 
        else
        {
            // Encontramos el nombre de usuario :)
            // Reemplaza el email por el UserName verdadero
            Login1.UserName = username;
        }
    }
}

Mandar mail con ASP.NET 2.0

C#
MailMessage message = new MailMessage();
message.From = new MailAddress("remitente@lo.que.sea");
message.To.Add(new MailAddress("destinatario@lo.que.sea"));
message.Subject = "Asunto";
message.Body = "Cuerpo";
SmtpClient client = new SmtpClient();
client.Send(message);


web.config
<system.net>
    <mailSettings>
        <smtp from="email@algo.com">
            <network host="localhost" port="25" defaultCredentials="true" />
        </smtp>
    </mailSettings>
</system.net>
« Newer Snippets
Older Snippets »
Showing 1-8 of 8 total  RSS