Working with DateTime.Now in Windows Azure apps

October 26, 2011

 

For most of us displaying the current date and time is summed up in the following statement: DateTime.Now;

No big deal, but what happens if the time that is displayed is of by a hour? Well most of us would check to see what the machines timezone is and adjust the timezone of the machine to the correct timezone.

But we are in Azure now, Windows Azure instances run on the GMT / UTC timezone, do we adjust the timezone here as well? We could by defining a startup task that adjust the timezone to your preferred one. And from a migration scenario this could be the cheapest and fastest method.

Doing some research on the DateTime  usage turns out that there are some pretty good best practices around. In the case of Windows Azure its best to use UTC time in your application and convert it to the proper display value.

So instead of doing:

   1: var currentDateTime = DateTime.Now;

Use the following:

   1: var myTimeZone = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");

   2: var currentDateTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, myTimeZone);

I leave the creation of the proper extension method up to you Winking smile

Sending email from a windows azure application using an Office 365 mailbox

October 25, 2011

For one of my projects at work I’m trying to figure out what the best way of sending email from a Windows Azure application is.

Installing your own SMTP server in the cloud is not recommended for a couple of reasons. The main one, not having a static IP, which is a requirement when configuring the SMTP server to its DNS and PTR records.

So that leaves me with a few other choices:

  1. Use an on-premise SMTP server
  2. Use a third party email provider
  3. Use our new Office 365 to relay mail

Well option 1. isn’t going to be sustainable for the long run seeing as our on-premise Exchange server is being replaced by Exchange Online which is part of the Office 365 offering.

Option 2. Is a very good option and probably the best on which I will elaborate shortly.

For my setup I chose option 3, for the most part because I liked the idea of having a full Microsoft solution.

So what exactly did I do? I created myself a MVC.Net 3 application that includes the following class:

/// <summary>
/// Sends email
/// </summary>
public class EmailNotifier
{
    readonly string smtpUserName;
    readonly string smtpPassword;
    readonly string fromEmailAddress;
    readonly string smtpServer;
    readonly string smtpPort;

    public EmailNotifier()
    {
        smtpUserName = RoleEnvironment.GetConfigurationSettingValue("SmtpUsername");
        smtpPassword = RoleEnvironment.GetConfigurationSettingValue("SmtpPassword");
        smtpServer = RoleEnvironment.GetConfigurationSettingValue("SmtpServer");
        smtpPort = RoleEnvironment.GetConfigurationSettingValue("SmtpPort");
        fromEmailAddress = RoleEnvironment.GetConfigurationSettingValue("EmailAddress");
    }

    /// <summary>
    /// Sends an email to specfied address <paramref name="emailAddress"/>.
    /// </summary>
    /// <param name="emailAddress">The email address.</param>
    /// <param name="subject">The subject.</param>
    /// <param name="body">The body.</param>
    public void SendEmail(string emailAddress, string subject, string body)
    {
        var message = new MailMessage(fromEmailAddress, emailAddress)
        {
            Subject = subject,
            Body = body,
            IsBodyHtml = false,
            BodyEncoding = Encoding.UTF8
        };
        
        var smtpClient = new SmtpClient(smtpServer, int.Parse(smtpPort))
        {
            Credentials = new NetworkCredential(smtpUserName, smtpPassword),
            EnableSsl = true
        };
            
        smtpClient.Send(message);
    }
}

As you can see nothing special just a simple class using the System.Net namespace to send email directly via the SmtpClient class. Just note line 40 using SSL is required.

As for the SMTPserver and Port settings we need to retrieve those from Office 365. If you login to the account, from which name you will be sending the email from, go to the account settings page and at the bottom you’ll find the Settings for POP, IMAP and SMTP Access.

image

So nothing to it! But wait there is a little caveat I should warn about. Unlike your on-premise SMTP server, Office 365 has some limits as to the amount of recipients a single user can send emails to. These limits can be found in the Office 365 help. So I have a limit of 500 emails recipients I can send email to, good enough for me.

