Archive

Posts Tagged ‘programming’

Sending mail in .Net – just a few tips

January 31, 2009 4 comments

Sending mails in .Net is actually very easy. In just a few lines you can send you very first mail automatically:

MailMessage mailMessage = new MailMessage();
mailMessage.To.Add(new MailAddress("myfriend@domain.com"));
mailMessage.Subject = "Adrian's blog rocks";
mailMessage.IsBodyHtml = true;
mailMessage.Body = "Check out this cool blog";
SmtpClient emailClient = new SmtpClient();
emailClient.Send(mailMessage);

That’s pretty much it! You’ll probably ask about the from email address and the SMTP server. These are configured in Web.config:

<configuration>
    ...
    <system.net>
    ...
    <!-- the mail settings used to send emails -->
    <mailSettings&gt
      <smtp deliveryMethod="Network" from="admin@domain.com"&gt
        <network host="smtp.domain.com"/&gt
      </smtp&gt
    <mailSettings&gt
    ...
    </system.net>
    ...
<configuration>

But anyway you can specify them too:

mailMessage.From = new MailAddress("admin@domain.com");
SmtpClient emailClient = new SmtpClient("smtp.domain.com");

Multiple recipients

If you want to send your message to multiple recipients, just use message.To.Add. So if you have a string with semicolon(;) separated email addresses here’s the code for you:

String emailAddresses = "a.friend@domain.com; another.friend@domain.com";
foreach (String to in emailAddresses.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries)) 
{
    mailMessage.To.Add(new MailAddress(to));
}

The same goes for CC, BCC, ReplyTo.

Flag a message

Are you a fan of those follow up message? Let me show you how to send them. The idea is pretty simple: those mail messages have two headers – one for the flag and one for the follow up date. To get/set headers of a mail message just use the Headers property.

mailMessage.Headers["X-Message-Flag"] = "Follow up";
mailMessage.Headers["Reply-By"] = DateTime.Now.AddDays(1).ToString("ddd, dd MMM yyyy HH:mm:ss %K");

The above will send a message to be followed up one day later from the sending time. The format of the date in the Reply-By header is specified in RFC822 and if you want to know how to format a date in .Net, see this. If you just want to send your message use what I compiled for you.

The invalid subject error

If you try to set the message subject to a string that contains invalid characters you will get the error System.Net.Mail: The specified string is not in the form required for a subject. This can be easily fixed with

mailMessage.Subject = Regex.Replace(subject, @"[^ -~]", "");

Advertisements
Categories: Software Tags: ,

Internationalization for Swing standard components

July 30, 2007 5 comments

Internationalization is a very hot topic, especially on desktop applications. Java offers very nice, easy-to-use and comprehensive tools for this. And, unlike Microsoft, there are not undocumented features. On what I’ll go a little bit deeper in here is not an “undocumented” feature, but a little bit harder to find documentation for. As said, localizing a Java desktop application (developed on Swing) is pretty easy and straightforward. But what is a little bit harder is to localize the Swing standard components, like a file chooser dialog or a confirmation dialog.

For changing the localized texts on this components is fairly easy: simply set a key on the UIManager.

UIManager.put(name, value);

You must do this before creating the component or call SwingUtilities.updateComponentTreeUI(rootComponent) after.

What is more difficult is to know the right names for each component. Below I described some of the most important keys, the associated Swing components and their meaning. I also attached a screenshot with a file chooser dialog to easily identify its components (on the description you will also find a number to refer to the component on the given screenshot). Please keep in mind that these are LnF dependent.

JFileChooser components

