Tuesday, November 30, 2010

How To Use Impersonation in ASP.NET Configuration With IIS 7.5 And Integrated Pipeline

While working on a few applications that have Impersonation="True" in my ASP.NET configuration, I ran into the following error upon deployment to an IIS 7.0 or 7.5 server:

"HTTP Error 500.24 - Internal Server Error An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode"

This is essentially a 'flag' warning that is raised when using Impersonation in your web.config and deploying to an IIS 7.0+ server using an Application Pool with Integrated Pipeline. If this configuration was mistakenly added, you can remove the configuration or set it to 'False' to fix the problem. There are (2) solutions for those that do need Impersonation="True".

1. Switch the Application Pool on IIS to use a 'Classic' Pipeline.
2. Add the following configuration to your web.config under the <system.webserver> section:

<!--When using 'Integrated Pipeline' on IIS on the server, and if your application does not rely on impersonating the requesting user in the 'BeginRequest' and 'AuthenticateRequest' stages (the only stages where impersonation is not possible in Integrated mode), but still requires Impersonation in other areas of the application, ignore this error (500 - Internal Server Error) by adding the following to your application’s web.config-->
<validation validateIntegratedModeConfiguration="false"/>

I actually used the explanation from the following helpful IIS Blog link (here) to create the XML comment above the configuration, and I reccomend reading it for a more in depth explination direct from an IIS Program Manager.

Monday, November 22, 2010

Book Review: Professional ASP.NET Design Patterns By Scott Millett

Let me begin by stating that Professional ASP.NET Design Patterns is a fantastic book that was worth every minute I spent reading it. The author, Scott Millett, is a great community leader and extends himself in several ways including spending time on the forums contributing to others into his strong insight of Domain Driven Design, Architecture, and Design Patterns. He has extended that helpfulness by writing this book that takes a dive into Design Patterns and Architecture from an ASP.NET UI centric view. However I would not get too fixated on the 'ASP.NET' in the title as probably more than half of this book could just as well have been called "Professional .NET Design Patterns" as it provides design patterns that are truly useful to all types of .NET applications once moving below the topmost UI layer. There are several chapters devoted to ASP.NET patterns including MVC which makes this still focused mostly on ASP.NET, but I would still recommend this book to WinForms and other SmartClient developers as well.

This book's target audience is broad and could reach to several different types of software engineers. It is probably suited best for Senior Engineers, Architects, Leads, or generally seasoned developers. It is not really an introductory book (this is a good thing; there are plenty of those books out there already), so if you don't know what acronyms like OOP, OOD, UI, BLL, or DAL mean at a minimum already then you may want to read something along the lines of an introduction to Object Oriented Programming book 1st to gain some traction. This is however a terrific book for those that do have a lot of experience with a traditional 3-layer logical architectures, and are looking to bridge the gap to more sophisticated architectures using Domain Driven Design and other implementations of either Martin Fowler's or the GoF design patterns within.

Scott does a wonderful job of layering the book (chapters) as you would an application. Each chapter takes either a single layer or design pattern and goes into detail on its responsibilities, relationship to other layers, and implementation with easy to follow along code samples. In fact I highly recommend downloading the code samples from the WROX website (WROX Code Download) The entire set of code samples are in C#, but don't let this slow up any VB.NET devs out there. I am actually a VB.NET developer (C# in the past) but we all know that you don't get too far in this industry without reading both so this should not be any problem.

The 1st third of the book (roughly) concentrates mostly on individual logical layers of an application and how they work together to build an application. Within each layer, there are examples of Design Patterns (both Fowler and GoF) that are used and shown why they are useful within that particular layer. There is also a section on IoC and DI which I really enjoyed and are reoccurring patterns in the layers throughout the book. The 2nd third of the book concentrates mostly on ASP.NET architectures and techniques like MVC, MVP, and AJAX patterns. The last third is devoted to a case study example that uses the knowledge gained from the previous chapters. The book reads and flows extremely well and was one of the reasons I enjoyed reading it so much.

I will also note that this is a great book for those of you familiar or have read the GoF book Design Patterns Elements of Reusable Object Oriented Software. As we all know code examples used to conceptually explain design patterns are not always critical, but Scott's book puts a fresh '.NET' perspective on several of the GoF patterns which is really nice. This helps to see how these patterns apply directly in .NET instead of taking the SmallTalk or C++ examples from the GoF book and translating them into .NET.

The book wraps up with a full case study example putting all of the chapters together (Agath's e-commerce store). This again strengthens the flow of the book with an extended example using everything learned from the previous chapters, This solution is included in the 'Chapter 14' folder in the downloadable code and is a nice reference to show everything from the book.

Well I will wrap this review up by saying this book is one for the shelf of 'Top Reference' books that go right next to the development machine. This is one of those books that you think, "How do I do that in the Repository Layer...", and then pick up the book to get a refresher. I would definitely recommend this book and keep an eye out for future books from Scott Millett. Nice Job!

Monday, November 15, 2010

Day 2: Visual Studio Live! Orlando 2010

Another beautiful and informative day here in Orlando, FL at Visual Studio Live 2010. I would have to pull my old conference materials for comparison, but I really like the 4-5 class per day format. I seem to remember 6 or more classes per day in the past which can maker for a really long day especially if learning new concepts. However, this format has been perfect.

Had great classes with industry leaders like Leonard Lobel, Gus Emery, and Jason Bock. I also must note that one of the best byproducts of these conferences is the side conversations and networking that occurs informally. Everyone at these conferences is here for one reason: they are the leaders of their respective teams or companies in reference to software development and related ares and love what we do. For this reason, everyone is eager to chat, talk, and discuss their jobs, work, applications, etc which is quite nice.

One new product I learned of today was Microsoft WebMatrix. http://www.asp.net/webmatrix This is an all inclusive tool to rapidly build web applications using shared pre-built components built by the development community, and hosted on IIS Development Express. What I was instantly amazed by was how Rabi Satter (@rsatter42) wrote in '1' line of code (no joke) a Twitter client that searches for a keyword that took me probably 500-1000 lines of code (between Silverlight client and WCF proxy service) to do essentially the same thing. OK no denying that is nice, and the technology offers more of the same (Twitter, Facebook, Wiki, Blogs, PayPal, etc). It is still in Beta and will probably not revolutionize web development and having everyone run away from their current platforms, but it certainly will have a presence.

Lastly, I had the unique and great pleasure of dining this even with 2 prominent leaders of our industry, Rocky Lhotka and Jason Bock. Seeing how I have listened to them speak, read books from them, Twitter feeds, blogs, etc. it was a real nice experience to hang out with not only some top echelon developers, but also some just really cool guys. Everyone at dinner liked the band Rush (hey, who doesn't) which made for some good conversation as well. I hope to hook up with you guys more in the future and highly recommend those of you in the industry to check these guys blogs out as well: http://www.lhotka.net/ and http://www.jasonbock.net/JB/Default.aspx

Sunday, November 14, 2010

Day 1: Visual Studio Live! Orlando 2010

This is my 3rd Visual Studio Live (formally VSLive!) and I am enjoying it as much as ever. If you ever get the chance to attend one of these events (Orlando, Las Vegas, Redmond, etc.) try and do it. The information is terrific and the insight from experienced presenters, peers in our industry, and general networking make it all worth it.

Today I attended the workshop named "Making Effective Use of Silverlight and WPF" with Rocky Lhotka (@RockyLhotka on Twitter) and Billy Hollis (http://slmasters.net/). Talk about (2) all-stars of our industry. Billy's knowledge of UI design with Silverlight and WPF (and other UI technolgoes too WinForms, etc) combined with Rocky's experience being an experienced OOP and Architecture engineer (research CSLA.NET) makes for a wonderfully informative day.

I had the pleasure of being on the front row for the presentation and enjoyed the back and fourth complimentary knowledge of .NET technologies. Unfortunately for me, I asked a question regarding a .xap being downloaded to the client, potentially exposing sensitive code (for a small % of shops, or developers still using antiquated architectures with wayyy too much code in the UI including sensitive connection strings, password, etc.) and made me sound like a noob. People were coming up to me at break telling me, "Just leave that code on the server and make a WCF call..." Yep, I know. Just was trying to raise a quick conversation for ex-web developers to understand Silverlight's deployment. Ow well. :)

Rocky (4th time attending presentations) and Billy (2nd time hearing presentations) can offer a lot of knowledge for those wanting to a lot about A+ presentation design (Billy) or OOP and .NET Technologies (Rocky) and should be checked out this week. If you are attending Visual Studio Live I highly recommend any presentations by either these (2) presenters. Nice job gentlemen.

Monday, November 1, 2010

Download FTP Files Using FTP Over SSL (SFTP) in .NET

Recently with the help of some folks over at StackOverflow I got pointed in the right direction for working with files on a FTP server and communicating with it via FTP over SSL. I had success using FTP client software to view and download files, but needed the code to do this programmatically in .NET. It is essentially easier than I thought and just casts a 'WebRequest' object to an 'FTPWebRequest' object and then the methods called are identical to those used in a traditional WebRequest call.

The main 3 obstacles I ran into where the following:

- Getting the Object parameter values set properly to match those of the client software I was already having success connecting with.
- Validating the Server's SSL Certificate programmatically.
- Getting around a 550 error I kept receiving when accessing the file directly.

So let’s get right to all of the code:

'Using an anonymous method, check to make sure the SSL Certificate being served up is the correct one.
'This method of inlining the validation is good for a simple single certificate check; for more involved
'checking you will want to use the line below and long hand the method call.
ServicePointManager.ServerCertificateValidationCallback = Function(obj As [Object], certificate As X509Certificate, chain As X509Chain, errors As SslPolicyErrors) (certificate.Subject.Contains("CN=ftp.domain.com"))
'Wire up a method that will be called upon creating the FTtpWebRequest and will validate the SSL Certificate
'ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf CertificateValidation)

'Create an FTPWebRequest providing the URI of the FTP server to connect
Dim Request As System.Net.FtpWebRequest = DirectCast(WebRequest.Create(New Uri("ftp://sftp.domain.com/MyFiles/Folder1/MyFile.txt")), System.Net.FtpWebRequest)
'Set that we will be downloading a file
Request.Method = WebRequestMethods.Ftp.DownloadFile
'We are going to enable SSL for the communication with the FTP server as required by the remote server.
Request.EnableSsl = True
'The credentials needed to log onto the server
Request.Credentials = New Net.NetworkCredential("UserName", "Password")
'Use a 'Passive' data transfer process. This setting was the same in my FTP client software.
Request.UsePassive = True
'Create a 'Reponse object getting the downloaded file
Dim Response As System.Net.FtpWebResponse = DirectCast(Request.GetResponse(), System.Net.FtpWebResponse)

'Read the File using a StreamReader:
Dim sr As New StreamReader(Response.GetResponseStream())
To solve my 1st issue I mentioned (get object parameters set), I essentially found and configured the FTPWebRequest object to mimic an existing workable connection from my client software. A lot of the FTP 'lingo/jargon' is identical between .NET and FTP client software. I recommend connecting to the FTP server as I did 1st using client software (i.e. FileZilla) to make sure you do have everything correct before running in circles with code that would never work because you don’t have permissions anyway.

Next I had to validate the servers SSL certificate programmatically. I was able to use a Lambda Expression using an anonymous method to to create a delegate that would check to make sure the proper SSL Certificate was being presented. If the validation logic is more elaborate, you can use the commented out call to wire up an event to a method named 'CertificateValidation()' by assigning the ServerCertificateValidationCallback on the ServicePointManager object.

Private Shared Function CertificateValidation(ByVal sender As Object, ByVal cert As X509Certificate, ByVal chain As X509Chain, ByVal [error] As System.Net.Security.SslPolicyErrors) As Boolean

'Make sure the correct certificate is being used:
If cert.Subject.Contains("CN=ftp.domain.com") Then
Return True
Return False
End If

End Function
Now either method could technically just return 'True' and all certificates would be trusted and validated, but I wanted to make sure I am actually presented with the correct certificate. You can easily find out the name of the certificate by turning on tracing in the web.config (explained below). Then you can make sure the proper certificate was served, and then Return True. This process actually exists the 1st time you probably connected to the FTP server with the FTP client software (i.e. FileZilla). A dialog probably presented itself asking if you trusted the certificate. This code is dealing with that process programmatically.

The last fix was in regards to solving this specific issue:

"The remote server returned an error: (550) File unavailable (e.g., file not found, no access)."

Now this was probably an issue specific to my setup, but I mention it because the oversight is probably common. I received this upon getting the FtpWebResponse object. The issue stemmed from the URI I was providing. I knew the URI had to be the full path to the file I wanted to download, so I used ftp://sftp.domain.com/MyFiles/Folder1/MyFile.txt I tried in a browser and had the same issue. I ended up turning on a listener to log System.Net traffic. The following article has directions on doing this: Using System.Net Tracing This output (found in the root folder in my project after running) showed that the default path was already /MyFiles/Folder1. This was already the path as soon as I connect to the base URI of sftp.domain.com, and I should have recognized this from the FTP client software, as I was directly taken to this folder location each time I connected. Therefore, when I fully qualified the URI, it actually resulted in looking for the following: ftp://sftp.domain.com/MyFiles/Folder1/MyFiles/Folder1/MyFile.txt This showed me that all I needed to do was just use the host + filename like the following which worked perfectly: ftp://sftp.domain.com/MyFile.txt

This code demonstrated how to download a file from a FTP server using SSL, but there are many other operations you can do as well (i.e. Uploading, file renaming, directory listing, etc.). Just modify the Enumeration value of 'Request.Method'.