If your requirement is to send lots and lots of email this might not be the best solution and that’s why I would recommend Option 2 too use a third-party email provider. (ie. unifiedemail, sendgrid)

Windows Azure Tools: Unable to connect to dfService.

October 5, 2011

 

Installed the azure 1.5 SDK yesterday. When I tried to start my simple web role on my development fabric it was taking forever and would eventually end with the message: Windows Azure Tools: Unable to connect to dfService.

Apparently the path being used by the csrun.exe to save its state cannot contain spaces, so setting the environmental variable  _CSRUN_STATE_DIRECTORY to a path without spaces solves the problem.

For the complete story: http://207.46.172.252/en-us/library/hh472165.aspx

The curious case of the non transformed web.config when publishing to Windows Azure

February 7, 2011

Whilst tinkering with my solution, I’m trying out different configurations which sometimes involve adjusting my transformation templates I’ve configured on the web.config’s.  Unfortunally the Windows Azure Tools 1.3 version packages the solution, does the transforms BUT doesn’t put them in the web application folder. The files are stuck in the obj\release\transformwebconfig\transformed folder.

My quick fix for now is to, remote desktop in and copy the file by hand. But of course this is just a cheap transient solution which won’t survive a Re-Image.

Keep you updated!

Update: 08-02-2011

What did I found out thus far: Webtransformations do work if it is the main webrole/site being transformed. But if you have virtual directories pointing to other webprojects in your solution the behavior is as mentioned earlier.

Publish packages are actually encrypted zip files. For debugging purposes you can turn of encryption by adding the _CSPACK_FORCE_NOENCRYPT_ environmental variable to your system variables and set it to true.

image 

If you wonder what the publish… – action really does, it calls for MSBUILD file Microsoft.CloudService.targets which can be found at: C:\Program Files (x86)\MSBuild\Microsoft\Cloud Service\1.0\Visual Studio 10.0\.

If you want to view the output of the publish you’ll have to adjust your Visual Studio settings: Tools –> Options.. –> Project and Solutions –> Build and Run, set the MSBuild project build output verbosity at Detailed.

image

…. keep you updated

 

Update 2:

Submitted a bug at microsoft connect: https://connect.microsoft.com/VisualStudio/feedback/details/641913/visual-studio-azure-tools-sdk-1-3-not-packaging-multiple-sites-correctly

Running through WIF training kit got stuck on the setup

January 31, 2011

Whilst expanding one’s knowledge on Windows Azure one will eventually end up with the authentication and authorization dealings using Windows Identity Foundation. Windows Identity Foundation (WIF)  is a Microsoft technology that offers APIs for ASP.NET and WCF developers that can be used to build claims-aware and federation capable applications.

Microsoft has released the identity developer training kit to get you started on WIF. My con-colleague Patriek van Dorp also recommends reading Programming Windows Identity Foundation to get a firm grasp on all the facets of building claims based applications. Of course I ordered the book and started on the training kit but whilst getting my Identity Groove on I immediately run in to trouble setting up certificates for my lab: WindowsAzureAndPassiveFederation.

To keep the story short I forgot to run the SetupCmd. Why? I had so many problems with the Azure trainingkit not running properly settings up labs, I automatically run in do it yourself mode.

For those still  reading, doing it yourself can be quite educational you’ll get into the whole certificate registration hell process. The training kit uses CAPICOM, MakeCert, pvk2pfx to setup certificates on your machines to enable trust relations between the various components in your solution. For me making a certificate was not that hard seeing that the command was readily available in the setup scripts.  But because I didn’t have CAPICOM installed I was not sure how to install the certificates correctly.

 

image

The certificate you need to have installed in the Windows Azure Web Role comes from the LocalMachine location. Unknown to me was that the certificate I installed in the store didn’t contain a private key (I uploaded the .CER file, I should have uploaded the .PFX file) . I wanted to remove the file but was sure as the command I was supposed to use to remove it from my localmachine location store. After some looking around I found the answer to view my certificates from my localmachine, the thing to remember is to select the local computer. From this screen it’s easy to view your certificates but also delete and import new ones.

