Programming Amazon EC2 by Jurg van Vliet and Flavia Paganelli is practical in nature and takes you through all the steps to create and configure accounts, develop applications, and deploy applications. If you’re new to Amazon EC2 (and related services) this is definitely a good place to start, because it goes through all the components Amazon offers, such as S3/Cloudfront and RDS for data storage. It also looks at how you can setup your application to scale up and down, and ensure your application has excellent uptime. The book takes you by the hand based on some applications the authors have created themselves. Although this approach makes the book practical, it sometimes reads as (irritating) marketing for their applications.

Workflow Services in .NET 4 allow you to do long running processes. But when you do that, there's an interesting question: when a workflow has been suspended, under which user is the workflow running when it is active again. To answer this question I created a simple workflow that writes the user in the current thread to a log. On the initial call, the user making the call was logged (in this case I used Windows Identity Foundation to authenticate, but this should be the same for all types of authentication). After a Delay of a minute that user was gone, and instead the user in the current thread was unauthenticated. This means that any code you call from the workflow can't rely on Thread.CurrentPrincipal to get the proper authorizations. You have to save the user, and somehow reinstate principal so it runs under the original context. Alternatively you can use some form of delegation.
Working with Windows Idnentity Foundation can be quite a minefield. Solve one issue, and the next creeps up. Because it's all these little tweaks to make it work, I often find myself thinking "How did I solve that last time?" One of those issues is the exception Could not establish trust relationship for the SSL/TLS secure channel with authority 'somesite.runningunder.ssl' There are two reasons why you can run into this exception, each discussed below.
The certificate isn't trusted and/or the URL doesn't correspond with the URL in the certificate. If this is the case, you get certificate warnings when you browse to the service WSDL with a browser. The best way to solve the former is to have your (development) environment
work with certificates it trusts. This means setting up a Certificate
Authority (Active Directory Certificate Services), placing the root CA
certificate in the Trusted Root Certificates of the machine your clients
(and services) run on, issuing the needed certificates from the CA, and
placing these where they are needed. Alternatively, you can just add a
single line of code to your client so it ignores certificate issues before you do any service call: System.Net.ServicePointManager.ServerCertificateValidationCallback =
((sender, certificate, chain, sslPolicyErrors) => true);WARNING! ONLY USE THE ABOVE CODE FOR DEVELOPMENT PURPOSES. IT IS NOT SECURE.
If after you've done the above you still get an exception, the above code is likely not even being hit. That means you (also) have the problem below.
You've setup identity trust in your client, and the certificate reference is incorrect. This often happens when you copied some configuration from somewhere, and forgot to change the corresponding certificate reference. The red stuff in the client configuration below (which is much longer in a real configuration) is the culprit. It should contain the encoded certificate.
<system.serviceModel>
<client>
<endpoint address="https://YourServer/Service1.svc"
binding="customBinding"
bindingConfiguration="CustomBinding_IService1"
contract="ServiceReference1.IService1"
name="Service1Binding">
<identity>
<certificate encodedValue="MIIF5jCCBM6gAwIBAgIKYSt2tQA..."/>
</identity>
</endpoint>
</client>
</system.serviceModel>
To solve this, you need to get the base64 encoded certificate string, and paste it in place of what's in there now. To get it you can do the following: - Browse to the endpoint with your browser.
- View the certificate information.
- Save the certificate to file.
- Open the certificate with notepad.
- Copy the encoded value between the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- placeholders.
I've been working with WCF for quite a while, and every so often I run into this exception:
ArgumentException: The provided URI scheme 'https' is invalid; expected 'http'.Parameter name: via
The problem is obvious. You're trying to access a service under HTTPS, but it's being called with HTTP. Under most bindings you can solve this by adding somehting like this to the client binding configuration: <binding name="MyBinding">
<security mode="Transport">
<transport clientCredentialType="None" />
<message clientCredentialType="None"
negotiateServiceCredential="false"
establishSecurityContext="false" />
</security>
</binding>
When you use a (custom) ws2007FederationHttp binding, for instance when working with Windows Identity Foundation, the above won't work. In that case you need to look in the binding for the <httpTransport> element and replace it with <httpsTransport>.
Recently I had the pleasure of diving into audit logging. I’m working on a government project which involves the law making process, so it is imperative that all database changes are completely traceable. That means that we need to be able to trace who made which changes and when. We’re working with latest and greatest version of SQL Server (i.e. SQL Server 2008 R2), which has a feature called SQL Audit. Reading the documentation SQL Audit seemed to do everything we need, except that it doesn’t know which application user is making the changes. This is logical since it is a web application and we’re using delegation. For this reason we were already planning to have the application send along the user id when it does an insert, update or delete, and we decided to only logically delete a record. So far so good.
When it came to testing, we quickly found that SQL Audit logs the SQL statement making the change. Sounds right doesn’t it? Well actually it isn’t. LINQ-to-SQL, LINQ-to-Entities and other O/R Mappers use parameter queries, and in fact if you edit records in the SQL Management Studio UI, the same is true. The problem is that the parameters are not part of the SQL statement being logged! So we can see which database user made what kind of change, but not which data was changed, and hence not which application user made the change either. Back to the drawing board :(.
In reviewing our options, we looked at:
- All logging in the O/R Mapper: Not an option, because we need to know what DBA’s do too.
- SQL Trace: not recommended by Redmond, and it takes a huge performance hit.
- Triggers: in transaction, taking enormous performance hit.
- C2 auditing: tracks all changes, so it gathers huge amounts of data, not easily searchable.
- Change Data Capture: really for BI purposes, deleted after three days, no indication of the user making the change.
All of the above options have some sort of problem associated with it. The conclusion is that there is no single solution, unless Microsoft fixes the SQL Audit issue (you can vote on it here: https://connect.microsoft.com/SQLServer/feedback/details/624935/sql-server-2008-database-audit-on-insert-update-and-delete-actual-sql-and-not-parameter-values).
We now do the following:
- In the Data Access Layer add the application user that did the insert or update in an extra field on the table.
- Only do logical deletes (i.e. add a “Deleted” flag to a table).
- Track all changes using Change Data Capture (which uses the transaction log and therefore has less impact on performance).
- Export CDC data to an “Audit Database” periodically (like using a data warehouse).
- Use SQL Audit for all changes done by a database user other than the DB account used by the application.
- Export SQL Audit logs to the Audit Database periodically.
By cross referencing SQL Audit and CDC data, we can figure out who changed what if the change was made outside the application.
I just upgraded my blog to the latest version of dasBlog. I also moved to another hosting provider. All content has been migrated, but there may be links that are not working on very old posts. I'll check these in the coming days so everything works as it should. If you happen to run ito problems, let me know.
I'm currently working on a project where we have a lot of semi-independent moving parts. One aspect is that we communicate with different applications, in a BizTalk style manner. We do this using Workflow Services to ensure delivery and have fault tolerance when running inside Windows Server AppFabric (see my post What is Windows Server AppFabric and why should I use it?). However, we wanted to ensure that these Workflow Services all provide the same interface from out side of the application, so we can call into them generically. This by the way happens when a status changes occurs on some entity we use. Getting the Workkflow Services to expose the same contract (more or less) is relatively easy. You just ensure that all services use the name namespace, operation name, and parameters. However, calling those generically through WCF was a bigger challenge. Basically we have a table with state transitions, which can hold some string of information about what to do. The choice we made is to have this string be equivalent to the endpoint configuration in the web.config file. Now all we need is a correct WCF contract, and off we go. That took a little tweaking too, but with the help of the below two posts by Ron Jacobs, we were able to pull it off:
Thanks Ron!
Yes, HTML is great. HTML5 (now just known as HTML) is going to be great. It will finally bring that much needed functionality it’s been lacking all these years, and cross-platform to boot. All the major browser vendors are saying HTML is great, and that their browser supports it best. So what could possibly be wrong? Well, for one the browser really seems to be an out-of-date mechanism to provide rich functionality. As an application platform it’s coming apart at the seams, because users want applications that work awesome on their device of choice. Forget the clunky, lowest common denominator browser-based interface, users want Apps with a capital A!
So while one side of the industry is focusing on standardizing on HTML, the other side (within the same companies) is moving in an entirely different direction. The amazing number of apps available and the growth rate in the Apple AppStore, and the Android and Windows Phone equivalents, is the best evidence that this is actually working better. Cross-platform? Forget it! Cross-platform is slow(er), one size fits all, and most important… not sexy.
Don’t underestimate the importance of being sexy. Let me explain by example. The Dutch government has all laws published on the web at wetten.nl. That means it works in all modern browsers on all platforms, including tablets and phones. There’s no flash involved or anything, so it is truly cross-platform. Also, this is very much in line with efforts of recent years to have the entire government use open standards and open source (see NOIV at http://noiv.nl/service/english/). With mobile touch devices on the rise, the user interface of wetten.nl might need an update to be more suitable to touch and smaller screens. Since the website is all HTML, CSS, and JavaScript, the obvious and NOIV route would be to make adjustments to suite the upcoming devices. But what happened instead? An iPad App was built. Is this a logical choice? Nope, not even close. Even if you don’t look at NOIV and look at reach. The website has a far wider reach, and if you wanted to do something beyond that, well there’s a whole lot more Windows PCs out there than there are iPads. Not to mention that it leaves other devices out in the cold. So really, that much effort (and tax payer money) to build an App that adds nothing? Yep, that’s what “sexy” does.
But wait, isn’t Microsoft betting on HTML with Windows 8? Maybe, but I’m not 100% sure about that one yet. Also, Microsoft isn’t known for its choices when it comes to mobile devices. Microsoft sort of invented the tablet almost 10 years ago, but Apple has taken the credit. Microsoft phones haven’t done particularly well, although Windows Phone shows promise. I love mine actually, but I rarely open the browser on that thing. It’s all apps (yup, guilty!)
Where does this leave us? Well, HTML is going to be around for a long long time, but as things are going it will go back to its original purpose: browse information, and primarily for PCs. PCs which are some are already saying are “legacy devices” (I personally believe we’ll move more to hybrid devices, and different devices connected like with Dropbox, Skydrive, iCloud etc.) For the development community this is actually great. Where previously users were complaining about stuff not being cross-platform, they are now actually demanding customized apps for the specific platform they are using, and the government actually tramples over its own guidelines. This means developers have an excuse to have to build an app for at least two or three platforms, so we won’t be out of a job anytime soon. That said, it means that what’s going on at the server is getting more important, because we have to reuse functionality at some level for the costs not to get out of hand. Enter cloud computing, which is great for developers like me: graphically impaired. This by the way is also great for internet providers, providing they can keep up with the bandwidth demand.
As a developer all I can say is thank you Mr. Jobs for putting users with their nuts in the bear trap, and loving it.
In recent years the development story for Internet Explorer wasn't particularly appealing. If you wanted to fix CSS and JavaScript errors, IE was definitely not the tool you wanted to use. Also, seeing what was going over the wire wasn't possible with IE, and as a result developers flocked to FireFox and other browsers offering (plugins) to help with these issues. You don't have to be a genius to understand that in the long run this wasn't helping IE in terms of market share. And with the renewed focus on webbased (HTML5) apps, Microsoft has stepped up and produced built in developer tools, also known as the F12 developer tools. So, what's in there and what can you do with it? What's taking so long?As with IE8, there are inspector tools for HTML, CSS, and script. Since I am by no means an HTML/CSS guy, I'm not the best judge when it comes to these tools, but for what I need from those I've been pretty satisfied. For me, the new profiler and network tools are much more interesting, because they respectively hook into the browser rendering engine and what's going over the wire with HTTP. If you've been using tools such as Fiddler or HttpWatch, the latter of the two should be more or less familiar. As you can see in the image below, it shows all the HTTP requests going out to the server, when in the timeline these requests were going out, and how long that took. If you've never seen something like this, you can see that this provides great insight into what goes down under the covers.  If you need more details about the timing information, you can select one of the items, and see more. As you can see below, that information doesn't only include HTTP information, but also information about the time it took to render and JavaScript to fire. If there's a page that is slow to appear in the browser screen, this will give you great insight into where your time is going.  Is this functionality better than commercial tools such as HttpWatch? Not at this time, but I have a feeling Microsoft isn't done yet. Tools like that are specialized, and Microsoft is playing catchup. One annoying thing I found is that if I have multiple requests bouncing back and forth, filling in a form, etc. IE9 tools will only show me the last interaction. It could be I'm missing something, but I haven't been able to figure out how to see the whole list of requests since I started capturing, and I'm too lazy to figure it out. That means I find myself going back to HttpWatch for that (at the moment). That said, the tooling is good, so if you don't want to spend the extra dime for other tooling, this will do in most cases. Except of course that this only works in IE9, whereas some of the tools out there work in multiple browsers. But wait... there's more. What I'm I getting?An interesting question is always: what HTML will a certain browser actually get. This is where the F12 tools have another nice new feature. You can change the user agent string the server is receiving, and as a result inspect what happens on the HTML, CSS, script side when other browsers come in. Obviously this doesn't make IE9 behave itself as one of the other browsers, but it can provide nice insights nonetheless, especially to tweak what robots are seeing.
 How will it look?The last thing that I fond really useful is the ability to change the browser so you can check the user experience for users with different settings. As you can see from the image below, you can disable css, script, and the pop-up blocker. In the environment I'm working in now, there's often the need to see whether everything still works if JavaScript is disabled, and there this is a great tool. It definitely beats going into the browser settings and changing these settings every time you have to test.
 Last but not least, you can easily resize the browser screen to fit a certain size. I always used Windows Sizer for this, but having this built in is better, because I rarely use it for anything but webdevelopment.  What's more?
There's a whole bunch of stuff I haven't gone into here, so I advise you to play around with the F12 tools for a while. I'm also betting we'll see a lot more where this came from in the not too distant future. Microsoft is investing heavily in HTML5, and is actually trying to use "the best HTML5 support" as a unique selling point for Windows.
If you're a developer using the Microsoft platform and want to learn Windows Azure development, Developing Applications for the Cloud on the Microsoft Windows Azure Platform (Patterns & Practices) is the book for you. It's a clear book which rides on a good practical case that covers most of the important angles. Because this is a Practice & Patterns book, it also spends quite some time teaching you the right mindset for building (multi-tenant) cloud applications.
The downside of the book is that it really assumes a good familiarity with the Microsoft .NET Framework and C#. Without that, you're not going to understand much of the cases, apart from the high-level cloud information. That said, the book starts with a good explanation of why you would want to build cloud applications, the types of scenario's that fit well, and what Windows Azure (and in more general terms Platform-as-a-Service) development means. The example case really covers most scenario's and choices people will come across, and that means it also covers all the core technologies within Windows Azure. Another great thing about the book is the many links to articles and other (free e-)books that provide deeper insight into a certain aspect or technology. Be aware that Windows Azure is a fast moving platform, with changes on a regular basis. Although most of the core concepts in this book will remain the same for a long time, it can't keep up with all the new developments. I hope new editions will follow to keep up with the changes.
Reading iOs 4 Programming Cookbook by Vandad Nahavandipoor left me confused about the book’s intentions. The book’s audience is stated as for novice AND experts. That rarely works and this is no exception. That said, there is some good, practical content
The first few chapters cover topics aimed mostly at the novice developer. In a language basics book these chapters would typically be somewhere half way through the book. So this is only useful if you just started to learn Objective-C without reading a book. The cookbook format doesn’t help here, because discussing these topics benefit from a nice flow, which the cookbook format doesn’t have. This goes for a lot of content covered. The content itself is not bad, but it should have been covered textbook style, not cookbook style.
Several chapters are good in the cookbook format, such as chapter 4, which deals with maps and location. It quickly explains how to get things done in a practical manner. The book goes back and forth between content that should be part of a textbook (e.g. gestures, networking) and stuff more suitable for a cookbook (e.g. audio/video, camera).
All in all, I think you can get quite a few handy tidbits from this book, but to be fair, this should be split into two books. One textbook, that really starts at the basics of Objective-C programming and teaches you good programming practices, and one cookbook with the good cookbook stuff from this book and with more practical recipes to give it more body.
p.s. I realize I have a real Microsoft aura around me, so for some it may come as a surprise that I read an iOS book. However, I like to keep myself informed about things outside my comfort zone. I am also reading an Oracle book :).

I sometimes use the Visual Studio Class Diagram when I'm designing a system. Because I like to test my assumptions in such a situation I want to be able to quickly create classes that just work. Unfortunately, when you add a property in a class, Visual Studio generates code like this: public string SomeProperty
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
In most cases what I need is: public string SomeProperty { get; set; }
Fortunately, the PowerToys for the Class Designer and Distributed System Designer solve this problem. After installing these (and turning it on in the Add-In Manager), the right click menu is enhanced with a lot of new options. One of the is Add->Auto-Imlplemented Property, as shown below.
Earlier I blogged about finding performance issues in an ASP.NET app "in the large" (see here). I'd like to reiterate that doing this for a web app is critical, because it not only shows you where the bottlenecks are, but also how these affect the entire application. I said I'd follow up on profiling, so here it is...
Once you know what the bottlenecks or "hot spots" are, you can dive into figuring out what the problem is with these pages. This is where profiling comes in. Profiling lets you know what is happening inside your code. It shows you how long a method call is taking and how often a call is made. Both of these are interesting, because performance bottlenecks can be caused by calls taking long, but also by too many calls to a method. Now, I won't get into the details of how to profile with Visual Studio 2010 (you can read Beginners Guide to Performance Profiling for that), but when you use this tooling, you should focus on one page at a time. The profiler will throw a heap of information at you, so dealing with one page is hard enough. Once you have this information you have to determine what's really going on. Is this somehting you can fix by changing a few lines of code, or is there a more structural problem you need to solve? Pages that under no load take 10 seconds or more likely have a structural problem, so you need to check if there is a lot of code being executed that is just waste. Also, be sure to focus on big fish first. You can worry about micro-optimizations (such as a different string compare mechanism) later. That said, you should try to make such optimizations part of your coding guidelines, rather than looking at that afterwards. Micro-optimizations are only really interesting for very high performance apps. A 10th of a second loss here and there isn't going to make a lot of difference apart from maybe needing to scale-out a little earlier.
It is typically a good idea to separate general authorizations of a user from application specific authorizations. This is why we invented Application Roles (Settings Administrator), which are separate from Organizational Roles (System Administrator).When using Application Roles, we can map these roles to Organizational Roles. In organizations using Active Directory, Organizational Roles are typically stored in AD. Application Roles can then be stored using Authorization Manager (AzMan) in XML or AD in Application Mode (separate from the organization AD).
Over the years I've built quite a few applications that use the above model, and it works well if you authorize with roles. But these days I do most of my work using things like Claims Based Authorization, so the question is "Does this translate to teh CBA world? And if so, how?". The answer is that yes, it does translate (very well actually), at least in Windows Identity Foundation.
In the CBA world an application receives a token with claims about the user. Like with roles, this should typically be claims not specific to the application, unless the only source for the claim information lies within (or is only accessible to) the STS. This serves two purposes:
- The token is generally usable across applications, so the STS can deal with this more easily.
- Tokens are not stuffed with a lot of claims.
The latter is actually more important than you might think. Adding more claims means a bigger token, and there comes a point where the token is so large that for instance ASP.NET rejects the request, because it is bigger than the accepted request size (which you should only increase if really necessary).
Now, one of the great things about CBA is that it enables me to create business logic which checks the authorization based on meaningful values, rather than a role. On top of that, I wouldn't want to have a hybrid security system for the claims stuff and the application specific stuff. Fortunately, In Windows Identity Foundation I can add claims to a claims identity, and these claims then behave the same as the claims acquired from the STS token. The only difference is that the issuer is set to LOCAL AUTHORITY, rather than the STS, which means these claims are really only usable locally in my app (or service). The code to add a local claim is easy: IClaimsPrincipal claimsPrincipal = Page.User as IClaimsPrincipal;
IClaimsIdentity claimsIdentity = (IClaimsIdentity)claimsPrincipal.Identity;
claimsIdentity.Claims.Add(new Claim("http://MyApp/SomeAppClaim", "SomeValue"));
You can execute code like this when a session starts, and add all application specific claims for the user (identified by an STS claim) to the claims identity. The local claims then get the same lifetime as the claims originally from the token, so you only have to add them once. This way adding application specific claims is still separated from the functional code. Which was the benefit to start with.
Although the above code will definitly work, there is another option when using WCF, known as Claims Transformation. With Claims Transformation you can define policies that define ClaimSets to add to a user's token. This model is much more flexible, as explained in the MSDN article Service Station: Authorization in WCF-Based Services (jumps straight to the Claims Tranformation section). That article is from the pre-WIF era, but you can do similar stuff with teh ClaimsAuthorizationManager in Microsoft.IdentityModel.
Performance issues can creep up in all sorts of places. Finding them is all about knowing where to look. This also depends on how you look, which can be at the application as a whole ("in the large") or at individual functions ("in the small"). The latter is known as profiling. Because (ASP.NET) web applications are all about large numbers (of users), looking at the application as a whole is a good place start. This is where load testing (a.k.a. stress testing) comes in. Load tests will show you which pages are performing poorly, which is the first step in determining where to take a closer look. Load Testing 101: ASP.NET Web Applications is a great starting point to get yourself up to speed with the mechanics of a good load test, even though its from 2006.
One thing in the article that I think is absolutely critical is about creating a single user base line. This will show you which pages are doing well, when run on their own vs. pages that are doing not. The results of that test already give you an indication of where to look. In fact, a full load test may actually skew the results, because fast pages can be held up by slow pages if the request queue fills up. Fast pages can be identified under load from the difference between the best, average, and wordt results. For fast pages these show huge differences (from few tenths of a second to tens of seconds), whereas slow pages have numbers which are bad across the board.
If you're looking for tools to do load tests, checkout the Web Capacity Analysis Tool (WCAT) provided by Microsoft. The downloads can be found here:
An interesting tool you can use with WCAT is the WCAT Fiddler Extension for Web Server Performance Tests. It helps you to record a path through your app with Fiddler, and then use that path in a WCAT load test.
Note: I will cover profiling ("in the small" testing) in a different post.
A while back I blogged about how to deal with unsecured responses in WCF (see this post). I've had several people ask me for the code that you can use in case you can't use the mentioned hotfix. Attached is the code for a message encoder that intercepts the MessageSecurityException thrown by the original encoder. The encoder wraps around the actual encoder you want to use, so you'll have to configure it like this: <system.serviceModel> <extensions> <bindingElementExtensions> <add name="unsecureResponseEncoding" type="UnsecureResponseEncoder.InterceptingMessageEncodingElement, UnsecureResponseEncoder, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /> </bindingElementExtensions> </extensions> <bindings> <customBinding> <unsecureResponseEncoding> <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16" messageVersion="Soap11WSAddressing10"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> </textMessageEncoding> </unsecureResponseEncoding> <!-- removed for briefity --> </customBinding> </bindings> <client> <!-- removed for briefity --> </client> <behaviors> <!-- removed for briefity --> </behaviors> </system.serviceModel>
The main thing the UnsecureResponseEncoder does is override the ReadMessage methods of the message encoder. All else is just plumbing to wrap the original encoder and use it as is. In ReadMessage the received message is retrieved and place in a local variable. If a MessageSecurityException occurs, this is caught, and an UnecureResponseException is thrown, which includes the original message. Higher up in the call chain you can parse the original message and extract the fault information. The example below shows an altered proxy call so the proxy actually returns a FaultException<>. SomeResponseMessageContract ISomeService.SomeServiceMethod(SomeRequestMessageContract request)
{
try
{
return base.Channel.Aanleveren(request);
}
catch (UnsecureResponseException exception)
{
if (String.IsNullOrEmpty(exception.ResponseMessage) == false)
{
// Put original response message in XmlDocument so you can manipulate it
XmlDocument xml = new XmlDocument();
xml.LoadXml(exception.ResponseMessage);
// Add namespaces concerning faults, including your custom fault schema
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xml.NameTable);
nsmgr.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
nsmgr.AddNamespace("fault", "http://somefaultschema/");
// Retrieve the fault node and extract information.
XmlNode faultNode = xml.SelectSingleNode("/soapenv:Envelope/soapenv:Body/soapenv:Fault", nsmgr);
if(faultNode != null)
{
SomeFault fault = new SomeFault()
{
SomeFaultInfo = faultNode.GetNodeStringValue("detail/fault:SomeFault/fault:SomeFaultInfo", nsmgr),
};
if(String.IsNullOrEmpty(fault.SomeFaultInfo) == false)
{
throw new FaultException<SomeFault>(fault, exception.Message);
}
}
}
throw; // If not properly handled, rethrow original exception
}
}
I've been trying to find a way in which I can easily map competences, books, certifications etc. The goal here is to be able to determine what you need to do to reach a certain competence or certification. Now, there may be some fancy tool out there to do this, or you could just whip up Visio and start drawing, but a) I don't want to buy a new tool, and b) I want this to be interactive.
I just finished a demo that uses the Dependency Graph functionality in Visual Studio Ultimate. I've used similar tooling before (from NDepend) for auditing and reviewing, but this time around I'm using it as part of my solution rather than to review a solution. I've expressed compentencies and books in classes, and if a competence is required for another, I'm adding a reference to it in a prerequisites list. The same happens with books you could read to learn about the competence.
After letting Dependency Graphing do its thing, you end up with a graph such as the one below. The great thing is that it's interactive. You can delete/colapse in the diagram what you don't need, and you can select the items for which you want to see more detailed dependencies. In the graph below, I've selected several constructors to show me all the dependencies.

