Tuesday, April 06, 2010

Debugging SQL And The Fun Attached To That

Having come across this problem in Commerce Server 2002 recently:
Server Error in '/' Application.

Source:Microsoft OLE DB Provider for SQL ServerDescription:Incorrect syntax near '('.Source:Microsoft OLE DB Provider for SQL ServerDescription:Invalid object name 'MSCS_CatalogScratch.dbo.Catalog__Query__Results__for_spid__304'.Source:Microsoft OLE DB Provider for SQL ServerDescription:Invalid object name 'MSCS_CatalogScratch.dbo.Catalog__Query__Results__for_spid__304'.
I discovered that the stored procedure failing was called "ctlg_GetResults_for_SingleCatalog" but how to work out where?

This page came in useful: http://support.microsoft.com/kb/316549

Basically, it's stepping through SQL Stored Procedures in Visual Studio. The account you're accessing the DB requires execute permissions, etc, of course, but from there you should be able to step through the process just like code. Well, almost.

Friday, April 02, 2010

Always Check IIS

This is a lesson we all learn over and over again, I believe.

Recently trying to get the files in the MVC web app's directory '/Scripts/*' to be accessed I was constantly frustrated in not being able to load simple .js files, etc, in the browser page.

In this case, it was because Default Web Site in IIS already has a Scripts virtual directory setup. This, of course, does not behave as a normal subdirectory would and was stopping access to the files within it by the browser. This is expected, unless you've forgotten that fact because you've been working on WinSrv2k3 for too long...

Tuesday, March 23, 2010

Cannot Load ...global.asax

Ok, this may not cover every situation where the global.asax file is not able to load, but one thing to check, if annoying and persistent, runtime, global.asax errors are popping up is the build output directory. I had mine set to \bin\Development where it should have been \bin

Nuff said.

Wednesday, March 10, 2010

Easy Reflection

Reflection in .NET, as in Java, is pretty easy (and fun.) It is worth taking an amble down the many classes and tutorials in, and relating to, the System.Reflection namespace.

It is vitally important not to over-use reflection and to be aware that any reflection code probably has a better, non-reflection API somewhere to get the job done.

That said, there are easy mechanisms to get some basic reflection, like calling an empty argument constructor:
Hopefully, I'll flesh this out with some examples and more links to other places, but for now, this will have to do.

Hashing Passwords For Commerce Server

This post generally applies to Commerce Server 2007.

Initially labouring under the impression that CS2k7 used SHA1 or SHA256 (depending on which version is installed)...
I then learnt that we were, in fact, using MD5...
For those who want to know, MD5 is old, SHAn is newer. I believe CNG is the newest mechanism, but is not yet used by CS...

Tuesday, March 09, 2010

The Right Or Wrong Level Of Abstraction

I just have to post this:
I'm doing some encryption-involved work atm and this is particularly relevant.

It's also relevant because I often find myself, usually at the beginning of a project (like, right now), asking me, "What level should I be working and is there an API to do this for me?"

Usually, the answers are, "Don't know" and "No", in that order. Which is annoying but also called, "Life."

Anyway, read that article, the articles linked from it. It be good. Here it is again...

Drive Space Disappearing Captain!

Being very mystified recently that my drive apparently kept filling up, no matter how much space I freed by file deletions, I went on the hunt for any directory et al that might be growing, uncontrolled.

My journey took me to the directory:
  • C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data
Where I found a "nnn_log.ldf" file which was over 50% of my total drive capacity.

Upon opening "SQL Server Management Studio" I found the database in question, opened the Properties dialog and clicked on Files, in the left-hand list of panels. There, under the "Autogrowth" field of the "Database files:" display was a happily chugging "By 10 percent, unrestricted growth".

Simply changing the restricted size to something sensible did not work as hitting Ok threw an error dialog up.

A quick Googling later and this showed up:
So, to get rid of an overly large log file attached to the DB, the process is thus:
  • Take DB offline
  • Detach DB (Untick "Keep Full Text Catalogs", if that is the problem part)
  • Delete the overly large file
  • Re-attach DB, removing the LDF file from the "database details" gridview
  • Click "No" to skip re-attaching the log files/full text catalog (you've deleted it)
  • Open the DB's "Properties -> Files" dialog
  • Under "Autogrowth" click "..."
  • Untick "Enable Autogrowth"
  • Click Ok
For your DB, you should now have removed any overly large files and stopped any existing files from getting any bigger. Of course, if you do need them to grow, just keep an eye on the Autogrowth properties.

Thursday, March 04, 2010

T-SQL InformationSchema.Columns

A handy bit of T-SQL was passed to me today (by @jaminadey) which returns all the fields in a given table which are non-null...
  • SELECT * FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = '' and is_nullable = 'NO'
Of course, you'll see there are lots of other fields which can be inspected, so play around and introspect that DB!

Friday, February 26, 2010

Good Exception Rules - By Hanselman

Just wanted to stick this up as it's a good line of thought for handling exceptions.
There are, of course, many ideas on this, but 'from the horses mouth' often works well :)

Thursday, February 25, 2010

Sync Google Contacts To Your iPhone Contacts

Ok, this is fairly straightforward if you've already set up your Mail/etc on your iPhone to use Google Mail as an Exchange account.

If not, you've got some backing up to do, but it's ok - this blog post documents the whole process and makes it fairly painless:
One warning it makes: You will lose all your contacts and calendar entries if you simply sync with Google with importing your existing contacts into Google first!

Tuesday, February 23, 2010

Shared Heap Exhausted Or Damaged

I recently had an issue which caused a lot of error messages in the Control Panel -> Admin Tools -> Event Viewer -> Application log. While I've not fixed this issue on my machine specifically, I thought this was worth recording. The error I'm getting is:

The description for Event ID ( 1 ) in Source ( nview_info ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details. The following information is part of the event: NVIEW : devenv: shared heap exhausted or damaged

Some may find the following link useful in this situation.

Sunday, February 21, 2010

The Project Is Not Supported By This Installation

Today I got this error dialog when trying to open a solution "The project file '....csproj' cannot be opened. The project type is not supported by this installation." Visual Studio went on to display all the projects in the solution it could, except the website project.

Googling this returned this helpful post:
Indeed, reading the 5th post on that thread lead me to deleting the ProjectTypeGuids element from within the first PropertyGroup element. Hitting Reload Project in Solution Explorer showed the project correctly.

Friday, February 19, 2010

Different Build Modes

It is often useful to have different Visual Studio build modes in order to make better/more appropriate compilations of your projects for different environments, such as Development (your local dev machine), Staging (internal/client testing) and Production (final, fully live environment.)

To this end setting up VS properly is important and actually fairly simple. The process I use is thus:
  • Create a \Configuration directory in the root of your web project
  • Create \[build mode] directories for each build mode inside the \Configuration directory
  • Open the web project properties panel, click "Build Events" and paste this into the first multi-line text box, titled "Pre-build event command line":
mkdir $(ProjectDir)Configuration\Current
copy $(ProjectDir)Configuration\$(ConfigurationName)\*.config $(ProjectDir)Configuration\Current
  • Create empty ConnectionStrings.config and AppSettings.config files within each of \Configuration\[build mode] directories. These will need the initial empty elements for their appropriate config blocks, such as and
  • Replace the above config blocks in your web.config file with element attributes pointing to the \Configuration\Current directory:
  • Open the Solution Configurations drop down and select "Configuration Manager..." This is on the Standard toolbar and will probably show "Debug" as the default item.
  • Create the appropriate build modes under "Active solution configuration". Select New... and just create a series of new configuration names, such as Development, Staging and Production. Copy the default settings from Debug, for ease of use.
  • Using the Active solution configuration drop down, select each of the configuration modes you've just created and for each one click New... under the "Configuration" column for each project in your solution. When the New dialog opens, just create the configuration with the same name as the active solution's configuration: Development under Development and so on. Again, copy the Debug project configuration, for ease of use.
  • After closing the configuration dialog, select a configuration mode from the drop down and hit Build -> Build Solution.
At this point you may discover the following exception when building:
The command "mkdir .........." exited with code n.

This happens because one of the files you're asking copy to work upon either doesn't exist, doesn't have permissions to access or the directory your command refers to simply isn't there.

Problem: The directory will be missing if your Visual Studio build mode is currently in, for example, Release and you've only got \Configuration directories for, eg, Development and Staging. The problem copy is hitting is that the \Release directory doesn't exist.

Solution: Change the current build mode to Staging or Development and all should be well.

Wednesday, February 10, 2010

Not Validating A Complete Model

I am currently trying to edit a single model object through a series of views, using the MVC 2 RC 2 framework, found here:
I discovered that while using the default server-side validation that my model could not be properly validated because some of the model properties were not fully populated, or had incorrect values when, for example, the first view's form was submitted. The incorrect/null/etc values were fine for me because the process had not reached the point they would be populated, but the ModelState.IsValid still returned false, of course. This would be fine, except I needed it to be true, fitting to my standards of what was 'true' about the state of 'my model'.

The method I came up with follows, but I will say that it's not perfect and will almost certainly be superseded by something better in the future. Here it is:

///
/// Used simply to ensure that validation has occured for the model properties that were rendered on
/// the current view.
///
/// The list of form field names to check for errors. Eg: the FormCollection object
/// True if none of the ModelState values matching the whitelist keys have errors attached, else false.
private bool IsModelStateFieldsValidated(IEnumerable whiteList)
{
foreach (string key in whiteList)
if (ModelState[key].Errors.Count > 0)
return false;

return true;
}

If the action method takes a 'FormCollection collection' parameter then that can simply be passed into the IsModelStateFieldsValidated method directly.

The method above just very simply checks the field names which were on the page (which, of course, may not be every property in the model class) and checks that there were no exceptions found in the ModelState value collection - for those property names only. Any other exceptions will be ignored, because they are not pertinent to the current view.

Another Problem Solved By Someone Better Than Me

Ok, this is one of those woods-for-the-trees situations. Basically, I had been mucking about with custom model binders:
And had added a class attribute to my model class to handle the post back binding of the model. This worked fine. The following, however, I forgot about this and was trying to use the default server-side validation.

Problem: The server-side validation was not working.

Solution: Remove the custom model binder.

Reason: It was returning just an empty model object every time.

This solved a host of problems, in fact.

The EditorTemplates Directory

Having been trying to get a model property to render the appropriate editor in MVC, recently, I was having some trouble getting the editor - provided by a very talented colleague - to render correctly, or, in fact, at all.

Not having been introduced to the structure of the shared directory (it doesn't seem to be mentioned in the http://www.asp.net/learn/mvc/ pages) there was an issue with understanding how the Html.EditorFor method would provide my custom editor.

This was solved when I came across David Hayden's blog page:

Monday, February 08, 2010

MVC's HtmlAttributes Parameter

In MVC's model it is very easy to generate HTML tags, or XHTML elements, as I believe they prefer to be known these days.

What wasn't so obvious was the optional htmlAttributes parameter, available in all the Html.TextBoxFor(...) Html.LabelFor(...) etc etc.

My question was, "How do I use this, what's it for, why, when, where, who, whether, whence, etc?"

Yeah, I'm not so great at forming questions sometimes. But the answer came in the form of Rob Conery's blog entry:
And so I've learnt that you can simply have disabled="disabled" in a new {} and the ...For adds the values as attributes to your HTML element. Read Rob's article for a better description.

However, if you're still having trouble with this (eg: ActionLink doesn't seem to link certain htmlAttributes assignments) you can check out this post at stackoverflow:
Top notch.

Yes, I need to get the code embedding sorted on this 'ere blog thingy...

Friday, February 05, 2010

Learning More About Linq To Xml

Being armpit-deep in the slightly clearer .NET waters of MVC 2 RC 2 has lead me to getting further into the (shark infested?) LINQ deeps. Therefore, when I went looking for some good "how to sort XML using LINQ" on google, I came across this:

Finding Out More About MVC

[EDIT] Ok, irony of ironies... Literally AS I was writing this, the MVC team at MS were putting out their latest version: MVC 2 RC 2. You can get it here (and yes, it fixes the problem I've described below): http://weblogs.asp.net/scottgu/archive/2010/02/05/asp-net-mvc-2-release-candidate-2-now-available.aspx


So, after some working with MVC 2 RC (Full title: ASP.NET Model-View-Controller Version 2, release candidate, or so I'm told ;) I discovered some lovely things about MVC. One of which, in particular, is the TryUpdateModel, or UpdateModel, method available in the Controller class. This is supposed to take a FormCollection from your Edit (et al) Action method (ie: response from a postback) and populate your model instance for you. It should do this by using an optional whitelist and blacklist of class property names and the names of the fields on your View's form, then by using reflection to assign those properties values.

You'll notice, of course, that the above tends towards the opportunity rather than the specific. This is because the only output from the TryUpdateModel I've had is an error stating "Value cannot be null or empty. Parameter name 'name'." Woo hoo.

Anyway, fortunately there's lots of help on this subject, below... and hopefully my own solution, later...
And so, in the end, I've had my first look at downloading the source for an open MS framework and there are lots of things to be learnt in reading other organisation's code. It's an interesting project and doesn't have to be long and painful. Just grabbing a download and browsing should throw up an idea or two and hopefully show the right or wrong way of approaching things. Or, at the very least, a different way.

Also, I just wanted to point out that these are a great pair of posts:

Friday, January 29, 2010

Setting Up MVC

Having moved to the RC version of ASP.NET MVC 2.0, I've been looking around for resources (some repetition follows):

Google Data And Client Libraries

Quick link for those looking to get the Google .NET API:
Working with Google's APIs to extract I've discovered some very useful links:
I've now been attempting this fun for a little while and there seems to be a fair bit of mis-direction around the Google .NET APIs. My (and others, it seems) main concern is that the .NET APIs seem to cater very well for most Google Labs/Apps uses, except for Google Analytics. Issue #1 being how to even get access/login with .NET. I have since discovered the actual Analytics .NET libraries, so the links are here. However, currently, it's important to note that the links above don't directly link to the libraries you really need.
The code I used to get an authentication token from the Google Analytics Service is:

using Google.GData.Analytics;

AnalyticsService analyticsService = new AnalyticsService(ConfigurationManager.AppSettings["ApplicationName"]);
analyticsService.setUserCredentials(ConfigurationManager.AppSettings["Email"], ConfigurationManager.AppSettings["Password"]);
string analyticsAuthToken = analyticsService.QueryClientLoginToken();
return analyticsAuthToken;

Wednesday, January 27, 2010

Transforming XML Browser-Side

I like using XML and XSLT and find it a simple and powerful way to produce friendly, web-centric content. My utopia would be an easy to develop SQLXML output, which can be pumped as directly as possible to the browser, which then uses XSLT client side to render XHTML.

Currently, this is possible by using (for me) C# to pull the SQLXML content from the DB (I'm using T-SQL, ie: MSSQL http://msdn.microsoft.com/en-us/library/ms345117(SQL.90).aspx), processing it using the .NET XML transformation API (http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63) and pushing the produced XHTML to the browser.

This approach is good because any extraneous processing or user values, validation, security and browser differences can be catered for, while removing strain on the browser. It's important to note that asking the client to do the XSL transformation isn't a great idea because browsers like Mobile Safari will ask a remote service to do the transform, which slows things down and will obfuscate a lot of data away from your app.

However, if you want to go ahead with having the browser do the heavy XSLT lifting, the best place to start is:

Posting Data From Server Side

Just a quick link, but might bolster this with more useful stuff later...

Sunday, January 24, 2010

Generics

Generics. They're generic. Sssss...

Good link:
Something I was wondering about recently was how to define constraints upon multiple generic types. Eg: If I have a class definition with more than one generic:
public class MyClass

How do I specify constraints (restrictions to the base types which the generic types can inherit from)? Answer (from the link above [5th code paragraph]):

public class MyClass
where T : String
where K : IComparable

Easy when you know how.

Wednesday, January 20, 2010

SQL Trees

Ok, so it's been bugging me for ages, I'm just going to start compiling all the SQL tree structure knowledge here. I might have started this in a previous post, and will try to find that, if I did, and aggregate the posts sometime...

Friday, January 08, 2010

Tuesday, December 15, 2009

Thursday, December 10, 2009

DataBind

With nothing of particular note to bulk up this entry, I'm hoping to later collect all my knowledge on data binding into one post...

The Links...

Tuesday, December 08, 2009

Lifehacker Roundup

And lastly, from the Network Lights site: http://www.itsamples.com/index.html - the best part? They provide source code for a lot of stuff.

Stuff it, instead of consecutive posts for this stuff, I'll just build up this week's...
And the fun continues on Thursday...

Wednesday, December 02, 2009

Debugging Tools And Fun, Erm...

Some useful links if you're trying to find web dev debug tools:
Of course, deploying your DLLs in debug mode can help your logging, but release mode is going to provide at least 4x performance improvements. If you attach a profiler for checking memory usage or performance, you can leave your .pdb files up to get more information as these contain the .NET symbols used for inspecting the code. Please don't leave them there, as they are a serious security consideration - in short, if a hacker were to copy your pdb files from your server they've effectively stolen everything but the source code:
Here's some profilers that don't involve installing Visual Studio on a live server (always a bad idea):
There are, of course, sites out there for providing information about your site:
Of course, if you're intent on debugging in Firefox (www.firefox.com, of course) you should have:
Some tools for developing your code (essentially, my favourites, as there are tonnes, Microsoft's list notwithstanding (http://msdn.microsoft.com/en-us/magazine/cc300497.aspx)):
And a list of developer must-have's:

Thursday, November 19, 2009

Dealing With Exceptions

Knowledgeable blogs on the subject of debugging, crashes, exceptions and dumps - good reading:
Grabbing the dump file and getting at the data from the dump:
Very useful links for debugging, including dump file cheat sheet and analysis check list:
Every developer's starting point when looking for debugging tools:
Page of links for Microsoft debugging tools:
WinDbg is the top one:
At time of writing this is labelled "Install 32-bit version 6.11.1.404 [16.9 MB]"

And finally, why you should use try...catch...finally, or even try...finally:

Sunday, November 01, 2009

XSLT, XPath Knowledge Base

XPath explained and easy-to-use grid of descriptions...
Very useful XSLT scripts (including url encode/decode templates)...
A list of XSL elements and descriptions...
.NET 3.5 page on navigating XML in XPath...
Using XPath and LINQ...

Saturday, October 31, 2009

String.Reverse And Microsoft Interviews

A question which often comes up in interviews (and, I'm told, at Microsoft) is "write a method/function to reverse a string."
This, of course, isn't very difficult and lots of people get it wrong or give up. The following links are useful in getting the best answer, but really the best answer is how you work it out at the time. My opinion, though, is that the best answer is along the lines, "I'd look up some good examples and apply what I've learnt to the actual problem I have." This is appropriate simply because most people at work (especially when programming) are not in the firing line solving some real time James Bond type challenge and that there is usually a better solution created/invented/found by someone more intelligent/luckier somewhere in the world.

None of the points above are excuses for laziness or stupidity, however. Mostly, in my experience, points are gained by having experience and applying it well. Therefore;
It's also worth noting that:

string reversed = forwardStr.Reverse();

does not work. See link above.

[EDIT]

I'll include some extra links here, found recently while pondering the current state of affairs in the world. It's interesting to note that (it seems) a large number of interviews think that some (alleged) programmers are not, in fact, programmers...

Monday, October 19, 2009

Roundup: Week Ending 16/10/09

Hmmm...
And the not-gizmodo not-lifehacker...

Chasing The Tail

Sunday, October 18, 2009

System32 Always Opening! Argh!

I've had this infuriating event happening every time I log into Windows. The Windows\System32 directory keeps opening up in Windows Explorer, every single time, just after I log in. This didn't used to happen, is really annoying and just highlights how crappy Windows can be.

Fortunately, there's a solution - even Microsoft know about this. And it's weird. My initial google search on this brought back this handy little site:
Which lead me to this Microsft knowledge base article:
Which lead me to opening the registry editor (Start -> Run -> regedit), following the path down the registry folders to:
  • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
And finally deleting the entry for "MultiScreen", which had a value of " ". Like I said; Weird.

Anyway, this seems to have solved the problem. Why there is code somewhere inside Windows which opens the System32 directory when you log in if there is an invalid registry entry is beyong me, but at least it's fixed now.

Thursday, October 15, 2009

How To Capture Page Output, Caching

Found this on the net, while trying to capture the rendered output of a page...
Only takes a little modifying to adjust to writing to disc. In .NET2.0 and above you can use the File.WriteAllText to dump out your html file and easily implement disc caching:

The Fear Of The Noob

Monday, October 05, 2009

That Will Always Be The Dream

Roundup: OCR, LifeHacker, Gizmodo And The iPhone, For The Week

This week's latest...
Some verrry interesting stuff last week...

Wednesday, September 30, 2009

Useful, Popular And Commonly Required MSDN Pages

Just thought a collection of these would be good. I'll try to keep it updated...

Tuesday, September 22, 2009

Monday, September 21, 2009

Properly Handling CDATA In .NET XSLT

Prologue:

I have a T-SQL table of data, one field of which contains escaped X/HTML - that is, it has XHTML where the important characters, like < and >, are represented as &lt; and &gt; etc. Some of this XHTML is broken because the writer was probably using a rich-text editor which sent fragments of XHTML to the database. Of course, using SQLXML to pull this out I find that the body of some of the elements contains this escaped HTML. So now I need to unescape it back into normal HTML, so it can be rendered on a page without hassle, but without making it part of the XML document.

Sumary:
Ok, so, in summary, we have valid XML with escaped XML (or XHTML) which needs to be wrapped sensibly so it's not mixed up and we need to do this in .NET.

First problem:

Unescaping the code, in XSLT, is a little tricky, but if you assume every element which needs unescaping is the same, then we can do this:

<xsl:template match="Description">
<xsl:copy>
<xsl:value-of select="node()" disable-output-escaping="yes" />
</xsl:copy>
</xsl:template>

What this does is match every element named 'Description' in the original XML and unescape it's content - so code like &lt; and &gt; become < and >. Simple. If you want to do that for specific elements only, just move the 'value-of' XSL element to where you want it.

Second problem:

We now have XML containing some more XML, which should really be considered plain text, until it's needed. So, we want to keep this 'inner XML' as it is (ie: pretty XML and not escaped) but indicate that it's not part of the current XML document.

Second solution:

Wrap the body content of the elements we want to remain as body content in a CDATA tag, like this:

<xsl:template match="Description">
<xsl:copy>
<![CDATA[<xsl:value-of select="node()" disable-output-escaping="yes" />]]>
</xsl:copy>
</xsl:template>



What the CDATA block does is tell any parsers that the content is to be, essentially, ignored. Simple.

Unfortunately, the CDATA block tells the parser not to parse the content within it, so what we actually end up with is:

<Description>
<![CDATA[
<xsl:value-of select="node()" disable-output-escaping="yes" />]]>
</Description>

Third problem:

If you just add the CDATA block to your XSLT a standard parser will take the XSL element within it as to be ignored, and not process it.

Third solution:

The answer to this is not to include the CDATA block ourselves, but to tell the XSLT document which elements need to contain the CDATA block, instead. Thus, the XSLT parser will wrap them itself. We do this by adding the 'cdata-section-elements' attribute to the output element of the XSLT document:

<xsl:output method="xml" indent="yes" cdata-section-elements="Description" omit-xml-declaration="yes" />

Now, every <Description> element, in the output XML, will contain a CDATA block which wraps the body content of the element, like this:

<Description>
<![CDATA[
<strong>Some content that was parsed from the value-of XSL element.</strong>]]>
</Description>

However, if you have been trying this as we go along and seeing something different - ie, it's not working for you - that's because, in .NET, you have to handle XSLT in a certain way.

The short answer is, here's the C# to do it:

/// <summary>
/// Takes a string containing XML to be parsed and a string containing the the XSLT to do the parsing.
/// </summary>
public string NewTransform(string xml, string xsl)
{
// create the readers for the xml and xsl
XmlReader reader = XmlReader.Create(new StringReader(xsl));
XmlReader input = XmlReader.Create(new StringReader(xml));

// create the xsl transformer
XslCompiledTransform t = new XslCompiledTransform(true);
t.Load(reader);

// create the writer which will output the transformed xml
StringBuilder sb = new StringBuilder();
XmlWriter results = XmlWriter.Create(new StringWriter(sb), t.OutputSettings);

// write the transformed xml out to a stringbuilder
t.Transform(input, null, results);

// return the transformed xml
return sb.ToString();
}

/// <summary>
/// Takes an absolute path to a file which is then loaded into a string and returned.
/// </summary>
public string LoadFileAsString(string fullpathtofile)
{
using (var sr = new StreamReader(fullpathtofile))
return sr.ReadToEnd();
}

The key to ensuring that the cdata-section-elements attribute, and therefore the CDATA block, is handled correctly is the t.OutputSettings - passing the settings to the writer informs it of the intentions of the XSL transformer.

Epilogue:

I battled with all of the above until I stumbled upon this post, so thank you to everyone there:

Thursday, September 17, 2009

Augmented Reality On The iPhone

Well, I've finally found something cool, useful and right here, right now...
I found this via the original link...
Now, signing up (free, easy and quick) to the iPhone app Yelp, gives you something very useful: Switch on Monocle (shaking the iPhone isn't necessary any more - I discovered too late!) and it'll show you which restaurants, bars, etc are in the direction your phone is facing. It's that easy to find places. Tapping the screen takes you to the contact information and from there the world is yours!

Yes, I'll say it again, I'm in love with the iPhone. Well done Apple - and all the enterprising developers out there making the best use of a very good gadget!

Space Photos On A Budget

Recently, some MIT students took their own photos of the Earth's curve...
Further reading, mostly derived from the above links, but the Apollo stories are some of Mankind's most important, heroic and touching...

Wednesday, September 16, 2009

Make Sure Your IIS Uses The Correct .NET Version - Unrecognized attribute 'type'

Recently, I created a new .NET 3.5 web site in VS2008 and started getting this error:
  • Parser Error Message: Unrecognized attribute 'type'.
This page helped me here:
Essentially, the problem is that IIS must be configured to use the correct version of .NET to run the site. Therefore, I opened the IIS panel "properties" for my site, clicked the ASP.NET tab and switched the version from .NET 1 to 2 and everything was fine.

Point IIS to .NET 2 even for .NET 3.5 web apps.

So, yes, the issue was I was using the wrong version of .NET to run my website. D'oh!

Lifehacker Fun

LifeHacker fun...

Wednesday, September 09, 2009

iPhone Problems And Solutions

Well, I love the iPhone, but like any device it's not perfect. Ok, I've not found anything that isn't pretty much perfect (built by Apple, at least) but having found my first problem, hopefully here's some solutions, some generally useful links follow...
  • Unsent email won't send. A sent email fails to appear in the "Sent" folder and the message "1 unsent email" displays at the bottom of the mail application.
    For me, this resolved itself, I assume by finally managing to send. Here is a useful link related to the issue:
    http://support.apple.com/kb/TS1426?viewlocale=en_US
Generally useful links to be aware of:

Sunday, September 06, 2009

Loving Up The iPhone

Finally made the switch from a dying T-Mobile Windows Mobile MDA Vario II, to the 16GB iPhone 3GS and it's awesome! This thing completely surpasses all expectations in performance, usability, speed and sheer number of applications available - there are far more applications than for Windows Mobile and they are so easy to get. The addictive nature of downloading to the iPhone, I think, would compare to the discovery of P2P file sharing.

Anyway, I was disappointed when I discovered (yes, lots of this is new to me) that I can't just dump files onto the iPhone like I can with the iPod (using it as an external HD, for example) or that ringtones cannot be selected from any music on the device. I did, though, find a very good page with instructions on how to do this. Originally written, then tidied up, for the iPhone 3G, this page is accurate for 3GS as the method is fairly generic;
In short, it goes like this:
  1. Get an audio file and edit to around 20-30 seconds
  2. Save as MPEG-4 (.m4a - see WavePad for easy converting)
  3. Change file extension to .m4r
  4. Drop into the Ringtones section of iTunes
  5. Sync Ringtones to your iPhone
The ringtones will now be available in the Sounds section of you iPhone's settings. Easy. There is more detail on the above link and a pointer to the http://audiko.net/ site for even easier conversions, but manual conversion was my preference (and is really very easy.)

WavePad is available here:
On the other side of the coin, we have videos for the iPhone. As with iPod and iPod Touch, there are plenty of videos to purchase or stream (iPhone comes with a YouTube app) but what if you have a load of wmv's or avi's you want to just dump there? I would get the iPod/iPhone video converter Videora because it has all the "want that one" simple functions that you could need, while being fast and producing quality output. Then it's simply a case of syncing your iPhone to your videos (videora can auto-add conversions to iTunes' library or you can manually drop them onto the phone) to make them play on the iPhone.
Red Kawa, the makers of Videora, even have easy-to-use apps for making wallpapers for the iPhone, but with the wallpaper selector built in, I don't think those are necessary.

Tuesday, September 01, 2009

Friday, August 21, 2009

Equals Equals Vs. Equals

Recently I was asked, "What's the difference between 'a == b' and 'a.Equals(b)'. The short answer is that the second is a method call (easily overridden) and the first is not. While this is true, it's not the whole truth.

The real answer breaks down into two parts. First, for value types such as int, bool and float, the '==' is a direct comparison - it does compare the value of a and b. This is also true for 'string's, though these are a special case. For value types the '.Equals()' also compares the value of a and b because every value type can be treated as though it is boxed - .NET implicitly allows the class methods and properties to be called on their value type siblings.

For reference types - those created from classes, such as String, Int32, MyCarClass etc - the value comparison '==' cannot be called because an instance of a class is not the most primitive type of data the system can work with (in fact, Java calls value types 'primitives'.) In this case, the class must provide an 'Equals()' method - and every class does because all classes inherit from Object. However, because the default implementation (from Object) of 'Equals()' is to compare the references (ie: memory address value, not the data contained at that address), if 'Equals()' is not overridden you might find that two objects with the same value return false from Equals().

All the classes representing value types provide the appropriate Equals method (in that they all compare the value and not the reference of the object.) But for your own classes you must override Equals and provide your own implementation - because .NET does not implicitly know how to compare instances of your own classes. (It is possible to write reflection code which can do this, but it is long, difficult and prone to infallibility, so don't do it - unless you fancy a learning challenge ;)

So, in short (but not as short as earlier) the guide is:

For int: == compares the value, .Equals() compares the value (this is the .Equals() in Int32).
For Int32: == compares the value by calling the .Equals() in the Int32 class, .Equals() compares the value.
For MyInt32: == compares the references of the variables, .Equals() calls the method in your MyInt32 class.

If you want the '==' operator to perform a value comparison on instances of your own classes, you can use the 'operator' keyword and define your own '==' functionality;
For example, in a class called 'MyClass', if you have a working 'Equals()' method:

public static bool operator ==(MyClass a, MyClass b)
{
return a.Equals(b); // or whatever comparison you want to do
}

Another site with some code:

Thursday, August 20, 2009

Tuesday, August 11, 2009

I'm Back, And It's Ok

Thought I would just post something that might be of use to anyone trying to get back-end (or "code-behind") code working inside the ASPX or ASCX of their control - this can be useful to avoid having to do a full code release or if the page/control is dynamically loaded, say from a DB or plain text...
Isn't that great? Just a script block with runat=server and you're done.

This might also be useful:
Run along now, you're done.