image

Windows Azure – Problem with WCF service In development environment

January 17, 2011

 

I was getting a CommunicationObjectFaultedException every time I started my service and I didn’t have any clue as to why. Because during my earlier runs it just “worked”.

I thought last week while presenting on Windows Azure to my colleague’s I had every thing well prepared and tried and tested every thing.

This was one of those kind of moments you want you computer program to be alive so you could hit it in the face. 

Today I figured out what I did “wrong”. What happened was that I did a check-in of the code, which is no problem in itself, but it is a problem because it makes the web.config READ-only. And for some obscure reason the devfabric controllers wants this to be readable.

In short I checked out the web.config and could start my service again :-)

image

Finding hard to track problems with WinDbg

December 1, 2010

This week a college ask me to help him out tracking some strange behavior on one of the production servers of one of our clients. Having found no hints himself in log files and event logs he started to think that Microsoft commerce server was swallowing exceptions (because it has happened  in the past).

After I verified the where no abnormalities in the eventsviewer and logs I started following my colleges instincts and started my very first WinDbg session hoping to get back a MS commerce server stacktrace to pinpoint where stuff went wrong.

Having heard of WinDbg at teched two years earlier I was kind of excited to use it for the very first time. I remembered that you had to do something to get .Net stacktraces and yes google is your friend. You need to load in the proper SOS.dll but I was still getting:

CLR exception – code e0434f4d (first chance)

turns out I forgot to ENABLE the CLR exception which you can do by going into the debug menu and enabling it.

image

And there was a nice trace which I could get with the !clrtrace command. Turns out there was no commerce server problem but the businessvalidationexception that was thrown wasn’t handled properly.

Lesson learned WinDbg is kewl! and validate the chain of events (and investigate the exception handling strategy ) before you go and install serious debugging tools on a production environment.

 

Hans

Windows server App-fabric auto-start rocks!

November 16, 2010

My colleges and I were debating in how best to build a robust service for our third-party email providers. The biggest problem is that our third-party email providers aren’t very robust in their up-time. Setting up reliable messaging is something we expected we were doing by using a third-party provider. Well that was a mistake:D

So we have to use some sort of queuing mechanism, for storing messages if our third-party is offline. Off course windows offers MSMQ out of the box so we got to play around with it in combination with WCF we got a head start with Dennis van der Stelt’s excellent blog post.

As I have been reading up on Azure and the new capabilities of the windows server appfabric  the idea of hosting our reliable service in IIS looked promising. In the windows server appfabric (IIS 7.5) you have the option of auto starting your services, which you need if you want read the queue if it has been filled while the service was offline. You could always host in a windows service but then you would miss out on the great diagnostics features hosting in IIS brings you.

Although the debate we had in the office was about using NServicebus V.S. native WCF. We know that NServiceBus offers more out of the bus box but we only need basic queue functionality and NServiceBus brings a bit more to the table. As we don’t want our support staff bothered by yet another framework to learn/know about it we ended with native WCF functionality.

Setting up Windows Azure Billing account

November 3, 2010

Yesterday me and my boss where setting up an Azure account and whilst the steps to setting up an account are pretty straightforward, we had some wishes that we had troubles figuring out.

 

What we wanted to do is use our MSDN Premium account benefits, which entitle you to use the Windows Azure platform for free for a curtain number of hours.

 

Services by Subscription Level (no extra charge) * Premium, Ultimate & BizSpark
Windows Azure Small compute instance 750 hours / month
Storage 10 GB
Transactions 1,000,000 / month
AppFabric Service Bus Connections 5 / month
Access Control Transactions 1,000,000 / month
SQL Azure Web Edition databases (1GB) 3
Data Transfers Europe and North America 7 GB in / month
14 GB out / month
Asia Pacific 2.5 GB in / month
5 GB out / month

To use these benefits we had to sign-in with our MSDN-account via the MSDN subscription page.

When you sign in you will be directed to the Microsoft Online Services – Customer Portal, where will have to setup your credit card information.

MSDN Azure description

