Blog Home  Home Feed your aggregator (RSS 2.0)  
.Net Jonesie - Monday, September 28, 2009
A simple programmers blog
 
# Monday, September 28, 2009

It’s been a while since I’ve blogged anything about EPiServer – 2 reasons -  1) I haven’t done an awful lot with it lately and 2) it’s just so easy it seems silly to blog about. However, over the last couple of weeks I’ve been helping out on a web site replacement project and one of my tasks was to install and configure the various servers – development, staging, UAT & production.  So, me thinks it’s time to talk about it.

SuperDeploy

Normally EPiServer installation is performed manually using the EPiServer setup and Deployment Centre tools.  However, for this project we attempted to script the entire process using PowerShell scripts.  We have created a deployment tool with PowerShell – aptly named SuperDeploy – that we use for SharePoint installation and database creation.  This is very useful for creating fully automated installations that we can use during development and when we need to install on the clients environment.  So, it seemed natural that we should extend this to work with EPiServer.  SuperDeploy uses a simple XML file to define what to install and where - the how is hard coded into PowerShell functions in the script.

Anyways, SuperDeploy works very well and provided a nice repeatable installation for all servers – up to a point.  With a bit more work it could do everything but time is.. you know what, so some manual steps were needed to finish off the production server.

The final production installation had 2 web servers identically configured.  The EPiServer site files were installed to a folder on F:\ and this folder was mirrored between the 2 servers using Windows DFS – so changes to files on one server were automatically and instantly copied to the other server – essentially meaning we had a single set of files for both servers.  We could have had the files on a external drive array of some sort but this would mean a single point of failure.  Replicating the files between servers provides an extra level of redundancy. The EPiServer virtual file system (VPP) was also replicated using the same DFS mechanism. The SQL 2005 database was on a third server and this was mirrored using log shipping to a forth server.

Load Balancing

I’ve come to notice over recent years than when something looks hard and not very well documented – it turns out to be obvious and simple.  Such is the case with the configuration of EPiServer load balancing. 

Documentation of the setup of EPiServer load balancing is hard to find. In fact the only documentation I could find was a single blog post.  This worried me somewhat as there isn’t a lot of detail in this post and it wasn’t an official EPiServer document. But I needn’t have worried – 5 of the 6 steps were correct but step 4 is applicable to IIS 6, not IIS 7 which we were using.  For IIS 7, httpModules must be specified in the <system.webserver> section of the web.config – not in <system.web>.  You can also configure these in IIS Manager.

The setup of Microsoft NLB was already done for us and the tool linked to in the above post proved that the network was indeed setup correctly. 

The hardest part was testing that the servers were actually load balanced.  Fortunately – a mistake by me editing the IIS config meant that one of the sites would not run.  Browsing from a test client machine gave me an HTTP 500 error from IIS. It was impossible to know which server was failing so we disabled one of the servers from the load balancing by turning off the NLB agent.  When the client browser was able to see the site correctly we new a) which server was broken and b) NLB was working.  Crude?  Yes, but good enough.  Some better testing is still required of course, but that's another story.

Even the smoothest installation can have surprises.  When we ran the site, we were prompted to login to view the home page – which is strange as it’s a public web site with anonymous access enabled.  We compared the production server configuration of IIS and web.config to the other servers and these were identical – we thought.  In the end, we configured the IIS anonymous access user to be the application pool account rather than IUSR and the setup was done.

Morals of the story

EPiServer installation is easy – even for multiple load balanced servers. If you do have multiple server then ensure they are identically configured – Virtual Machines are a life saver!  Mirroring or sharing the site installation folder will help with this (but it also means a mistake on 1 server will potentially be a mistake on all servers – instantly!). 

Script your installation as much as possible.  It make repeating your installation simple.

Install often and early – preferably as part of your development cycle.  Don’t wait till the end of the development to test your deployment – YOU WILL REGRET IT – trust me!  If you can, have your automated build cycle run your deployment script every night.

Be pragmatic.  Perfect is great if you can afford it but customers and bosses are rarely willing to pay for this.  Good enough is usually good enough!

Monday, September 28, 2009 8:40:52 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]   EPiServer | General | PowerShell  | 
# Thursday, August 20, 2009

Here’s the slides and code from my user group session last night – Getting Started with Azure Development.

I covered the basics of Web and Worker roles, storage and a bit of the service bus.

Use as you see fit.

Drizle.zip (3.53 MB)

WindowsAzureStartingUp.zip (229.92 KB)
Thursday, August 20, 2009 2:00:33 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [3]   Azure | NZ .Net User Group  | 
# Thursday, July 23, 2009

After posting about using TCP with the .Net Service Bus and making it look sooooo simple, I’ve lost most of today trying to get the fracking thing working!  I doesn’t matter what I do in the config, the service host keeps prompting me for a Card (from CardSpace) even though I had everything setup for UserNamePassword creds.

After much stuffing around I noticed that my solution had the wrong version of the service bus DLL (0.15.0.0 – March CTP I think).  This was my bad – I had copied the DLL to a solution folder.  So I grabbed the '”new” version (0.16.7.0) from the July CTP Assemblies folder and tried that.

Same result!  Arg!

Looking in the GAC I could see it had version 0.16.0.0.  What the ?!!

Time for a reinstall me think.

Download from MS.  Install. Chug chug….

Ok, now I have version 0.16.71.1.  Right. Fine.

But the GAC still has 0.16.0.0 and my app still is broked.  Lord - give me strength!

I re-added the project assembly reference to my local non gac copy and set copy local and now it all works again.

I can’t delete the old version from the GAC without uninstalling the SDK completely so it will have to stay there.

Weird!  The Joy of CTP.

Thursday, July 23, 2009 2:54:08 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [2]   Azure  | 
# Wednesday, July 22, 2009

Checkout this cool video if you want a 4 minute elevator pitch (ok, so a slow elevator).

http://blog.smarx.com/posts/what-is-windows-azure-a-hand-drawn-video

Wednesday, July 22, 2009 11:27:25 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]    | 

We recently implemented the .Net Service bus to expose some in-house WCF services to the world wide world. It may be useful for me and others if I describe how to do this :) This setup allows you to switch between tcp and http relay binding with configuration.

The Host

For the in-house systems you need to create a host – you cant use IIS as the service bus requires a connection to be initiated by both ends of the communication.  We created a Windows Service application that also runs as a console app.  This is much simpler when developing and debugging.  To create this service:

1) create a new windows service using the standard VS template and add a reference to Microsoft.ServiceBus (in addition to your service and data contracts which I hope are in separate assemblies!)

2) change the Application Output Type to Console Applications.

3) add some code to Program.cs to flick to console mode:

if (args.Length > 0 && args[0].ToLower() == "/console")
{
  myService.RunConsole(args);
}
else
{
  ServiceBase.Run(ServicesToRun);
}

4) in your service code add the following method:

internal void RunConsole(string[] args)
{
  OnStart(args);
  Console.WriteLine("My ServiceHost is running... Press Enter to stop the service");
  Console.ReadLine();
  OnStop();
}

Now for the service bus stuff.

5) in the service class, add a member for the service host:

ServiceHost _host = null;

6) in the OnStart method of your service add the following :

// create a behavior for the service bus – it need creds of some type
TransportClientEndpointBehavior behavior = new TransportClientEndpointBehavior();
behavior.CredentialType = TransportClientCredentialType.UserNamePassword;
behavior.Credentials.UserName.UserName = Properties.Settings.Default.ServiceBusSolutionName;
behavior.Credentials.UserName.Password = Properties.Settings.Default.ServiceBusPassword;

// create an address for the service bus.  config allows a switch between tcp and http
Uri address;

if(Properties.Settings.Default.ServiceBusBinding == "nettcp")
{

  address = ServiceBusEnvironment.CreateServiceUri("sb", Properties.Settings.Default.ServiceBusSolutionName, Properties.Settings.Default.ServiceBusServiceName);
}
else
  if(Properties.Settings.Default.ServiceBusBinding == "basichttp")
  {
    address = ServiceBusEnvironment.CreateServiceUri("http", Properties.Settings.Default.ServiceBusSolutionName, Properties.Settings.Default.ServiceBusServiceName);
  }
  else
    throw new ArgumentException("Invalid binding for Service Bus");

// create the host
_host = new ServiceHost(typeof(MyService), address);

// update all the end points with the new behavior – you may need more than one – or not – up to you
foreach (ServiceEndpoint endpoint in _host.Description.Endpoints)
{
    endpoint.Behaviors.Add(behavior);
}

// open the portal to another dimension – a dimension of sight and sound
_host.Open();

Now for some config.  For me this was the hardest part.  Hard coding WCF config is much simpler!

7) create some service model bindings for netTcpRelayBinding & basicHttpRelayBinding

<bindings>
  <netTcpRelayBinding>
    <binding name="default" />
  </netTcpRelayBinding>
  <basicHttpRelayBinding>
    <binding name="default">
      <security mode="None" />
    </binding>
  </basicHttpRelayBinding>
</bindings>

8) add an endpoint for your service:

<endpoint name="MyServiceEndpoint"
          address=""
          binding="netTcpRelayBinding"
          contract="MyApp.ServiceContracts.IMyService"
          bindingConfiguration="default" />

 

9) if you want to use  basic http then add this instead:

<endpoint name="MyServiceEndpoint"
                address=
http://mysolution.servicebus.windows.net/MyService
                binding="basicHttpRelayBinding"
                contract="MyApp.ServiceContracts.IMyService"
                bindingConfiguration="default" />

And that’s about it for the service host.  If you need to have metadata support (WSDL) then that’s a whole other story that I will try to blog about seperately.

The Client

Azure worker roles do not have a web or app .config you can use for WCF configuration settings.  Web roles do have a web.config but this can only be changed by a redeploy of package so it’s not the best idea to put anything but service configuration in there.  In my case, I needed to access the in-house services from both the web and worker roles so I created a class lib project with a single helper class.

1) create a Windows Class Library and add references for Microsoft.ServiceBus plus your service and data contracts.

2) Create a static class with a single static method – call it what you like but something like GetClientChannel() will do.  Add the following code:

IMyChannel channel;  // this is a simple combo interface of IChannel and IMyService

Uri address;


// create the behavior for SB creds
TransportClientEndpointBehavior behavior = new TransportClientEndpointBehavior();
behavior.CredentialType = TransportClientCredentialType.UserNamePassword;

// get the creds from the cloud config
behavior.Credentials.UserName.UserName = RoleManager.GetConfigurationSetting("ServiceBusSolutionName");
behavior.Credentials.UserName.Password = RoleManager.GetConfigurationSetting("ServiceBusPassword");

// create a channel factory

ChannelFactory<IMyChannel> channelFactory = new ChannelFactory<IMyChannel>();

// create the binding – config allows us to select http or tcp

if (RoleManager.GetConfigurationSetting("ServiceBusBinding").ToLower() == "basichttp")
{
  channelFactory.Endpoint.Binding = new BasicHttpRelayBinding(EndToEndBasicHttpSecurityMode.None, RelayClientAuthenticationType.None);
  address = ServiceBusEnvironment.CreateServiceUri("http", RoleManager.GetConfigurationSetting("ServiceBusSolutionName"), RoleManager.GetConfigurationSetting("ServiceBusServiceName"));
}
else if (RoleManager.GetConfigurationSetting("ServiceBusBinding").ToLower() == "nettcp")
{
  channelFactory.Endpoint.Binding = new NetTcpRelayBinding(EndToEndSecurityMode.Transport, RelayClientAuthenticationType.None);
  address = ServiceBusEnvironment.CreateServiceUri("sb", RoleManager.GetConfigurationSetting("ServiceBusSolutionName"), RoleManager.GetConfigurationSetting("ServiceBusServiceName"));
}
else
{
  throw new ArgumentException("Invalid service bus binding configuration option: " + RoleManager.GetConfigurationSetting("ServiceBusBinding"));
}

// update the factory for A B & C

channelFactory.Endpoint.Address = new EndpointAddress(address);
channelFactory.Endpoint.Behaviors.Add(behavior);

channelFactory.Endpoint.Contract.ContractType = typeof(ICRMChannel);

channel = channelFactory.CreateChannel(new EndpointAddress(address));
channel.Open();

return channel;

 

Tada!  All done.  Provided I haven’t introduced any bugs then this should give you a connection to you in-house services, by passing any firewall crap that those pesky IT people seem to insist on.

Enjoy :)

Wednesday, July 22, 2009 9:42:56 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]    | 
# Friday, July 17, 2009

