sessionStorage and localStorage not working in Internet Explorer 10

November 23, 2013

I stumbled over an interesting issue when testing the web storage support in Internet Explorer 10 (localStorage and sessionStorage).

Basically, when loading an HTML document from the local drive without using a web server (file:// protocol), these features are not working in Internet Explorer 10.

When you run the following code in Internet Explorer 10:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Web storage test</title>
</head>
<body>
    <script type="text/javascript">
        if (window.sessionStorage) {
            alert("We have session storage!");
        }

        if (window.localStorage) {
            alert("We have local storage!");
        }
    </script>
</body>
</html>

It will display the alerts only when running from a web server (local or remote) using the http(s):// protocol. When trying to open the file locally without a server, window.localStorage and window.sessionStorage will be unavailable and the alerts will not show.

If you are looking for alternatives, take a look at this stackoverflow post which lists a handfull:
HTML5 Local Storage fallback solutions

Hope this helps someone stumbling upon this issue.

A quick test with current versions of Firefox and Chrome, showed that these browsers do not share this problem.

Resizing a WPF control while maintaining a specific aspect ratio

October 15, 2012

When you are developing a Windows Presentation Foundation (WPF) application you have a lot of options to layout your controls automatically. Builtin panels like the Grid, the DockPanel or the StackPanel allows for flexible layouts. There is also the Viewbox decorator control which scales it child while (optionally) preserving its aspect ratio.

The disadvantage of the Viewbox is however that it scales its content instead of resizing it. So if you put a Button inside a Viewbox you will notice that its text and the control itself will appear “zoomed in” which makes it inapt for certain applications.

For this reason I wrote my own decorator which overwrites the Measure and Arrange methods to resize its child to a specific AspectRatio that you can give it as a dependency property. After understanding how Measure and Arrange work together it was actually quite easy to develop and does not require a lot of code.

Here is a visual comparison between the Viewbox decorator and my own AspectRatioLayoutDecorator:

Comparison of ViewBox and AspectRatioLayoutDecorator

As you can see the ViewBox scales the button and makes it look really ugly, while our custom control will resize it content nicely.

The usage in WPF is quite easily. Just wrap the content you want to resize in the AspectRatioLayoutDecorator:

<my:AspectRatioLayoutDecorator AspectRatio="1.25">
   <Button>Test</Button>
</my:AspectRatioLayoutDecorator>

Of course instead of setting a fixed AspectRatio you can animate and data bind it like any other dependency property.

Here is the source code of the control:

public class AspectRatioLayoutDecorator : Decorator
{
   public static readonly DependencyProperty AspectRatioProperty =
      DependencyProperty.Register(
         "AspectRatio",
         typeof (double),
         typeof (AspectRatioLayoutDecorator),
         new FrameworkPropertyMetadata
            (
               1d,
               FrameworkPropertyMetadataOptions.AffectsMeasure
            ),
         ValidateAspectRatio);

   private static bool ValidateAspectRatio(object value)
   {
      if (!(value is double))
      {
         return false;
      }

      var aspectRatio = (double) value;
      return aspectRatio > 0
               && !double.IsInfinity(aspectRatio)
               && !double.IsNaN(aspectRatio);
   }

   public double AspectRatio
   {
      get { return (double) GetValue(AspectRatioProperty); }
      set { SetValue(AspectRatioProperty, value); }
   }

   protected override Size MeasureOverride(Size constraint)
   {
      if (Child != null)
      {
         constraint = SizeToRatio(constraint, false);
         Child.Measure(constraint);

         if(double.IsInfinity(constraint.Width)
            || double.IsInfinity(constraint.Height))
         {
            return SizeToRatio(Child.DesiredSize, true);
         }

         return constraint;
      }

      // we don't have a child, so we don't need any space
      return new Size(0, 0);
   }

   public Size SizeToRatio(Size size, bool expand)
   {
      double ratio = AspectRatio;

      double height = size.Width/ratio;
      double width = size.Height*ratio;

      if (expand)
      {
         width = Math.Max(width, size.Width);
         height = Math.Max(height, size.Height);
      }
      else
      {
         width = Math.Min(width, size.Width);
         height = Math.Min(height, size.Height);
      }

      return new Size(width, height);
   }

   protected override Size ArrangeOverride(Size arrangeSize)
   {
      if (Child != null)
      {
         var newSize = SizeToRatio(arrangeSize, false);

         double widthDelta = arrangeSize.Width - newSize.Width;
         double heightDelta = arrangeSize.Height - newSize.Height;

         double top = 0;
         double left = 0;

         if (!double.IsNaN(widthDelta)
            && !double.IsInfinity(widthDelta))
         {
            left = widthDelta/2;
         }

         if (!double.IsNaN(heightDelta)
            && !double.IsInfinity(heightDelta))
         {
            top = heightDelta/2;
         }

         var finalRect = new Rect(new Point(left, top), newSize);
         Child.Arrange(finalRect);
      }

      return arrangeSize;
   }
}

The control not only works in a Grid, but also quite nicely in a StackPanel or any other form of layout.

I hope it’s useful to someone else. If you think it’s useful for you and you want to use it in your own project it would be nice if you leave a small “thank you” in the comments, so that I know it actually helped someone.

Making Cross-Domain Calls in SignalR

March 30, 2012

I saw this stack overflow post today on how to use SignalR across domains:
http://stackoverflow.com/questions/9751157/signalr-accross-domains

Since I wanted to try out SignalR anyway I thought it would be a nice way to get started and see if I can solve the problem and write a small tutorial on how to do it.

The first step in using SignalR cross-domain is to tell it where to find the hub to connect to. This is done using the following code that you should insert at the beginning of your JavaScript code:

$.connection.hub.url = 'http://[someotherdomain]/signalr';

If you try your application like this it will not work and you will have the same problem as the poster mentioned above. This is because for security reasons many browsers don’t allow cross-domain calls by default. A server has to add the special Access-Control-Allow-Origin header to its response to tell the browser to allow cross domain calls to this specific site.

You can add this value to your ASP.NET page using:

Response.AppendHeader("Access-Control-Allow-Origin", "*");

However even with this modification SignalR won’t do the cross domain call – at least not in Internet Explorer 9 where I tested it. Like the original poster I was stuck for quite a while because I didn’t find any solutions. The error message I got was:

SignalR: Connection must be started before data can be sent. Call .start() before .send() 

Poking arround the jQuery code and debugging a bit I eventually saw that there is a check inside jQuery to see if the call is a cross domain call or not and eventually this part of the code will terminate with the error “No transport”.

With this new error message I came upon this page explaining the problem and suggesting a possible solution to force jQuery into making a cross domain call using the following JavaScript line:

jQuery.support.cors = true; //force cross-site scripting

And it worked!!!

I also found some references suggesting JSONP as a possible solution, but it seems more complex and at least for me the solution above works fine.

Creating an URL to a WebAPI ApiController inside an ASP.NET MVC View

March 27, 2012

Introduction

Today I was trying to add some dynamic content to my new IT consulting website. My website is based on ASP.NET MVC, but I needed to load some dynamic content in one part of the page and I thought I would try out the new ASP.NET WebAPI framework for this.

Problem

Creating the ApiController was easy, but when I wanted to use the controller in my ASP.NET MVC view, I wasn’t sure how to include the Url of the controller. Hardcoding the address didn’t feel right, especially because for the MVC controllers you have the really useful Url.Action method, which takes the name of an action and a controller and generates an URL to call this action. Unfortunately there wasn’t any built in method to call an ApiController. My first attempt was to use the following call instead, specifying the name of the route I want to use directly:

Url.RouteUrl("DefaultApi", new{controller="[CONTROLLERNAME]"})

Unfortunately, this didn’t work as expected — the function didn’t produce any Url.

After some googling I came across this stackoverflow post, with the missing piece of the puzzle:

Solution

Basically all you have to do is to add an empty httproute parameter to the Url.RouteUrl call. This apparently helps the system differentiate between normal routes and WebApi routes. So the final call looks like this:

Url.RouteUrl("DefaultApi", new{httproute = "", controller="[CONTROLLERNAME]"})

Keep in mind that the first parameter to RouteUrl refers to the name of the route you used in the RegisterRoutes function, which is “DefaultApi” by default.

Akzente.IT – New web site online!

March 22, 2012

My new web site at akzente.IT is online!

You will find some more information about me and my projects there.

My goals for the web page were twofold. First of all I wanted to have a nice virtual “business card” – a place where I can present myself to potential employers with a list of my skills and the projects I have done in the past.

My second goal was to use this opportunity to learn more about ASP .NET MVC (with Razor) and HTML5 and I have to say I’m very happy with the results. I think it was the first time I actually enjoyed creating a website. I have full control of the generated HTML, I didn’t have any hard to debug errors so far and the separation that MVC gives me is really cool. I’m actually using this to generate different views of my project page. I have a single controller responsible for the list of projects which delegates to different views depending on an input parameter (e.g. to generate a text only version for carreer networks) and it works quite nice. I’m thinking about extending this to automatically create a resumé in Word generating Office Open XML with a Razor view. I’m curious if this works.

Another interesting page is the blog page where I show some recent blog posts with links back to this blog. It was amazing how easy it was to build this.

public class BlogController : Controller
{
    [OutputCache(Duration = 60*60, VaryByParam = "none")]
    public ActionResult Index()
    {
        var model = new Blog();
        string feedUrl = "http://coding4life.wordpress.com/feed/";
        using (XmlReader reader = XmlReader.Create(feedUrl))
        {
            var feed = SyndicationFeed.Load(reader);
            model.Feed = feed;
        }
        return View(model);
    }
}

My favourite is the controller attribute for output caching, which will cache the generated result for 1 hour, so that it loads faster and doesn’t hit the blog to hard in case there are many visitors.

That’s all about the website for now. I also have a profile now on GULP, check it out: https://www.gulp.de/Profil/AkzenteIT.html

Generate Entity-Framework DDL-Script for SQLite

April 17, 2011

By default the Entity Framework designer for Visual Studio only generates DDL Scripts for Microsoft SQL Server (CE).

However you can change the template file (.tt) which is used to generate the SQL statements. Just click on empty space in the designer and take a look in the property sheet window.

The default template is called SSDLToSQL10.tt and resides in a subfolder of the Visual Studio program files directory.

For one of my projects I needed the generated SQL to be compatible with SQLite, so I modified the original file for SQLite and created a new version, which you can download below.

After downloading the files and putting them in the correct directories, you should be able to select them inside the EF designer.

Keep in mind that I can’t give any guarantees that this files will work as you expect. I wrote them specifically for my project and I’m just sharing them in the hopes that they are useful for anyone.

Download the following zip file: SQLiteGen.zip

You will find 2 files in the zip file:

Put the SSDLToSQLite.tt file in the directory
.\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\Entity Framework Tools\DBGen\

Put the GenerateSQL.Utility.ttinclude file in the directory
.\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\Entity Framework Tools\Templates\Includes\

You are done! Smiley Now you should be able to select the new template in the Visual Studio designer and enjoy the newly SQLite compatible SQL script.

Allowing cross-domain access from Silverlight to a standalone WCF-Service

March 12, 2011

Introduction

Silverlight by default only let’s you access services which come from the same domain as the domain that served the Silverlight control. This guards against some types of security vulnerabilities.

A service can however opt-in to allow calls from Silverlight controls hosted on other domains. To do this a service has to provide a clientaccesspolicy.xml or crossdomain.xml file, which specifies the access policy for this service.

Silverlight, when asked to do a cross-domain call, will look for this file at the root of the domain where the target service is hosted.

The following is a sample clientaccesspolicy.xml file:

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-request-headers="SOAPAction">
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>

You can also use a crossdomain.xml file, which is used by Adobe Flash, but is also recognized by Silverlight.

Standalone WCF-Services

It’s easy to provide the required file for a service hosted on web server like IIS. For a standalone WCF service however, there is no built-in functionality to achieve this.

You can however create a separate service which is responsible only for serving the required policy file and make it available at the services domain root.

The idea is copied from this forum entry (thanks Yi-Lun Luo): http://forums.silverlight.net/forums/p/21678/77494.aspx

Creating the web service class

[ServiceContract]
public class CrossDomainPolicyRetrieverService
{
    [OperationContract, WebGet(UriTemplate = "crossdomain.xml")]
    public Stream GetFlashPolicy()
    {
        return getPolicy("crossdomain.xml");
    }

    [OperationContract, WebGet(UriTemplate = "clientaccesspolicy.xml")]
    public Stream GetSilverlightPolicy()
    {
        return getPolicy("clientaccesspolicy.xml");
    }

    private static Stream getPolicy(string file)
    {
        if (!File.Exists(file))
        {
            WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
            return null;
        }

        WebOperationContext.Current.OutgoingResponse.ContentType = "application/xml";
        return File.OpenRead(file);
    }
}

This simple web service has 2 methods corresponding to the two files mentioned above. It will search for the file in the application directory and return them as the response for the file.

Configuring the service

To configure the service add the following lines to your app.config file:

<?xml version="1.0"?>
<configuration>  
  <system.serviceModel>
    <services>
      <!-- snip... regular services -->

      <service name="MyNamespace.CrossDomainPolicyRetrieverService">
        <endpoint address="" binding="webHttpBinding"
                  contract="MyNamespace.CrossDomainPolicyRetrieverService" 
                  behaviorConfiguration="policyBehavior">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        
        <host>
          <baseAddresses>
             <!-- Root Domain where the other services are hosted -->
            <add baseAddress="http://localhost:8732/"/>
          </baseAddresses>
        </host>
      </service>
    </services>
    
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="policyBehavior">
          <webHttp  />  
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>
  <!-- snip... -->
</configuration>

Testing the service

To should now be able to access the policy files using any web browser and pointing it at /clientaccesspolicy.xml (e.g. http://localhost:8732/clientaccesspolicy.xml)

By setting a breakpoint inside the service methods, you can easily watch Silverlight accessing the corresponding resource files.

Increasing the maximum item count of a feed in the Windows Feeds Engine

September 14, 2009

This post mainly serves as a reminder for myself, because after each reinstall of Windows I have to search for this all over again and it is not very easy to find.

By default the Windows Feeds Engine stores only a limited amount of items per feed (200). You can only increase this limit up to the predefined maximum of 2500.

If like me you like to preserve every blog entry made (or at least more than 2500 items per feed), you can increase this limit by creating the following registry DWORD value:

HKCU/HKLM\Software\Microsoft\Feeds\MaxItemCount

I usually set it to 0x7fffffff, which is the largest possible positive 32 bit integer you can set. Basically it means preserving every blog entry ever made for a specific blog.

image

Source: http://msdn.microsoft.com/en-us/library/ms685364(VS.85).aspx

Hello world!

July 7, 2006

Hey,

my name is Thomas Krause and I will blog some random thoughts here about C#, programming in general and some other technology related stuff. My native language is german, but my plan is to blog mainly in englisch, so just forgive me for my grammar mistakes and don’t hesistate to correct me.


Follow

Get every new post delivered to your Inbox.