terug naar het overzicht

Removing dependencies from a Windows service

door Ronald 18-8-2011

Provisior, one of the products we develop here at ITQ, has two components: an intranet website and a Windows service. We use the Windows service for long-running processes that you typically do not want to run inside a web server.

 

The Windows service is installed the first time you start the website. When it’s installed, we add a dependency to the NetLogon service. This prevents the Provisior service from starting before the NetLogon service. We did this because our service attempts to access a SQL Server database right when it starts using integrated authentication. This fails when the NetLogon service has not started yet.

 

All of this works fine when the machine that runs Provisior is joined to a domain. However, when that is not the case, the NetLogon service doesn’t run. You can start it, but it stops again immediately with the following error in the event log (at least on my machine):

 

This computer is configured as a member of a workgroup, not as a member of a domain. The Netlogon service does not need to run in this configuration.

 

So now I have a Windows service with a dependency on NetLogon that doesn’t run. How to fix this? Apparently, removing service dependencies is only possible from the Windows registry. You need to go to the following registry entry: HKLM\SYSTEM\CurrentControlSet\services\<service>. There you find a REG_MULTI_SZ key named DependOnService where you can remove any services your service depends on. After doing so I had to reboot my machine because the service control manager did not see my update.

 

I could have updated Provisior to install the NetLogon dependency only when the machine is joined to the domain (here is some info on detecting whether your machine is joined to a domain). However, Provisior is hardly ever run on a machine that is not joined to a domain. This only happens in testing scenario’s so I’d be changing code just for this very specific case.

Tags: , , ,

Development | Provisior

Prevent duplicate form submits in combination with jQuery client-side validation

door Ronald 8-5-2011

The title says it all: I want to prevent clients from posting the exact same data twice (or more) but I also want to use client-side validation. Let’s first explain why this is problematic.

 

Preventing duplicate form submits is easy. You disable the submit button in the onclick event handler:

<input type="submit"
       onclick="$(this).attr('disabled', 'disabled');" />

This works fine without client-side validation. But now suppose that some client-side validation rule has triggered and the form is invalid. You now have a disabled submit button on your form.

 

To fix this, we must make sure to only disable the button when the form is valid. We introduce a Javascript function to do this:

   1: function disableSubmitButton(b) {
   2:   // Disable submit button as soon as possible to prevent
   3:   // duplicate submits.
   4:   $(b).attr('disabled', 'disabled');
   5:   var valid = $(b.form).valid();
   6:   if (!valid) {
   7:     // Re-enable submit button when form is invalid.
   8:     $(b).removeAttr('disabled');
   9:   }
  10: }

And our button now looks like this:

<input type="submit"
       onclick="disableSubmitButton(this);" />

The valid() method is available from the jQuery Validation Plugin. It provides a lot of client-side validation options and can be used out-of-the-box with ASP.NET MVC3.

 

That was easy. When a user clicks the button, it is disabled immediately unless the form is invalid. However, this appears to work only in Internet Explorer. In Chrome and Safari (I haven’t tested Firefox), if the form is valid, it is no longer submitted. This has probably something to do with the fact that I define a custom onclick handler, preventing some default onclick handler from running. In Internet Explorer this problem doesn’t occur for some reason.

 

To fix this, I changed the disableSubmitButton function to the following:

   1: function disableSubmitButton(b) {
   2:   // Disable submit button as soon as possible to prevent
   3:   // duplicate submits.
   4:   $(b).attr('disabled', 'disabled');
   5:   var valid = $(b.form).valid();
   6:   if (valid) {
   7:     // Submit form when it is valid.
   8:     $(b.form).submit();
   9:   }
  10:   else {
  11:     // Re-enable submit button when form is invalid.
  12:     $(b).removeAttr('disabled');
  13:   }
  14:   // Always return false to prevent Internet Explorer from
  15:   // posting the form (which would then be the second post).
  16:   return false;
  17: }

The submit button is changed to:

<input type="submit"
       onclick="return disableSubmitButton(this);" />

A bit more work than I thought it should be but it works.

Tags:

Development

Using the FileHelpers library in a medium trust environment

door Ronald 6-5-2011

Yesterday I found out the hard way that you should never use a third-party library without doing some preliminary checks. First of all. always check the license: does the author allow you to use his library and if so, how exactly? Second, check whether the library allow partially trusted callers.

Many hosting providers allow you to run your web applications in medium trust instead of full trust. This means that code executing inside your application is not allowed to do a number of things like: opening files, accessing the registry, write to the event log or emitting dynamic classes using System.Reflection.Emit.

Yesterday I was deploying a website to a hosting provider that included the FileHelpers library. If you need to parse CSV files into something you can work with, this is the library for you. It parses CSV files into strongly-typed objects and provides a host of configuration options to do this. Obviously, it has to use some kind of reflection to set property values. At a minimum, it has to call PropertyInfo.SetPropertyValue somewhere. Fortunately, this call is not under any security restrictions.

However, probably for performance reasons, this is not how the FileHelpers library implements setting properties. Instead, it uses the System.Reflection.Emit namespace to build a dynamic class that is then used to set property values. The System.Reflection.Emit namespace is littered with methods that have the SecurityCritical attribute. These methods can therefore only be used in a full-trust environment. Which means that the FileHelpers library can not be used in my website...

The obvious question then is: couldn't you have checked this beforehand? Well, actually I could have. Assemblies that should allow calls from partially trusted callers must explicitly set the assembly-level attribute AllowPartiallyTrustedCallers. The FileHelpers library doesn't have this attribute. Therefore, the first call into the library generates an exception: System.Security.SecurityException: That assembly does not allow partially trusted callers.

This was a bit of a problem since I promised a customer that the website would be live today. There are probably better fixes but what I did was the following (only works for FileHelpers by the way). I downloaded the source code and included it into my solution. This still makes no difference because there are still the SecurityCritical attributes in the System.Reflection.Emit namespace. The only difference is that errors are now thrown a little later in the process but it is at least possible to call FileHelpers methods. Now I got a little lucky. FileHelpers has been around since the first version of the .NET framework when probably not all necessary functionality of System.Reflection.Emit was available to implement FileHelpers. Anyhow, the code contains some #if NET_1_1 directives that prevent the use of System.Reflection.Emit (instead, System.Reflection is used). So I simply set this compiler symbol and it all worked.

Tags: , ,

Development | Security

Confused by jQuery 1.6 .attr() and .prop()

door Ronald 4-5-2011

I just read the jQuery 1.6 release announcement and I must admit I'm a bit confused about the new .prop() method and the breaking change to the older .attr() method. In jQuery 1.6 a distinction is made between DOM attributes and DOM properties. Attributes are things like style, class and title and represent the state of the DOM as retrieved from the document. Properties are things like value, checked and disabled and represent dynamic state of the document.

For example, suppose an input element: <input id="myInput" type="checkbox" checked="checked" />.

If you called $('#myInput').attr('checked') in jQuery 1.5 you got back the value true. In jQuery 1.6 it would be "checked" (the actual value of the attribute). If you call $('#myInput').prop('checked') you get back true. So far so good although a lot of people will probably be annoyed by the breaking change to the .attr() method because there are thousands of lines of code that check the value of a checkbox by using .attr().

However, besides breaking .attr(), the announcement of this change is very confusing. If you want to set the checked attribute of a checkbox, I would expect you should use: $('myInput').prop('checked', true). But the announcement has the following line:

In jQuery 1.6 Boolean attributes (such as selected, checked, etc.) can now be toggled by passing in true or false to .attr() to either add or remove them.

This is inconsistent. If you call .attr('checked') you get back the value "checked" but you should set the attribute by passing in the value true. Or can you still call .attr('checked', 'checked') as you could in jQuery 1.5?

