Compsoft Flexible Specialists

Compsoft plc

Compsoft Weblog Compsoft Website News Archive Privacy Policy Contact Us  

Monday, October 05, 2009

This week, I have been mostly getting JSONP

I've just finished writing a test harness for a sms texting service. While writing this little tool I ran into a problem with cross site scripting issues.

Essentially its a form that is submitted to a page which then invokes methods to deal with the faked sms. It actually plays the part of the sms gateway host and saves me 50pence a shot!

The form submission is via AJAX, but because its on a different domain I get no success or useful error responses. This is where JSONP comes in.

As of jQuery 1.2 you can get JSON data from another domain if you add a JSONP callback and a little bit of handling on the server.

You also get the proper success and error responses.

The form looks a little like this:

<form action="http://someOtherDomain/cross-site.php" method="get">
 input1:<input id="input1" name="input1" value="suits you sir"/>
</form>
<button type="button" id="btnsubmitjson">jsonp submit</button>
<div id="response"></div>


The javascript that handles the button click event appends the JSON callback to the url and then submits the form with the power of jQuery:

function submitjson(){
    posturl = $("form").attr('action');
    posturl += "?jsoncallback=?"; //append the JSON call back
    $.getJSON(posturl, $("form").serialize(), function(data) {
        $('#response').text(data.name);
    });
}

And the final part (which is not so obvious) is the response required, generated by the server:

<?php
$data = '{"name" : "'.$_GET['input1'].'"}';
echo $_GET['jsoncallback'].'('.$data.');';
?>

And its this last magic bit in the responding with $_GET['jsoncallback'] which makes it all work!

Now I can point my tool where ever I like, AND get the right responses (ah yeah).

Labels: , , ,

Tuesday, November 11, 2008

Tristan Smith: Tech Ed 2008 Day 2

Introduction to the Entity Framework

I really felt for the speaker here, a quirky, excitable American woman. Both because it's the first session of the day with most people barely awake and also because the audience seemed semi-hostile. Hostile, I imagine, as a result of Microsoft announcement that they're effectively killing LINQ to SQL (which a lot of developers have invested time and code in) in favour of the Entity Framework (EF). As we have also invested in LINQ to SQL for our data access, this seemed like an important session for us.

We currently do a lot of code generation based on the shape of the database so we'll have to update our generation when we make the switch. While there are some obvious gains by using EF which were mentioned, I wasn't sold, the relatively few benefits over LINQ to SQL didn't seem to justify a switch.

Unfortunately the session barely skimmed the surface, no real depth was gone into.

How IT will change in the next 10 years and why you should care

Definitely my favourite session so far presented by an awesome speaker.
There were so many areas that were covered, it's hard to summarise.
Some interesting points were brought up around subjects such as the move towards virtualisation, how the green friendliness of hardware is going to have it's impact and is already.

A really interesting point was the way in which the next generation of employees are going to be the first generation of Digital Natives(DN). Here we are as Digital Immigrants, we were there before the great migration, we've been working through the change and are enjoying the gadgets but we're just not in that same headspace. The DNs of today instinctively navigate and manipulate social networks living their online identities. He pointed out that they're going to be entering the work force where they're to be stripped of their online identities, given a crappy email address and effectively disconnected. Quite a culture shock it will be for them.

The IT industry's carbon footprint is already larger than that of total global aviation. How increasing power consumption means Microsoft will dump their entire computers if a new machine has sufficient power savings. Heat is the great enemy. For the huge savings, data centres are being moved to cold places such as Greenland where there are beefy data backbones between the USA and Europe.

Introducing ASP.NET MVC

In ASP.NET Webforms, there is no master handing your pages and controls the data they need, nothing takes responsibility. The masterpage, page, controls can all have their own presentation, data access and logic.
This can make code less maintainable because you're not sure what in the hierarchy has broken. Wouldn't it be nice if you could have a clean separation of the data, logic and view? Yep! and that's what MVC is all about.
As a result of being separated out like this, your code becomes a lot more testable and you can swap out the different parts as you need.

While this sounds like the golden chalice, it takes a lot more work to make a page. There is a definite hard work tax involved, it's harder to get the same kinds of AJAX functionality that you would by just slapping an ASP.NET AJAX Update Panel around your code.

ASP.NET practices with MVC
Following up on the introduction to MVC which I was very impressed with, this session talked about some of the implementation issues and pitfalls you're likely to encounter.

Also mentioned was Unity, Microsoft's Inversion of Control offering allows you to remove the relationship reliances between layers of your code meaning when one part of your system is rewritten, providing it still matches the interface signature, it can just be swapped out.