Key name Associated component Description Default value
FileChooser.openDialogTitleText JFileChooser The text on the title bar (open dialog) Open
FileChooser.saveDialogTitleText JFileChooser The text on the title bar (save dialog) Save
FileChooser.lookInLabelText JFileChooser The text for the label in front of the folder selection box (open dialog) – 1 Look In:
FileChooser.saveInLabelText JFileChooser The text for the label in front of the folder selection box (save dialog) – 1 Save In:
FileChooser.upFolderToolTipText JFileChooser The tooltip of the button for navigating to the parent folder – 2 Up One Level
FileChooser.homeFolderToolTipText JFileChooser The tooltip of the button for navigating to the home folder – 3 Desktop
FileChooser.newFolderToolTipText JFileChooser The tooltip of the button used to create a new folder – 4 Create New Folder
FileChooser.listViewButtonToolTipText JFileChooser The tooltip of the button for switching to list view – 5 List
FileChooser.detailsViewButtonToolTipText JFileChooser The tooltip of the button for switching to detailed view – 6 Details
FileChooser.fileNameHeaderText JFileChooser The text placed on the header column displaying the file name in the detailed view – 7 Name
FileChooser.fileSizeHeaderText JFileChooser The text placed on the header column displaying the file size in the detailed view – 8 Size
FileChooser.fileTypeHeaderText JFileChooser The text placed on the header column displaying the file type in the detailed view – 9 Type
FileChooser.fileDateHeaderText JFileChooser The text placed on the header column displaying the last modified date of the file in the detailed view – 10 Date Modified
FileChooser.fileAttrHeaderText JFileChooser The text placed on the header column displaying the file attributes in the detailed view Attributes
FileChooser.fileNameLabelText JFileChooser The text of the label in front of the textfield containing the selected file name – 11 File Name:
FileChooser.filesOfTypeLabelText JFileChooser The text for the label in front of the filter selection box – 12 Files of Type:
FileChooser.openButtonText JFileChooser The text on the button used to select the file on an open type dialog – 13 Open
FileChooser.openButtonToolTipText JFileChooser The tooltip text for the button used to select the file on an open type dialog – 13 Open selected file
FileChooser.saveButtonText JFileChooser The text on the button used to select the file on a save type dialog – 13 Save
FileChooser.saveButtonToolTipText JFileChooser The tooltip text for the button used to select the file on a save type dialog – 13 Save selected file
FileChooser.directoryOpenButtonText JFileChooser The text on the button used to open a folder while browsing – 13 Save
FileChooser.directoryOpenButtonToolTipText JFileChooser The tooltip text for the button used to open a folder while browsing – 13 Save selected file
FileChooser.cancelButtonText JFileChooser The text on the button used to cancel the file selection dialog – 14 Cancel
FileChooser.cancelButtonToolTipText JFileChooser The tooltip text for the button used to cancel the file selection dialog – 14 Abort file chooser dialog
FileChooser.updateButtonText JFileChooser
FileChooser.updateButtonToolTipText JFileChooser
FileChooser.helpButtonText JFileChooser
FileChooser.helpButtonToolTipText JFileChooser
FileChooser.newFolderErrorText JFileChooser The error text to appear when an error occurs while creating a new folder Error creating new folder
FileChooser.acceptAllFileFilterText JFileChooser The description, to appear in the filter combobox, for the filter used in the file chooser to accept all the files. All Files
OptionPane.yesButtonText JOptionPane The button caption for confirmation in an option dialog Yes
OptionPane.noButtonText JOptionPane The button caption for denying an option dialog No
OptionPane.cancelButtonText JOptionPane The button caption for aborting an option dialog Cancel
ProgressMonitor.progressText ProgressMonitor The text for the progress monitor Please wait

If you want to see all the keys defined in the UIManager that paste the code below that will output them.

UIDefaults defaults = UIManager.getDefaults(); 
System.out.println(defaults.size()+ " properties"); 
for (Enumeration e = defaults.keys(); 
    e.hasMoreElements();) { 
  Object key = e.nextElement(); 
  System.out.println(key + " = " + defaults.get(key)); 
}

This code doesn’t display the properties in the above table. Those properties are subject to localization and they could be displayed using UIManager.get(propertyName) or UIManager.getString(propertyName, locale).

Categories: Software Tags: , , ,

