How To Fix Archives - Page 3 of 12 - Digital Tool Factory blog How To Fix Archives - Page 3 of 12 - Digital Tool Factory blog

The Digital Tool Factory Blog

Linq projection with the extension method syntax

I’ve looked this up an embarrassing number of times – here is how you do linq projection with the extension method syntax

List<TypeClassification> typeClassifications = ctx.Classes.Select(e => new TypeClassification() {Name = e.Name, TypeClassificationID = e.ClassificationID}).ToList();

Hopefully I shall remember.  I’m not sure why I can’t remember the exact syntax.


18
Apr 14


Written By Steve French

 

How to set mime types, aka Content Types with Windows Azure Storage

The Problem

I recently came across the conundrum of files not being availble for download after I uploaded them to Windows Azure Storage.

The Cause

Usually the problem is an incorrect mime type, but since Azure does not have mime types I had to do some more digging.

The Solution

It turns out there is a property called “ContentType” that must be set on the Azure Storage Blob programatically – here is an example

CloudBlockBlob blockBlob = container.GetBlockBlobReference(filename);

if (GetFileExtension(filename).ToUpper() == “.SWF”)
{
blockBlob.Properties.ContentType = “application/x-shockwave-flash”;
}
else if (GetFileExtension(filename).ToUpper() == “.MP4”)
{
blockBlob.Properties.ContentType = “video/mp4”;
}
blockBlob.SetProperties();

Once I did that everything worked as intended.


01
Aug 13


Written By Steve French

 

How to fix problems in adding ssl certs on Windows Azure Websites

For some reason, most likely because you never do it more than once a year, adding ssl certificates to a server is poorly documented and unnecessarily complicated.  Here are some things I learned recently about adding ssl certs on Windows Azure Websites.

I recently added a cert to this site, https://digitaltoolfactory.net which is hosted on Windows Azure Websites.  It looks simple enough, just upload a file, sure it’s a .pfx file, but those are avilable aren’t they?

Off I go to NameCheap.com, plunk down my $10 and get a GeoTrust Rapid SSL Certificate.  Then you have to generate a CSR – from there just go to your IIS manager and

  1. Click on “Create Certificate Request” (Common Name is the domain name btw)
  2. Do Everything it asks
  3. You will then plug that into your SSL Provider, they will then email (of all things) you back a long code
  4. Go Back to your IIS Manager and click on “Complete Certificate Request”
  5. You will then have a file – this is not the file you use
  6. From there click on the server certificate, and then click “Export”
  7. That will generate the .pfx file
  8. From there you can upload the file to Azure
  9. You then have assign the bindings to that certificate
  10. Restart the site in the Azure Manager

That’s it!

There are a few caveats.

The big one is that if you have any errors in this process Azure will not tell you – instead all you will get is the big scary “This site claims to be DigitalToolFactory.net, but the actual certificate is for *.WindowsAzureWebsites.net”.

The other caveat is that Microsoft is charging $9.00 per month to host a site site with Secure Socket Layer bindings, which is ridiculous.   By my estimation it costs more to host the cert than to host the actual site, which makes it unique in all web hosting.  Why they do this I don’t know.  I’m glad to have the option, but the amount seems ridiculous – hopefully that fee will drop soon.


26
Jul 13


Written By Steve French

 

How to explain caching to clients

'Translator' photo (c) 2010, Mace Ojala - license: http://creativecommons.org/licenses/by-sa/2.0/I recently implemented a quick performance fix on a client’s site recently by implementing caching.  I explain caching with the following metaphor.

Imagine that your site is a book.  A book written in a weird mix of Latin, Sanskrit and Old Norse.    It’s precise,  complicated and requires translation into English by an expert translator before it can be read by the public.

Your web server translates the book.  Anytime, someone tries to read the book they cannot read it directly; they need someone (the web server) to translate the book.  This can take a lot of time and energy for the translator to do, but it has to be done.

 

A simple version of the process

To clarify, the process works like this

  1. Person makes a request, i.e. “what does that book say? [Non Resource Intensive Step]
  2. The translator looks at the book, and makes a careful translation into modern day English of the book from the original Latin, Sanskrit, and Old Norse.    This can take a long time [Resource Intensive Step].
  3. After the translator completes the translation he sends it on it’s way to the person who made the request [Non Resource Intensive Step].
  4. The person who makes the request receives the translation and the interaction is complete [Non Resource Intensive Step].