With everything in code, I could now create a user interface that enables you to query the map for what you still need to do to get to the competence/certification you want.
In the early stages I've commented on Microsoft not going the right way, because a major selling point could be that you can run Azure in the cloud or in your own data center. That seemed not to be possible. When Azure almost went live, MS had changed sufficiently to maybe make this possible in the future. With Azure Appliance, this is now definitly a reality.
A recurring theme in web programming is calling a function periodically and/or at a specific date and time. This has two aspects:
- Calling a function on a scheduled basis
- Making sure time-outs don't interfere
Calling a function on a scheduled basis To be able to call a function on your web app, you first need an endpoint (a URL) that you can call to kick the function off. In ASP.NET you can do this in several ways:
- Create a page that calls the function.
- Create a handler (ASHX) that calls the function (more efficient than a page).
- Create a WCF service that allows calls with HTTP GET, as discussed in this blog post by Sasi Suryadevara.
With your endpoint in place, you can use the Windows Task Scheduler to invoke the function at any given time and at intervals as low as one minute. With the Windows Task Scheduler you have several options again:
- Create a VB Script that calls the URL, as discussed in this blog post by Steve Schofield.
- Create a PowerShell script that calls the URL (same as option 1, but more modern).
- Have the Windows Task Scheduler open Internet Explorer and open the specified URL (e.g. C:\PROGRA~1\INTERN~1\iexplore.exe -extoff http://www.google.com, which starts IE without extensions). If you do this, you also need to specify that the Task Scheduler closes IE after 1 minute, which you can do in the Settings tab of the task (Windows 2003), or in the Trigger configuration (Windows 2008), as shown below. NOTE: I've found that IE sometimes doesn't close, even if you tell Windows to close it. Eventually this will cripple your scheduled task.
 Task Settings in Windows 2003
 Trigger configuration in Windows 2008
Note: In Windows 2008 the dropdowns governing duration and interval show 30 minutes as lowest value. You can in fact change this to 1 minute by editing the text.
Making sure time-outs don't interfere A web based call is bound to time-out after a few minutes. If you task takes longer than that, this may abort the call depending on how you programmed it, and what webserver settings are used with regards to disconnected clients. To ensure a time-out does not interfere, you can spawn a new thread and have it call the function. That way the thread handling the request can return a response to the client, and the function is carried out regardless. One issue that may arise there is that the function itself hangs or takes too long. You may want to add logic to ensure that it's aborted after a certain time, and add logging to notify you of this, and possibly also ensure that the function can only be run by one caller at a time.
I keep forgetting that I need to use GPEDIT.MSC to configure the Windows Shutdown Event Tracker (which you really don't need in a virtual machine).
Sometimes we come across integration scenario's that look straighforward, but where the devil is in the details. We needed to integrate our asp.net/silverlight application in an existing ASP "classic" site (yes, the still exist). The catch was that we needed to call the ASP "classic" site in a server to server call to get some information, but we needed to do this under the context of the current user. You may be wondering why we didn't go through a shared database or someting, but the problem is that there is little knowledge left of the old app, so changing the existing app was a no go.
So, in order to impersonate the user, you need your server-sided request look like that user. This means forwarding the cookies the user sends, and sending back the cookies the server sends to the user. Below is code that demonstrates that. HttpWebRequest webRequestToServer = (HttpWebRequest)HttpWebRequest.Create("http://somedomain/somepage.asp");
webRequestToServer.CookieContainer = new CookieContainer();
foreach (String cookieKey in Request.Cookies)
{
HttpCookie cookie = Request.Cookies[cookieKey];
Cookie serverCookie = new Cookie(cookie.Name, cookie.Value, "/", "somedomain");
webRequestToServer.CookieContainer.Add(serverCookie);
}
HttpWebResponse webResponseFromServer = (HttpWebResponse)webRequestToServer.GetResponse();
foreach (Cookie serverCookie in webResponseFromServer.Cookies)
{
HttpCookie clientCookie = Response.Cookies[serverCookie.Name];
if (clientCookie == null)
{
clientCookie = new HttpCookie(serverCookie.Name);
}
clientCookie.Value = serverCookie.Value;
clientCookie.Expires = serverCookie.Expires;
Response.Cookies.Add(clientCookie);
}
webResponseFromServer.Close();
This code works fine in a test environment, but there is a catch... in some cases the domain of the server is not set in the cookie you get on the server side. The problem with that is that when you set the domain, it doesn't correspond to what the server expects. You can see this if you write out the cookies you send/receive (both on the browser connection and te server-server connection) to a log or something (including the domain. It took a while to figure out, but replacing "somedomain" with Request.ServerVariables["LOCAL_ADDR"] did the trick.
An important reason I have a Windows phone is because I have control over which applications I buy and from whom. I decide what I can or cannot install on my phone. With Windows Phone 7 Series Microsoft is blocking this "sideloading", so users can only download and install new software through Marketplace. Basically Microsoft is following the Apple iPhone model with this, and the reason is for this is clear: follow the money. Microsoft has realized that Apple is making millions of dollars from the percentage they get on apps sold through the app store. This is logical, because ultimately it is not your device that makes the difference, but what you can do with it. Functionality and content sell, it's as simple as that.
As I said an important reason for me to have a Windows phone, and not an iPhone, was the control I have over my device. I think I am not alone in this, and I've heard a lot of people using Apple products (iPhone in particular) complain about this too. It's the one thing the makes Apple impopular compared to Microsoft, so I guess Microsoft just wants to be the impopular company. Windows Phone 7 Series will also be impopular to vendors. On that front Microsoft is thightning the screws as well. Microsoft now determines the hardware specs and as vendor you have little options to alter the appearance of the OS. This means there are less options to differentiate yourself from competitors.
I think the new Microsoft policy will ultimately drive people away, rather than gain momentum. It will drive people to Android based phones where phone vendors and users are still in control. If you look at the momentum Android already has, more people will also choose Android over iPhone for the same reasons.
When you're using signing or encryption on your SOAP requests, WCF exepects the response to be signed/encrypted too. When the response is not signed/encrypted the message encoder throws a MessageSecurityException. This is perfectly fine behavior, but in interop scenario's can really bug you, because some WS-* implementations don't sign/encrypt Fault messages. Now, because the message encoder throws the exception, you can't get to the underlying SOAP fault. This means that you have no clue why you received a fault in the first place.
To fix this, Microsoft has provided a hotfix. With this hotfix in place you can specify enableUnsecuredResponse="true" in the binding configuration to allow unsecured responses. Unfortunately this means that also valid responses don't have to be signed/encrypted, defeating the purpose of signing and encryption altogether!
As an alternative, you can implement your own message encoder that wraps the encoder that is actually used. In the wrapper you can either store the received XML for use higher up in the call stack, or retrieve the fault and throw a FaultException<>. Without jumping through hoops the latter option does require your wrapper to know about the fault types it needs to handle. With the former option you can handle the exception higher up in the call stack by catching the MessageSecurityException and throwing a new exception with the XML of the message as a property.
Two months ago I spoke at WDI 2010 in Warsaw, Poland on ASP.NET Web Forms vs. ASP.NET MVC. I should have posted the slides for that session soon after, but just didn't get around to it because of all the work thrown at me. Here they are... finally. Slides (668.34 KB)
Thanks to the great folks organizing the conference. They took great care of me and managed to get a good crowd together. Even though it was a pretty large audience, the level of interaction was very good.
Microsoft has been kind enough to give me the Microsoft Most Valuable Professional Award again. That's the 8th year I can call myself an MVP. Thanks Microsoft for the recognition. As a token of my gratitude I've made some long overdue blog posts :).
If you've ever tried svcutil.exe to import WSDL which has doesn't have <sp:OnlySignEntireHeadersAndBody> specified in the security policy, you'll know that this doens't fly. SvcUtil will tell you the the security policy is not supported. So why is this? I assume this has something to do with the a statement in paragraph 6.6 in the WS-SecurityPolicy specification, which states:
Setting the value of this property to 'true' mitigates against some possible re-writing attacks.
So apparently Microsoft decided that setting it to false is not a good idea, and decided not to support setting it to false (omitting the element).
Talking to a non-WCF webservice is like a box of chocolates... you never know what you're going to get. After solving the issue mentioned in my previous blog post, I had another problem. For some reason the service didn't expect a <wsa:ReplyTo> element if the value was anonymous. Later on the other party adjusted the service so it actually worked as expected from WCF, but in the mean time I did write a message inspector to solve the problem. Besides solving the problem it also is a nice little example of a message inspector. public class RemoveAnonymousReplyToMessageInspector : IClientMessageInspector
{
private const string ReplyToNode = "ReplyTo";
private const string WSAddressingNamespace = "http://www.w3.org/2005/08/addressing";
public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{} // Not used for this scenario.
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
{ // This method is called before the request is sent. You can read/manipulate the message here. // If you're using signing or encryption, that is done after this, this is the // unencrypted/unsigned mesage.
request = RemoveAnonymousReplyTo(request);
return null;
}
private Message RemoveAnonymousReplyTo(Message message)
{
if (message.Headers.ReplyTo.IsAnonymous == true)
{
int index = message.Headers.FindHeader(ReplyToNode, WSAddressingNamespace);
message.Headers.RemoveAt(index);
}
return message;
}
}
To use this, you'll need to create a class implementing the IEndpoint behavior and add the MessageInspector in ApplyClientBehavior, as follows: public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
RemoveAnonymousReplyToMessageInspector inspector = new RemoveAnonymousReplyToMessageInspector();
clientRuntime.MessageInspectors.Add(inspector);
}
Recently I found myself trying to talk to a webservice using signing. It was a WCF calling a Java webservice using a certificate to sign messages. I kept getting the following exception message:
The incoming message was signed with a token which was different from what used to encrypt the body. This was not expected.
After a wild goose chase we finally figured out that the certificate was corrupted. Just installing the certificate again solved the issue.
I've written quite a few functional designs over the years and I've found that for users needing to validate it having visuals is key. In most cases prospective users don't understand what they really get until they see screens. On the opposite side of the spectrum telling developers what to do also is much easier with a screen, especially when you are debating what would be the best and most efficient (coding wise) way to give a user certain functionality. In these situations just getting a piece of paper and draw is the best you can do. The last few years I've done this on and off on my tablet. I can sketch on it, but the results are often so poor to see (and read!), that I can't possible put it in a functional design. This is where a good mockup tool comes in.
A good mockup tool should make you feel like you are drawing, but provide you with predefined controls to make your job fast and easy. Recently I came across Balsamiq Mockups, which is simply jaw dropping. Let's start with the result, which looks pretty much like a hand drawn thing. At first glance that may not seem like a big deal, but it is. It states clearly "This is a mockup, the actual thing may look different". If you give a user something that looks like a screen shot, that is what to expect to get. With this they know it will look differently when it is done, and this also makes it much easier to debate your choices and come up with better ideas (to quote David Platt, "Thy User Is Not You", so they will come up with stuff you didn't even dream about).
Ok, so the result is great, what about getting there? Well, that's a piece of cake, really. Balsamiq is as intuitive a tool as I've seen and I was able to create a pretty complex screen in about 10 minutes. There's a bunch of commonly used controls (and some less common), and you can easily find what you need. Also, you can download tons of additional controls from http://mockupstogo.net. Placing, moving, resizing etc. is all very easy because of the snapping support. Want to see for yourself? Look here.
The last things that I find refreshing is the licensing model and fee. It only costs $79 for a single license, and that comes with updates forever (and they update frequently, so they say). Because the tool is already so good, this means you can use it for years, without having to worry about support or having to get a new version.
This is just a great tool. I am sure I will be using it often.
At my company we we're looking at creating a generic STS that does not require Active Directory Federation Services 2.0, and we were also thinking about putting it up on CodePlex. Dominick Baier from Thinktecture beat us to it with StarterSTS. He's also posted some webcasts on how to use it. Good stuff, so instead rolling our own, we'll be using/extending this one.
A while back I blogged about testing VirtualBox. At the same time we've tested Windows Virtual PC, and it's been disappointing pretty much across the board:
- It doesn't run on our company's Lenovo T61's, which displays some vague error message. Since most of our developers have a T61, this means they can't use it at all. Virtual PC 2007 and VirtualBox run fine, so it isn't clear why WVPC can't. We have some different machines where it does work, so we went on testing on those to see how well it works, in case Microsoft steps up and fixes the T61 problem and starts supporting 64-bit guests. See the remaining points for my experience...
- The integration features of WVPC suck. Even something simple like dragging a file from the guest to the host or vice versa doesn't work. The reason is that with Integration Mode enabled, you're actually connected to the guest through Remote Desktop Connection. Microsoft has done this to leverage some of the advantages of RDP (as Ben Armstrong explains), but IMHO they should find a different way to do so.
- Starting/stopping a guest takes forever, and renders my laptop inoperable while doing so. With VPC 2007 hibernating or restoring a hibernated VPC with 1.5 GB of memory takes several tens of seconds, but I can easily use all other applications while doing so. WIth WVPC just restarting a hibernated image tages 3-5 minutes and during that time my other applicaties are pretty much frozen. I can get a cup of coffee (if I'd drink coffee), eat a sandwich, and go to the John, during the wait. I have no clue why this works as bad as it does, because VPC does this perfectly fine.
The only thing that's been a positive experience is the performance once it has started. That said, I can't really tell if VPC 2007 or VirtualBox work better or worse, so I can't even praise WVPC on this point.
So for now it is back to VPC 2007, with our final decision on switching to VirtualBox postponed until we really need 64-bit support.
On a side note, we've been trying to get the open source version of VirtualBox working, and that appears to be quite a challenge. There are no binaries, so you need to compile yourself. Even though we have a recent build, getting all the prerequisits is hardly possible. Some of the needed SDKs are no longer available. Our conclusion up until now: the open source version is not really viable (at least for Windows), and possible only there for marketing reasons ("see, we do open source").
Windows Identity Foundation introduces a new ClaimTypes class. It contains predefined claim type URIs for claims defined by OASIS and Microsoft. In the WIF SDK project templates for a custom STS this ClaimTypes class is mixed with the one already in System.IdentityModel.Claims, which is rather confusing. So, what's the difference?
Functionally: None. All claim type URIs in Microsoft.IdentityModel.Claims.ClaimTypes are identical to corresponding types in System.IdentityModel.Claims.ClaimTypes. That said, Microsoft.IdentityModel.Claims.ClaimTypes adds a few new claim types.
Technically: Claim types in System.IdentityModel.Claims.ClaimTypes are defined as static read only string properties, whereas in Microsoft.IdentityModel.Claims.ClaimTypes the claim types are string constants.
My advice: for clarity always use Microsoft.IdentityModel.Claims.ClaimTypes.
Earlier this year I was pretty negative about the Azure story from Microsoft. My main gripe was that (from my perspective at the time) it was not a write-once, run-anywhere story, so you couldn't run your current apps in Azure without modification. I'm very pleased about what I've seen now from PDC. Microsoft has opened up Azure in many ways, giving you much more control over what's happening. In fact, you can get your own virtual machines and have complete remote admin access. Also, they've been really thinking about how to tie your existing hosting environment to Azure and vice versa. It will be possible to connect a web app inside Azure securely to a database server in your own data center.
I must say I'm impressed at how well Microsoft has listened to all the feedback about Azure. With all the changes they've implemented I feel that it has now become interesting for some of the services my company is implementing, whereas previously we weren't even considering Azure.
Windows Identity Foundation, formerly known as "Geneva", has shipped. I've been talking about Geneva/WIF on several occasions and I absolutely love it. It opens the door for a whole new realm of authentication/authorization scenario's. SharePoint 2010 will be the first Microsoft Product to support it, apart from the new Active Directory Federation Services 2.0, which was part of the development effort and was formerly known as "Geneva" Server. Be sure to check it out!
Recently I found myself having to debug a large stored procedure that calls all sorts of sub-procedures. Also, the data set was rather large and it only failed sometimes. SQL Management Studio in this scenario isn't very helpful for several reasons:
- The number of PRINT messages that it'll show is limited, so if the error is out of range... tough luck.
- Even with PRINT messages it can be hard to pin down which statement is actually in error.
- Line numbers are never accurate.
- It seems View Dendencies sometimes misses out on dependencies.
- View Dependencies doesn't show the number of times a proc is called from another proc.
SQL Profiler, which also comes with SQL Server is a much better tool when it comes to pin-pointing the erronous statement(s), after which you can modify your code to show an error message that prints the values causing the hickup. When you use SQL Profiler, be sure to select more than just the default events. Click Show All Events and select all Error events, as well as the Stored Procedure events that show Starting and Completed of SQL statements with stored procedures. Then, once the root procedure is done, do a Find through the trace for "Error", and you can see exactly which statement is causing the error.
My company regularly works on public facing websites, and as such it is imperative we test the sites we create with most common browsers. Naturally that means at least Internet Explorer, FireFox, Safari, and Opera. With the last three we just download and install om some test (virtual) machine. With IE however this is somewhat more complicated (although not impossible to run different versions of IE side by side. However, Microsoft provides a set of Virtual PC images known as the Internet Explorer Application Compatibility VPC Image. These images enable you to test different versions of IE on different versions of Windows. These images have a limited lifetime (between 1-4 months), so you'll have to download a new set on a regular basis, but other than that this is really handy. The following configurations are available:
- Windows XP SP3 with IE6
- Windows XP SP3 with IE7
- Windows XP SP3 with IE8
- Windows Vista with IE7
- Windows Vista with IE8
Unfortunately these configurations are all en-US, so if you want to test with say a Dutch version of Windows, you'll have to create your own images (which is what my company has done, even for en-US).
Today http://orchard.codeplex.com/ went live. Orchard is an open source Content Management System that the folks from Redmond are working on together with the ASP.NET community, and which I've been following with much interest. Orchard is based on ASP.NET MVC, which means I'd favor it over something like Umbraco when it is mature enough. Why? Because this should mean that it blends easier with your regular development efforts, rather than having to deal with an entirely different templating technology. Umbraco for instance uses XSLT, and even though I wrote a book a about XSLT and my company is well versed in XSLT because we do a lot of BizTalk, it is troublesome for plain ASP.NET developers.
Keep in mind that Orchard is relatively new and a lot of scenario's are still not supported. But at the pace the team is going, you'll soon see more advanced stuff being possible. You can make yourself heard about what you'd like to see through CodePlex or through one of the sessions at TechEd or PDC this month.
Lately I've been making time to read more again, and I thought I'd share my findings. My most recent read is Solid Code: Optimizing the Software Development Life Cycle by Donis Marshall and John Bruno. My feelings about this book are mixed. On the one hand, it gives a good overview of software engineering practices. On the other hand, an overview is all that it is. It doesn't really do a good job at giving any details. That said, I think it is a good read for junior/medior developers to get a sense of all the stuff they should be aware of when building software. For senior developers and architects a quick scan to see if they have a gap somewhere is enough. From there you can explore books specialized at the topic(s) you need to know more about. Some of the topics covered include, design, testing, performance, scalabiltity, and security.
As an aside, I've read several books now that cover Agile development methodologies. What strikes me everytime is that the given examples are always about product development, and this book is no different. Product development and custom software projects however are very different. In product development you can work with fixed budget and fixed time, and cut features if either budget or time doesn't allow you to create them. Custom software projects can't do this as easily. Clients are not going to give you a bag of money and a schedule and say "we'll see what makes it into the final version". The client wants to know what he/she is going to get for the money they pay. This means that in custom software projects, you need to have a much more detailed view up front of what needs to be implemented. I'm not saying this precludes Agile development practices, but there is a certainly a difference at the start of the project, because a large chunk of the design work has to be done earlier in the project lifecycle.
Every once in a while (when I use a new dev environment) I hit this error:
Saving Changes in not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can’t be re-created or enabled the option Prevent saving changes that require the table to be re-created
Each time I forget how to fix this, so by posting here I know I'll never forget. Check Pinal Dave's blog post on this error (hint: it's in the Option menu). Thanks Pinal!
I was working on this little app I wrote a while ago and wanted to add some features requiring (de)serialization. So, I took the original class and made it a DataContract so I could use it with the DataContractSerializer. The class then looked more or less like this: [DataContract]
public class MyClass
{
List<Trip> m_Items = new List<Item>();
[DataMember]
public IList<Item> Items
{
get { return m_Items; }
}
}
Serialization went fine, but when I tried to deserialize the same object, I got a null reference exception. Of course you say, you should have added a method tied to de OnDeserializing event, because the constructor of the object doesn't work and hence the m_Items field is never initialized. The code I added to solve this looked like this: [OnDeserializing]
protected void Init(StreamingContext context)
{
m_Items = new List<Item>();
}
To my surprise I still got the same exception. I finally figured out that the problem was the type of Items. It is was an IList<> instead of a List<>. To avoid tying a class to a specific implementation of a list, I usually use an interface, which is good practice in most cases... however, not when you want to do deserialization :).
At BataviaLabs we were debating coding guidelines the other day and came across this one: do you use #if or the ConditionalAttribute to indicate to the compiler if a method should be compiled. Let me elaborate...
If you have a method you only want to compile in a debug scenario, you have the following options:
1) Use #if DEBUG as shown below class Program
{
static void Main(string[] args)
{
#if DEBUG
SomeMethod();
#endif
Console.WriteLine("End");
Console.ReadKey();
}
#if DEBUG
internal static void SomeMethod()
{
Console.WriteLine("SomeMethod");
}
#endif
}
2) Use the ConditionalAttribute as shown below class Program
{
static void Main(string[] args)
{
SomeMethod();
Console.WriteLine("End");
Console.ReadKey();
}
[Conditional("DEBUG")]
internal static void SomeMethod()
{
Console.WriteLine("SomeMethod");
}
}
The difference between these two methods is enormous. The first sample is very explicit. Any code you don't want to compile into the production build is placed between #if DEBUG and #endif. If you try to call SomeMethod in a production build, the compiler will give you a compile error. The ConditionalAttributeon the other hand doesn't require you to remove the calls to SomeMethod. If a method is marked [Conditional], any calls made to that method are removed from the build by the compiler. A proviso here is that [Conditional] only works with methods that don't return a value (i.e. void).
I much more prefer #if DEBUG, because it is explicit. I can't run into a situation where from reading the code I'm thinking "SomeMethod is being executed", but it actually isn't because the compiler removed the call. Comments anyone?
When testing a UI, especially a web UI, it is imperative you do so at all resolutions you expect your users to use. So, how do you size the browser to 1024x768 on a 1680x1050 screen? The answer is a little tool called Sizer. It allows you to set a window to a prefixed size or you can drag the window size and it will show the actual size as a tooltip.
I keep forgetting how to force the transaction log in SQL Server to shrink, so I'm posting here primarily so I know where to find the how to :). Often the log does not shrink when you try to shrink from SQL Managent Studio. The solution, before you shrink the database do:
BACKUP LOG <DatabaseName> WITH TRUNCATE_ONLY
Thanks to Pinal Dave for this one (see his post SQL SERVER - Shrinking Truncate Log File - Log Full)
We have an ASP.NET application that we normally run under Forms Authentication using the ASP.NET Membership API. For a particular client we changed this to using Windows Authentication instead. On the production environment, we were running into the following exception:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
We checked all the connection strings the app uses... all good. Finally, we figured out what was wrong. We had removed the Membership section from web.config so it was going back to the default in machine.config. That setting uses the LocalSqlServer connection string, which we don't use. However, in the default machine.config, this points to the App_Data folder using SQL Server Express. In most environments, this wouldn't be an issue immediately, because SQL Server Express would just create the aspnet database and use that. However, in a hardened environment SQL Server Express is either not there (our case) or has no rights to create the App_Data folder and/or place create a new database. ASP.NET doesn't know this... it just can't access the SQL Server instance it is looking for, hence the above exception.
I'm delighted to be speaking again at VSLive in June. This time at the Venetian hotel in Las Vegas. I'll being doing two sessions on Monday, June 8:
- Understanding Transactions in WCF, which deals with why, how, and when to use transactions in WCF.
- Advanced Access Control with WCF, which deals with claims based authorization and the Geneva Framework.
Over lunch I will be available for 1-on-1 Q&A, but if you run into me at other times outside my sessions I'm open for questions too.
Checkout the full conference agenda for all the great sessions and speakers at VSLive, Las Vegas. I can really recommend going there, because the sessions are great and the speakers very accessible. I also think the Venetian will be a great venue (I have never stayed at the Venetian, but I have been inside and it is definitly something to see).
Thanks to Microsoft for my new MVP Award. It is nice to get the recognition. A thank you is in order to the people that enable me to do the work that got me the award, starting with my wife Annette and my children Jarod and B'Elanna. They have a workaholic for a husband/dad, but don't complain about it (much). Others that receive a thank you are my partners at BataviaLabs who give me the freedom to write and speak at conferences, our team at BataviaLabs that help me code all my wild ideas, and the people that publish my articles and invite me to speak at their conference.
I read this post from Steven Martin at Microsoft and frankly I'm disappointed. Microsoft is not the only company building cloud computing services, but they have a clear advantage over most of the providers: they own the operating system. As such, a unique selling point would definitly be that they can provide you with cloud services, but also enable you to run your applications in your own data center without modifications. If I build an application for the Windows platform, I want to build it once and be able to run in on any server infrastructure. As it looks now, this is not possible. Once built for the cloud, it must remain in the cloud unless you refactor the application for use in your own environment. I really hope Microsoft sees that this is a mistake and that it will actually gain them clients if they allow this. There is another factor here and that's trust. I'd like to have a backup scenario in case Microsoft fails to deliver. With the Azure platform as is, there is no backup scenario. You either go for it full-blown, or you don't. It is my belief that many people will decide not to go with Azure in the first place because of this. In fact, I am now much more reluctant to tell my clients about Azure as an option.
Recently I encountered an exception related to System.Security.Permissions.FileIOPermission while trying to send email from ASP.NET (dasBlog actually). This has nothing to do with rights set on folders! It is a trust (code access permission) issue, and it will happen if your application is running under Medium Trust. Elevating the trust level will definitly help. From what I've read, defaulting to the system defined SMTP settings (i.e. removing any SMTP settings form web.config) will also work, but I have not tried this yet.
Thank you for all who attended my sessions in San Francisco. Below are the slides and samples for my sessions.
VTH4 - Understanding Transactions in WCF Slides (561.73 KB) | Samples (540.1 KB)
VTH16 - Supporting POX/REST with WCF Slides (369.58 KB) | Samples (302.82 KB)
VTH25 - Simplify WebPart (and Control) Development with WebPart Skinning Slides (359.85 KB) | Samples (447.66 KB)
The VTH25 samples include the full installer. However, be sure to change the uploadskinfeature.bat to point to the correct server. You can read more about the VirtualPathProvider I mentioned in VTH25 session here.
The wonderful folks at VSLive! have invited me again to do three sessions at their San Francisco event from February 23 to February 27, 2009. These are the sessions I'll do (all on Thursday 26):
- Understanding Transactions in WCF
- Supporting POX/REST with WCF
- Simplify WebPart (and Control) Development with WepPart Skinning
The first two are obviously about WCF. The last talk is primarily about SharePoint, but the discussed techniques will work with ASP.NET WebParts and WebControls as well.
I really like VSLive! because they have some great content and top tier speakers. The speakers (myself included of course) are also very accessible, because the event is not as huge as some of the other conferences these days. So if you intend to go to a conference this year, VSLive! is going to be worth your money.
Have you ever wondered if/when a transaction in WCF upgrades to the DTC? There two simple ways to check this:
- Open Performance Monitor and add a new counter. Get the counter Active Transactions from the Distributed Transaction Coordinator section.
- Open Component Services and go to My Computer in COM+. There is a folder for Distributed Transaction Coordinator, through which you can view the DTC statistics.
In both cases, you'll see the active transactions jump from 0 to 1 when a transaction upgrades to DTC. This happens when you cross a service boundary. If you just use a transaction within the service, WCF will stick to the Lightweight Transaction Manager as long as you stay within you AppDomain or access a single database (SQL Server 2005 and up).
For those of you that attended my sessions in Dallas, here are the demo's for
If you attended the latter, you'll remember that I wrecked my prepared demo (note to self: never change configs just before a session). I finally figured out what was wrong. I changed some configuration on the server side and I thought I did the same on the client. Apparently I did not, because when I updated the service reference on the client it worked.
At a session about ASP.NET DynamicData at VSLive in Dallas, one of the attendees asked me about my thoughts of DynamicData becoming a part of ASP.NET MVC. I commented that currently DynamicData is very much based on the current ASP.NET paradigm of pages and controls, whereas ASP.NET MVC is not. ASP.NET MVC presents a new way of thinking to the ASP.NET world and I find it hard to believe that millions of developers will jump on the ASP.NET MVC bandwagon immediately after its release (let's face it, it hasn't even been released yet) and leave their old coding styles behind. You need to learn to think differently first. Also, if ASP.NET MVC becomes the primary ASP.NET paradigm, there is a whole lot of code that is still using ASP.NET the way most of us do at the moment. That said, ASP.NET MVC is very interesting.
Ok, so back to the original question. If you look at Scott Guthrie's post about the ASP.NET MVC Release Candidate, you'll see that there is scaffolding support on based on the model, instead of table based scaffolding using in ASP.NET DynamicData. The model based scaffolding enables you to create different views of the model in no time.This is very cool, because it provides you with way more control over what is happening than in DynamicData. And because it is based on the model, you're not tied to database objects, but rather to business objects. How you persist those is up to you.
I still think ASP.NET DynamicData and ASP.NET MVC are going to live side-by-side for quite a while, and that they will use concepts that were created for one or the other. The main reason for this belief is based on my earlier comment: I think ASP.NET MVC and ASP.NET "Classic" will run side-by-side for a loooooong time. I do feel that ASP.NET MVC ultimately provides us with more flexibility and will at some point become the more dominant paradigm.
At VSLive in Dallas last week I promised to follow up with a post about securing an ASP.NET Dynamic Data application. Your first concern is not exposing all the tables, so although it demo's well, never set ScaffoldAllTables to true. That however, does still not solve how you can provide read-only access to certain users, while providing edit access to others. The most elegant way to do that is at the Data Model level, using a custom security attribute. There's a great sample on how to do that on the Dynamic Data Samples on Codeplex. The specific sample you want is Secure Dynamic Data.
If you don't want to spend the time to understand how security at the Data Model works, you can also just use ASP.NET Roles to secure specific parts of your site. Since securing folders/files that way has been around since ASP.NET 1.x, that should be easy enough :). There is a gotcha though: you cannot secure dynamic folders. In other words, a Dynamic Data path /SomeTable/List.aspx is not securable, because SomeTable is not an actual folder. With three simple steps you can get around this.
Step 1: Create a folder corresponding to a specific role, for example "Readers".
Step 2: Create a web.config in that folder limiting access to the role(s) you want to give access.
Step 3: In globas.asax, route the tables and actions that apply to the specific role to that folder, like this:
routes.Add(new DynamicDataRoute("Readers/{table}/{action}.aspx") { Constraints = new RouteValueDictionary( new { action = "List|Details", table = "EvaluationSubjects|Reports", }), Model = model });
I will be speaking at VSLive! again, this time in Dallas from 8 until 11 December. I'll be doing the following sessions:
- Introduction to ASP.NET Dynamic Data (Tuesday 9 December, 11:15 AM)
- POX/REST Strategies with WCF (Thursday 11 December, 1:45 PM)
- Understanding Transactions in WCF (Thursday 11 December, 4:45 PM)
VSLive! is a very nice and relaxed event with great content. So it's a great opportunity to learn new stuff and new people. If you want to attend the Dallas show and see me speak, you can get a $300 discount by entering the discount code SPVAN. I hope to see you there.
I've been working on a small Windows Mobile app and I had a really weird problem. While working in the emulator everything worked fine. However, when I deployed it to my Smartphone (HTC S710), it didn't show the labels. Textboxes etc. worked fine, but the labels didn't show up, no matter what I did. Some of the things I tried:
- redeploy
- changing the font of the labels
- making sure there was no overlap between labels and textboxes
It took me about an hour to get it working. I went into the settings and because there wasn't anything about screen/font settings I finally looked at those of the startup screen (option 4), thinking that this didn't have anything to do with my app. As it turned out the culprit was a color scheme that I downloaded from the Windows Mobile site called EarthView.
I while ago I created the control shown below. It acts a multi-select ListBox from the API perspective, but works by selecting items and moving them over. Pretty much all elements can be styled, such as the headers, the ListBoxes and the buttons. I'd love to have one with some JavaScript that allows drag-n-drop, but that's too much work for me. Feel free to copy and extend the source code(3.15 KB).
I run a a development team and we're working on some functionality that we're likely going to share between different projects. The problem is that part of the functionality are some adminstration pages that we want to be able to develop separately, deploy as part of customer's. The requirements we have are roughly the following
- We can version the pages separately, so that when we patch the shared functionality, we don't have to rebuild/redploy the entire site.
- We don't have to copy files from one project (the project with shared functuionality) to another (the project that is customer specific).
- In our source control the customer's website is really a separate project and not a branch of the project with shared functionality.
- The administration pages should be themed to the customer's site and additional admin pages may be added custom for the customer's website.
The best way, we figured, was to deploy the shared functionality as a seprate assembly, similar to a precompiled website. A precompiled website however is one thing, AFAIK you can't dump two precompiled websites into the same application. I did figure out a way to deploy the site as an assembly, by putting the admin pages inside an assembly as an embedded resource. We then pull the pages out using a VirtualPathProvider. There are great implementations out there using the VirtualPathProvider, such as serving a website from a ZIP-file and from a database (which is what SharePoint does).
If you don't know what a VirtualPathProvider is, let me quickly fill you in. When ASP.NET gets an aspx page for the first time, compiles that page and stores the result in a system directory. Only when you change the file will ASP.NET recompile the page. Now, the file system that ASP.NET gets the page from is virtualized, which means that ASP.NET does not know how the underlying file system is implemented. By default this is the normal Windows file system, but you can create a provider that uses another storage mechanism. As long as it works just like the file system, this will work fine. You can use a database, XML file, ZIP file, web service, or whatever as the underlying file system. All you have to do is create a few classes, including an implementation of the VirtualPathProvider, register the provider in global.asax, and you're off. The great thing is that because you're supplying ASP.NET with the page, your page benefits from ASP.NET (pre)compilation. This means that if you build a CMS with content in a database, the database is only hit the first time the page is requested and the content is compiled into the page.
So, what we can do is put the aspx pages inside an assembly as an embedded resource and serving the pages from there. Because the pages are inside a regular .NET assembly, it can be linked into a project and be updated when there is a patch, without affecting the application's it is contained in. All we have to do is redeploy the assembly. It sounds a bit weird, but it actually works, as you can see in the attached demo (51.54 KB). Be aware that this is really just a demo. It is just meant to prove it works. The logic to get directories is flawed (which has something to do with the fact that directories are not preserved in embedded resources), and possibly more is. However, you can access the following pages:
- \AdminHome.aspx
- \Default.aspx
- \NewFolder1\HTMLPage1.htm (only works in VS webserver or IIS7 in integrated mode)
Default.aspx is kind of funny, because the code behind class is compiled in the class and the page itself embedded. Enjoy!
I've now read several books on SharePoint development, such as Developer's Guide to the Windows SharePoint Services v3 Platform , Microsoft harePoint 2007 Development Unleashed, and Programming Excel Services. I've found each of these books lacking, particularly the last two. The Unleashed book is more a reference than anything else and especially in the more advanced topics I really didn't find what I was looking for, which is not what you'd expect from an Unleashed title. The Excel Services book is a disappointment if you are looking for good information about Excel Services. If you want to learn to develop WebParts it is quite good however. In that sense the book has been completely misnamed. I hope that my next pick will be better (that said, two of the three books were given to me).
I just moved my blog to a new server and in the process did a long overdue upgrade of dasBlog. Unfortunately now all download links fail and some images are missing. I will be correcting this, but if you find a link/image that doesn't work, please drop me a line. Thanks.
Jeff Prosise made a nice blog entry about hiding the root node in the SiteMapPath-control. Some people, like myself, experienced an issue when the current node and the root node ar actually the same. Somehow the check that should avoid that issue fails. I believe because the current node is in fact a clone of the current node, and as such not equal to the current node (i.e. root node) itself. To get around this, I have changed the code somewhat to do the check on the actual nodes. The body of the HideRootNode-method is now as follows:
// Return root node in case this is the root. if(SiteMap.RootNode == SiteMap.CurrentNode) return SiteMap.CurrentNode;
// This is not the root node, so rebuild path without root. SiteMapNode node = SiteMap.CurrentNode.Clone(); SiteMapNode current = node; while (node.ParentNode != SiteMapNode.RootNode) { node.ParentNode = node.ParentNode.Clone(); node = node.ParentNode; } node.ParentNode = null; return current;
Thanks to Jeff for his original insight. It saved me a lot of time.
Log4net is a great tool for logging in a .NET application and everything is well documented. Finding what you need can be a pain though. If you checkout the configuration manual, you read about all the appenders and a little about the pattern of the message that is logged. You can set that pattern if you want. What they fail to provide however is a reference of the tokens you can use in a pattern (for instance %exception). They only show a sort of default pattern. After digging for about 10 minutes, I finally found the list within the SDK reference. It would be great it someone were to add I direct link to there from the configuration manual.
Visual Web Developer 2005 has a great feature for graphically impaired people like myself. In a page you could go to the Layout menu and select Insert Table. The dialog then had all sorts of table templates (see picture). In the 2008 version this dialog (in fact the entire Layout menu) is gone and replaced by a run-of-the-mill insert table dialog. Why on earth did Microsoft take this out?

I've been doing stuff with LINQ to SQL for a while now and there's one thing that keeps bugging me: Proper exception handling. IMHO LINQ to SQL should encapsulate the database. I mean, I don't care which database (SQL Server, Oracle, whatever) I'm working with, but if I call SubmitChanges on the DataContext, I'll get a SqlException if it fails on the database. I know that currently LINQ to SQL only supports SQL Server, but the model is just as valid for any other (relational)database. To my surprise there is no LinqException or something that encapsulates the SqlException, so now I have to write code that is aware of the fact that I'm dealing with SQL. You can of course solve this by using the Exception Handling Application Block, so you don't deal with specific exceptions in code, but it still feels funky.
Recently my latest (Dutch) book was released, titled XML - de basis. For that book I did an interview with Chris Lovett from the Microsoft XML Team. Below is the unedited version of that interview. There's a lot of cool stuff in the interview which I unfortunately had to cut for the book, because otherwise it wouldn't fit the number of pages available for the interview. Fortunately, my blog doesn't have that limitation :).
Please tell us who you are and what you do. My name is Chris Lovett, and I’m an architect on the Data Programmability Tools team in SQL Server, and I work on XML tools that ship in Visual Studio. As an architect I do lots of different things including: hands on product development on the XML editor in Visual Studio 2008 “Orcas”; cross-group collaboration to make sure all our tools fit together; playing with other concepts like XML Notepad; and thinking about and communicating our strategy and future directions for our technology.
How long have you worked for Microsoft and what did you do before your current position? I have worked on pretty much every XML core technology from Microsoft starting with MSXML in 1997, then to System.Xml in the .NET frameworks v1, and 2 and for the last few years I’ve been focusing on building XML tools in Visual Studio – for example, I was the primary developer on the XML editor in Visual Studio 2005. Before Microsoft I worked at IBM on OS/2 applications, then I joined the IBM Apple/IBM joint venture called Taligent, then I started my own company in Sillicon Valley with a bunch of friends from Taligent during the height of the .com boom and that’s what led me to Microsoft. A lot of the .NET Framework works with XML in some form or another.
Why is XML such a key component and what were the challenges you faced because of that? For one thing the .NET frameworks were designed during the peak of the XML hype curve J, but more seriously, many folks at Microsoft were waking up to the fact that not everything had to be buried in code. Some things could be very neatly described at a higher “declarative” level and HTML showed the world that “markup” is a great way to do that. So XML became the way to specify configuration information (.config files), and build information (MSBuild files), and setup information (WIX), object remoting with SOAP, and security permissions and so on. All of these domain specific uses of XML were then supported by our core System.Xml classes. It’s interesting to note that even those teams that didn’t swallow XML back in .NET v1.0 are fixing that, for example, we have the new AJAX work from the ASP.NET team and we have XAML in the Windows Presentation Framework (I’m a huge fan of WPF by the way. I’ve done a lot of UI development in the last 20 years and I have to say WPF totally rocks). So XML is touching everything from database, management, communications, content publishing and now even into the user interface layer. I was amazed at the last PDC just about every talk showed some snippet of XML somewhere during their talk.
I remember when we started XML at Microsoft most people thought we were crazy. The biggest challenge was convincing people the cost of parsing and storing verbose XML tags was worth it and our team has been working on performance, and scalability ever since. But the technical challenges are easy to overcome. The real reason XML become a key component of .NET, (and Windows, and SQL Server and Office) is because it achieved true cross-platform interoperability and because it was good enough for that job, which leads to the next question…
What do you (personally) like the most about XML and its associated standards? Simplicity, cross-platform interoperability and huge adoption. The great thing about XML is that it is humble. It’s not trying to solve world hunger. Just invent your own tags, group them into structures that make sense for your domain and viola. It is very simple and it is this concept that helped HTML take the world by storm. XML then improved on HTML by providing a clean separation between data and UI. It brought MVC to the masses so to speak.
The other day my 12 year old son was all excited and just had to show me what he discovered. He was editing Age of Empires XML files to tweak the behavior of the game using Notepad. I asked him how he knew that he could do that and how he knew the XML syntax. He didn’t know what “syntax” meant, but he knew how to edit XML ! Then the same week my doctor was all excited when he heard I worked on XML because he was involved in a software purchasing decision at our local hospital and it came down to their level of XML support. I couldn’t believe my ears.
The funny thing is that most programmers don’t really like XML. Probably because it doesn’t use curly brackets J, so most programmers treat XML a bit like the ugly duckling. But the reality is that the whole world gets markup – to them markup makes our programming world more approachable. There are still way too many programmers that don’t get this.
What would be your #1 tip to people learning XML, XML Schema, XSLT and XQuery? First of all I would say that XML 1.0 is the foundation. A must have. Can’t go wrong there, learn it, and learn how XML encoding works – that’s the number one issue people have with XML 1.0 – people don’t take the time to understand how UTF-8 encoding works which is a pretty important foundation to XML. Don’t worry too much about DTD, because we now have XML schema.
XML Schema (XSD) is a layer on top of XML 1.0. When you need a way to describe your XML structure in “standard contract” XSD is handy and most importantly – it’s there and it’s a standard. So don’t re-invent the wheel, but I’m not going to say that XSD is the be all and end all of data modeling, because it isn’t. A lot of things are missing, which is why people had to invent things like Schematron, and why Microsoft is working on EDM and SML and so on. Model driven development is now on the peak of the hype curve so I expect that modeling will be a battle ground for a long time to come. So take a pragmatic approach to XSD - use it if it fits your purpose. Some folks use other modeling approaches then have a tool that spits out the XSD – and that’s fine too.
Same goes for XQuery and XSLT – I think of these as being yet another layer above XSD. We did XSLT and XQuery because we figured that XML is data therefore people will want ways to query and transform that data. Makes sense, and I’ve done a lot of XSLT development, I still use it for specific tasks, but some things are a bit tedious. I find myself escaping to script a lot. XSLT 2.0 is a good improvement, but again, these things are not going to be the be all and end all of query and transformation languages.
For example, I’m a huge fan of the work they are doing in VB 9 with XML literals connected to our new Language Integrated Query (LINQ). It makes a lot of sense, because instead of having to “escape” to script, you just write the code you need right there in place – you have a complete general purpose programming language at your finger tips. VB-XML integration is big leap forward for VB programmers and allows those developers, who may not be as familiar with the standard XML technologies like XSLT, to easily process XML data inside their programs. It’s a huge advantage to the VB programmer and we think it helps make VB an extremely compelling language for XML programming – it makes me want to write VB again, and I’ve heard many others say the same thing. However, it is VB-specific so development teams that need cross-platform interoperability at the query/transform layer are likely to stick to the standard technologies like XSLT and XQuery.
There’s a very interesting tension going on here where general purpose languages like VB and C# are moving up into declarative space with LINQ but not going all the way into declarative, versus SQL, XQuery and XSLT which are fully declarative with no side effects, which are therefore more optimizable, but sometimes rather incomplete as programming languages go and rather hard to author in some cases. I really don’t know how it’s going to end up. I think we should continue innovating on both approaches and see what happens. It should be very interesting.
As for all the myriad other XML standards out there, there’s a lot of hype that you have to sort though. To me it’s a funny thing to see programmers going to town making XML more complicated with layer upon layer of new concepts. I remember going to a conference and people were telling me “stop! – we can’t take any more”. There is genius in simplicity. I’m glad to see the renewed focus on simple REST-ful XML based services for this reason. If simple works, why complicate it. Conversely, if it isn’t simple, chances are people just won’t use it.
What can we expect from Microsoft in the future in the XML arena? Will support for XQuery 1.0 and XSLT 2.0 become part of Microsoft’s offering? Microsoft is a pretty big place, so it’s hard for me to know all that is going with XML across the company. But I do know about .NET, Visual Studio and SQL server. As I’ve mentioned before we are shipping the XML support in Visual Basic 9.0 with XML literals, XML axis properties and integration with LINQ to XML. LINQ to XML is our API which we are adding to the XML runtime in .NET 3.5, it is a new XML object model that is designed to work well with the Language Integrate Query capabilities of C# and VB. We are also shipping some cool new features in the XML tools in Visual Studio 2008, including an incremental parser with extensibility API based on LINQ to XML that 3rd party XML designers can build on. We are also adding data breakpoints in the XSLT debugger and we have a new command line tool named “xsltc.exe” which takes XSLT and generates a .NET assembly which you can then deploy with your app instead of the XSLT source so you don’t have to compile XSLT on the server. Anton Lapounov has a great blog that talks about that. There is not much else new in the System.Xml runtime because Visual Studio 2008 is essentially a service pack release of the .NET 2.0 runtime, so we’ve fixed some bugs there. We are also working on some XML features in Silverlight and we put up a preview of our LINQ to XSD work on MSDN. We are working on a new XSD designer and you will see a CTP on MSDN pretty soon.
As for XQuery, you probably know we have a subset of XQuery already supported inside SQL Server. We currently have no official plans that we can announce on a client side XQuery engine but we are definitely interested in expanding client side query processing. LINQ offers a path to this (for both relational as well as XML). ESQL provides another client-side investment. We are open to customer feedback on the relative importance of client side XQuery compared to all these other possibilities. Meanwhile we are doing some XQuery improvements in SQL Server 2008, adding LET, better datetime support, and lax validation.
As for XSLT 2.0 - we’ve heard from customers and understand the improvements in XSLT 2.0 over XSLT 1.0, but right now we’re in the middle of a big strategic investment in LINQ and EDM for the future of the data programming platform which we think will create major improvements in programming against all types of data. But we are always re-evaluating our technology investments so if your readers want to ramp up their volume on XSLT 2.0 please ask them to drop us a line with their comments.
Meanwhile I was rather surprised by the positive feedback to my little XML Notepad 2007 tool. It now has over 1 million downloads and is still going strong. Not bad for a couple weeks work and no marketing. So something about this tool hit the sweet spot. The interesting thing there is it reaches out to the non-programmer community and I think that is the key and it has the right balance of simplicity and usability. A Swedish customer said it is “logam” – just enough. I think you should expect to see more from Microsoft in the future that helps to make XML something that everyone on the planet can deal with easily and in a way that integrates deeply with everything else Microsoft provides.
As the XML hype is wearing off, folks are realizing that not everything that made it through the standards process needs to be implemented. So I think you will see Microsoft continue to innovate on new XML technologies and tools like LINQ to XML and VB 9.0 XML and you’ll see Microsoft taking a more pragmatic customer-demand-driven approach to standards. Microsoft will probably never implement every standard that comes out but I’m confident you will see Microsoft continue to be committed to the really important XML standards, like XML 1.0, and any other standard that is essential to achieving cross-platform interoperability, including Open XML. There is enormous power in the cross-platform reach of XML and the huge industry adoption it has and I’m happy to see that Microsoft is continuing to do some really innovative work with XML.
For those interested in the demo of Using Windows Workflow Foundation in ASP.NET, you can download it here (269 kb). Note: this is the demo with the "double bookkeeping". The request/response inside a workflow isn't stable enough yet for release.
For those people interested in the demo's I did in the session Create Scalable Apps with Async Processing at VSLive! this week, you can download here (600 KB). To "install" the demo's, create a Visual Studio solution with two websites (one for each folder in the zip file). Run the web service to get a port number, then update web.config in the AsyncPages folder so that web services reference that port number (or take the port number currently in web.config and set the web service to run on the specified port). Enjoy!
I'll be at VSLive! in Las Vegas next month. On Tuesday, October 16th, I'll be speaking about two topics:
- Using Windows Workflow Foundation in ASP.NET
- Create Scalable Apps with Asynchronous Processing
The first is an introductory session about Windows Workflow Foundation (WF) and adresses how to deal with WF in ASP.NET. Because WF is not request-response by nature, this is more challenging than you would think. The second session discusses ASP.NET 2.0 Async Pages and Handlers and shows you how to use this with web services and databases.
Hope to see you there!
MOSS 2007 has it's own theming engine, separate from the ASP.NET theming engine. A downside of the MOSS approach is that you require an IIS reset to change a theme. Not very nice, so we wanted to use ASP.NET theming instead. This however causes problems with all pages in the _layouts folder, because they don't have <header runat="server" />. That tag is necessary, because ASP.NET needs to add CSS references and such to the <head> tag. Without that tag you receive the following error message:
Using themed css files requires a header control on the page
The solution is to define no theme for the pages in the _layouts folder. Since the pages in that folder are mainly dialog-type screens for SharePoint operations, this is not a problem from a look & feel perspective. That said, there are situations where you create your own pages and put the in the _layouts folder. For those pages you can apply a theme, providing there are no (MOSS) webparts and such on the page. In web.config this would look something like this: <location path="_layouts">
<system.web>
<pages theme="" />
</system.web>
</location>
<location path="_layouts/MyCustomPage.aspx">
<system.web>
<pages theme="MyTheme" />
</system.web>
</location>
Last year I wrote a book (in Dutch) about ASP.NET 2.0. For that book I did an interview with Scott Guthrie, General Manager of the .NET Developer Platform group at Microsoft. In the book the interview is of course translated and also edited to fit the book. Below is the original unedited version.
Who are you? My name is Scott Guthrie. I am the General Manager of .NET Developer Platform group within Microsoft, which means I run the development teams that build the CLR, .NET Compact Framework, ASP.NET / Atlas, Windows Presentation Foundation (aka Avalon), Windows Forms, IIS 7.0, Commerce Server, and the Visual Studio development tools for ASP.NET and WPF.
How long have you worked for Microsoft, and in what did you do up to becoming General Manager? I’ve been at Microsoft for 9 years. I’ve been focusing on frameworks, tools and servers for developers pretty much the entire time. Prior to my current role, I ran the teams that built ASP.NET, IIS 7.0, and Visual Web Developer.
You are generally seen as the (co-)creator of ASP.NET. How was ASP.NET conceived and where did you get the ideas from? We actually started the ASP.NET project in late 1997 and early 1998. At the time ASP was still relatively new, and we initially weren’t sure whether there was anything left to-do in the web space (little did we know)! We then spent a lot of time talking with developers and customers using ASP and quickly realized that there were a lot of things left to resolve.
Some specific issues/requests that came up again and again from customers: provide the ability to write much cleaner code that provided good code/content separation (rather than mixing code up in the HTML), provide the ability to write applications using a variety of coding languages (and not just VBScript and Jscript), deliver a more robust execution environment (avoiding memory leaks and crashes that could bring down the server), provide a much cleaner configuration/code deployment model, deliver a built-in security architecture, enable built-in output caching support to improve scalability, and more.
A colleague of mine (Mark Anders) and I spent about 2 months brainstorming ideas about how we could build a programming model that delivered all of this. Eventually we decided we needed to put together a prototype to try out the concepts, and I ended up coding it up over the Christmas and New Year’s holiday in 1997/98 (I was a hardcore geek then <g>). We showed off the prototype to a lot of people within the company, built a lot of excitement, and got the go ahead to build a team to deliver it.
What are the main differences between ASP.NET 1.x and ASP.NET 2.0? We spent a lot of time working with customers to identify where they spend their time writing code today within web applications, and then worked to add new features in ASP.NET 2.0 to help simplify these tasks dramatically. Some examples: Master Pages allow you to easily define a consistent layout across your site/application, the new Membership/Roles API provides an easy way to manage users/passwords/roles and allows you to build flexible secure application in only a few minutes, the new GridView/DetailsView/DataSource controls enable you to easily provide data entry and editing views on top of data (including 3-tier data access support), Web Parts provide the ability to enable portal-style layout within any page and enable drag/drop end-user customization that works both in regular ASP.NET applications and SharePoint solutions, Localization support has been added to make it much easier to build multi-lingual applications that can adjust at runtime depending on the culture/language of the incoming user, SQL Output Caching enables developers to output cache any content within a site and have it automatically be invalidated and re-generated when backend data changes on a site (dramatically improving performance), Site Navigation and Menu controls make it much easier to build menu structures and navigation across your sites, Health Monitoring makes it easier to monitor how your application is doing once it is deployed, and there are many more features I could keep calling out.
If you could give one tip to people learning ASP.NET 2.0, what would it be? I’d recommend spending time on the new http://www.asp.net web-site in the “Getting Started” and the “Learn” sections. We are putting out several new videos and tutorials each week on the site that help show how you can take best advantage of new features with ASP.NET. These can make it significantly easier to take full advantage of the platform and build great applications. I’d also recommend subscribing to my blog: http://weblogs.asp.net/scottgu. I try and post 1-2 tips/tricks a week that you can use.
What do you (personally) think is the coolest feature of ASP.NET 2.0? Master Pages is probably the most popular feature that virtually everyone takes immediate use of – so in terms of popularity that is probably the coolest.
I think the new ASP.NET 2.0 AJAX Extensions product we are shipping later this year is also really, really cool (note: this was formerly codenamed “Atlas”). This will provide a free, fully-supported AJAX library with suite of ASP.NET 2.0 server controls that enable you to easily add AJAX functionality to your ASP.NET 2.0 sites.
What are the long term goals for ASP.NET, and what will we see of that in the coming years? The next release of ASP.NET will have a lot of great additions. You will see even richer support for the AJAX Extensions built-into the next release, as well as much richer support for building more interactive user experiences that take full advantage of the browser.
You’ll also see ASP.NET take advantage of the new LINQ technologies that are coming out with .NET, and which will enable really rich data modeling and mapping support with code which will dramatically improve the productivity of working with data. When LINQ is combined with the ASP.NET 2.0 GridView, DetailsView and other data controls, you have a tremendously easy and powerful programming model for building AJAX enabled data applications. I’m really excited to see the applications people build with it. It is going to be a very exciting future!
I've been working with ASP.NET 2.0 for a long time now and I thought I'd seen most of it. Today I found something that must have flown under my radar all this time: the Health Monitoring API. Functionally this API is similar to log4net and the Enterprise Library logging Application Block. Although both of these work well I prefer functionality that comes "out-of-the-box", because you don't have to do anything to get it, it works, and your pretty sure it'll be kept up to date by the folks in the product team(s). So even if you're using another logging mechanism, be sure to check out the Health Monitoring API. How To: Use Health Monitoring in ASP.NET 2.0 from the Pattern & Practices group is a good starting piont.
Thanks to all that came to my sessions at VSLive in Orlando on Tuesday, and thanks for the great feedback. Below are the demo's for the two sessions. Updated slides decks will be made available on the attendee website.
Some of you asked which tool I used to demo the perf difference between sync and async (demo 1). Although you could use perf tools that come with VS2005 I used Application Center Test (ACT) that comes with Visual Studio 2003, because it is very easy to setup and shows nice graphics (which was most important for this demo). You can also use the free Web Application Stress Tool. The ACT script I used was (substitute "slow.aspx" with "slowasync.aspx" for the async test), with 50 browser connections:
Randomize() If Rnd(10) < 5 Then Test.SendRequest("http://testserver/Demo01/Fast.aspx") End If Test.SendRequest("http://testserver/Demo01/Slow.aspx") Test.SendRequest("http://testserver/Demo01/Fast.aspx")
Note: I've run this test in several setups with different hardware. In my Orlando session I showed numbers from ACT on the host to the web in a VPC. In my San Francisco session ACT was on a Dell D600 with the web running in a VPC on my Dell D800, which is a better way to test (in the Orlando setup ACT is drawing perf from the same CPU). The async perf is much better (even in percentages) with the SF setup. Be aware that there are a lot of variables: CPU capacity, memory, and last but not least... network interface. In another test setup I hardly saw any difference between sync and async. Why? Because the network was the bottleneck :(.
I've always felt that SVG wouldn't make it into the mainstream. Flash does about everything SVG does and is available on 99.9% of the desktops. In addition there are scores of Flash developers/designers out there. The only thing SVG had going for it was the support of Adobe, but I always thought they were in it because SVG was a potential Flash-killer. With the acquisition of Macromedia, Adobe doesn't need a Flash-killer anymore. In fact they probably wished SVG never saw the light of day. Last year Adobe anounced that they will discontinue their SVG Viewer browser plug-in, saying that SVG is a mature technology and that there are loads of mature implementations now. The directory of SVG viewers tells us otherwise. Now that Microsoft has put forward Silverlight, a Flash (and potentially HTML) killer, the future of SVG looks pretty grim. The two companies that in the past would benefit most from the rise of SVG now both would like SVG to be a thing of the past.
Download the demo's here (34.39 KB)
During the session I promised to give put a sample here about using delegates for asynchronous processing, but what's the use if you can just read it on MSDN: Calling Synchronous Methods Asynchronously. Again, be aware that you shouldn't use this in ASP.NET!!! This is for console, desktop, and Windows Services only! In ASP.NET this would exhaust the thread pool pretty fast.
Download the demo's here (85.85 KB). If you want the slides, send me an email.
If you want to do the AspCompat demo, don't forget to register the VB6 component from the command line with regsvr32.
We were recently faced with the error message The project file ' ' has been renamed or is no longer in the solution in Visual Studio 2005. The problem is that from this message you have no idea what is actually the matter. We finally figured out that this happens when a Web Project contains references to assemblies or projects it can't find. Here's how you solve this:
- Right click the Web project and select Property Pages.
- A window will open which lists all the references, either to the bin-folder, GAC or other projects in the solution.
- Remove those that show (unavailable) behind it.
- Chances are that now you can't build because the reference is not there. Simply add the reference again and you should be OK.
I've been invited to speak at VSLive in San Fransisco ASPLive from March 25 to March 29. I will be doing two sessions on ASP.NET:
- Understanding Multi-Threading (in ASP.NET)
- Creating Scalable Apps with Asynchronous Processing
The first session takes a closer look at the fact that ASP.NET is a multi-threaded environment and what that means for us (web )developers. The second session looks at asynchronous pages, handlers and modules, to increase the scalability of our apps without adding new hardware. For more information checkout the session abstracts on the VSLive site.
I hope to see you there.
Since January 1st Slovenia is using the Euro, so all e-commerce need to change to the euro. More accurately, the culture settings for Slovenia in Windows need to be changed. Unfortunately there is no patch available yet for Windows and you can't change the settings through the Configuration Panel (it'll change back automatically). Until the patch arrives, the following code can remedy the situation:
CultureInfo culture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone(); culture.NumberFormat.CurrencySymbol = "€"; culture.NumberFormat.CurrencyPositivePattern = 2; // € 19.95 culture.NumberFormat.CurrencyNegativePattern = 12; // € -19.85 Thread.CurrentThread.CurrentCulture = culture;
This changes the culture settings at thread level. Adding this to Application_BeginRequest in global.asax works like a charm, but don't forget to check the initial culture first...
For some reason the traffic on my blog has exploded. Not from regular users, but because of Trackback and Pingback. The log is full of requests to these to services. I have turned them off, because I don't have the time to fix it (if I felt like doing it in the first place).
UPDATE: I figured out why my traffic jumped. My blog was victim to a spam attack, which added numerous trackback URLs. Unless I figure a way out to get around that (or Dasblog has), I'm not turning on trackback ever again.
When you make columns invisible in a GridView-control the values in those columns are ignored when doing an update. If the update function, stored proc, or whatever expects these values (particularly when you use CollisionDetection="CompareAllValues"), the update will fail.
The solution: - Add the names of the invisible columns to the DataKeyNames-properties separated by a comma, so the values are available. - Create an event handler for the GridView.RowUpdating and add the code below. This copies all "key" values to the old and new values so the update will work.
IDictionaryEnumerator restoreOldValues = e.Keys.GetEnumerator(); while (restoreOldValues.MoveNext()) { e.OldValues.Add(restoreOldValues.Key.ToString(), restoreOldValues.Value.ToString()); e.NewValues.Add(restoreOldValues.Key.ToString(), restoreOldValues.Value.ToString()); }
I was looking for something totally different, but came across this article on the Oracle Technology Network about the differences between PHP and ASP.NET. First of all I was sort of puzzled by the obvious pro-PHP stance taken by Oracle (at least in this article). I expect Oracle to be biased towards Java, which their product line supports, but as far as PHP and ASP.NET are concerned they're just web technologies and both can use Oracle. As long as Oracle is used, what does Oracle care which of the two technologies is used? Secondly the pro-PHP bias I mentioned is very obvious if you look at the comparisons of speed and security. PHP faster than ASP.NET? I don't think so... and most tests seem to agree with me. The argument Sean Hull uses is that ASP.NET is much bulkier when it comes to the actual code being executed. Maybe so, but the CLR compiles and optimizes that plenty. Then when it comes to security Sean Hull comments that ASP.NET runs on IIS, which according to him must be qualified as unsafe because of its history. He goes on to comment that Apache is much safer. I guess he forgot to check the latest stats on securityfocus.com and secunia.com. The number of vulnerabilities in IIS6 found in its entire existence is 3 (or 5, depending on how you count), compared to the 32 (or 39) found in Apache 2.x during rougly the same period I would say IIS looks pretty good. Looking at the same timeframe (2003-2006) even IIS5 has had less vulnerabilities (14). 3+ years is quite a long time when it comes to the web, so history in that sense gives the edge to IIS, not Apache. Looking at the stats that is, the sentiment (or perception if you will) is still that IIS is (or could be) unsafe. I guess the time it takes to change someones perception is longer than 3+ years, so I guess Microsoft must battle perceptions that are nog longer justified.
One of the great things about a DataSet, from a code generation perspective that is, is that it is defined in an XML Schema with some added features for TableAdapters and such. I wrote a very simple code generator that takes a DataSet definition and an XSLT stylesheet and generates a code file. I also made it possible to call an XSLT stylesheet for each table in the DataSet so I could create Data Transfer Objects and such from the table definition. I had some trouble to get it going though because of a namespace issue. The namespace that you expect to be the default namespace isn't in actual fact as I'll explain with the following fragment: <xs:schema id="TrackingTracingDataSet"
targetNamespace="http://tempuri.org/MyDataSet.xsd"
xmlns:mstns="http://tempuri.org/My.xsd"
xmlns="http://tempuri.org/MyDataSet.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
xmlns:msprop="urn:schemas-microsoft-com:xml-msprop"
attributeFormDefault="qualified" elementFormDefault="qualified">
<xs:annotation>
<xs:appinfo source="urn:schemas-microsoft-com:xml-msdatasource">
From the above fragment you would think that the default namespace is http://tempuri.org/MyDataSet.xsd, because the default namespace is declare with the statement xmlns="http://tempuri.org/MyDataSet.xsd. The actual default namespace is however defined in the source attribute of xs:appinfo element, so the default namespace is urn:schemas-microsoft-com:xml-msdatasource.
Recently one of my collegues was trying to create a Web Setup project for an application in VS2005 and he commented "I can't add the Primary Output of the application to the setup, just the content." This is where VS2005 (or actually ASP.NET 2.0) differs from VS2003, so I explained that this was normal behavior and that his application didn't need to have an application assembly because ASP.NET 2.0 compiles everything on the fly. His reply was that you wouldn't want to have your source code sitting in the production enviroment, and he is absolutely right. The solution to this is precompiling your applications with aspnet_compiler.exe. This packages all your files, inlcuding the contents of your .aspx files in an assembly which is used to run the site. The .aspx files are still there, but these are just placeholder files with no contents. By default the .aspx files can't be edited (well, you can but that doesn't change what is sent to the browser), but this can be controlled. Checkout the MSDN article How to: Precompile ASP.NET Web Sites for Deployment on how to use aspnet_compiler.exe. For a complete rundown of precompilation see ASP.NET Web Site Precompilation.
Updated August 13, 2006 to reflect Sander's comment.
On my old blog (in Dutch) I commented that I thought the WindowsImpersonationContext was clumsy and I wrote a replacement that you can use as follows:
Console.WriteLine("Current user: " + WindowsIdentity.GetCurrent().Name); WrapperImpersonationContext context = new WrapperImpersonationContext(domain, username, password); context.Enter(); // Execute code under other uses context Console.WriteLine("Current user: " + WindowsIdentity.GetCurrent().Name); context.Leave(); Console.WriteLine("Current user: " + WindowsIdentity.GetCurrent().Name);
Recently a visitor noted that the code wasn't quite right (missng a few using statements, and I found some other small issues. The correct code (including namespace references) is below. It takes care of all that nasty calls into the Win32 API. The one thing you need to be aware of is that it requires permissions to call into a DLL (i.e. run unsafe code), which is why I added the attributes that indicate this. Unfortunately that renders this class useless in a hosted environment, unless you strong sign the assembly and pursuade the host to allow your assembly to run in Full or High trust. This however is a problem you will run into regardless your use of this class. As soon as you call LogonUser you need at least High trust. If this is something that should be possible under lower trust by default it's up to the folks in Redmond to add this functionality to .NET and handle it as such.
using System; using System.Runtime.InteropServices; using System.Security.Principal; using System.Security.Permissions; using System.ComponentModel;
public class WrapperImpersonationContext { [DllImport("advapi32.dll", SetLastError = true)] public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)] public extern static bool CloseHandle(IntPtr handle);
private const int LOGON32_PROVIDER_DEFAULT = 0; private const int LOGON32_LOGON_INTERACTIVE = 2;
private string m_Domain; private string m_Password; private string m_Username; private IntPtr m_Token;
private WindowsImpersonationContext m_Context = null;
protected bool IsInContext { get { return m_Context != null; } }
public WrapperImpersonationContext(string domain, string username, string password) { m_Domain = domain; m_Username = username; m_Password = password; }
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] public void Enter() { if (this.IsInContext) return; m_Token = new IntPtr(0); try { m_Token = IntPtr.Zero; bool logonSuccessfull = LogonUser( m_Username, m_Domain, m_Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref m_Token); if (logonSuccessfull == false) { int error = Marshal.GetLastWin32Error(); throw new Win32Exception(error); } WindowsIdentity identity = new WindowsIdentity(m_Token); m_Context = identity.Impersonate(); } catch (Exception exception) { // Catch exceptions here } }
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] public void Leave() { if (this.IsInContext == false) return; m_Context.Undo();
if (m_Token != IntPtr.Zero) CloseHandle(m_Token); m_Context = null; } }
This is a great tool that helps you create a sound threat model of your application, leading to a more secure application. Do yourself a favor and download it.
You can watch the top sessions (including Gates') on It's Showtime, as is the case with sessions from TechEd and other events.
I think Microsoft has made a smart move in renaming WinFX (including .NET 2.0) to .NET 3.0 (see blog post by Soma Somasegar). First of all there was a lot confusion about what .NET and WinFX are, and secondly WinFX is often confused with WinFS (the new file system). Us developers can all do with a little less confusion finding out way through development technologies.
I recently downloaded the Windows Workflow Hands On Labs for WF beta 2 and found the samples to be less than perfect. For instance the state management example (Lab 04) doesn't even build because there are some workflow fields set to private instead of public. Remedy that and the application will run. Not that it'll help... it crashes almost immediately. Looking at the code I can see that it is not beta 1, but I assume that it is pre-beta 2. This is a big disappointment because I'd like people within my company to do the labs to get to know WF. I hope the WF team tests and debugs the current hands on labs and puts out a new download that works well with beta 2.
Since I started as a programmer, I have hardly ever developed Windows applications. I mostly did web and components, GUI stuff is not my can of beans. That said, I do want to keep tabs on what's happening in with Windows GUI development, so I bought Programming Microsoft Windows Forms (a streamlined approach using C#) by Charles Petzold. I can tell you it was not the type of book I expected. What I expected was to learn how to build Windows applications, using a database and so on. Basically everything you need as a beginner to start developing full fledged apps. To my surprise the book is actually JUST about the GUI. There is the least amount of "clutter" of stuff that is not related to the GUI. In addition the whole book is setup so you can develop with just Notepad. The result is that the book has a very clear build up to how Windows Forms actually works. As such it was an enjoyable read for me.
The recent post by Scott Guthrie on Localization in ASP.NET 2.0 made me realize that most developers I know (myself included) don't know that much about localization. That's kind of ironic because I live in The Netherlands where the primary language is definitly not English. You would expect that in countries like that localization would be a big issue. It is not (well not here anyway).
Yes, it was bound to happen sooner or later, and now it has. I finally started a blog... well, I already had one, but it was only in Dutch. This time around I am bilingual, although chances are pretty huge that the Dutch and English content won't match. For now I've set the default language (or category actually) to English, under the assumption that I will do most posts in English... we'll see.
|