Passing POST parameters with AJAX

July 19, 2007 8 comments

AJAX can be used not only with webservices but with HTTP applications as well. So instead invoking a webservice, you’ll make an HTTP request. This comes veryhandy when using legacy application or when your usage of AJAX is very limited and webservices are simply too much.

What I wanted to share is a small trick on how to pass POST parameters with AJAX. The entire exercise will consist of defining a function called doPost that will receive as parameters the url and a two-dimensional array of parameters

function doPost(url, parameters) { 
  // create the AJAX object 
  var xmlHttp = undefined; 
  if (window.ActiveXObject){ 
    try { 
      xmlHttp = new ActiveXObject("MSXML2.XMLHTTP"); 
    } catch (othermicrosoft){ 
      try { 
        xmlHttp = new ActiveXObject(
            "Microsoft.XMLHTTP"); 
      } catch (failed) {} 
    } 
  }    

  if (xmlHttp == undefined &amp;&amp; window.XMLHttpRequest) { 
    // If IE7, Mozilla, Safari, etc: Use native object 
    xmlHttp = new XMLHttpRequest(); 
  }  

  if (xmlHttp != undefined) { 
    // open the connections 
    xmlHttp.open("POST", url, true); 
    // callback handler 
    xmlHttp.onreadystatechange = function() { 
      // test if the response was totally sent 
      if (xmlHttp.readyState == 4 
            &amp;&amp; xmlHttp.status == 200) { 
        // so far so good 
        // do something useful with the response 
      } 
    }  

    // create the parameter string 
    // iterate the parameters array 
    var parameterString;  

    for (var i = 0; i &lt; n; i++) { 
      parameterString += (i &gt; 0 ? "&amp;" : "") 
          + parameters[i][0] + "=" 
          + encodeURI(parameters[i][1]); 
    }  

    // set the necessary request headers 
    xmlHttp.setRequestHeader("Content-type", 
        "application/x-www-form-urlencoded"); 
    xmlHttp.setRequestHeader("Content-length", 
        parameterString.length); 
    xmlHttp.setRequestHeader("Connection", "close");  

    // send request 
    xmlHttp.send(parameterString); 
  } 
}

The parameters string can be constructed in a different way or even the parameters can be passed to the method in a different format. In the above case the parameters are passed as a two-dimensional array, everyline representing a parameter, again an array containing name (first element) and value (second element).

A call to the above function would look like this:

doPost("doIt.jsp", new Array(new Array("action", "action1"), new Array("id", "123")));
Categories: Web Tags: , , ,

Centering a DIV using CSS

July 11, 2007 2 comments

Using DIVs instead of TABLEs and CSS formatting should be a good practice for any web developer/designer. But how would you center a DIV? If you’ll do a page and you’ll want to optimize the contents for a specific resolution and center (this should be default and desired way) the contents then this will be one of your first CSS questions.

The answer is very easy. Supposing you have the following HTML fragment

<body> 
    <div id="content">My page</div> 
</body>

Then centering the content DIV will be made using the following CSS code:

BODY { 
    text-align: center; 
    min-width: 800px; 
} 

DIV#content { 
    margin-left: auto; 
    margin-right: auto; 
    width: 800px; 
    text-align: left; 
}

Now let’s see what exactly the code is doing. Centering the div horizontally is pretty easy. Simply specify a width (this is mandatory, otherwise it won’t work – usually it will be the resolution for which you want to optimize) and then set the right and left margin widths to auto.

Unfortunately only this won’t do the trick in IE (big surprise :D) and it will require another small hack. You have to set the text-align property for the BODY to center and then redo it for the DIV.

One last thing: in Mozilla, when resizing the window, a part of the DIV will fall on the left of the page, making the page unusable. Simply specify a min-width for the BODY.

If you take into account that you can replace BODY with any other DIV, then you have a general DIV centering method in just a few lines of CSS code.

Categories: Web Tags: , , ,