Deploy website to Windows Azure with Web.Config transformations

by Sander Gerz November 01, 2013 08:17

Web.config transformation is a simple and powerful inclusion in .NET 4.0 for generating configuration files for different environments. If you publish from Visual Studio, web.config transformation is very easy and painless. Publishing from Visual Studio to a Windows Azure hosted website also presents no particular problem. However, if you want to deploy automatically to Windows Azure using source control integration, you may have a more troubled experience. At least, that was my experience.

First, I followed these steps to publish the website from TFS. It works great if you use the same Web.Config for both development, staging and production. But when you want to use Web.Config transformation in the build process, and you do a search for this scenario, you will run into countless instructions, how-to's, stack overflow questions, and potentially some answers. All or any of them may work, but I was hit by two problems when queuing a new build.

Upon various attempts to get it to work, these two error messages appeared:

  1. The process cannot access the file 'Web.Config' because it is being used by another process.
  2. Could not write Destination file: Access to the path '...Web.Config' is denied.

The first is related to a problem to a bug in MSBuild whereby Web.Config is locked while reading the file, so it cannot also write to the file for the transformation. The second problem is related to Web.Config being readonly because of it's checked in status. MSBuild does get the latest version from TFS, but keeps the readonly file attributes. 

In order to fix this, I had to add this little snippet to my Web project file. 

  <Target Name="BeforeBuild">
    <Exec Command="attrib -R Web.Config" />
    <Copy DestinationFiles="Web.Temp.Config" SourceFiles="Web.Config" />
    <TransformXml Source="Web.Temp.Config" Transform="Web.$(Environment).Config" Destination="Web.Config" />
  </Target>

Firstly, we make sure that the file is no longer read-only. Then we copy this file to a temporary file. The transformation is done from this temporary file back into the original Web.Config.

Note that I use the parameter "$(Environment)" in this snippet. The value is taken from a parameter set in the Build Definiton. Under "MSBuild Arguments" I entered: /p:Environment=Staging. And this means that the value for Enviroment is set to, you guessed it, Staging. You need to make sure that you do have a Web.Staging.config transformation file in your project of course. 

After a very long search, trying out all kinds of scenarios with different parameters, pre-build and post-build tasks, it boiled down to this simple fix.

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Nice things to know when you're doing Windows 8 app development in html and JavaScript

by Sander Gerz June 22, 2012 11:07

Recently, I had my first Windows 8 app going through the process of certification for the Windows Store. Certification did not going smoothly the first time.

For a Windows 8 app to be certified, it has to meet a number of requirements: http://msdn.microsoft.com/en-us/library/windows/apps/hh694083.aspx?ppud=4

Upon failure, the test results will only mention the requirements on which it failed. While the requirements in themselves seem clear, upon failure they become quite obscure as they do not tell you what really went wrong. The first requirement for example:
1.1 Your app must offer customers unique, creative value or utility

Ok, so you build an app that you think is unique and valuable. But the tester may think it's not. There's little room for arguing.

The problems with my app referred to these two requirements

1.2 Your app must be fully functional when the customer gets it from the Windows Store
3.2 Your app must not stop responding, end unexpectedly, or contain programming errors

They seem logical at first hand, but they may still puzzle you because it's unclear what is wrong exactly. You have surely tested your app to not crash, and the app should be functional. Otherwise, you would not have submitted it, right? So what's wrong?

Here are some tips that you may find useful in pinpointing issues.

The location api
The Windows runtime offers a very easy to use api for retrieving the user's location.
http://msdn.microsoft.com/en-us/library/windows/apps/hh464926.aspx

When you add this capability to your app, through the manifest, the app will automatically ask for the user's permission. You need to take care of a few issues in your app when using the location api:

  1. What will you do in your app if the user does not allow the use of the location? Will you offer an alternative, provide a default location? Or will you limit the functionality?
  2. The location api is not always reliable. In about 10% of my test runs, the app could not get a location. On a second run, without changing the code, there was no problem and the location was retrieved instantly.
  3. If you run the app in the simulator, you can simulate another location by setting different values for latitude and longitude. Especially when running in the simulator, problem nr 2 showed up, where no location was detected. More importantly, what will your app do if a location is far from your own location. Will it still display relevant data? This is important to check as a tester will unlikely have your location.