This account will then become your Account Owner in the MOSCP (seeing as it has the creditcard information). If you don’t want your developers to have access to the billing information you can setup the Service Administrator account with a different live-id. The service Administrator is the account you use in the developer portal to manage you instances and services.

Service activation overview

So what didn’t worked out as well a we would have liked.

First of we had to use our MSDN email account as an billing account (this account is a multiuse account by multiple devs not a very clean solution)

Second the Service Administrator account is the only account that can put stuff in the cloud, I would rather see that I could assign multiple administrators (Which is announced at PDC2010 and should be available later this year)

Hans

JQuery clone() not maintaining "checked" state

July 8, 2010

If never been much of a front-end developer, but as most developers I manage my tags pretty well;-) but javascript has always been hell. I always stayed away from it but with JQuery the ballpark has changed a lot! Traversing the DOM has never been simpler, adding elements and attributes, moving them around, Childs play.

Yesterday my college noticed that the functionality I build for selecting checkbox items in div-popup’s didn’t work in IE8. So I’ve been puzzling why this was happing, this morning I found the culprit, it was the usage of the JQuery Clone  method.

JQuery offers a function to copy a element with all its events but as I found out the hard way checked state isn’t maintained during the function execution under Internet Explorer 6/7/8.

Which basically SUCKS!

After a lot of searching, I found out that there is a long standing bug ticket in the JQuery bugtracker. The bug is still unresolved but there where some workaround posted in the comments.

The workaround I chose is to implement was to override the clone function from JQuery itself. Note this clone function wasn’t approved to put in the core of JQuery due to performance reasons.

Overriding is quit simple just put the following script function in a javascript tag in your page (or separate file) . And call the function, the overriding magic is just on line Number 8.

   1:  function overrideJqueryClone() 
   2:  {
   3:      (function () {
   4:          // Store a reference to the original remove method.
   5:          var originalRemoveMethod = jQuery.fn.clone;
   6:   
   7:          // Define overriding method.
   8:          jQuery.fn.clone = function (deep) {
   9:              deep = deep != undefined ? deep : true;
  10:              var $this;
  11:              if (jQuery.browser.msie) {
  12:                  $this = this.add(this.find("*"));
  13:                  // Need to remove events on the element and its descendants
  14:                  $this.each(function () {
  15:                      this._$events = {};
  16:                      for (var type in this.$events)
  17:                          this._$events[type] = jQuery.extend({}, this.$events[type]);
  18:                  }).unbind();
  19:              }
  20:              // Do the clone
  21:              var copy = false, r = this.pushStack(jQuery.map(this, function (a) {
  22:                  if (!copy && deep && (a.hasChildNodes() || jQuery.nodeName(a, "select") || jQuery.nodeName(a, "input"))) copy = true;
  23:                  return a.cloneNode(deep);
  24:              }));
  25:              if (jQuery.browser.msie) {
  26:                  $this.each(function () {
  27:                      // Add the events back to the original and its descendants
  28:                      var events = this._$events;
  29:                      for (var type in events)
  30:                          for (var handler in events[type])
  31:                              jQuery.event.add(this, type, events[type][handler], events[type][handler].data);
  32:                      this._$events = null;
  33:                  });
  34:              }
  35:              // copy form values over
  36:              if (copy) {
  37:                  if (!jQuery.browser.msie)
  38:                      $this = this.add(this.find("*"));
  39:                  var origInputs = $this.filter('select,input[@type=checkbox]');
  40:                  if (origInputs.length) {
  41:                      var inputs = r.add(r.find('*')).filter('select,input[@type=checkbox]');
  42:                      origInputs.each(function (i) {
  43:                          if (this.selectedIndex)
  44:                              inputs[i].selectedIndex = this.selectedIndex;
  45:                          if (this.checked)
  46:                              inputs[i].checked = true;
  47:                      });
  48:                  }
  49:              }
  50:              // Return the cloned set
  51:              return r;
  52:          }
  53:      })();
  54:  }
  55:   

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

Simple isn’t it :-)


Follow

Get every new post delivered to your Inbox.