That all sounds good, but the problem is that the four step process has to happen each and every time anyone makes a request, especially the resource intensive step two.  So, if a web page gets 1000 requests an hour, resource intensive step #2 runs 1000 times.

 

The first request with caching

Now imagine if the translator makes a copy of the English translation after he sends it out the first time.  The first time someone makes a request for a translation the process looks like this.

  1. Person makes a request, i.e. “what does that book say? [Non Resource Intensive Step]
  2. The translator checks to see if there are any photocopies of the translation that are less than an hour old [Non Resource Intensive Step]
  3. The translator looks at the book, and makes a careful translation into modern day English of the book from the original Latin, Sanskrit, and Old Norse.    This can take a long time. [Resource Intensive Step]
  4. After the translator completes the translation he makes photocopies of the translation. [Non Resource Intensive Step]
  5. Then the translator sends the photocopy of the translation on it’s way to the person who made the request. [Non Resource Intensive Step]
  6. The person who makes the request receives the translation and the interaction is complete. [Non Resource Intensive Step]

Subsequent requests with caching

Subsequent requests for the book look like this

  1. Person makes a request, i.e. “what does that book say? [Non Resource Intensive Step]
  2. The translator sends the photocopy of the translation on it’s way to the person who made the request. [Non Resource Intensive Step]
  3. The person who makes the request receives the translation and the interaction is complete. [Non Resource Intensive Step]

The first time someone makes a request the process runs a little slower, but since each subsequent request for the book omits all of the resource intensive steps, the whole process take up much less time and fewer resources, making for a much lower delivery time on average, e.g. for every 1000 requests for a page, resource intensive step #2 runs 1 time, not 999 times.

Making a photocopy is pretty close to caching.  The web server makes a copy of the page it just created and sends it on it’s way to web browsers.

 

What are the downsides of caching?

What are the downsides of caching, and why doesn’t everyone use it?   I’ve seen two main reasons not to use caching.

  1. The contents of the book can change unexpectedly.  If it does, then the translator is handing out old editions of the book.  That might be fine for some sites, but for others it might be catastrophic   For example, if a blog serves up a slightly out of date version of a post no one will care that much, but if a stock market application serves up old stock prices people will care a lot.  With caching, the translation/web page can be up to an hour old.
  2. It makes debugging much harder if everyone sees slightly different versions of the same thing.

That’s how I explain caching to clients.  I’ve always had people find the metaphor clear and easy to understand.


18
Mar 13


Written By Steve French

 

How to install wordpress in a subdirectory of a site with an existing .htaccess file

This happened to me whilst working on a  pre-existing site recently.

 

The Problem

You are trying to install WordPress onto a subdirectory of an existing site that uses the .htaccess files for routing.  When you try to add in the changes needed for WordPress to work you break the existing site.

The Cause

WordPress .htaccess files do not play nicely with other .htaccess files

The Solution

Simply add in the WordPress generated .htaccess files in the WordPress directory, and everything magically works.

For Unix people this must be obvious, but for me it was surprisingly brilliant.

 


13
Mar 13


Written By Steve French

 

The case of the disappearing WordPress widgets

A silly one this time

The Problem

I was recently working on someone else’s WordPress theme that made extensive use of WordPress Widgets and the new dynamic sidebar feature.  I was able to recreate the widgets (there was a working staging site) but the on the production site the widgets did not appear.  What to do about disappearing WordPress widgets?

The Cause

I had changed the name of the theme.  For some reason the register_sidebar has to have the name hard coded, for example

register_sidebar( array(
		'name' => __( 'Banner Area', 'themename' ),
		'id' => 'Banner-area',
		'description' => __( 'Banner area', 'themename' ),
		'before_widget' => ' <div>',
		'after_widget' => '</div>',
		'before_title' => '<div><h1>',
		'after_title' => '</h1></div>',
	) );

The Solution

Just change the name of the theme to the new name and you’re all set!


12
Mar 13


Written By Steve French

 

How to fix the infamous “Unable to cast object of type ‘System.Int32’ to type ‘System.String’ error in asp.net mvc

The Problem

You have created a lovely model in asp.net mvc 4, using Entity Framework and a whole host of attributes.  One of the properties of your model looks like this

[Required]
[Display(Name = “Expiration Month (MM)”)]
[StringLength(2,ErrorMessage = “You must enter two digits”, MinimumLength = 1)]
[Range(1,12, ErrorMessage = “You must enter a valid month”)]
public int ExpirationMonth { get; set; }

That yields an error of

Unable to cast object of type ‘System.Int32’ to type ‘System.String

When the form is submitted, but not when the object is created (which is a bit odd)

The Cause

It turns out that you cannot use the StringLength data attribute on an int data type.  You would think you could since all you are actually interested in with that data attribute is the number of digits, but the data gods have decreed that you can’t.

The Solution

Just comment out StringLength and use the Range Attribute.


17
Jan 13


Written By Steve French

 

How to fix problems with data cacheing in ASP.net MVC 4, SignalR and Entity Framework

The Problem

I was using the wonderful SignalR libraries to create a status window (I have a VERY long running process in my new Data Hammer project, it takes about 15 minutes to run) and I need to inform the user on where the process is at any given time.  My original code looked like this

public class Chat : Hub
{
public void Send(int id)
{

DataHammerContext ctx = new DataHammerContext();

while (true)
{

string strName=ctx.ProcessSteps.Find(id).Name;
Clients.All.addMessage(“Status: ” + strName);
Thread.Sleep(1000);
}
}
}

And this would always display the same status, quite maddening.

The Cause

After much investigation I realized that my model of how Signal R works was flawed.  For whatever reason (by which I mean too long to go into here) the data context does not update with the while loop.

The Solution

The fix is simple, just recreate the data context every time and everything works like it should – here is a sample of the updated code.

 

public class Chat : Hub
{
public void Send(int id)
{

 

while (true)
{

DataHammerContext ctx = new DataHammerContext();
string strName=ctx.ProcessSteps.Find(id).Name;
Clients.All.addMessage(“Status: ” + strName);
Thread.Sleep(1000);

}
}
}


16
Jan 13


Written By Steve French

 

How to configure wildcard routing in asp.net mvc 4

The Problem

You are trying to configure Widlcard routing (i.e. something like http://domain.com/SomeUserName/) and find it problematic.

The Cause

That is largely by design – wildcard routing is resource intensive and rarely needed.

The Solution

If you want to do it anyway, use the following routes

routes.MapRoute(“Default”, “”, new { controller = “Home”, action = “Index”, id = UrlParameter.Optional });
routes.MapRoute(“CatchAll”, “{*id}”, new { controller = “Home”, action = “Handle”, id = “” });

Things to note

 

  • The Catch-All route is AFTER the home route
  • The syntax is *id – this will ensure that the value of ID is sent to the “Handle” action
  • The purpose of this route is to throw control to the “Handle” action with the appropriate value – Handle must be set up to use that value.

 

Okay, after some more digging (and some failed integration tests) here is what you have to do

Add in the following routes

routes.MapRoute(“Handle”, “Home/Handle/{id}”, new { controller = “Home”, action = “Handle”, id = “” });
routes.MapRoute(“User”, “{*id}”, new { controller = “Home”, action = “Index”, id = “” });
routes.MapRoute(“Default”, “{controller}/{action}/{id}”, new { controller = “Home”, action = “Index”, id = UrlParameter.Optional });

And then create an action called “Handler”, and change your Index action on your home controller to look like this

public ActionResult Index(string id=””)
{
if (!string.IsNullOrWhiteSpace(id))
{
return RedirectToAction(“Handle”, new {@id = id});
}
else {
return View();
}

What does this do?  It routes all wildcard traffic to your Index controller, which then hands it off to the “Handle” Action.  You would think that you could just hand everything off to the Handle action, but if you do that, then your Index action becomes inaccessible,  and in some circumstances you get a recursive loop where the handle action is called endlessly.  That does show an interesting error screen though.

One annoying side effect of this course of action is the need to map out each and every route explicitly, otherwise the wildcard route will pick it up and hand it off to the “Handle” action, which will take it somewhere where you do not want it to go.


04
Jan 13


Written By Steve French

 

How to fix problems with entity framework decimal precision

The Problem

You are attempting to change a database column of type decimal from a precision of two decimal place to one decimal place via data annotations, and there does not seem to be a good way to do it.

The Cause

There isn’t a good way to do it.

The Solution

However, there is at least one non-elegant way to do it – in your OnModelCreating code in your data context, enter in the following piece of code

protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
modelBuilder.Entity().Property(xx=>xx.Handicap).HasPrecision(12, 1);
base.OnModelCreating(modelBuilder);

}
The “HasPrecision” part is the key – the second parameter is the number of decimal places to use


12
Dec 12


Written By Steve French

 




Copyright 2011 Digital Tool Factory. All Rights Reserved. Powered by raw technical talent. And in this case, WordPress.