Certification issue 1.2 for my app was related to this location api. Due to various reasons, the app would not get a location or not a location for which it had relevant information. A few solutions to tackle this are:

    1. Try to retrieve the location a few times. Yes, that may sound weird, but my app now tries to retrieve the location 4 times:
    var locService = new location.locationService();
    setTimeout(function() { locService.getLocation(processLocation); }, 0);
    setTimeout(function() { locService.getLocation(processLocation); }, 1000);
    setTimeout(function() { locService.getLocation(processLocation); }, 3000);
    setTimeout(function() { locService.getLocation(processLocation); }, 8000);
    setTimeout(function() { testLocation(); }, 10000);

    The function getLocation() is simply a call to getGeopositionAsync() on an instance of Windows.Devices.Geolocation.Geolocator(), and calls back to processLocation when it's done. The function is executed instantly, then again after 1, 3 and 8 seconds. After 10 seconds, there's a test to see if the location was found. If not, a message will display. I have found that the app will sometimes have the location instantly, sometimes the second try or the third try. Still, there are cases when even after 4 tries, a location could still not be found.

    2. If you know that your app only provides relevant data within a certain area, you can add this as a comment to the tester when you submit your app. Of course, it's better to provide the user with an alternative, like a default location or a way to enter a preferred location.


Displaying messages
You know that you should notify the user that there's no network, a location could not be found, or any other situation that may impact the functionality of the app. This notification could be subtle in a status location, but you can also use this method:

http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.popups.messagedialog.showasync.aspx

var message = new Windows.UI.Popups.MessageDialog("No network connection.");
message.title = "Network error";
message.showAsync();

The message is shown asynchronously, meaning that the application will continue even while displaying the message. If you have another message to show, then you will get an 'access denied' exception on showing the second message. If you do not handle that exception, your application will crash. This was certification issue number 3.2.

You fix it by keeping track of any open dialog messages. Or you can put the message.showAsync() method in a try-catch block. I chose the latter.

Other tips

The tips above were enough to fix the app and let is pass through the certification process. There are some other tips that helped me in building the app.

Windows 8 App Samples

Before you start building, download the Winodws 8 app samples: http://code.msdn.microsoft.com/windowsapps/Windows-8-Modern-Style-App-Samples

It’s like a buffet of code examples on how to accomplish certain things. The documentation on these samples are usually not that great, so you will have to take some time to figure out how a piece of code works fine in the example, but fail in your own app. Especially with the HTML/JavaScript examples, you will find that there’s a reference to an html-element in JavaScript that you don’t have (yet). With the XAML examples, that’s usually less of a problem because of compilation and type checking.

About page 

All apps have some sort of about page. If you request data from the internet, you will most likely also need some sort of disclaimer and privacy policy. These pages are supposed to be opened as a flyout, though the settings charm. Here’s the sample on how to create this page.

http://code.msdn.microsoft.com/windowsapps/App-settings-sample-1f762f49

CSS

Obviously, when you’re building your app in HTML and JavaScript, you also need to use CSS. This is all very convenient for web developers. If you are a more or less experienced web developer, that know your way around JavaScript and HTML, making an app for Windows 8 is pretty easy to do. There are a number of Microsoft-specific CSS rules that you will probably need to use:

  1. Grid Layout -  http://msdn.microsoft.com/en-us/library/windows/apps/hh453256.aspx
  2. Touch: Zooming and Panning - http://msdn.microsoft.com/en-us/library/windows/apps/hh453816.aspx
  3. Media Queries: http://msdn.microsoft.com/en-us/library/windows/apps/hh453556.aspx

The documentation is unfortunately lacking on a number of properties, and I cannot discuss them all here. You will not need them all, and most templates already have the necessary styles. One tip is to use

-ms-scroll-snap-type:mandatory;
-ms-scroll-snap-points-x: snapInterval(0%,50%);

This will make sure that when you have an app with multiple pages that you can slide from left to right, the page will ‘snap’ to the left of the screen. See: http://msdn.microsoft.com/en-us/library/windows/apps/hh441264.aspx

Happy coding.

Currently rated 4.1 by 336 people

  • Currently 4.122857/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Microsoft DevDays 2011– I’ll be there

by Sander Gerz April 12, 2011 22:46

 

This year, I’ll be at the annual Microsoft DevDays in The Netherlands where you can ask me anything on web development. My base of operation at the conference will be somewhere in the ‘Ask-the-Experts’ area. Though you may also find me hanging around in the Community Lounge.

But if time permits, I seriously hope to find some time to go some sessions too. With many interesting sessions running in parallel and with limited time, it’s important to have some criteria up front to make a decision where to go, and what to skip. These criteria usually involve: speaker (good) and topic (interesting). That’s nice and easy, but how do know if a speaker is any good, and if the topic is interesting? Hopefully, some tips below may help in that respect.

First, I set a goal for my self. What is it that I want to take away from the conference? Do I have a current project or a future one in mind? Is a certain problem bugging me that needs to be resolved? That makes the topic more important than the speaker. On the other hand, I also like to be surprised. It can soon get boring and a waste of time to attend a session on a subject that you are very familiair with already. With a conference like TechEd I always learn most from the IT Pro sessions, because that’s an area that I usually only follow from afar. And you learn about stuff you hardly knew existed. Granted, it’s also stuff that’s not readily applicable in my own daily work.

Anyway, being interested in web development, and already trying to keep track of most stuff Microsoft pushes out. Here’s a list of sessions I’d like to attend on Day 1:

1. 09:15 - 10:45  The Keynote (link). Especially Rob Miles can put a smile on my face, but I’m not sure what his role will be as he’s only mentioned as a speaker and not his topic.

2. 13:30 - 14:45  Windows Azure AppFabric: Building, Managing, and Connecting High-Density, Multi-Tenant Cloud Applications (link). It’s quite a long title, but both the topic and speaker are interesting. The timeslot is difficult in that there are quite a few interesting sessions going on at the same time. Fallback-sessions, in case I can’t find the room (yes, that happens Knipogende emoticon ) or it’s too crowded would be: Unlocking the Secrets of REST with WCF (link) and This Costs What? Estimating Costs in the Azure Cloud (link).

3. 15:05 - 16:20  Taking Control of your World with the .NET Micro Framework (link). Again with Rob Miles, just for the fun of it.

4. 16:30 - 17:45  This slot is again a challenge as several topics interest me, like What's New in Silverlight 5 (link), Test Driving ASP.NET MVC (link) but being really into C#, I should probably not miss Behind the Scenes of 10 C# Language Features by Bart De Smet (link).

In the evening, there’s GeekNight where the focus is on fun and less on function although the two can certainly mix well together. Mobile is hot it seems with cool sessions like:

Developing iPhone/iPad, Android and Windows Phone 7 Applications with C#, Visual Studio, Mono Touch en Mono Droid (link), Windows Phone in Rhyme and 3D (link) and Hoe Ontwikkel je een XNA Game voor de Phone 7, Xbox 360 en de PC met Dezelfde Code Base (link).

Actually, more sessions in the evening make me curious, but I haven’t managed to implement the me.Clone() method.

Then there’s Day 2, with these sessions on my agenda:

1. 09:15 - 10:30 HTML 5 - That's What You Need to Know Today (link) because I really need to get an update on the status of HTML5 and see if it’s usuable on websites with a large audience or not.

2. 10:50 - 12:05 Demystifying the .NET Asynchronous Programming Landscape (link) since async programming can be a lot simpler. At the same time, I’m running into disk I/O as the next bottleneck.

3. 13:15 - 14:30  Entity Framework 4 Tips en Tricks (link) although I’m a bit confused by the level-indicator: a 200-level ‘PowerTraining’ on subject that the audience should be familiar with. Alternatively, I could try Advanced Debugging with Visual Studio 2010 (link) with a great speaker on a difficult topic.

4. 14:50 - 16:05 WCF Web APIs, HTTP your way (link) even though I’m not a big fan of WCF (talking about configuration hell) but exposing APIs on a couple of projects I’m working on can be a great boost for exposure.

Not all timeslots are covered in this list. As I said, I should be at the Ask-the-Expert area as well. So it seems, you will only find me there on Day 1 from 10:45 to 13:30  and on Day 2 from 16:15 until the conference ends Knipogende emoticon . In summary, there are more interesting sessions than time permits, so this year’s Microsoft DevDays should be a blast. Hope to see you there!

Currently rated 4.2 by 290 people

  • Currently 4.155173/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

.NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET | .NET

Sending Tweets with C#

by Sander Gerz April 07, 2010 16:09

 

If you ever want to send updates to Twitter from C# it fairly easy to do. Recently, we added the option to send a tweet when someone registers for our upcoming dotNed user group meeting. Below is the client code.

using System;
using System.Web;
using System.Net;
using System.IO;
 
namespace Dotned.UI.Framework
{
    public class TwitterClient
    {
        public string Username { get; set; }
        public string Password { get; set; }
        public Exception Error { get; set; }
        private string _twitterUpdateUrl = "http://twitter.com/statuses/update.json";
 
        public TwitterClient(string userName, string password)
        {
            this.Username = userName;
            this.Password = password;
        }
 
        public void SendMessage(string message)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(_twitterUpdateUrl);
                request.Credentials = new NetworkCredential(this.Username, this.Password);
 
                SetRequestParams(request);
 
                string post = string.Format("status={0}", HttpUtility.UrlEncode(message));
                
                using (Stream requestStream = request.GetRequestStream())
                {
                    using (StreamWriter writer = new StreamWriter(requestStream))
                    {
                        writer.Write(post);
                    }
                }
 
                WebResponse response = request.GetResponse();
                string content;
 
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(responseStream))
                    {
                        content = reader.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                Error = ex;
            }
        }
 
        private static void SetRequestParams(HttpWebRequest request)
        {
            System.Net.ServicePointManager.Expect100Continue = false;
            request.Timeout = 50000;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded"; 
        }
    }
}

It is important to notice that you need to set a static flag in the ServicePointManager. Otherwise, Twitter will reply with error 417 – Expectation Failed.  Here’s an example that shows how to use this class:

   1: TwitterClient client = new TwitterClient("__Sander", "[not telling you of course...]");
   2: client.SendMessage("Testing my twitter client code.");

Currently rated 3.4 by 17 people

  • Currently 3.411765/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Why Silverlight?

by Sander Gerz November 14, 2009 20:05

Here’s a video I shot at the Silverlight panel discussion at TechEd Europe 2009 in Berlin.

Question was: what is the problem that Silverlight is trying to solve?

From what I could get out of the answers, the idea is threefold:

  1. Silverlight is a solution to line of business applications that, for reasons of reach, need to run in the browser.
  2. Silverlight is a media platform that support DRM and (live) streaming capabilities.
  3. Silverlight is a better alternative to Flash, especially for developers that are comfortable with the .NET Framework and languages such as C# and Visual Basic.

These answers were not given all at once in this particular video, but it became more clear during the rest of the discussion.

Are the reasons mentioned here valid, and what’s your reason for using Silverlight?

Currently rated 4.3 by 4 people

  • Currently 4.25/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Add bindings to a website (quickly)

by Sander Gerz August 18, 2009 11:58

As you know, IIS 7 is a powerful webserver. Just last month, after only three months of development time, we deployed the new website http://www.beurs.nl/ on an IIS 7 platform (with SQL Server 2008 back end).

This site, with over 7 mln pageviews/months, was built using ASP.NET MVC and Entitity Framework. A technology decision we haven't regretted. One advantage of ASP.NET MVC was the relative ease to support old urls that were still in use by other websites, and search engines. This meant that a url like http://www.beurs.nl/frame2.php still works. Sure, you can do that with simple URL rewriting, but obviously there are other advantages to using ASP.NET MVC. The webservers (three, load balanced) also run other sites, such as one for creating charts and another for the back-end CMS.

When figuring out which legacy urls to support, we found that the previous site had multiple aliases, such as koersen.beurs.nl, koersen3.beurs.nl, ticker.beurs.nl, etc. If we had a dedicated ip address for the primary site, and seperate ones for the other sites on the server, we could simply use a wildcard for all hostheaders. But... we do not. As a result, we needed to add each hostheader individually. The way to do this is described in this post. Though not difficult, it's quite a pain to do for 15 hostheaders, on three webservers. Yes, it's possible to share IIS 7 configuration, but we preferred not to. We do use DFS to mirror the website-folders.

As it turns out, it's not too difficult to add these binding from the command prompt:

c:\Windows\system32\inetsrv\appcmd.exe set site /site.name: www.beurs.nl /+bindings.[protocol='http',bindingInformation='*:80:forum.beurs.nl']
c:\Windows\system32\inetsrv\appcmd.exe set site /site.name:
www.beurs.nl /+bindings.[protocol='http',bindingInformation='*:80:grafieken.beurs.nl']
c:\Windows\system32\inetsrv\appcmd.exe set site /site.name:
www.beurs.nl /+bindings.[protocol='http',bindingInformation='*:80:koersen.beurs.nl']
...
etc


A simple script that takes 30 seconds to make and 2 seconds to run. AppCmd.exe is the single command line tool for managing IIS 7.0  that every developer/it pro should know.

 

Currently rated 3.6 by 7 people

  • Currently 3.571429/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

OpenSpaceCode code

by Sander Gerz June 06, 2009 11:01

