giovedì 8 agosto 2013

C# - Writing Only Number in a TextBox

If you have a Text Box and you want that your users write only numbers, you can use the following code:

private void textBox_KeyPress(object sender, KeyPressEventArgs e)
            if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar) &&                                     !char.IsPunctuation(e.KeyChar))
                e.Handled = true;

How you can understand the code is in the "KeyPress" event of the TextBox. 

My Two Cents ... 

C# - Sending Html Mail With Image(s)

Sometimes could be usefull sending html mail with image as a web page; we can use it for different purposes, for example news letters or  advertisements.
The Following Code shows how is possible to do it in C#.


using System.Net.Mail;
using System.Net.Mime;


string body = "<html> " +
              "     <head> " +
              "          <title>You HTML Mail With Image</title> " +
              "     </head> " +
              "     <body> " +
              "     <img src='cid:YourImage' /> " +
              "     </body> " +

            SendMail("", "FromDescription", "", "ToDescription", "MailObject", body, "", "User", "Password");

private void SendMail(string from, string FromDescription, string to, string toDescription, string MailObject, string body, string SmtpServer, string user, string password)
            MailMessage mailMessageWithEmbeddedPicture = new MailMessage();
            mailMessageWithEmbeddedPicture.IsBodyHtml = true;
            mailMessageWithEmbeddedPicture.From = new MailAddress(from, FromDescription);
            mailMessageWithEmbeddedPicture.To.Add(new MailAddress(to, toDescription));

            mailMessageWithEmbeddedPicture.Subject = MailObject;
            mailMessageWithEmbeddedPicture.Body = body;

            AlternateView altViewHtml = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);

            LinkedResource embeddedPicture = new LinkedResource("YourImage.jpg", MediaTypeNames.Image.Jpeg);
            embeddedPicture.ContentId = "YourImage";


            string warningMessage = "Use an E-mail Client that support HTML message!";

            ContentType contType = new ContentType("text/plain");
            AlternateView altViewText = AlternateView.CreateAlternateViewFromString(warningMessage, contType);


            SmtpClient smtpClient = new SmtpClient(SmtpServer);
            smtpClient.Credentials = new System.Net.NetworkCredential(user, password);


My Two Cents ...