Archive for Novembre 11th, 2008

Union in C#

CodeKeep C# Feed Novembre 11th, 2008

Description: Union in C#

Link: http://www.codekeep.net/snippets/9ab1f74a-cf6e-4eaf-899e-f88c18d59038.aspx

    [StructLayoutAttribute(LayoutKind.Explicit)]
    struct SignedUnion
    {

        [FieldOffsetAttribute(0)]
        public sbyte Num1;
        [FieldOffsetAttribute(0)]
        public short Num2;
        [FieldOffsetAttribute(0)]
        public int Num3;
        [FieldOffsetAttribute(0)]
        public long Num4;
        [FieldOffsetAttribute(0)]
        public float Num5;
        [FieldOffsetAttribute(0)]
        public double Num6;
    }

Send an email using authentication

CodeKeep C# Feed Novembre 11th, 2008

Description: Send an email using authentication

Link: http://www.codekeep.net/snippets/d27e9332-ace6-41b1-bac1-01bafa401cd7.aspx

public Boolean Send(String subject, String body)
        {
            try
            {
                MailMessage message = new MailMessage(
                    m_from, m_to, subject, body);

                NetworkCredential creds = new NetworkCredential(m_smtp_username,
                    m_smtp_password);

                SmtpClient smtpClient = new SmtpClient();
                smtpClient.Host = m_smtp_server;
                smtpClient.Port = m_smtp_port;

                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials = creds;

                smtpClient.Send(message);

                return true;
            }
            catch (SmtpException)
            {
                return false;
            }
        }

Take a screenshot

CodeKeep C# Feed Novembre 11th, 2008

Description: Snap.

Link: http://www.codekeep.net/snippets/af8ce5f9-2746-475e-b0f0-2478b9b2b99b.aspx

        public static void TakeScreenshot()
        {
            Bitmap bmp;
            Graphics fx;

            bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                Screen.PrimaryScreen.Bounds.Height,
                System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            fx = Graphics.FromImage(bmp);

            fx.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size,
                CopyPixelOperation.SourceCopy);

            String fileName = DateTime.Now.Ticks.ToString();

            bmp.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);
        }

Open a new browser window at client (from C# server side)

CodeKeep C# Feed Novembre 11th, 2008

Description: C# code that pops a new brower open at the client end using javascript

Link: http://www.codekeep.net/snippets/9cf7826d-4027-4569-8fd5-1507fc1b08c0.aspx

String file = Server.MapPath("file.html");

String script = String.Format("<script language='javascript'>window.open (\"{0}\",\"{1}\",\"status=1,resizable=1,scrollbars=1,toolbar=1\");" +
       "<" + "/script>", file, DateTime.Now.ToFileTimeUtc());

Page.ClientScript.RegisterStartupScript(this.GetType(), "script", script);

xml2object (Deserialize)

CodeKeep C# Feed Novembre 11th, 2008

Description: Deserialize from xml to object

Link: http://www.codekeep.net/snippets/29f70cd3-a43a-46ca-9559-da853a27d048.aspx

XmlSerializer deserializer = new XmlSerializer(typeof(SomeType));

using (FileStream fs = new FileStream(filepath, FileMode.Open))
{
	return (SomeType)deserializer.Deserialize(fs);
}

Object2Xml (Serialize)

CodeKeep C# Feed Novembre 11th, 2008

Description: Serialize an object into xml

Link: http://www.codekeep.net/snippets/bf9ce1fe-29ba-46d5-8af1-7ae94dc5a5da.aspx

XmlSerializer serializer = new XmlSerializer(typeof(SomeType));

using (FileStream fs = new FileStream(filepath, FileMode.Create))
{
	serializer.Serialize(fs, instanceOfSomeType);
}

String hashcode from byte array

CodeKeep C# Feed Novembre 11th, 2008

Description: Handy for generating a unique (ish) filename from a file or array of bytes

Link: http://www.codekeep.net/snippets/780b5eed-ebfa-4450-b8c6-09170c186032.aspx

  	/// <summary>
        /// Generates a hashcode for use as a filename from the given byte array
        /// </summary>
        public static String GenerateHashcodeFilename(Byte[] byteArray)
        {
            Byte[] hashVal = new MD5CryptoServiceProvider().ComputeHash(byteArray);

            StringBuilder sb = new StringBuilder();

            foreach (Byte b in hashVal)
            {
                sb.Append(b.ToString("X2"));
            }

            return String.Format("{0}", sb.ToString());
        }

Basis of a simple xml serializable class inc. a collection

CodeKeep C# Feed Novembre 11th, 2008

Description: Basis of a simple xml serializable class inc. a collection

Link: http://www.codekeep.net/snippets/36ed6afe-5067-44d3-91df-e23b41d17584.aspx

namespace Name.Space
{
    [Serializable]
    [XmlRoot("RootName")]
    public class SerializeSomething
    {
        private String x;

        private List<x> listOfx;

        public SerializeSomething()
        {
            listOfx = new List<x>();
        }

        [XmlArray(ElementName = "ListName")]
        [XmlArrayItem(ElementName = "Item")]
        public List<x> SomeList
        {
            get
            {
                return listOfx;
            }
        }

        [XmlAttribute(AttributeName = "AttribInRoot")]
        public String RootAttrib
        {
            get
            {
                //
            }

            set
            {
                //
            }
        }
}

Quick static file logger

CodeKeep C# Feed Novembre 11th, 2008

Description: Template for a static file logger. DIVIDER is whatever you use to seperate the entries i.e a row of dashes etc.

Link: http://www.codekeep.net/snippets/4b71f3d9-e4a8-437f-9946-64039f3eada8.aspx

    public static void Write(String message)
    {
        StringBuilder builder = new StringBuilder();
        builder.AppendLine(String.Format("[{0}]", DateTime.Now.ToString()));
        builder.AppendLine(message);
        builder.AppendLine(Resources.DIVIDER);

        File.AppendAllText(LOGPATH, builder.ToString());
    }

Set registry key value

CodeKeep C# Feed Novembre 11th, 2008

Description: Set registry key value

Link: http://www.codekeep.net/snippets/4f24c71e-fcb3-4b02-a2b6-951c34dc652e.aspx

RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\...\...\",true);
key.SetValue("Name", newValue);

Next »