Umbraco SQl to Find Nodes using a Certain Document Type

SELECT * FROM cmsContent C
INNER JOIN cmsContentType CT ON C.contentType = CT.nodeId
INNER JOIN umbracoNode N ON C.nodeId = N.id
WHERE CT.alias = ‘yourDocumentTypeAliasHere’

–use the node path to locate nodes in Umbraco

Advertisements

ASP.NET Session State IsNew – or is it?

A new session ID is generated for each request in applications that do not store data in the session dictionary.

Yes it’s amazing, but true. Logically you’d expect a new ASP.NET session object to be created when the user arrives at your site, and then expire 20 mins (or whatever you configure) after they leave, but in fact a new instance is created for each request, until (if ever) your code sticks some data into session state.

The reason for this is performance – at the end of the request life cycle any data placed in Session state is serialised and persisted using your chosen provider. If there’s no data, then ASP.NET skips the taks of maintaining the session ID and loading this again next time.

If you’re using the default InProc mode then the performance gain might be negligable, but if you’re for instance using SQL server then the job of adding an empty record to the session state tables, and reading this again (for no purpose) is very sensibly skipped.

What this does mean however is that the Session IsNew property will return true until you use Session State – so don’t use this flag to check if a user has just arrived at your site. If you need to check this you could place your own cookie to expire with the session (i.e. don’t set the cookie’s Expire property).

Key thing is – Session State might be new, but that does not mean your user’s session on the webserver is.

A new Session ID for each request (until you use session)

Caught me out twice now this – watch it with the Session.IsNewSession property – a new session ID is generated for each request in applications that do not store data in the session dictionary.
http://msdn.microsoft.com/en-us/library/aa479041.aspx

Application Timers (to replace scheduled tasks)

I do not like scheduled tasks.
They most often take the form of little bits of unversioned code (in console apps) that exist outside the main solution.
Moving these into the main application allows us to utilise the application’s logging utilities, adds versioning to the logic and configuration settings and ensures that the code is both updated and deployed along with the rest of the solution.

Below is some initial code – the idea is to have a singleton class that starts a set of timers. This can then be called from Application_Start or a similar global event.
Some improvements to the below would be to make the application timers use the provider pattern – so we can code up new timers when we need, and perhaps add a .config section to load these from.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Timers;
using System.Net;
using HobNobClubServices.Library;
 
namespace HobNobClubApps.Library
{
      /// 
      /// Singleton timer
      /// 
      public sealed class ApplicationTimers
      {
            private static readonly ApplicationTimers instance = new ApplicationTimers();
            private static bool timersInitialised = false;
 
            private ApplicationTimers() { }
 
            public static ApplicationTimers Instance
            {
                  get
                  {
                        return instance;
                  }
            }
 
            public void InitTimers()
            {
                  if (timersInitialised)
                        return;
 
                  InitHobNobInsuranceEmailAbandonedQuotesTimer();
 
                  timersInitialised = true;//Only do this once in the application:
            }
 
            private void InitHobNobInsuranceEmailAbandonedQuotesTimer()
            {                
                  Timer HobNobInsuranceEmailAbandonedQuotesTimer = new Timer();
                  int intervalInMinutes = Properties.Settings.Default.HobNobInsuranceEmailAbandonedQuotesTimerInterval;
                  HobNobInsuranceEmailAbandonedQuotesTimer.Interval = (intervalInMinutes * 60000); //Convert to millisecs
                  HobNobInsuranceEmailAbandonedQuotesTimer.Elapsed += new ElapsedEventHandler(HobNobInsuranceEmailAbandonedQuotesTimer_Elapsed);
                  HobNobInsuranceEmailAbandonedQuotesTimer.Start();
            }
 
            private void HobNobInsuranceEmailAbandonedQuotesTimer_Elapsed(object sender, ElapsedEventArgs e)
            {
                  string errorMsg = String.Empty;
                  try
                  {
                        int intervalInMinutes = Properties.Settings.Default.HobNobInsuranceEmailAbandonedQuotesTimerInterval;
                        //Set the delay in emailing people to the same as this timer interval (so if this timer runs every 30 mins, people will be emailed if they've left a quote alone for 30 mins):
                        string methodNameAndParams = String.Format("/EmailAbandonedQuickQuotes?delayInMinutes={0}", intervalInMinutes);
                        WebRequest webRequest = HttpWebRequest.Create(Properties.Settings.Default.HobNobClubApps_SLHobNobInsurance_HobNobInsurance + methodNameAndParams);
                        WebResponse webResponse = webRequest.GetResponse();                    
                  }
                  catch (Exception ex)
                  {
                        errorMsg = ex.Message;
                        ExceptionManager.LogExceptionEvent(ex, Logger.Source.HobNobInsurance);
                  }
 
                  Logger.WriteInfoLog(
                        String.Format("The HobNobInsuranceEmailAbandonedQuotesTimer ran at {0} {1}",
                                                DateTime.Now, String.IsNullOrEmpty(errorMsg) ? "with no errors (from the timer)." : "and failed with: " + errorMsg),
                              Logger.Source.HobNobInsurance);
            }
      }
}
 

Cookie Based (forms) Authentication Not Working in IE Iframe

Recently spent some time troubleshooting a 3rd party vendor being integrated into our site via an IFrame. Not really a great idea in the first place, with overflow:hidden and what have you – but the real issue came around their authentication process.
We were sending through an encrypted identifier on the iframe src querystring, which they succesfully matched to approved users on their system, however, after authenticating, the subsequent redirect would show that the user was no long logged in… so what was going on?
Turned out, after a lot of calls and testing, that this was the issue: http://stackoverflow.com/questions/389456/cookie-blocked-not-saved-in-iframe-in-internet-explorer.
Good old IE – never fails to provide useful features.

So essentially IE has a setting (thas is on, even on medium-low security) which says cookies served from a different domain than the current (in our case from within an iframe) are blocked, unless the remote server at that domain provides a “privacy policy”.

In some way this is a sensible enough approach – but unfortunately the solutions is (despite all the waffling about lawsuits in the StackOverflow post) as simple as adding this header to every response sent from the server:

'P3P: CP="NOI ADM DEV COM NAV OUR STP"'

So if you’re a reputable company, you’re likely to be in compliance with that anyway, if you’re not – then you probably haven’t got your full postal address on whois anyway… so one questions the value added from this IE safety net.
But it’s there, and it created some work hours for us.

Some .NET Debugging Tools and Tricks

Very interesting case study here http://www.wintellect.com/Consulting/Debugging of some Microsoft MVPs trying to find an error in a client’s ASP.NET application, while working off-site.
Couple of important, but lesser known debugging tools gets mentioned along the way: Sysinternals for monitoring your Windows server and .NET Reflector (which was previously Roeders Reflector until RedGate took it over) for digging through assembly code. Also Windows Server Minidump is worth knowing about.

A tool not mentioned in that article (because it’s not relevant) is the “Microsoft Intermediate Language Disassembler”, ILDASM – if you need to really take some .NET code apart.
For web application debugging the Fiddler Web Debugger is indispensable. You can get the basic functionality from here in the Firebug net tab – but Fiddler adds more debugging options, like for example the ability to change the data being posted to your web server.

Finally Visual Studio is of course the most used debugging tool for .NET developers, and there are some new debugger features in VS2010 that’s worth knowing about, like the ability to label break points, to pin the data tips to retain the value (and compare to the previous after a refresh) and even append comments to these.

Finally, finally – if you’re lucky enough to own a version of VS2010 Ultimate, you will also have access to IntelliTrace which lets you step backwards up through your code (with some limitation I believe).

Absolutely last finally – the best debugging tool is sometimes to have a cup of coffee, and then fetch one of your colleagues, or a friend or even Irene from reception – and explain to them what the code is trying to do, how it fails, what you have tried to fix it – and nine times out of ten (well six out of ten at least) somewhere along that process – between the coffee and rambling at innocent bystanders – you will probably at the very least come up with something you haven’t considered yet.

What’s New in ASP.NET 4 and .NET 4?

Seems MS are churning out new versions of everything at a pace – or is it just me? Quite often you fall into the trap of just tagging along – when I start a new website now and VS asks me – “do you want this in 3.5 or 4.0” – well I go for 4.0.
Why shouldn’t I? It’s nice to be up to date right? But of course the better question is “why should I?”

Well for the .NET framework it’s of course the case that 3.5 was built on top of the 2.0 CLR, and as such they we’re really just additions to the 2.0 framework (some people have speculated that MS were keen to speed up the advancement of their version numbers (Java EE recently made it to 6), and really 3.0 and 3.5 would have made a lot more sense as 2.1 and 2.2).
The .NET 4 framework however uses a grand spanking new CLR (with some improvements to garbage collections, and changes to allow support for functional programming ao), and a load of additional features to the framework.

Some C# changes include optional and named parameters which essentially allows you to pass only some parameters and/or in any order you like. Also we have a new keyword: dynamic. Basically this switches off type checking for parameters defined as such – so I can for example do this:

 
		public MyMethod(dynamic someObject)
		{
				someObject.DoSomethingCrazy();
		}

And the compiler will not attempt to check if someObject does indeed have a DoSomethingCrazy method. This is mainly intended for COM objects, but could also be used for reflection – and tbh could also be misused something awful.
You could start throwing dynamic objects around the place and pretty soon you’d have half of your application outside the compilers type checking – but of course why would anyone ever want to do that? (What could possibly go wrong?)
Kind of reminds me of the var keyword that was introduced in 3.0 – of course as this was just a convenience (the compiler would infer the type from the usage, and perform full type checking on compilation (if not intellisense had picked it up already)) – but it had (has) the same potential for misuse that dynamic does, imho anyway.
The var keyword was needed to support Linq – but pretty soon you saw code all over the place looking like Javascript – which did not really pose any risks – but on picking up someone elses code, the problem is that you have to start doing type inference as well – it’s not just the compiler.
When someone writes var x = GoGetMyThing(); – what do you think x is?
So you sit around hovering your mouse over stuff relying on good old Intellisense to do your job for you.
Anyways – of course as frameworks have to support more and more functionality, the potential for misuse will inevitable increase. And as someone pointed out the other day: I am of course free to programme all my projects in .NET 1.1 if it’s something I feel that strongly about.

With 4.0 we also got an update to the Visual Studio IDE – VS2010 – which besides a very neat design and a new and improved default font (Consolas) – also has some very useful new features.
A really nice feature you should def get to know is the Navigate To – use “ctrl+,” to pop this up. It basically allows you to search through everything, from file names to methods, interfaces – etc, and you can even use CamelCase or abbreviations to narrow your search.
Reference Highlighting is another one of my favourites – hover your mouse over any variable in the code window, and instances of this will be highlighted throughout the document. I’m telling ya – if MS ever removed Intellisense you’d see some stressed MS developers around.
Call hierarchy is an improvement to the “view all references” option – which allows you to see calls to and calls from any method or property. Very nifty when getting to know a new project. Also you can see all implementations of an interface (use this when you do the “go to ref” and you end up looking at the same interface every time) as well as all overrides of virtual and abstract members.
Also there is some improved support for unit testing, including the ability to stub out your code from the unit test that you of course always write before you do anything (don’t you? of course you do).

Moving swiftly along to the core of the matter (for me anyway) – ASP.NET 4.0: