CORS = XmlHttpRequest to other servers – without JSONP
As Webstep guru Thor Halvor explained in the this excellent blogpost – there are security restrictions to prevent/limit cross domain access of XMLHttpRequest’s – the cornerstone of AJAX.
Flash and silverlight has the same restrictions – and solves this by using crossdomain.xml and clientaccesspolicy.xml. These files are placed on the server you want to communicate with – and must contain * or the domain you want to contact the server from.
Anyways – there is a similar mechanism that XMLHttpRequest supports. This mechanism is called CORS – Cross-origin resource sharing. It is a newer(2004) and preferred alternative to JSONP – and works more or less like the xml files mentioned above. The only difference is that it isn’t implemented as a file – it’s part of the HTTP Header. This makes it a bit more difficult to set up than the others.
When a javascript on siteA wants to make a request to siteB – then the script first makes an initial OPTIONS request to site B – and looks at the HTTP Header it receives.
Access-Control-Allow-Origin: *
If the value is * – then it means that XmlHttpRequests can communicate with that site – from any other server – and a regular XMLHttpRequest can be made just like you were communication with your own server. You can of course type in domain names here to prevent everybody from using your API.
Here’s how to configure this on an Microsoft IIS Server – Web.Config – under the <configuration> node
<system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> </customHeaders> </httpProtocol> </system.webServer>
So to sum it up: use CORS whenever possible, instead of hacking your way around with JSONP. You’ll have prettier code, better error handling and it’s safer to use with regard to XSS Attacks as far as I have understood. Also – CORS supports all types of HTTP requests (Get/Post/Put,Delete), while JSONP only supports Get.
Read more about CORS here:
http://my.opera.com/core/blog/2011/10/28/cors-goes-mainline
A third (and the newest) alternative is UMP – I might blog more about this some other time.
Complete Dump of Asp.net WebRequest

Alternate way of dumping logs
Here’s a simple but very handy method that lists out all relevant data for a Asp.net web request. Posted Parameters, Query String, Http Headers, Cookies and Session variables are returned – and can be logged out to file/console etc.
Note that this static method can be called anywhere from your code – it does not have to be inside a aspx/ashx etc. The only requirement is that the code must run inside IIS and a web request must be assosiated with the current thread.
public static string DumpRequest() { StringBuilder sb = new StringBuilder(); sb.AppendLine(""); sb.AppendLine("------------- PostedParameters --------------"); foreach (string key in HttpContext.Current.Request.Form.Keys.Cast<string>().OrderBy(f => f)) { sb.AppendLine(key.PadLeft(40, ' ') + " : " + HttpContext.Current.Request.Params[key]); } sb.AppendLine(""); sb.AppendLine("------------- Query String ------------------"); foreach (string key in HttpContext.Current.Request.QueryString.Keys.Cast<string>().OrderBy(f => f)) { sb.AppendLine(key.PadLeft(40, ' ') + " : " + HttpContext.Current.Request.QueryString[key]); } sb.AppendLine(""); sb.AppendLine("------------- Http Headers -------------------"); foreach (string key in HttpContext.Current.Request.Headers.Keys.Cast<string>().OrderBy(f => f)) { sb.AppendLine(key.PadLeft(40, ' ') + " : " + HttpContext.Current.Request.Headers[key]); } sb.AppendLine(""); sb.AppendLine("-------------- Cookies -------------------------"); foreach (string key in HttpContext.Current.Request.Cookies.Keys.Cast<string>().OrderBy(f => f)) { sb.AppendLine(key.PadLeft(40, ' ') + " : " + HttpContext.Current.Request.Cookies[key].Value + " - ExpireDate: " + HttpContext.Current.Request.Cookies[key].Expires); } sb.AppendLine(""); sb.AppendLine("--------------- Session ------------------------"); foreach (string key in HttpContext.Current.Session.Keys.Cast<string>().OrderBy(f => f)) { sb.AppendLine(key.PadLeft(40, ' ') + " : " + HttpContext.Current.Session[key]); } return sb.ToString(); }
The result looks like this::
----------------------------------------- PostedParameters -----------------------------------------
----------------------------------------- Query String ---------------------------------------------
username : ted@example.com
----------------------------------------- Http Headers ---------------------------------------------
Accept : text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Charset : ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding : gzip,deflate,sdch
Accept-Language : en-US,en;q=0.8
Cache-Control : max-age=0
Connection : keep-alive
Cookie : timeOffset=-120; gs_u=1746198188:22843:26224:1320393450549; LANG=en; USER=a33f8…
Host : dev.filemail.com
User-Agent : Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome..
----------------------------------------- Cookies --------------------------------------------------
__utma : 155161261.1943841533.1313506820.1324476330.1325070578.60 - ExpireDate: 01.01.0001 00:00:00
__utma : 155161261.1943841533.1313506820.1324476330.1325070578.60 - ExpireDate: 01.01.0001 00:00:00
__utmc : 260895642 - ExpireDate: 01.01.0001 00:00:00
__utmz : 155161261.1313506820.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none) - ExpireDate:
__utmz : 155161261.1313506820.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none) - ExpireDate:
ASP.NET_SessionId : a2xlln05ibzzd2ajywhpizc0 - ExpireDate: 01.01.0001 00:00:00
gs_u : 1746198188:22843:26224:1320393450549 - ExpireDate: 01.01.0001 00:00:00
LANG : en - ExpireDate: 01.01.0001 00:00:00
timeOffset : -120 - ExpireDate: 01.01.0001 00:00:00
USER : a33f8a58568f430e8a0d48115ac7b13c - ExpireDate: 01.01.0001 00:00:00
----------------------------------------- Session --------------------------------------------------
- : -
UserObject :
Problems with Recycle Bin in Umbraco – No Document exists with Version ’00000000-0000-0000-0000-000000000000′
I recently had some problams emptying the Recycle Bin in Umbraco 4.6.1. I clicked Empty Recycle Bin - but after a few items got removed the progress suddenly stopped showing 201 items remaining. Crap.
Internet Explorer displayed a Javascript Error msg (with a stacktrace):
No Document exists with Version '00000000-0000-0000-0000-000000000000'
Waiting, restarting IIS and trying to empty the recycle bin again did not help. Time to Google.
I found part of the solution here:
The sql
SELECT * FROM umbracoNode, cmsContent -- return nodes WHERE nodeObjectType = 'C66BA18E-EAF3-4CFF-8A22-41B16D66A972' -- that are of type 'Content' AND umbracoNode.id NOT IN (SELECT nodeId FROM cmsContent) -- but are not in the 'Content' table
helped me identidy orphan nodes that should be removed.
For each unique umbracoNode.Id in the result (you will get a lot of rows with the same id using the sql above) i ran the sql below to remove these nodes.
DECLARE @TEMPID INT SET @TEMPID= 1843 -- TYPE IN ID HERE - e.g. 1843 DELETE FROM cmsContent WHERE (nodeId IN (Select id from umbracoNode where parentID = @TEMPID)) DELETE FROM cmsPropertyData WHERE (contentNodeId IN (Select Id from umbracoNode where parentID = @TEMPID)) DELETE FROM umbracoNode WHERE (id IN (Select id from umbracoNode where parentID = @TEMPID)) DELETE FROM umbracoNode WHERE (ID = @TEMPID)
Then I tried emptying the recycle bin again. Now it deleted 10 more items before it stopped.
I repeated the steps above again - first I ran the select sql to find the new orphan nodes, and then I ran the delete sql's. I was able to remove 43 more items from the recycle bin this way.
I repeated this procedure until my Recycle Bin was empty (I had to do it 6-7 times or so).
Make sure to backup your database before trying this approach.
Configuring Log4net from code!

Photo: A more traditional way of logging.
The first thing I do when creating a new .NET website/app is to add Log4net. I usually find some old code, and
- copy the log4net.dll,
- copy the log4net.config
- copy the c# code that loads the config file
For a lot of the smaller projects/solutions I am working on - there is no need at all to change log levels / appenders etc. during run time - so I configure log4net directly from my c# code. This means that I can drop the log4net.config file.
Here is a piece of code that creates a simple FileAppender. It can easily be modified to handle RollingFileAppenders etc..
Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
hierarchy.Root.RemoveAllAppenders(); /*Remove any other appenders*/
FileAppender fileAppender = new FileAppender();
fileAppender.AppendToFile = true;
fileAppender.LockingModel = new FileAppender.MinimalLock();
fileAppender.File = Server.MapPath("/") + "log.txt";
PatternLayout pl = new PatternLayout();
pl.ConversionPattern = "%d [%2%t] %-5p [%-10c] %m%n%n";
pl.ActivateOptions();
fileAppender.Layout = pl;
fileAppender.ActivateOptions();
log4net.Config.BasicConfigurator.Configure(fileAppender);
//Test logger
ILog log =LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
log.Debug("Testing!");
The result of the log test is:
2010-11-13 14:52:46,611 [20] DEBUG [_Default ] Testing!
A good place to put this code is in the entrypoint of your App (the Main(string[] args) method), or in the Global.asax if you are creating a web app (remember to grant the NETWORK SERVICE user write access to the folder you are logging to).
Happy logging!
-N
Upgrading Umbraco from 4.5.1 to 4.5.2

Umbraco is a Content Management System (CMS) developed in Microsoft .NET.
Some of its advantages is that it offers full design freedom, it's free to use, and perhaps most importantly - you can write your own user controls using the allmighty .NET Framework. A disadvantage with Umbraco (and a lof of other open-source solutions) is the hassle with upgrading to newer versions.

When attempting to upgrade a Umbraco 4.5.1 to 4.5.2 I followed this generic upgrade guide - which basically told me to overwrite some files and folder.The first thing I did was to do a full backup of the site (files + MS SQL database). Then, I copied the files, and opened the site in my browser.
A upgrade page was displayed - so far so good. I finished the different steps in the guide - it told me the upgrade had gone perfect!I tried to enter the site again to make sure the content was being displayed ok. But I was redirected to the Upgrade page again...where I tried to log in..
Problem: Admin can not log in after upgrading Umbraco
Possible Cause: Earlier versions of Umbraco handled password in clear text, current version uses hashing.
Possible Solution: Open web.config file - remove the passwordFormat="Hashed"
<add name="UsersMembershipProvider" type="umbraco.providers.UsersMembershipProvider" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" passwordFormat="Hashed" />
Problem: Site is not displayed at all after upgrade
Possible Cause: Upgrade bug?
Possible Solution: Log into Admin and republish entire site

Problem: XSLT is not working at all/behaving weird after upgrade
Possible Cause: New XSLT Schema! Data elements with Alias Attributes are no longer used!
Possible Solution 1: Set <UseLegacyXmlSchema>true</UseLegacyXmlSchema> in config/umbracoSettings.config
Possible Solution 2 (better): Replace XSLT code looking like this
$currentPage/descendant-or-self::node[string(data[@alias='umbracoNaviHide']) != '1']
with this
$currentPage/descendant-or-self::*[umbracoNaviHide != '1']
Tip: If you are unsure what the data(document/node) that you are trying to process with XSLT looks like - then insert this:
<textbox><xsl:copy-of select="$currentPage"/></textbox>
Problem: Umbraco installation contains different sites (hostnames), but only one of them works after upgrade
Possible Cause: Wrong setting in config/umbraco.config which got owerwritten during upgrade
Possible Solution: Set <ensureUniqueNaming>True</ensureUniqueNaming> in config/umbracoSettings.config
Thats about it I think - good luck upgrading!
Alvorlig sikkerhetshull i Asp.net
Microsoft annonserte for under en uke siden at det er oppdaget et relativt alvorlig sikkerhetshull i Asp.net / IIS som gjør at private filer som f.eks. web.config kan lastes ned. I disse filene ligger det ofte sensitiv informasjon som brukernavn / passord til databaser osv - så dette kan potensielt få store konsekvenser.
Inntil Microsoft lanserer en patch via Windows Update, anbefales det å slå på CustomErrors i Web.Config - som forhindrer angriperen i å bryte seg inn.
Se Scott Guthries blogg for detaljer:
http://weblogs.asp.net/scottgu/archive/2010/09/18/important-asp-net-security-vulnerability.aspx
Laste opp store filer i IIS 7.0
For å laste opp store filer (eller f.eks. sende store bytearray'er via Web Services) inn til en Microsoft IIS server kreves det en liten tweak.
I IIS 6.0 holdt det å justere opp maxRequestLength parametren i web.config. I IIS 7.0 må man også legge til/endre under <system.webServer>. Eksempelet under tillater å laste opp filer som er 2 GB store (IIS 7.0 støtter ikke større mengder såvidt jeg vet).
Microsoft IIS innstillinger og Asp.net session timeout
Her om dagen fikk jeg en forespørsel som i all enkelhet gikk ut på å justere Session Timeout for en ASP.NET webside. Denne instillingen spesifiserer bl.a. hvor lenge en nettleser kan stå innlogget på en webside før man blir logget ut. Har gjort dette mange ganger før, så burde gå som fot i hose.
Jeg gikk inn i web.config og endret session timeout verdien til 120 (minutter).
<sessionState cookieless="UseCookies" mode="InProc" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" stateConnectionString="tcpip=127.0.0.1:42424" timeout="120" />

Så gikk jeg inn i login siden og justerte loginTicket'en der til også å vare i 120 minutter (websiden bruker forms authentication).
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(“authTicketName”, false, 120); //120 minutes timeout.
Dermed burde alt være i skjønneste orden. Jeg logget inn på websida, surfet rundt litt.. og gikk til lunch. Når jeg kom tilbake 30 minutter senere prøvde jeg å surfe videre.. men ble redirected til loginsiden med en gang. Jeg var altså blitt logget ut.. etter ca 30 minutter.. what?
Etter å ta tenkt meg litt om (aka. googlet) fant jeg ut at årsaken til dette ligger i webserveren - Microsoft IIS 7. I App Pool'en her er det nemlig spesifisert at webserver prosessen skal avsluttes etter 20 minutters inaktivitet. Så mens jeg var midt i karbonadene døde prosessen.. og tok med seg session'en (og authticket'en) i dragsuget. Etter å ha endret denne verdien til 120 fungerer det som forventet.
På en webside med flere besøkende, så vil w3wp.exe prosessen sjelden/aldri stå på tomgang i 20 minutter.. slik at man ikke trenger å konfigurere dette i IIS. Men har du en webside med begrenset trafikk så bør Idle Time-out verdien justeres til Session sin timeout verdi (eller større).

