Programming Silverlight 1.0 with C#

by Troy Sabin 10. December 2007 16:55

Be the first to rate this post

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

Tags:

Design / Technique | Tools / Services

Use C# 3.0 Language Features with .Net 2.0 Runtime

by Troy Sabin 27. November 2007 17:06

Dustin Campbell (Did it with .Net) has an interesting post on leveraging Visual Studio 2008's mutli-targeting support to use C# 3.0 language features with .Net 2.0-targeted projects.

Visual Studio 2008's multi-targeting support for compiling projects to different versions of the .NET Framework is very powerful. Multi-targeting is a compelling feature because it enables users to continue working on solutions that target .NET Framework 2.0 and 3.0 while upgrading to the latest and greatest IDE. What isn't obvious is that all projects, regardless of target, are compiled with the C# 3.0 compiler. That means users can employ many of the new C# 3.0 language features in legacy projects. The only language features that can't be used are those that require library support from .NET Framework 3.5, in essence, LINQ, Expression Trees and Extension Methods. Implicitly-typed local variables, lambda expressions, auto-implemented properties, object and collection initializers, and anonymous types are all fair game. It's sort of like having C# 3.0-lite or C# 2.5.

Read more...

Be the first to rate this post

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

Tags:

Design / Technique | Tools / Services

Clean, Horizontal dasBlog Navigation

by Administrator 11. October 2007 17:03

I recently upgraded to dasBlog 2.0 and went ahead and updated my site design while I was at it.  With the new design, I wanted to use dasBlog's navigator links for the horizontal menu.  However, the navigatorLinks macro is hard-coded with a vertically-oriented table structure.  So I wrote a custom macro to provide the links in a simple unordered list that I could style with CSS.  I started from the source code for the navigatorLinks macro and just replaced the HTML-generating bits.  While I was tempted to consolidate the redundant logic, I avoided any other refactoring to save time.  For those interested, my code is below.  For more information on creating custom macros, read: Creating custom macros for dasBlog.

public class CustomMacro

{

    protected SharedBasePage requestPage;

    protected Entry currentItem;

 

    public CustomMacro(SharedBasePage page, Entry item)

    {

        requestPage = page;

        currentItem = item;

    }

 

    /// <summary>

    /// Return the navigator links in an unordered list.

    /// </summary>

    public Control GetNavigatorList()

    {

        string fileName = "navigatorLinks.xml";

        StringBuilder navigator = new StringBuilder("<div class=\"navigatorContainer\"><ul class=\"navigatorList\">");

        string itemTemplate = "<li class=\"navigatorListItem\"><a class=\"navigatorListItemLink\" href=\"{0}\">{1}</a></li>";

 

        try

        {

            string fullPath = HttpContext.Current.Server.MapPath(SiteConfig.GetSiteConfig().ContentDir + fileName);

            if (File.Exists(fullPath))

            {

                NavigatorXml nav;

                using (Stream s = File.OpenRead(fullPath))

                {

                    XmlSerializer ser = new XmlSerializer(typeof(NavigatorXml));

                    nav = (NavigatorXml)ser.Deserialize(s);

                }

 

                foreach (NavigatorItem navitem in nav.Items)

                    navigator.Append(String.Format(itemTemplate, navitem.Url, navitem.Name));

            }

            else

            {

                NavigationRoot nav;

                fullPath = HttpContext.Current.Server.MapPath("~/SiteConfig/" + fileName);

                if (File.Exists(fullPath))

                {

                    using (Stream s = File.OpenRead(fullPath))

                    {

                        XmlSerializer ser = new XmlSerializer(typeof(NavigationRoot));

                        nav = (NavigationRoot)ser.Deserialize(s);

                    }

 

                    foreach (NavigationLink navitem in nav.Items)

                        navigator.Append(String.Format(itemTemplate, navitem.Url, navitem.Name));

                }

                else

                {

                    return new LiteralControl("Add '" + fileName + "' to your SiteConfig directory<br />");

                }

            }

        }

        catch (Exception exc)

        {

            ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, exc);

            return new LiteralControl("There was an error processing '" + fileName + "'<br />");

        }

 

        navigator.Append("</ul></div>");

 

        return new LiteralControl(navigator.ToString());

    }

}

Be the first to rate this post

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

Tags:

Design / Technique | Tools / Services

Designing .NET Class Libraries Video

by Administrator 25. May 2007 13:54

Krzysztof Cwalina is a Program Manager on the Microsoft .Net Framework team and one of the principal architects of the base class library.  Along with Brad Adams, he wrote the Framework Design Guidelines, which is available on MSDN or in hardcover.  The hardcover includes in-line comments from several other framework developers, which provide background on the reasoning and internal debates that occurred around various guidelines.  If you haven't read it, I highly recommend it.

If you're more of a "wait for the movie" type of person, you're in luck!  Krzysztof recently gave a Designing .Net Class Libraries presentation to Microsoft Research, which was recorded and is available online.  It is a three hour presentation, so you might want to bring sodas and popcorn.  From Microsoft:

This class presents best practices for designing frameworks that are reusable object-oriented libraries. The guidelines are applicable to frameworks ranging in size and in their scale of reuse from large system frameworks to small components shared among several applications. They started as a small set of naming and design conventions, but have been enhanced, scrutinized, and refined to a point where they are generally considered the canonical way to design frameworks at Microsoft. They carry the experience and cumulative wisdom of thousands of developer hours, over three versions of the .NET Framework.

[Update: 10/15/07]  The video is now available for download for offline viewing.

Be the first to rate this post

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

Tags: ,

Design / Technique | References / Resources

No Referer Header in Unsecured Situations

by Administrator 27. March 2007 15:39

Discovered this today when trying to link from a secure page on an ecommerce site to an un-secure file on a media streaming site that pseudo-authenticated the request by validating the referrer header.  From Microsoft:

Internet Explorer Does Not Send Referer Header in Unsecured Situations

SUMMARY
When linking from one document to another in Internet Explorer 4.0 and later, the HTTP Referer header will not be sent when the referer is a non-HTTP (or non-HTTPS) page. The Referer header will also not be sent when linking from an HTTPS page to a non-HTTPS page.

MORE INFORMATION
The Referer header is a standard HTTP header in the form of "Referer: <URL>," which indicates to a Web server the URL of the page that contained the hyperlink to the currently requested URL. When a user clicks on a link on "http://example.microsoft.com/default.htm" to "http://example.microsoft.com/test.htm," the theoretical example.microsoft.com Web server will be sent a referer header of the form "http://example.microsoft.com".

However, Internet Explorer will not send the Referer header in situations that may result in secure data being sent accidentally to unsecured sites. For example, Internet Explorer will not send the Referer header for each of the following example hyperlinks from one document URL to another document URL:
javascript:somejavascriptcode --> http://example.microsoft.com
file://c:\alocalhtmlfile.htm  --> http://example.microsoft.com
https://example.microsoft.com --> http://www.microsoft.com
     
This prevents local file names from being sent inadvertently to Web servers when linking from local content to Web sites that might snoop on such information. Also, many secure (HTTPS) Web servers store secure information such as credit-card data in the URL during a GET request to a CGI or ISAPI server application. This information can be unwittingly sent in the Referer header when linking out of an "https://" server to an "http://" server elsewhere on the Web. Internet Explorer attempts to prevent this bad practice by not sending the Referer header when transitioning from an HTTPS URL to a non-HTTPS URL.

Be the first to rate this post

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

Tags: , ,

Design / Technique

High Performance Web Sites

by Administrator 27. March 2007 14:23

I recently upgraded my Safari subscription to the "all you can eat" option.  One of the benefits is access to "rough cuts" - books that are still in development, but already have substantial content.  One such book that I've been browsing is High Performance Web Sites, by Steve Souders - Yahoo!'s "Chief Performance Yahoo!".  He offers 14 rules that "have been tested on some of the most popular sites on the Internet and have successfully reduced the response times of those pages by 25-50%". 

