When ScriptResource.axd Suddenly 404′s
Posted on | March 31, 2011 | 11 Comments
This is the bad dream for any ASP.NET programmer: In a single day, suddenly, all the sites stop working.
Together.
With no apparent reason.
Even sites you didn’t touch for a few months.
It happened to me a week ago, when I went to a short skiing vacation.
Before leaving I’ve checked all my currently maintained sites, and everything was fine.
I’m coming back, and suddenly all sites have the same problem: UpdatePanels don’t work.
A further investigation shows that not only UpdatePanels don’t work – nothing in the ASP.NET AJAX Toolkit works.
Opening firebug I see “ASP.NET Ajax client-side framework failed to load” error message, and multiple “Sys is not defined” errors.
Some more investigation shows: /ScriptResource.axd returns “404 Page Not Found”.
This post is exactly about this problem: it can happen for many reasons, and each reason has its own fix.
While looking for a way to fix my problem, I believe I’ve tried most, if not all of the fixes for such a bug, and hopefully, once you encounter a 404′d ScriptResource.axd, this post will help you fix yours.
If there’s any cause I have not mentioned here, please let me know of it in the comments, and I’ll add it.
Possible Cause No. 1: a Badly Configured Redirection/Rewrite Module
This happens quite a lot in large sites that use URL rewriting or redirecting techniques.
For some reason the redirection module decides to redirect *.axd “virtual” files to somewhere else, somewhere that usually does not exists, and therefore returns “404 Not Found”.
Checking for this issue is pretty easy: Try going to /WebResource.axd.
Just make sure you don’t simply go to www.yourdomain.com/WebResource.axd, but rather find a link to it in your site’s source and copy all request parameters too.
If it works, your redirection probably works fine.
If it does not, it would be a good idea to try debugging your Redirection Module and seeing what it does with your *.axd files.
Note: there are some more reasons why both ScriptResource.axd and WebResource.axd won’t work, but usually it’s a redirection issue.
Possible Cause No. 2: Missing ScriptResourceHandler in Web.Config
This can happen sometimes when you edit your Web.Config file, and accidentally delete a line or two.
Many websites and forums I’ve read suggested creating a new ASP.NET web site and copying their Web.Config to your page as a fix for this bug.
Actually, that’s a total overkill, and a very bad idea, as your Web.Config probably has some more customizations that will be overridden. This can totally fuck up your site.
A saner fix is really simple: open your Web.Config file, and make sure you have the next line under system.web/httpHandlers:
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false" />Possible Cause No. 3: Misconfigured IIS
This one is pretty easy to diagnose too:
Open the IIS Manager on your server, click “Modules”, and make sure you have “ScriptModule-4.0″(Or whatever it’s called under .NET 3.5 in case you did not upgrade yet) in there.
If it’s not there – click “Add Managed Module”, and fill in:
Name: ScriptModule-4.0
In the “Type” drop down locate and select:
System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
Or something similar(Depends on your installed .NET Framework and ASP.NET version).
In case it’s not there, go to “Possible Cause No. 4″.
Possible Cause No. 4: Misinstalled/Broken .NET Framework/IIS
This sometimes happens too – something got fucked up in your server configuration and broke your .NET framework or IIS.
Just uninstall .NET Framework 4 and/or .NET Framework 3.5 SP1, and reinstall them anew.
Reinstalling IIS could be an idea too, but remember it can break some of your configuration, so I’d resort to it only if nothing else helps, and even then, take down notes on how each and every site of yours was configured and back up any SSL certificates, to make sure you reconfigure them correctly.
Possible Cause No. 5: Rewind Your Fucking Watch
And here comes the reason why all my sites broke down: after reinstalling IIS, after tearing all my hair out, when I’ve already backed up everything, preparing to reinstall my whole system, I’ve noticed something new:
Instead of returning 404′s ScriptResource.axd suddenly returned a “500 Internal Server Error” status code.
Dunno what triggered the change, probably the reinstallation of IIS or .NET Framework, but this have helped quite a lot – I could see some error message.
And error message was: “DateTime.UtcNow is not configured”.
I don’t remember the exact error message, but can’t (and seriously don’t want to) replicate the error, and back at the time I was more worried over why the sites don’t work rather than on what shall I post on my blog.
Anyway, I’ve checked the server’s windows clock, saw that it’s off by one hour.
Moved it back to normal, and violla! Everything works.
Seriously, Microsoft! WTF?!
Visual Studio 2010 is eating your Hard Disk space with IntelliTrace
Posted on | March 12, 2011 | 2 Comments
Here’s a quick post that might be helpful for some of my readers.
Recently, I’ve noticed that my C: hard drive free space is slowly dwindling, although it’s a system-only partition, that beside programs that require to be installed on the system partition, I hardly ever put anything in it.
Using a nice tool called WinDirStat(that you can download 100% free from http://windirstat.info/r), I’ve noticed a very interesting thing:
C:\ProgramData\Microsoft Visual Studio\10.0\TraceDebugging\ was taking a whooping 18.5GB of hard disk space!
Looking inside I’ve found a year-worth of IntelliTrace logs. Some of these logs reached 250MBs for a single log. Others were smaller, be there was a hell lot of them. To be precise, there was a log for every time I’ve clicked the “Debug” button in Visual Studio 2010, and considering I’m spending most of my day in Visual Studio, that’s a lot!
So, what I suggest you to do first, is go to that folder (C:\ProgramData\Microsoft Visual Studio\10.0\TraceDebugging\ by default), and delete everything you can find there, that alone will free a few Gigs at least.
Next, fire up Visual Studio and go to Tools > Options > IntelliTrace and disable it!
Turn it back on only when you are really going to use IntelliTrace for debugging your code. For most programmers this is going to be never.
Now please don’t mistake this article for me saying that IntelliTrace is useless – this is far from the truth. IntelliTrace have saved my ass countless times when trying to Debug ambiguous code.
However, it would also be a lie to say that there are many people who are using it on a daily basis.
Scope of Entity Framework Object Context in ASP.NET Websites
Posted on | February 28, 2011 | 12 Comments
Today I’d like to talk about something that have been on my mind for some time, and is tended to be presented in a really wrong way on many web sites, and what’s even more tragic, in many ASP.NET Programming books.
What I’m talking about is the scope of your Entity Framework Context on ASP.NET Websites.
In other words, I’m referring to how long should an Entity Framework ObjectContext exist, when should it be created, and when destroyed.
To answer these questions, we have two main concerns:
- Keep Context as small as possible – we don’t want to download the whole database into our memory.
- Make sure we don’t have two related entities come from different contexts.
Bad solution number one: the “using” paradigm
One of the worst solutions I’ve ever seen, which is unfortunately the most common one, is the “using” paradigm, I’m sure you’ve all seen it:
public void Whatever() { using(var context = new BlablaEntities()) { // ... Whatever logic goes here } }
Yes, this does answer our first concern – the object context is kept to a minimum size, as its scope is the scope of our function, no more, no less. But just you try to pass or return an entity to another function, and you are lost.
Who knows what other entities will that function use, and where are they coming from?
What’s worse is a problem I like to call as the “lost object context”.
Let us say you have function A that loads an entity from the Database.
Than it passes it to function B, which passes it function C, which passes it to function D.
Function D is the function that saves our entity back to the database after B and C manipulated it.
How will function D know to which ObjectContext is our entity attached?
So now you have two options: pass the ObjectContext throughout all functions, and make sure it never gets lost.
Or, you can detach your entity at function A, and re-attach it at function D.
First option is problematic, because this brings you into a position where each entity must always be passed together with its context – something that makes your code really cumbersome.
Second option is even worse, as once you detach your entity, you can no longer access any entities it relates to.
Bad solution number two: Context per Session
This solution is far less common, but I have seen it from time to time, so I guess I should address it too.
It’s usually implemented by programmers that have understood why solution one is bad, but have not put enough thought (or reading) into finding a good alternative.
protected void Session_Start(object sender, EventArgs e) { Session["Context"] = new SalKniyotEntities(); }
This brings quite a few problems:
First, you create a context for each session, even for session that might not need an object context whatsoever, which is quite a waste.
But what is worse – Sessions tend to last long before they expire, and are all kept on your server’s memory.
Now, let us say you have a hundred unique visitors simultaneously.
This means you are going to keep a hundred ObjectContexts in your memory constantly.
Also, those hundred visitors are each viewing large portions of your website, resulting in you keeping a hundred copies of your whole database in your memory – bad idea!
Good solution: Context per Request, on demand
Well, I guess I bored you enough with my bad solutions, so it’s time to give a good answer:
You create one ObjectContext per request, and store it in a place where any page and method will be able to access: the HttpContext.Items dictionary.
This a dictionary that is unique per request, and lives only while this request is processed – a.k.a. no more than a few seconds.
This way, your context usually won’t grow too much in size, and yet, all entities are attached to the same ObjectContext.
Our context will be created only once it is needed, therefore, requests that don’t access the database, will never create an ObjectContext in the first place.
Only thing you’ll have to be careful about – don’t store entities in the Session, or you will face mixed contexts yet again.
But that is a good practice any way – never store any large objects in your Sessions, store their IDs instead, and load them from DB in case there’s a need.
In the long run, and when you have many active Sessions, this will prove to be efficient.
So, what’s the easiest way to create one Entity Framework ObjectContext?
If you’ve been reading my other posts, you’ll probably know, that my answer to any question would be – extension functions!
So, go forth and create a static class “HttpContextExtensions”.
public static class HttpContextExtensions { public static BlablaEntities GetObjectContext(this HttpContext httpContext) { if (httpContext.Items["context"] == null) httpContext.Items.Add("context", new BlablaEntities()); return (BlablaEntities)httpContext.Items["context"]; } }
This class has a single method: GetObjectContext which extends the HttpContext class.
This function checks if there’s any ObjectContext already stored in your request, and if not, creates one.
Now, whenever you need an object context in your page, simply write:
var context = Context.GetObjectContext();
And you’ll either get the already existing context, or a context will be created and given to you.
Note: when accessing the context not within you pages (such as in static context, or within HttpModules), you can still obtain a reference to your object context by calling
var context = HttpContext.Current.GetObjectContext();
Got any thoughts about this method?
Please let me know in the comments.
Tutorial: DataBinding from Entity Framework to a WPF DataGrid
Posted on | February 10, 2011 | 10 Comments
Let us say that you are an experienced .NET WinForms programmer, you have written a hundred forms that have a stupid DataGrid, you have bound countless data models to these grids, and frankly, although you know how to do it very well, you are sick of it all, and hope you’ll never see a single DataGrid ever again.
And then your boss comes in and tells you he had a chat with a friend, and that friend told him that WPF is the word in our days.
And now you’ve got to convert the whole application to WPF! What a bummer!
Every first encounter with WPF for a WinForms programmer is traumatic, as it’s a totally different world, and anything you knew till now is invalid.
What’s even worse – there’s no good documentation.
Of course, there are books, but nobody reads books in our time, we just want to go to Google, copy paste some code, and be done with it, don’t we?
Even MSDN is not very clear on how to do pretty basic things.
What usually scares newbie WPF programmers is the fact that you have no ability to access the Grid’s rows directly, you have no option to see when rows are added or deleted, and generally speaking – you can’t control anything.
However, once you are done reading this article, you’ll not only understand how easy it is to bind data to a WPF DataGrid, but you’ll also be amazed how elegant it is.
Anyway, let’s jump into business.
You’ve got a Data Model you’ve got through Entity Framework, and all you have to do is bind it to that stupid WPF DataGrid, make it editable, make it deletable, and make it possible to add new Entities.
For simplicity let’s define our model like this(I’ve removed all the Entity Framework metadata to make the thing more readable):
class Car { int ID { get; set; } string ModelName{ get; set; } int MakeYear { get; set; } int CarMakerID { get; set; } CarMaker CarMaker { get; set; } } class CarMaker { int ID { get; set; } string Name { get; set; } }
First, let’s define our DataGrid to contain only the flat info about our cars (ID,Model,MakeYear), and make the CarMaker name readonly.
Don’t worry we are going to let our user pick the CarMaker soon enough.
<DataGrid AutoGenerateColumns="False" Name="carsGrid"> <DataGrid.Columns> <DataGridTextColumn Binding="{Binding Path=ID}" Header="ID" IsReadOnly="True" /> <DataGridTextColumn Binding="{Binding Path=CarMaker.Name}" Header="Car Maker" IsReadOnly="True" /> <DataGridTextColumn Binding="{Binding Path=ModelName}" Header="ModelName" /> <DataGridTextColumn Binding="{Binding Path=MakeYear}" Header="Make Year" /> </DataGrid.Columns> </DataGrid>
A couple of things you should notice:
• The “Binding” Attribute: this is where you bind columns to properties.
It could be either a flat property such as ModelName and MakeYear, or a complex mapping such as CarMaker.Name.
• We did not mark in any way that MakeYear is a numerical value, but WPF will take care of all that by itself.
If the user tries to submit non-numeric characters there, the cell will be marked red, and data will not be saved.
Now for the DataBinding itself, we do not bind the data directly, but rather use an ObeservableCollection, you’ll see why in a second.
private void BindData() { var dataSource = new ObservableCollection<YouDataType>(context.Car); dataSource.CollectionChanged += CollectionChanged; carsGrid.ItemsSource = dataSource; carsGrid.DataContext = dataSource; }
And here’s why:
private void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) foreach (Car car in e.NewItems) context.AddToCar(car); else if (e.Action == NotifyCollectionChangedAction.Remove) foreach (Car car in e.OldItems) context.DeleteObject(car); }
This is standard code for collection change, and the only thing you ever gonna change in it are the names of the entities you want to bind to your DataGrid.
It will collect all changes ever made to your entities.
Now, to commit everything back to the database, all you have to do is add a “Save” button, and give it a very simple handler:
private void saveButton_Click(object sender, RoutedEventArgs e) { context.SaveChanges(); BindData(); }
That’s it!
The DataGrid itself takes care of assigning the values as they are changed by the user. So all you have to do is just save the changes, and rebind the grid as new IDs are assigned.
Only thing we have left to do now is let our user pick CarMakers off a drop-down list.
If we were writing a WinForms application, it would have been a huge pain in the ass. Luckily, in WPF we have DataGridComboBoxColumn, which makes this job as simple as writing HelloWorld!
All you’ve got to do is create a static property to your form that will return a list of available car makers:
public static List<CarMaker> CarMakers { get { if (System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv") return new List<CarMaker>(); return context.CarMaker.ToList(); } }
Noticed the weird “if” statement?
It is needed to make sure we are not in Designer Mode.
Without it, whenever you try to open your form in Designer Mode, it will throw exceptions as it has no DataContext to load the data from.
Once we have this, replace the “ReadOnly” CarMaker column with:
<DataGridComboBoxColumn Header="Car Maker" ItemsSource="{x:Static my:MyForm.CarMakers}" SelectedValueBinding="{Binding Path=CarMakerID}" DisplayMemberPath="Name" SelectedValuePath="ID" />Other than the ItemsSource attribute, everything is quite self-explanatory.
The ItemsSource attribute binds to our static property we have just created, so all you have to do is replace “MyForm.CarMakers” with your form and property name.
There you go!
Now you can bind any Entity Framework data you wish to your WPF DataGrid and then commit it back whenever the users wishes to save his work!
Regular Expressions in Entity Framework
Posted on | January 31, 2011 | 2 Comments
No matter what school of programmers you belong to, I’m pretty sure you’ll agree with me – Regular Expressions are awesome. You can do very complex input validation with them. You can do intricate searches with a single line of code. A few extra-badass programmers even managed flying to the moon through Regexes only.
So why the hell can’t you use them in your queries?
A search in Google for “Entity Framework Regex” or “Entity Framework Regular Expressions” brings no luck, but I still want to use Regexes in my Entity-to-SQL queries.
Even worse, if you came from MySQL background, like me, and are sure that you’ll be able to use the very convenient REGEXP function, you are in for a huge disappointment – there is none like that in SQL Server.
So, how do we query our nice database with those magical Regular Expressions?
First of all, we’ll need to introduce Regex support to our SQL Server, this would of course be done through CLR Functions.
If you are unsure on how to create those, check out this nice tutorial Microsoft so generously gave us: http://msdn.microsoft.com/en-us/library/ms131052.aspx
The code for the function is pretty straightforward:
using System.Data.SqlTypes; using System.Text.RegularExpressions; using Microsoft.SqlServer.Server; namespace DatabaseFunctions { public class UserDefinedFunctions { public static readonly RegexOptions Options = RegexOptions.Multiline; [SqlFunction] public static SqlBoolean RegexMatch( SqlString input, SqlString pattern) { var regex = new Regex(pattern.Value, Options); return regex.IsMatch(input.Value); } }; }
Deploy the function on your SQL Server, and now you can do stuff like this:
SELECT * FROM dbo.Item WHERE dbo.RegexMatch([Name],'Windows .* Home Edition') = 1
This is all nice and fun, but being able to run queries with regexes is only half job done, we still want to use this function in our Linq to entities queries.
So, first, don’t forget to update your DataModel with the new function, and then you’ll have to map it.
Unfortunately, unlike with Stored Procedures, Entity Framework doesn’t have any inbuilt mechanism to generate this code for you, so you’ll have to do this on your own.
I’d suggest doing so outside the Model’s .designer.cs file, as it might be overridden once you re-generate the model.
What I prefer doing is creating an extension method (In case you are not familiar with the concept, I suggest you read this article: http://msdn.microsoft.com/en-us/library/bb383977.aspx ).
The code for the mapping function would be:
public static class Extensions { [EdmFunction("MyModel.Store", "RegexMatch")] public static bool RegexMatch(this string input, string pattern) { throw new NotSupportedException("Direct calls are not supported."); } }
Note the “EdmFunction” attribute on the function: this is where the magic happens, the body of the function just throws an exception, as it will never be called directly.
Why does Microsoft force us to write this ugly code? I don’t know, but it’s the only way to make it work.
Anyway, the EdmFunction attribute takes two parameters:
• NamespaceName – which should always be in the format [Your model's name].Store
• FunctionName – which is quite self-explanatory
Once you have done that, the road is clear to write Queries such as the next one:
var item = (from i in context.Item where i.Name.RegexMatch("Windows (.*) Home Edition") select i).ToList();
Congratulations! Now you can write LINQ2Entity queries that search for Regex patterns!