These are the sessions for the OpenSpaceCode day.

image

Currently rated 3.3 by 6 people

  • Currently 3.333333/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Back to one week of TechEd Europe

by Sander Gerz May 12, 2009 17:25

Even though the Dutch Microsoft DevDays are still ahead of us, here’s a chance to look even further at TechEd Europe 2009. This year, it will be hosted in Berlin. But what is more surprising is the change back to a single week forwall both developers and IT pros. I certainly welcome this decision, and was never happy with the split that was made in the last few years. Even though I’m more active as a developer, I certainly spend a lot of time on managing a mixed Exchange 2003/2007 environment, and Windows Server 2003/2008 and need to help out every once in a while to troubleshoot on infrastructure.

But it would not only be for my personal benefit. I think it’s important and interesting for developers and IT pros to be able to see what’s happeing on the other side of the ‘fence’. Mark the dates in your calendar: 9-13 November 2009.

Currently rated 3.3 by 14 people

  • Currently 3.285714/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Working around "Cannot create an object of type 'System.Boolean' from its string representation"

by Sander Gerz April 18, 2009 21:05
In ASP.NET Web Forms most times there’s a need to set ASP.NET Server Control properties at runtime. This, for instance:
<asp:Button runat="server" id="Button1" visible="true" />

It is pretty straightforward to set the value of the visible-property in a code-behind page, like so:

protected void Page_Load(object sender, EventArgs e)
{
Button1.Visible = false;
}

However, it would be nice if you could to things like this

<asp:Button runat="server" id="Button1" visible='<% =User.IsInRole("Editor")%>' />

One might expect that that the expression above is evaluated such that the visible-property is true when the current User has the role of Editor and false if not. Unfortunately, executing this bit results in an exception:
Cannot create an object of type 'System.Boolean' from its string representation
'<%= User.IsInRole("Editor") %>' for the 'Visible' property. 
These problems are discussed also here and here. The reason is that the string-value of each property on a server-control is evaluated and parsed to its desired type. So you could set the property to "True" or "true", but not to an expression that needs to be evaluated.
The solution is to use a databinding syntax, which is pretty easy to do
<asp:Button runat="server" id="Button1" visible='<%# User.IsInRole("Editor") %>' />

As you can see, we simply add the pound/hash sign and remove the equals from the expression. This databind-expression is interpretered quite differently at runtime.

  • <%= %> is in reality the same thing as Response.Write().

  • <%# %> is more in related to assigning a value to an object. In the ASP.NET lifecycle, the <%# %> operators are evaluated before the page writes the first byte to the response buffer.

The problem with using a databinding expression is that you need to execute a DataBind() method either on the control itself or on the entire page. Executing DataBind() at page level can have negative side effects when you have multiple controls on the page with associated databinding logic. DataBind() at pagelevel triggers events, perhaps at times when you don’t want them. Using DataBind() in the codebehind for relevant controls defeats the idea a bit that we want to set a property with some simple rules and preferably in one place only.

A solution for this is to add another property (or attribute if you will), that just executes DataBind() on the current control. Something like this:

<asp:Button runat="server" id="Button1" visible='<%# User.IsInRole("Editor")%>'
code='<% DataBind(); %>' />

 

Unfortunately, that doesn’t work, because at runtime, the ASP.NET rendering engine will complain that a Button-control doesn’t have a property “code” so it doesn’t know what to do with it. However, we can trick it to ignore the property for rendering, but still execute the code, like so:

<asp:Button runat="server" id="Button1" visible='<%# User.IsInRole("Editor")%>' meta:code='<% DataBind(); %>' />


Prefixing the attribute with the text meta: with make the renderer ignore the value, but the code will still execute. Please note that the example uses meta:code, but it doesn’t really matter what name you give the attribute. It could be meta:execute or meta:whateveryouwant, as long as it’s not meta:resourceKey, because that property has special meaning.

It may not be the most elegant solution, but hey, if it works, I’m ok with it. With the rise of ASP.NET MVC we’ll probably see more of this type of coding anyway.

Currently rated 2.9 by 74 people

  • Currently 2.932432/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

.NET

Sharepoint Designer 2007 free download

by Sander Gerz April 04, 2009 10:55

Yes, that’s right. If you are working with Sharepoint, you can download the designer for free. Here’s where you can donwload it: http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=baa3ad86-bfc1-4bd4-9812-d9e710d44f42

Currently rated 3.0 by 33 people

  • Currently 3.030303/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen | Modified by Mooglegiant