Tags:

Development

IE9 Jumplist

door Sander 28-3-2011

In the latest version of Internet Explorer users now have the option to pin a tab to the taskbar. It works like a favorite, but just one click away instead of having to open the browser first.

Pinning a tab is a nice feature, but they didn’t stop there, these pinned pages can also supply custom jumplists to make access to common tasks even friendlier.

To demonstrate this feature I added a jumplist to our own product Provisior Smile

 

pinnedtab3

 

Provisior uses a MasterPage to define the overall layout of the site. This is where the custom jumplist lives as well.

This is what a jumplist item looks like in the HTML source:

<meta name="msapplication-task" content="name=Mijn Info;action-uri=http://localhost/Celerior.Annapurna.UI/MyInfo.aspx;icon-uri=http://localhost/Celerior.Annapurna.UI/App_Themes/Light/Icon/myinfo.ico" />

Just another meta in the page head section, easy enough. But what about dynamic jumplist items? Here’s how I take care of that:

 

In the MasterPage codebehind I created a simple method that adds a new <meta /> to the page header. Note that the head section in the aspx needs to have the runat=”server” attribute set to programmatically manipulate the header.

private void addMeta(string name, string content)
        {
            var m = new HtmlMeta();
            m.Name = name;
            m.Content = content;
 
            Page.Header.Controls.Add(m);
        }

To add the jumplist item I can now write the following in the MasterPage Page_Load event:

addMeta("msapplication-task", "name=Mijn Info;action-uri=" + webHost + "/MyInfo.aspx;icon-uri=" + iconPath + "myinfo.ico");

The code above outputs the <meta /> in the first codesnippet.

 

In the Page_Load you can now write anything you want about when the jumplist items are shown.

 

There are some other tricks you can do like set the name of the jumplist and the size of the browser window when the site is launched from the taskbar:

<meta name="application-name" content="Provisior" />
<meta name="msapplication-window" content="width=1024;height=768" />

There is also a way to do all this in Javascript but I’ll let you discover that on your own (Here is a good start Smile)

 

To see some of these jumplists in action, try pinning Twitter or Facebook to your taskbar and right-clicking the icons.

 

Have fun!

Tags:

Development | Provisior | Internet Explorer 9

Comparing WIF claim sets from AppFabric Access Control Service V2

door Ronald 16-1-2011

Windows Identity Foundation or WIF is a Microsoft technology that allows you to move authentication and authorization logic out of your application. Suppose you are building a web site, then using WIF you no longer have to build your own login page and user store. Instead, you let a so-called Identity Provider, sometimes called a Security Token Service or STS authenticate your users. Your web application, called the Relying Party (RP), has a trust relationship with the STS and when the STS presents a user token to the RP, the RP knows that the user represented by the token is authenticated.

To clarify the example a little, suppose you choose Windows Live as your STS. When I hit a secure section of my web site, WIF intercepts the request and redirects it to the Windows Live authentication page. I sign in with my Windows Live credentials, Windows Live creates a security token for me and redirects me back to my web site using this security token. WIF checks the token and I’m authenticated.

Multiple identity providers

In the example above I used a single STS but suppose I want to allow users from multiple identity providers (Google, Yahoo, Facebook, etc). Microsoft has a solution for this called AppFabric Access Control Service V2, available on portal.appfabriclabs.com. It is a proxy between your application and currently five identity providers.

image

In the screenshot I have activated two identity providers.

Claim sets

When you sign in to an identity provider, it generates a token that represents who you are. So what exactly is a token? A token contains a set of claims about a user and is digitally signed by the STS. So when I login to Windows Live, a token is generated that contains some claims about me. A claim can be an e-mail address or a last name or anything else that the identity provider may wish to disclose about you. And that’s what we are interested in today. Each identity provider provides a different set of claims. Some may produce more claims, others may produce just an identifier. So the question is: what are the claims provided by each identity provider currently supported by AppFabric ACS?