Rule 1 - Minimize HTTP Requests
Rule 2 - Use Edge Computing
Rule 3 - Add an Expires Header
Rule 4 - Gzip Components
Rule 5 - Move Stylesheets to the Top
Rule 6 - Move Scripts to the Bottom
Rule 7 - Avoid CSS Expressions
Rule 8 - Inline in Home Pages
Rule 9 - Minimize Domains
Rule 10 - Minify JavaScript
Rule 11 - Avoid Redirects
Rule 12 - Remove Duplicate Scripts
Rule 13 - Turn off ETags
Rule 14 - Make AJAX Cacheable and Small

A more appropriate title might be "High Performance Web Pages", as these are predominately page-level optimizations.  That is the title of the book's companion web site, wich has before/after examples of each of the rules.  This site is worth checking out, even if you don't have the book or a Safari subscription.

Be the first to rate this post

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

Tags: , , , , ,

Design / Technique | References / Resources

SQL Service Broker Poison Messages

by Troy Sabin 26. March 2007 19:02

My client's global ecommerce site fronts an ERP system, which does the actual order processing and fulfillment.  We had a requirement to implement a "near real-time" integration solution to allow the web site to continue to accept orders when the ERP system is down for maintenance.  To this end, we decided to leverage SQL Server 2005's new Service Broker technology to queue transactions.  It is a true message queuing system within a database - first in/first out, guaranteed delivery, etc.  The web site pushes orders into a queue and a separate windows service pops them out and passes them to the ERP system through a set of web services.

All good so far.  Since we had no need for distributed message delivery, an in-database queue was ideal.  It is more efficient and reliable than a home-grown table-based solution.  And it is more efficient and performant than an external MSMQ-type solution.  Then we discovered this:

Poison Messages

A poison message is a message that can never be processed correctly. A simple example is an order header with an order number that already exists in the database. When you try to insert the header into the database, the insert will fail with a unique constraint violation, the transaction will roll back, and the message will be back on the queue. No matter how many times you try, the insert will fail, so that the service will go into a loop processing the same message over and over. This will cause the order entry to hang and can severely affect database performance. To keep a poison message from bringing your server to its knees, Service Broker will disable the queue if there are five rollbacks in a row. This allows the rest of the server to continue, but the order-entry application is dead, because the queue is disabled.

Okay, that makes a lot of sense - the keep a message from bringing your server to its knees part.  However, why they decided to kill the entire queue instead of quarantining the poison message has me baffled.  That seems a bit extreme.  [Insert clever analogy here.]  In our case, if the queue is disabled the web site will not be able to accept new orders.  Thus, our "near real-time" integration model is kaput. 

The good news is we discovered this in test and can work around it.  The message can be received on a separate transaction from other SQL operations and, if necessary, the message can be explicitly added back to the order queue for later processing or quarantined in a trouble queue for human intervention - depending on the nature of the web service errors. 

This feature should really be advertised so people can take advantage of it before it brings down their system!

Roger Wolter gives it some promotion in his MSDN article: Architecting Service Broker Applications

Be the first to rate this post

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

Tags: , ,

Design / Technique

Debugging Asp.Net with SSL

by Administrator 19. March 2007 14:17

I just read James McCaffrey's MSDN article on Test Automation for ASP.NET Web Apps with SSL.  Aside from the test automation advice, he describes a useful trick for running/debugging a secure web site locally with a temporary/test certificate - without getting the usual security alerts.  From James:

Setting up a Test SSL Server

Until recently, it was quite a chore to set up a test Web server with SSL enabled. You can purchase a "real" SSL certificate from one of several providers, but that takes time and money. Another option is to generate a self-signed SSL certificate using the makecert.exe utility that is part of the .NET Framework Tools, then install it onto your Web server. But now there is a much simpler way.

The IIS 6.0 Resource Kit (available for download from Windows Deployment and Resource Kits) contains several valuable tools including one—selfssl.exe—which makes it very easy to create and install a self-signed SSL certificate for testing purposes. The screenshot in Figure 4 shows exactly how I did this.

The key is to use the /T switch so that the local browser will trust the certificate and also to use the /N switch to specify "localhost" as the Common name. Amazingly, this is all you need to test with HTTPS directly on the Web server. If you want to test HTTP with SSL from a remote client machine, the first time you manually browse to the test server you will get a Security Alert dialog asking if you want to proceed. If you click on the View Certificate button, then click on the Install Certificate button, you will enter a wizard. If you accept all the defaults in the wizard, then after you finish installing the certificate the client will be able to access the test server without the warning dialog and your test automation will run from the client.

Although the selfssl.exe tool is part of the IIS 6.0 Resource Kit and does not explicitly support earlier versions of IIS, my colleagues and I have successfully experimented with it on IIS 5.0. I have also used the makecert.exe tool to generate a self-signed x.509 certificate that can be used for testing. The MSDN Library has instructions for the makecert.exe tool at Certificate Creation Tool, but using the selfssl.exe tool is easier.

After you are finished testing with your self-signed SSL certificate you will want to remove it to prevent possible interaction effects on your test server. The easiest way to remove the certificate is by using the Microsoft Management Console (MMC). Launch MMC and add the Certificates snap-in for a Computer Account to manage the Local Computer. Now you should expand the Certificates store and then expand the Personal folder. After selecting the Certificates folder, your self-signed certificate will be displayed and you can delete it.

Be the first to rate this post

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

Tags: , , ,

Design / Technique

Localized Configuration Files

by Administrator 15. March 2007 11:23

.Net 2.0 makes it easy to create and use strongly typed custom configuration sections.  While working on a client's global/localized site, I had a need for country/locale-specific configuration settings.  The client must be able to add/change/delete these settings without restarting the web app.  Since updating web.config will cause a reset, we decided to use separate files for each locale.  The files have the same structure as the web.config (just the custom sections), so I wanted to leverage the existing configuration section handlers and get all the strongly-typed goodness.  So after some digging, I found that I could use ConfigurationManager.OpenMappedExeConfiguration.  We created a generic LocalConfigurationManager<T> class with a static GetSection method that takes a file path and section name and returns the desired section handler.  A simplified version is below:

public static T GetSection(string configPath, string sectionName)
{
   ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
   fileMap.ExeConfigFilename = configPath;
   Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
   return config.GetSection(sectionName) as T;
}

To use it:

SomeSectionHandler section = LocalConfigurationManager<SomeSectionHandler>.GetSection(someFile, someSection);

The config file must adhere to the same rules and structure of a standard app/web.config files, including the definition of the section handler within the configSections element.  So a minimal structure will look something like this.

<configuration>
   <
configSections>
      <
section name="customSection" type="Namespace.SomeSectionHandler, SomeAssembly" />
   </
configSections
   <
customSection>
      <
customSetting ... />
   </customSection>
</
configuration>

Be the first to rate this post

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

Tags: ,

Design / Technique

ASP.Net Caching Strategies for Localization

by Administrator 13. March 2007 10:31

One of my clients is presently in the performance testing/tuning phase for their site, which supports 10 countries with localized content.  Localized sites require a bit more work to enable ASP.net caching.  In the declarative code you must set the VaryByCustom attribute of @Outputcache to a meaningful value.  This value is arbitrary, but should be something logical like 'uiCulture'.  Then, override HttpApplication.GetVaryByCustomString to return the current UI culture string when the 'custom' parameter value matches the value you specified in the VaryByCustom attribute.

Michele Leroux Bustamante has an article on the TheServerSide with some good tips on ASP.Net localization, in general.  It includes a "Caching Strategies for Localization" section with sample code for the above techniques.

Be the first to rate this post

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

Tags: , , , ,

Design / Technique | References / Resources