So far, so good. Twitter has not taken over my life.  I’ve tweeted and chirped a little this week and have found a few colleagues to follow and vice versa. It’s also been a little useful and has helped me solve a couple of problems quicker than the usual methods (forums and web searches).

It’s interesting to see Twitter going main stream.  When one of our sales guys asked which twitter client to use I thought ‘oh well, twitter is surely dead now!’ but then I read that CRM 5 will have a Twitter interface and I’m guessing (truly – no insider info anymore) we will see similar functionality in Office 2010. Google Wave has this too.

I’m not tempted to create the next killer twitter client yet.  Tweetdeck works well enough for me at this stage but I can see that I will soon run out of screen real estate.

Best thing about twitter?  It’s go me blogging again :)

Friday, July 17, 2009 3:42:30 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]   General  | 

PowerShell takes a while to learn – especially if you have an aversion to manuals as I do – I prefer to learn on the fly.  So, when I wanted to convert a variable containing a comma delimited string into an array I was lost.  After a bit of playing and ‘binging’  I found that it was actually very very easy:

# start with a string
$roles = "db_owner"

# now it’s an array of 1 element
$roles = ,$roles

Sweet!

Friday, July 17, 2009 11:33:27 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [1]   General | PowerShell  | 
# Wednesday, July 15, 2009

I searched for a while to find an easy way to run a command from a PowerShell script and wait for it to finish.  Most of the example I found use Invoke-Expression but this wont wait.  In the end I resorted to the tried and true .Net Fx:

# run a command line and wait for it to be done   
function RunAndWait([string] $command, [string] $arguments)
    {
    $proc = New-Object     System.Diagnostics.Process
    $proc.StartInfo.FileName = $command
    $proc.StartInfo.Arguments = $arguments
    $proc.Start()
    $proc.WaitForExit()
    }

You need to seperate the command (aka FileName) from any arguments, but otherwise this seems to work nicely.

However, PowerGui doesn’t always wait when you are debugging so be careful if you are stepping through your script and expect it to stop in logical places.

Wednesday, July 15, 2009 10:39:11 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]   General | PowerShell  | 
# Thursday, July 09, 2009

The July CTP of the .Net Services SDK only support 2008, Vista or Windows 7.  This is true of the previous CTP’s but it was not enforced until the latest release.  Luckily for me there is a simple workaround.

On a machine that does have the July CTP installed, take a look in C:\Program Files\Microsoft .NET Services SDK (July 2009 CTP)\Assemblies.  There is a tool in here called RelayConfigurationInstaller.exe.  Copy this and the Microsoft.ServiceBus.dll to your target machine and run the exe with /i.  Then copy the DLL to the GAC and your done.

It appears as though RelayConfigurationInstaller simply adds the required machine.config settings on the target machine.  You could also do this manually if required.

Of course, this is not officially supported but MSFT are listening.  If you really need legacy OS support for this then post a message to the forums and ask for it before it’s too late.

Full Credit to Clemens Vasters for this tip.

Thursday, July 09, 2009 8:49:59 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]    | 
# Wednesday, July 08, 2009

Having a blog is like having a nagging wife – not blogging makes me feel guilty.  The thing is, I just don’t have the time to to write the type of blog posts I like to write – long and accurate.  Not that I’m ever very accurate, but well …

Anyways, I’ve been ranting about how stupid twitter is and what a complete time waster it is without actually trying it.  Then it occurred to me that twitter might actually be a useful alternative to long exhaustive blog posts.

So, I’ve signed up again and am tweeting a little about very development focused things.  You wont catch me tweeting about the weather or Michael Jackson etc.  Currently I’m into Azure dev so I’m finding lots of little things to chirp about.  I haven’t found a lot of tweets to follow yet apart from the obvious candidates – scottgu etc – but I did get my first reply today when I sent a message to a Microsoft tweet.  Very sweet!

Follow me if you love me :)  jonesienz

Wednesday, July 08, 2009 4:39:01 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [1]   Azure | General  | 
# Tuesday, June 16, 2009

I’ve been doing quite a bit of fun work with Azure lately – and it’s great! – mostly :)  It’s early days yet and there are a couple of (hundred?) things to sort out before they go live I guess.  The main problem with anything new like this is the lack of documentation and real world expertise when you strike a problem.  So, I thought I should blog solutions to the problems we have struck lately.  Here’s a little one.