Silverlight 2 for Mobile: Developing for Mobile Devices
Mobile development gives you a lot of functionality with a very small footprint.
Somewhere it falls far short of windows and web development is when it comes to graphics. Generally the trade off of using the compact framework is dull looking forms, text and interactivity. While you can do pretty graphics, the work required renders it generally unfeasible.

Silverlight mobile looks to change all that, giving you the full Silverlight experience you'd get on the desktop with all the same awesome animation, vector graphics and interactivty.
For situations where you have a Silverlight website, you can have the mobile get a different experience by checking the type of device requesting the page and redirecting to different content. With Nokia as well as Windows Mobile phones supporting Silverlight, it's a really good way of standing out from the crowd.

Labels: , , , , , , , , ,

Friday, November 10, 2006

Tim Jeanes: Microsoft TechEd (Friday)

A session on creating secure websites today was a little disappointing in that we didn't learn much, but I took it as encouragement that we're already doing things the right way. (There was one small vulnerability that it brought up, but of course I can't tell you what that is until I've got back and fixed it in the one site it applies to. It's pretty well a one-line fix, so I don't feel too bad about that.)

Microsoft have a new product out for analysing the potential security risks in your websites, but as it mostly seems to be a matter of your ticking boxes to say what technology you're using and it then telling you what to watch out for, I think I'll stick to reading the relevant articles on MSDN.

The seminar "Accessibility in the AJAX age" was led by one of the contributors to the w3c standards for page accessibility. With browser technology moving forwards so quickly, and innovations such as AJAX driving the user experience forwards, it's encouraging to hear that accessibility devices such a screen readers are (just about) keeping pace with these changes. Though it's still extremely easy to confuse such devices (or human users with any of a range of disabilities) by writing poor html or css, so long as stick to the basic tenet of having your html say exactly what you mean, rather than using layout tricks to make the final result look like what you mean, then you're not going to go too far wrong. Making sure the only javascript event you rely on is the onclick event, and that you never expect anyone to click something that isn't a link or a button will give you reliable DHTML.

AJAX makes things a little trickier though. A blind user will know to click a link to expand a details panel, for example, but their screen reader will take a snapshot of the updated page with the "Please wait... loading" message you thoughtfully put in. As the completion of the asynchronous call to the server uses only javascript to update the page, this doesn't appear to the user. The way round this is to navigate a hidden IFrame to a blank page (with a GUID in the query string to prevent any caching issues). Screen readers will take this navigate event as its cue to reread the html and present the changes to the user.

These blogs, by the way, have been uploaded over the wireless network in free moments between sessions. It's pretty impressive that they've set up a network capable of supporting the needs of 6,000 people armed with laptops.

There's a short video of our exploits here.

Labels: , ,

Wednesday, November 08, 2006

Tim Jeanes: Microsoft TechEd (Wednesday)

We saw some more of LINQ this morning, and holy crap! - this is so going to change the way we work! It just makes it so easy to get your hands on exactly the data you need where and when you need it. When combined with the new anonymous classes in C# in .NET framework 3.0, you get all the type casting and intellisense you'd expect from a proper class, but without the hassle of creating a whole new class just for that one time you want to use it. So, on your customer list page you can create an anonymous class on the fly that holds just the details you want from the customer table (with any aggregate data from child tables), without having to make a "CustomerSummaryDetails" class to hold it. It's a beautiful thing.

I was very impressed with how LINQ saves data back to the database - it supports all common models for data concurrency and transactions right out of the box. However, it frightened me a little that if you query the same table twice, both resultant datasets will refer to the same object in memory. This has the potential to be either very powerful or very dangerous. Similarly, I'm not convinced we'll still have enough control over how LINQ saves changes to child tables. We caught the speaker at the Ask The Experts stand over lunch and though he put our minds at rest over some issues, we managed to throw him slightly with these kinds of questions, so I remained unconvinced.

I later attended an extended Q&A session with Anders Hejlsberg - the head of C# language design - who also had a big hand in LINQ. I think it'll take a bit of a paradigm shift on our part: whereas Gentle.NET takes snapshots of the data in the database and lets you play with them in object form, LINQ considers your objects to be a representation of the underlying data: you only have one instance of that object in memory, just as there is only one instance of the object in the database. Everything we already do is still possible (and slicker in many cases), but we'll just have to alter the way we handle our objects a little.