For this post I have not yet tested Microsoft Active Directory Federation Services 2.0 because I haven’t set that up yet. When I have, I’ll update this post or write a new one describing the possibilities that ADFS offers.

Before we start it is important to note that AppFabric ACS simply passes all claims from each identity provider through unchanged.

Windows Live ID

Windows Live is the provider that offers the least amount of claims. It only gives your application a unique user identifier. The other claim is added by AppFabric ACS to let you know what identity provider was used (you’ll see this claim type for every STS).

WindowsLive

Windows Live does not offer any options for getting more user information. This is a deliberate choice to protect user’s privacy. This is also the reason that Windows Live does not ask the user for confirmation to share information with a third-party application: no personal information is actually shared.

Google

Google offers a little more user information when asked for it. Besides, Google as an additional step explicitly asks your permission to share your information with AppFabric ACS. In my case this means that I have to confirm that rwwilden-appfabric-labs.accesscontrol.appfabriclabs.com is allowed access to information from my Google account.

Google

The reason Google asks for your permission to share information is that they actually provide information that can be traced back to a person.

Google does not offer any options for getting additional information.

Yahoo!

Yahoo! provides the same claims Google does. They also have a confirmation step to allow the user to think again before sharing information with a third-party application.

Yahoo!

Facebook

Facebook does not have a very good record of keeping its user’s data private (I inserted some random links to sites I found when searching for ‘facebook privacy violation’). However, the set of claims when using Facebook as your STS is limited. The extra claims are an access token and an expiration date.

Facebook

Besides, Facebook asks for your permission when you sign in for the first time, just as Google and Yahoo! do.

However, you can configure AppFabric ACS to ask the Facebook STS to grant access to an extensive set of permissions based on the access token claim. For example, I can let AppFabric ACS ask Facebook for permission to read a user’s birthday.

FacebookAppFabricACS

The above screenshot is from the AppFabric ACS portal. When I sign in this time via Facebook I get a new request for permission (in Dutch) asking me to allow the third-party application access to the birthday field.

image

When I allow this, there are no new claims added to the claim set. However, I can use the provided access token to get additional user data via Facebook’s Graph API. The url

https://graph.facebook.com/rwwilden?fields=birthday&access_token=

gives me a small JSON document:

{
   "birthday": "04/11/1977",
   "id": "100001960422926"
}

containing my birthday. So far so good. My application has requested permission to access my birthday, I have given this permission and using the provided access token claim I can access the birthday field.

What about other fields? The documentation for the Facebook API User object specifies that I need the user_work_history permission to read the work field. I have never given this permission so the following url should generate an error or at least no work history.

https://graph.facebook.com/rwwilden?fields=work&access_token=…

And it works as expected:

{
   "id": "100001960422926"
}

 

Conclusion

The differences between identity providers currently supported by AppFabric ACS are large. On the one end there is Microsoft with Windows Live, providing only a user identifier. On the other end there is Facebook with a lot of configuration options. If you want to support Windows Live ID, the only information the STS gives you is that a user is authenticated. Additional user information can only be stored inside your application.

Even if you use Google or Yahoo! you probably need to store additional user information. The Facebook API offers all personal information you may ever need to know about your users so there is no need to store any additional user information inside your application. Facebook clearly wins when you look at it from an application builder standpoint.

From a privacy standpoint it is clear that Microsoft wins. For a third-party application making use of Facebook as an STS it is very easy to know all about its users. It’s only one button click away.

Tags: , , , ,

Cloud | Development | Informatie beveiliging | Security

Using the ASP.NET MVC 3 Razor view engine in Windows Azure

door Ronald 11-1-2011

Yesterday I was trying to upgrade an ASP.NET MVC 2 web application to ASP.NET MVC 3 RC2. I also wanted to use the new Razor view engine that allows a more compact and less obtrusive way of writing ASP.NET MVC view templates.

There already is an excellent guide of how to upgrade your MVC 2 application to MVC 3 RC2. If you are running your MVC 2 application in Windows Azure, you must take some additional steps, which are described here. Visual Studio 2010 doesn’t (yet) allow you to specify an ASP.NET MVC 3 Web Role, so when running in Azure, you always have to upgrade if you want to use MVC 3.

You should reference some extra DLL’s from your MVC project and make sure that for all these DLL’s you set Copy Local to True. This is necessary because on the virtual machine your application is deployed to these DLL’s are not in the GAC. The DLL’s you have to reference are:

  • Microsoft.Web.Infrastructure
  • System.Web.Helpers
  • System.Web.Mvc
  • System.Web.Razor
  • System.Web.WebPages
  • System.Web.WebPages.Razor
  • WebMatrix.Data (I’m not sure why this one is necessary)

and these are located either somewhere below C:\Program Files (x86)\Microsoft ASP.NET for 64bits or below C:\Program Files\Microsoft ASP.NET for 32bits. So far so good.

Having taken all the required steps (or so I thought) I tried to run my first Razor template in the Windows Azure emulator:

image

No what I expected: The name ‘ViewBag’ does not exist in the current context. I must have forgotten something. After double-checking I had all the required dependencies that all had there Copy Local property set to True, I took a better look at the Compilation Source. My page appeared to extend from System.Web.WebPages.WebPage. This class doesn’t have a ViewBag property so that explains the compilation error.

Back to the upgrade instructions. It appeared I had forgotten one small step. In the Views sub directory there is an additional Web.config file. In an MVC 3 project, it contains a new configuration section: system.web.webPages.razor. In this section, a new page base type is specified: System.Web.Mvc.WebViewPage. After copying this Web.config file from another MVC 3 project, everything worked as expected.

A classic case of RTFM. But if you ever happen to see this compiler error when using the Razor view engine, check your Web.config file.

Tags:

Cloud | Development | ASP.NET MVC

Telerik RadChart Pie part colors

door Sander 4-1-2011

Fun little task today of making every pie-part a different color, but still within the range of colors used in the style of our app (Provisior).

 

I was unable to find a simple example as to go about this so here is one for those in need of one. The sample code is used with a Telerik RadChart for ASP.NET AJAX.

 

The cause of the problem is the unknown number of pie-parts that the chart will render. I could just make them all the same color, but that isn’t very pretty to look at and the default color aren’t bad, but they look out of place in our app (see the Provisior website and you’ll know what I mean).

 

before

 

We use a lot of white and gray in our style sheet, but to add some life to all the white and gray, we use orange. That will be the color from which we start mixing up new colors ending with red.

 

after

 

That is looking a lot better Smile Here is how this is done:

 

// The starting point of the G value in our RGB color
int baseG = 216;
 
// The amount we change the color for each item
int stepSize = baseG / uxChart.Series[0].Items.Count;
 
// Values for the G in our RGB colors
int mainG = baseG;
int secondG = 0;
 
foreach (var item in uxChart.Series[0].Items)
{
    // Set each item to a slightly different color.
    item.Appearance.FillStyle.MainColor = 
                        Color.FromArgb(255, mainG, 0);
    item.Appearance.FillStyle.SecondColor = 
                        Color.FromArgb(255, secondG, 0);
 
    mainG = mainG - stepSize; // Lower the main G value
    secondG = secondG + stepSize; // Raise the secondary G value
 
    // Don't let the colors error out due to an invalid value.
    if (mainG <= 0)
    {
        mainG = 0;
    }
 
    if (secondG >= 255)
    {
        secondG = 255;
    }

}

 

This code is executed right after the RadChart is databound using the .DataBind() method.

 

This is not perfect though, as you can see in the picture below. Having many parts in the Pie makes the changes to the colors very small which turns the Pie into one big gradient. The lines separating the parts add enough detail for me, so I’m fine with that.

 

lots

 

So there you go Smile

Tags:

Development | Telerik

Windows Azure Extra Small VMs

door Ronald 16-12-2010

At PDC10 Microsoft announced a new Compute Instance Size: Extra Small. Previously, there were four Azure Virtual Machine Instance sizes: Small, Medium, Large and Extra Large, each with its own price and resources. The standard price for an Extra Small instance is $0,05/hour (to compare, the Small VM costs $0,12/hour). What you get for this price is not a lot as you can expect:

 

  • 1 x 1GHz processor
  • 768 MB memory
  • 20GB storage
  • 5Mbps network bandwidth

 

These low resource levels are achieved by having multiple XS VMs share resources on the same node.

 

In my opinion the new XS VMs are interesting for two reasons. First of all, they’re ideal for testing purposes. Individual developers can get there own Windows Azure account and use it to deploy only XS instances. A few days ago I deployed an ASP.NET MVC app to four XS instances. After confirming everything worked, I removed the hosted service and the whole excercise cost me just $0,20.

 

A second reason this may be interesting is when you have a large workload that you can divide over a (very) large number of nodes. Suppose you have a workload that can be divided into 1000 chunks. Using 1000 Extra Small instances will cost you $50,00 per hour, using the same number of Small instances will cost you $120,00 per hour.

 

Deploying Windows Azure roles to Extra Small VMs is really easy. Just like the other VM sizes you select it in the role’s property panel:

 

image

Tags: ,

Cloud | Development

First impressions of the new Windows Azure Management Portal

door Ronald 1-12-2010

Yesterday evening I was working on a small Windows Azure project. One web role and one worker role with blob storage and a queue. I deployed the app yesterday using the ‘old’ management portal. This evening I had to choose: do you want to continue using the old portal or do you want to use the new and improved Silverlight management portal. That’s an easy choice to make.

 

At first looks it’s pretty complete. The home page offers some links to help pages in case you don’t know where to find your services. On the left you have a menu and the top contains a ribbon bar.

 

image

 

I’m not really into reading tutorials so the menu item ‘Hosted Service…’ seems the next logical step. It brings you to a window with some new menu options and the top-level one is ‘Deployment Health’. I’m not really a power user but it seems my single deployment is healthy, lucky me!

 

image

 

What’s also cool and what you see in every window is a timer that tells you when the data on the current window will be refreshed. In this case it’s 4 seconds until the next refresh.

 

As you can see I have one hosted service and one storage account. Selecting my hosted services brings you to the next window that shows my Azure subscription containing one hosted service.

 

image

 

There’s a wealth of information here. The properties pane on the right shows you relevant information for the selected node. You can select additional columns with information like ‘Environment’, ‘Subscription ID’ and others. When you select the ‘Storage Accounts’ menu item you can see the endpoint urls for your blob, table and queue storage and you get easy access to your primary and secondary access keys for accessing your storage.

 

Although I’m using just a tiny amount of the functionality offered by Windows Azure it seems that this new Silverlight portal is a huge improvement over the previous web-based one. First of all it gives the impression that it’s really fast. Second there’s a lot more information readily available. In the web-based portal this information was usually one or two clicks further away.

 

Until now I found one thing missing in the new portal and that’s the billing information. I’m not sure they should incorporate this into the Silverlight application but there should at least be a link to the Microsoft Online Services Customer Portal.

 

As you may have noticed in the screenshot, there’s a menu item in the bottom left corner called ‘Virtual Network’. This is actually the feature I told you about in a previous post that allows you to connect to on-premises machines from Windows Azure services. Unfortunately the beta program hasn’t started yet or my subscription for the Azure Connect has failed so I can give you no more details on that.

 

Maybe next time more on Windows Azure itself or on one of the new beta features (Extra Small VMs, Windows Azure Connect and VM Role).

Tags: ,

Cloud | Development