The .Net Service Bus allows you to expose in-house systems to the wide wide web without all that pesky firewall configuration.  Essentially, it sites between the client and server and routes (WCF) messages.  You can read all about it here.   It only took us a morning to figure out how to configure our WCF’s but we had problems when it came time to deploy the web-role client to Azure. 

Required permissions cannot be acquired.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Security.Policy.PolicyException: Required permissions cannot be acquired.

So, after some research, the solution was very simple.  You just need to allow full trust for the web role which is achieved by setting the web role’s enableNativeCodeExecution to true in the ServiceDefinition.csdef file.  See here for the full story.

More on Azure soon…

Tuesday, June 16, 2009 10:46:01 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]   Azure  | 
# Tuesday, April 14, 2009

MSDN are testing a new version of the Library pages that are designed for low bandwidth connections.  If you browse to any library page you will see a link under the breadcrumb, e.g:

This will display a vastly stripped down version of the usual pages. 

You will be returned to normal mode if you navigate to any other library page or use the persist option at the top right of the page.

The speed of MSDN in this mode is great.  The only thing I miss is search.

Enjoy!

Tuesday, April 14, 2009 10:08:41 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]   General  | 
# Sunday, April 05, 2009

Recently I wrote an article for http://devshaped.com.  This was a lot of fun. So much so that I want to do more!

Sunday, April 05, 2009 7:49:09 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]   General  | 
# Friday, April 03, 2009
I haven't used WIX a lot so I'm no expert, but I do know that is way better packaging solution than anything else that ships with Visual Studio currently.  Version 3 of WIX had progressed to the point that MS were helping to have it included in the VS 2010 out of the box.  Which is slightly ironic if you know the history of WIX.

However, it appears than plans and people have changed and WIX will NOT ship with VS2010.

This is very sad for us poor developers who are left with little out of box choices for solution packaging.  Sure you will still be able to get WIX yourself but many shops don't like to let developers help themselves to open source tools and are even meaner when it comes to paying for tools.  Inclusion of WIX with the VS2010 release would have moved WIX to the mainstream and finally put a nail in the coffin of VDPROJ packages.

For the full story, read here.

If you think this is a mistake then it may not be too late.  Microsoft always listen to customers.  If enough of us talk about this and express opinions then they may change their mind or at least offer WIX as a Power Tools or some such thing.

If you would like to have your say then either blog about this yourself or send an email to Soma (VP of Developer Division) via his blog: http://blogs.msdn.com/somasegar/contact.aspx

Friday, April 03, 2009 7:56:27 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [1]   General | Visual Studio  | 
# Saturday, March 28, 2009
It's been a fantastic time being an MVP for the last 6 years.  I've really enjoyed being involved in the community and doing what I can to spread the good work that Microsoft do.  However, all good things come to an end.  I've had a year off presenting and organising to concentrate on personal projects so have not been re-awarded this year.

I'm going to miss the comradeship of the fellow MVP's and the occasional 'secret' that we got to hear. No doubt I will lose my sanity again before too long and get involved in some community activities.  I'll be back :)

Saturday, March 28, 2009 6:30:51 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]   General  | 
Here's my grand conspiracy theory.  It's 2007 and you realise that your puppet Bush & co is not going to be in office forever and that wars eventually end.  Your next pet President is a has-been who is unlikley to get power.  Your oil producing, weapons manufacturing empire is under threat.  What do you do? 

Well, how about an old fashioned recession?  Its worked in the past, right?  You can make a few quick billion on the stock market and use that to invest in the bargains that will follow the crash.  Rattle a few cages and the price of oil will go up.  Make sure your President pardons a few friends and free's up some land for development before he goes.  Then make a bit of a mess for the next do-gooder President to keep him busy enough so that he leaves you alone for a while.

Hey, this would make a great board game!  Call it Global Domination or Get Richer Quicker.  It could work like Monopoly, except you would start with 400 hotels and $12 Billion.  The idea would be to steal as much money off the other players as you can by manipulating politicians and the media, buying up the hotels and killing off the employees.

It's very hard not to be cynical but I believe that the current global financial crisis has largely bypassed New Zealand - or it may just be that the IT industry is more sheltered from it than other industries.