Hejlsberg talked about his future plans for C#. Microsoft will be taking their current support for partial classes one step further by enabling partial methods too: you can define the signature of a method in one half of your partial class and then instantiate it (if needed) in the other. (If you don't instantiate it then the compiler removes not only the method signature, but also all calls to that method.) This perfectly fits a problem we've hit regarding the validation of classes, one half of which has been created by a code generator.

We'd found a work-around, but as Hejlsberg said that this exact use is the main driver for introducing this new feature, it's nice to see that we're one step ahead of the game! Incidentally, Hejlsberg also said that partial classes were introduced in the first place to enable the safe regeneration of code after the underlying database changed. This is exactly the use we've made of them - it fixed the inheritance workaround we'd used before - another encouragement that our coding practises are right up there with the best of them! omg omg 1337 hax!

Another interesting session today was looking at the ASP.NET AJAX toolkit. Microsoft are providing a good-sized library of out-of-the-box AJAX controls, and though we've not had the business incentive to use them in the past, I think the ease of use I saw today means that we'll be incorporating these into our web applications in the very near future. They're supplying pretty well every type of control that will be commonly useful, and they're all vastly configurable. The demonstration also covered how to build your own AJAX control using the various helper libraries that Microsoft have prepared (that handle everything from the browser-to-server interface to ensuring your control will work under the varying DOM models implemented by all the major browsers). Quite frankly, building your own control looks pretty horrendous, and it's the sort of thing you'll quickly forget unless you do it every day. However, as with most technologies it's enough to know that it can be done, and the ample resources on the web will fill in the gaps as and when you need them.

The session entitled 'Encrypting Without Secrets' took a look at the strengths and weaknesses of public/private key-pair encryption, highlighting the issue that all this generally achieves is transferring what the secret is from one thing to another. Initially your secret is that one big critical document, or perhaps your credit card details; after encryption you tend not to worry too much about who gets to see that encrypted text, so the secret now becomes your private key. Unfortunately, a private key is a lot smaller than a whole bunch of company secrets, and getting your hands on the key unlocks a whole load of valuable information. Typically the private key is kept on the server as the encrypted information, merely for convenience's sake. Avoiding this much-overlooked weak link in the chain is a fascinating topic, especially if you're not to introduce any other new weaknesses, whilst keeping your secure systems usable.

I really hope they do something different for lunch tomorrow though - they've served the same thing two days running now, and though I'm generally not averse to paella, I am when it tastes like that...

Labels: , , , , ,

Tuesday, November 07, 2006

Neil Bostrom: Microsoft TechEd (Tuesday)

ASP.NET AJAX
Previously known as "Atlas", this is Microsoft's open source implementation of AJAX. When I say open source, the client scripting is open source and is compatible with all major current browsers (IE, Firefox, Netscape and Safari - even on the Mac). This client scripting is being developed by the community in an open source fashion.

Server side scripting for this technology is Microsoft's usual closed source but is only compatible with ASP.NET so no real reason to make it open source. A lot of the server side work is drag-and-drop; you can change most of your existing code to start using the power of AJAX (when appropriate).

Neat features with this AJAX framework are that it will plug straight into existing web services. and has bridging code to allowing AJAX script to seamlessly call current web services.

SQL Server 2005: Advanced Indexing Strategies
All of this session made me see that I need to learn a lot more about sql server! and soon!

Summary of this session was try to always have a clustered index of your standard tables. Try to make the clustered index narrow (limited fields), unique (identity field, datetime / identity or GUID) and small (Identity). Sometimes the best non clustered indexes are the ones that cover a lot of fields. This gives the sql optimizer a bunch more options.

Kimberly Tripp knows her stuff and is incredibly passionate about SQL server and all it entails. She has made a bunch of online webcasts discussing almost every aspect of sql server and getting the most out of it. As soon as I get back to the office I will be downloading them all!

Language Integrated Query (LINQ) Framework
I personally believe this is the best thing to come out of TechEd: It's Gentle.NET on steroids backed by Microsoft. It's a well thought through framework for querying almost anything inside .NET. Objects in memory, you want to filter them? Job done. Sort, group, aggregate? Job done. You want to do all that with data from sql server? Job done. You want to all that with xml document / web services? Job done.

I believe this will fundamentally change how I write my code and I'm picking up a copy as soon as I can!

Visual C# IDE Tips and Tricks
Class Diagrams - You can drag framework classes into the class diagrams to explore them in more detail
Refactoring - All the refactoring in C# is code snippet based, meaning you can change the refactoring to suit your needs
Debugging - You can control more closely what is debugged and how it's displayed using the Debugger attributes available in the framework

Labels: , , , , , ,