I have plenty of work. I'm not worried about being laid-off any time soon.  My employer is doing pretty well this year.  Other IT companies I know have plenty of work.  There are still lots of jobs available in IT.  Basically, everything is pretty much the same as it always is.

The main difference I can see is that people are slower at paying bills and the news media are constantly reminding us of the doom and gloom.

Recessions are great for some people.  There is a lot of money to be made for those that are prepared and there is no better way to be ready for a recession than to start one yourself!  I have no doubt that this has been created for the benefit of a few individuals and companies.  Fortunately, New Zealand is small enough to be ignored most of the time.




Saturday, March 28, 2009 6:22:31 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [2]   General  | 
# Friday, March 20, 2009
If you are into styling SharePoint - and who isn't! - then you might find these useful:  Ten Themes for SharePoint is VSeWSS Projects.  I think there is a yellow one in there ... :)


Friday, March 20, 2009 10:06:15 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]   General | Sharepoint  | 
# Monday, February 02, 2009

Microsoft have release ASP.Net MVC RC 1 last week - twice.  The first release was quickly refreshed to fix some issues so if you downloaded early last week, you may need to get the download again. Check here.

I have had a quick attempt to upgrade my 1 project and it all worked pretty sweetly and the upgrade process was very SIMPLE.

However.  Several of my crud views use FckEditor for long text fields.  A post-pack of these views triggers page validation:

   A potentially dangerous Request.Form value was detected from the client

Normally, turing off page request validation in the page and / or web.config will fix this :

   <pages validateRequest="false">

but for me and others (see comments at Phil Haack link above) this does not help.

So, looks like I will be rolling back to the beta until this is resolved.

Update: 

RTFB!  http://haacked.com/archive/2009/02/07/take-charge-of-your-security.aspx.  I haven't tried this yet, but it is almost certainly the solution.

Monday, February 02, 2009 9:42:02 AM (New Zealand Daylight Time, UTC+13:00)  #    Comments [1]   General  | 

Reading Paul a post on Hacked.com I saw mention of a new thing - the Web Platform Installer. This is a nifty tool that can be used to install the .Net Framework, ASP.Net, Visual Web Developer, ASP.MVC, Silverlight tools and other bits and peices. All from one very convienient and SIMPLE interface.

Using Virtual Machines for development these days I am often setting up new machines. This will save me a bit of time there. It's also great for helping friends and noobs get started with web development and will reduce the amount of time I spend on emails and awkward phone calls.

Well done Microsoft!

Monday, February 02, 2009 9:12:23 AM (New Zealand Daylight Time, UTC+13:00)  #    Comments [0]   General  | 
# Sunday, January 18, 2009

It's sad but understandable that Rod has decided to through in the blogging towel. While I haven't been following a lot of bloggers lately, Rod's posts were always insightful and often inspiring and I always tried to keep up to date with his feed.  You will be missed Rod - which seems impossible now that I say it. 

 

Sunday, January 18, 2009 9:19:54 PM (New Zealand Daylight Time, UTC+13:00)  #    Comments [0]   General  | 
# Thursday, January 15, 2009
I'm loving MVC.  In fact, it is my new love.  SharePoint is out - that was a bad relationship anyway - too sadistic.

There are however, a few things in the current beta that require a workaround or two.  Here's one.

To create a dropdown list in MVC you use the HtmlHelper thus:

<%= Html.DropDownList("CityID") %>

then in your controller you add the following before calling the view:

ViewData["CityID"] = new SelectList(from c in someDataContext.Cities orderby c.Name select c, 
"CityID","Name", selectedCityID);

where selectedCityID is the item you want preselected in the list.  Note that the ViewData key and the control name all match.  And this just works.  Easy as cake.

But now, suppose you want an option at the top of the list such as "[select a city]" when you are adding new records.  Again, this is a peice of pie, just do this :

<%= Html.DropDownList("[select a city]", "CityID") %>

The dropdown list will now contain this extra option at the top of the list of city, and it's value will be blank.

BUT..  the specified selectedvalue of selectedCityID will not be selected any more.  If you look a the page source generated by the HtmlHelper you will see that none of the options has selected=selected.

I dont know if this is a bug and/or if it will be fixed by the release candidate (due any day) but as a workaround I have used the following jQuery code to pre-select the default option:

$(function() {
  $("select[@name='CityID'] option[@value='<%= ViewData.Model.CityID%>']").attr('selected', 'selected');
});

Hope this helps someone else :)

Thursday, January 15, 2009 9:34:24 AM (New Zealand Daylight Time, UTC+13:00)  #    Comments [3]   General  | 
# Sunday, December 28, 2008

I've been writing a small app using the latest ASP.Net MVC Beta and JQuery - for fun and for work - and got caught out by a problem I'm sure Ive had before.

When ever you have a script tag dont self close it like this:

<script type="text/javascript" src="Scripts/jquery-1.2.6.min.js" />

For me this would stop all subsequent scripts from executing and sometimes result in a completly blank page.   I had the same result in Firefox and IE 7.  Instead, allways have a seperate end tag:

<script type="text/javascript" src="Scripts/jquery-1.2.6.min.js"></script>

Happy New Year :)

Sunday, December 28, 2008 4:57:44 PM (New Zealand Daylight Time, UTC+13:00)  #    Comments [0]   General  | 
# Sunday, November 16, 2008

I've been tasked with cleaning up a few remaining bugs in a system that is about to go live.  I spent most of last week trying to figure out this one. 

A page in a site included an asp:FileUpload control.  This was working fine but then suddenly stopped.  When the user submitted the form the FileUpload control would be cleared and nothing happened - no postback, no file uploaded, nothing.  Ah, but only in IE 7 (we didn't have 6 to test with), FireFox works fine.

So, to cut a very long story short and to save anyone else from murderous thoughts, here is the reason and solution (at least for me).

After turning on script debugging I could see an exception on the ASP.Net postback event:

function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}

The message displayed was htmlFile: Access Denied.

After much googling I found a few forum threads (heres one) that indicated that this was a security feature introduced in XP SP2, the idea, I think, was to prevent files being uploaded without the user knowing about it. Unfortuately none of the suggested solutions apply or work for me. 

After winding back the source day by day to a version that worked I was able to determine that the inclusion of an onload event handler in the body tag of the page was the cause.  Removing this fix the problem immediately.

Conslusion?  Well, I think IE is thinking that the onload event handler could be doing something dodgey so it enters a hightened state of alert and locks out the upload control.

Parting Shot:  Why the frac is this behaviour not documented by Microsoft and the IE team?  Maybe it is and google can't find it... but I doubt that.

Heopfully you wont waste 3 days like I did trying to solve this.

Sunday, November 16, 2008 11:19:21 AM (New Zealand Daylight Time, UTC+13:00)  #    Comments [0]   General  | 
# Tuesday, October 28, 2008

Tommorow I leave Christchurch for (up to) 6 months work in Sydney.  I'll be working for Intergen Solutions Pty - the Oz version of Intergen NZ - on an EPiServer web site for one of our customers, but I'll be back in NZ as required, probably monthly.

I'm really looking forward to:

  • doing some coding again - seems like I have not done any real coding for a year but I'm sure that's not strictly correct
  • decent weather - winter has been long and cold and as I get older I enjoy it less and less
  • the Sydney lifestyle - beaches, booze and babes :) (hope the wife isn't reading this!)
  • getting involved with the Sydney .Net community.  I'm already booked to do the Office Dev Con and to see Steve Balmer at some MS event.
  • doing stuff that is worthy of blogging again

but I worry about:

  • the heat - it was 31c there on Monday - that's about my limit.  It will take me a few weeks to get used to that again
  • the cost - finding accommodation is hard, finding cheap accommodation is very hard.  Plus, my 20yo daughter will be joining me in a few weeks for the summer so I need 2 bedrooms.   If you happen to have or know of a 2 bed furnished unit in Sydney that is available soon then please drop me a line!
  • homesickness.  I normally enjoy the first 3 days in a big city and then want to be back in my own bed.  Being away from the family for up to a month at a time will be a challenge for everyone.

And I'll be missing Code Camp :( which sounds like it is going to be a great event.

 

 

Tuesday, October 28, 2008 9:24:00 AM (New Zealand Daylight Time, UTC+13:00)  #    Comments [1]   General  | 
Copyright © 2010 Peter G Jones. All rights reserved.
DasBlog 'Portal' theme by Johnny Hughes.
Pick a theme: