Friday, September 17, 2010

Azure Links

Credit to Neil Mackenzie for this list - fromhttp://nmackenzie.spaces.live.com/blog/cns!B863FF075995D18A!706.entry

Azure Team

http://blogs.msdn.com/b/azuredevsupport/ – Azure Support Team

http://blogs.msdn.com/b/dallas/ – Microsoft Codename Dallas

http://blogs.msdn.com/b/sqlazure/ – SQL Azure Team

http://blogs.msdn.com/b/cloud/ - Windows Azure Developer Tools Team

http://blogs.msdn.com/b/windowsazurestorage/ – Windows Azure Storage Team

http://blogs.msdn.com/b/windowsazure/ – Windows Azure Team

Individual

http://blogs.msdn.com/b/partlycloudy/ – Adam Sampson

http://bstineman.spaces.live.com/blog/ – Brent Stineman (@BrentCodeMonkey)

http://blog.structuretoobig.com/ – Brian Hitney

http://channel9.msdn.com/shows/Cloud+Cover/ – Cloud Cover (@cloudcovershow)

http://www.davidaiken.com/ – David Aiken (@TheDavidAiken)

http://davidchappellopinari.blogspot.com/ – David Chappell

http://geekswithblogs.net/iupdateable/Default.aspx – Eric Nelson (@ericnel)

http://gshahine.com/blog/ – Guy Shahine

http://blogs.msdn.com/b/jmeier/ – J.D. Meier

http://blogs.msdn.com/b/jnak/ – Jim Nakashima (@jnakashima)

http://blog.maartenballiauw.be/ - Maarten Balliauw

http://nmackenzie.spaces.live.com/blog/ Neil Mackenzie (@mknz)

http://azuresecurity.codeplex.com/ - Patterns & Practices: Windows Azure Security Guidance

http://oakleafblog.blogspot.com/ – Roger Jennings (@rogerjenn)

http://dunnry.com/blog/ – Ryan Dunn (@dunnry)

http://scottdensmore.typepad.com/blog/ – Scott Densmore (@scottdensmore)

http://blog.smarx.com/ - Steve Marx (@smarx)

http://blogs.msdn.com/b/sumitm/ - Sumit Mehrotra

http://azure.snagy.name/blog/ – Steven Nagy (@snagy)

http://blog.toddysm.com/ - Toddy Mladenov (@toddysm)

Azure Status

http://www.microsoft.com/windowsazure/support/status/servicedashboard.aspx – Azure Status

Other Clouds

http://highscalability.com/ – High Scalability

http://perspectives.mvdirona.com/ – James Hamilton

http://www.allthingsdistributed.com/ – Werner Vogels

SQL Azure Management - Backup and Monitoring

SQL Azure Backup and Restore
SQL Azure does not support the normal SQL Server BACKUP commands.

It does provide inherent data redundancy and reliability. However, this will not help if:
  • There is an app bug which corrupts your data.
  • There's a hacker who destroys your data
  • The Microsoft's datacenter loses all of your data (unlikely but possible)
To cope with these scenarios, there are two mechanisms currently available to backup your data:
  • You can use the SQL Azure copy commands to copy your database contents to a second, still stored within SQL Azure - this will protect again only the first problem above (assuming the hacker has a way into your Azure store)
  • You can use the open source SQL Azure Migration Wizard to download data to a local copy - this will provide a recovery mechanism for all 3 items above
The use of this second tool is discussed further below:

SQL Azure Data Migration

Warning - using this for a backup process will involve a large amount of data transfer (which will cost money), but it's better than not having a backup at all.

Backup

To use this tool:
  1. download it from http://sqlazuremw.codeplex.com/
  2. choose "Analyze and migrate T-SQL database"
  3. choose the Azure database - yourserver.database.windows.net - username - username@yourserver - and password.
  4. Note that you can only connect to the SQL azure database from IP addresses whitelisted on the firewall settings on the SQL Azure web control panel
  5. choose "[databaseName]"
  6. choose "script all database objects"
  7. hit "next" and it will slowly happen
  8. choose your local SQL server to connect to
  9. create a new SQL server database
  10. hit "next" to insert the data into your local database
For restore, you need to go in the opposite direction

Restore

To do this:
  1. typically suspend the Azure web application
  2. use the Azure web user interface to drop the existing SQL Azure database
  3. run the steps above in reverse - from local to SQL Azure
  4. restart the Azure web application.
Notes:
    1. connect to SQL Azure using SQL Server Management Studio
    2. open a "New Query"
    3. type "CREATE DATABASE backupName AS COPY OF mainName"
    4. Hit Execute

      The state of the copy can then be monitored using "select name, state, state_desc from sys.databases where name = 'backupName"
Note that costs of running multiple databases on Azure suggest that you should not keep taking more and more backups and storing them all within SQL Azure.

SQL Azure Monitoring
There really isn't much that can currently be done in the way of monitoring the health of an Azure SQL Server.

This http://msdn.microsoft.com/en-us/library/ff394114.aspx document describes the ability to query:
  • Database size
  • Number of connections - and their activity
  • Some simple query performance
However, this doesn't really provide any clue as to monitoring the database "health" - e.g. uptime/status, loading, etc.

There is some access to overall status at http://www.microsoft.com/windowsazure/support/status/servicedashboard.aspx - but this is at a very coarse level.

The only current suggestions for checking a SQL server instance is alive are:
  • just rely on Microsoft uptime (under their SLA) - not ideal
  • use tools like Nagios to add "HTTP" monitoring to Azure applications connected to the SQL Server database - use this web monitoring to check the health of the server (at least to check it is alive).
  • try to build something (e.g. a web app) based around sys.dm_exec_connections (http://msdn.microsoft.com/en-us/library/ff394114.aspx) which would provide some analysis of loading.
  • try to extend the enzo SQL library - http://enzosqlbaseline.codeplex.com/ - it's benchmarking tools might give you some clue on current loading (but this monitoring might also impact your current performance).

Thursday, September 16, 2010

If you can't run the Visual Studio wizard for SharpArchitecture

If you see a series of messages like "A problem was encountered
creating the sub project 'sharp.Core'. A project with that name is
already opened in the solution."

Then it could be due to problems with AnkhSVN - see
http://www.softweb.net.au/blogs/development/sharp-architecture-new-project-wizard-is-incompatible-with-ankhsvn

So I had to uninstall source control to get it working....

Tuesday, September 14, 2010

Azure - stuck in Initialising-Busy-Stopping...repeat

This link seems a good reference!
 
http://blog.toddysm.com/2010/01/windows-azure-deployment-stuck-in-initializing-busy-stopping-why.html

Some points:
  • missing dependencies
  • problems with initialising WAD (Azure Diagnostics connection string)
  • problems with other connection strings
  • lack of permission (medium trust!)

If you hit a problem with ConfigMonitoringPoll - Polling for configuration changes - when using Azure Diagnostics

Reported as:
Polling for configuration changes:Microsoft.WindowsAzure.StorageClient.StorageClientException: The specified blob does not exist. ---> System.Net.WebException: The remote server returned an error: (404) Not Found. at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at Microsoft.WindowsAzure.StorageClient.EventHelper.ProcessWebResponse(WebRequest req, IAsyncResult asyncResult, EventHandler`1 handler, Object sender) --- End of inner exception stack trace --- at Microsoft.WindowsAzure.StorageClient.Tasks.Task`1.get_Result() at Microsoft.WindowsAzure.StorageClient.Tasks.Task`1.ExecuteAndWait() at Microsoft.WindowsAzure.StorageClient.CloudBlob.DownloadToStream(Stream target, BlobRequestOptions options) at Microsoft.WindowsAzure.Diagnostics.ControlChannel.<>c__DisplayClass10.<ConfigMonitoringPoll>b__f() at Microsoft.WindowsAzure.Diagnostics.ControlChannel.TryExpectError(HttpStatusCode status, Action act) at Microsoft.WindowsAzure.Diagnostics.ControlChannel.ConfigMonitoringPoll(Object sender, ElapsedEventArgs args); TraceSource 'WaWebHost.exe' event

Then the problem might be that you must initialise the Azure Diagnostics from the start of the WebRole - and not from the start of app in Global.asax - just add this new file to your webrole project:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using Microsoft.WindowsAzure.ServiceRuntime;

namespace MyProject.Web

{

public class WebRole : RoleEntryPoint

{

public override bool OnStart()

{

AzureDiagnostics.InitializeAzureDiagnostics();

return base.OnStart();

}

}

}

Adding Diagnostic monitoring to Azure

If you want to get some diagnostics from Windows Azure deployed applications then follow the instructions on: http://msdn.microsoft.com/en-us/library/ee843890

This gives you a solution like:

    public static class AzureDiagnostics

    {

        public static void InitializeAzureDiagnostics()

        {

            // do not run this code if we're not running in the cloud.

            if (!Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.IsAvailable)

                return;

 

            // Enabled the capture of partial crash dumps

            Microsoft.WindowsAzure.Diagnostics.CrashDumps.EnableCollection(false);

 

            // configure and start the diagnostics

            DiagnosticMonitorConfiguration dmc = DiagnosticMonitor.GetDefaultInitialConfiguration();

 

            AddPerformanceCounters(dmc);

            AddLogs(dmc);

            AddSystemEventLog(dmc);

            AddInfrastructureLogs(dmc);

 

            DiagnosticMonitor.Start("DiagnosticsConnectionString", dmc);

        }

 

        private static void AddInfrastructureLogs(DiagnosticMonitorConfiguration dmc)

        {

            dmc.DiagnosticInfrastructureLogs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;

            dmc.DiagnosticInfrastructureLogs.ScheduledTransferPeriod = TimeSpan.FromMinutes(10.0);

        }

 

        private static void AddSystemEventLog(DiagnosticMonitorConfiguration dmc)

        {

            // Add event collection from the Windows Event Log

            dmc.WindowsEventLog.DataSources.Add("System!*");

            dmc.WindowsEventLog.ScheduledTransferLogLevelFilter = LogLevel.Verbose;

            dmc.WindowsEventLog.ScheduledTransferPeriod = TimeSpan.FromMinutes(10);

        }

 

        private static void AddLogs(DiagnosticMonitorConfiguration dmc)

        {

            dmc.Logs.ScheduledTransferPeriod = TimeSpan.FromMinutes(10);

            dmc.Logs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;           

        }

 

        private static void AddPerformanceCounters(DiagnosticMonitorConfiguration dmc)

        {

            List<string> counters = new List<string>();

            counters.Add(@"\Processor(_Total)\% Processor Time");

            counters.Add(@"\Memory\Available Mbytes");

            counters.Add(@"\TCPv4\Connections Established");

            counters.Add(@"\ASP.NET Applications(__Total__)\Requests/Sec");

            // These network interfaces removed - not that interesting for now

            //counters.Add(@"\Network Interface(*)\Bytes Received/sec");

            //counters.Add(@"\Network Interface(*)\Bytes Sent/sec");

            foreach (string counter in counters)

            {

                PerformanceCounterConfiguration counterConfig = new PerformanceCounterConfiguration();

                counterConfig.CounterSpecifier = counter;

                counterConfig.SampleRate = TimeSpan.FromSeconds(10);

                dmc.PerformanceCounters.DataSources.Add(counterConfig);

            }

            dmc.PerformanceCounters.ScheduledTransferPeriod = TimeSpan.FromMinutes(5.0);

        }

    }

 

 

Monday, September 13, 2010

Re: "The "COM0" port did not open." Bada device development

If you're trying to debug a Bada device and you see "The "COM0" port
did not open." under the entry for the Broker.exe in the Bada IDE
Console, then:

1. If it's the first time you've ever tried to connect then check that
you've installed the necessary USB drivers and have the device
attached.
2. If you've previously been using this fine, but this has suddenly
stopped working then try:
--- rebooting your phone
--- killing broker.exe in the PC task manager
--- setting your phone's USB connect to Samsung Kies or to Mass
Storage, and then using Run As rather than Debug As in the IDE
--- hit the task manager on the phone and choose "End All Applications"

I'm not entirely sure what worked for me... but I think it was a
combination of the last few in the end!

Saturday, August 21, 2010

Setting up a Samsung Wave (Bada) for debugging

Full instructions here - http://www.careace.net/2010/08/07/run_your_wave_app_on_actualdevice/

So far seems to work very well (although it does seem to help if you disconnect and reconnect the Wave between each debug session!)

Wednesday, August 18, 2010

View Stored Procedure Source Code

If you want to see the raw SQL behind your stored proc (like you can
in SQL Server Management Studio) then use:

EXEC sp_HelpText 'your procedure name'

Found in http://stackoverflow.com/questions/467482/how-do-i-programmatically-retrieve-sql-server-stored-procedure-source-that-is-ide

Sunday, July 11, 2010

A problem with "The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF"

Something changed on one of the web services I was using - suddenly one of my requests was failing with a WebException - 

The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF


To fix this I had to add this to my web.config/app.config:

<system.net>
    <settings>
      <httpWebRequest useUnsafeHeaderParsing="true" />
    </settings>
</system.net>

Simples ;)

Friday, May 21, 2010

Low Pass Javascript

As part of the runsat work, I've had a continual battle to get elevation results "realistic"

This is particularly challenging because of "noise" in the sampled elevation data.

The latest attempt at this, has been to use a low pass filter - based on work at http://mshook.appspot.com/z/firkernel.htm - to smooth the elevation data.

You can see the effect:

Wednesday, April 28, 2010

Speeding up ASP.NET debugging on XP (I hope!)



The original line reads:

     <compilation debug="true" strict="false">

and we changed it to

     <compilation debug="true" strict="false" optimizeCompilations="true">

So we added one switch (during the development cycle).

But to get this working, you might need to install something like:

http://support.microsoft.com/kb/961884

Thursday, February 25, 2010

Blocking user agents in IIS7

I had a problem with a very specific User-Agent - GBPlugin from Brazil.

Not sure why but this User-Agent was blocking IIS7 (not my ASP.Net app but IIS7 itself :/)

To solve this, I tried blocking GBPlugin a few ways - URLScan, RequestFiltering and my own custom http module. However, eventually I worked out how to do it using the generic URL rewrite module:

Although I of course configured this using the IIS UI not going direct to the .config files - just felt safer on the live server.

Monday, February 15, 2010

Enabling Screen Rotation on Samsung Omnia II phone - also enabling classic Microsoft Settings Control Panel

It took a little finding - but together these guys give the solution:


Two registry keys to change:

  1. HKLM\System\GDI\Rotation\HideOrientationUI and change the value to 0
  2. HKEY_LOCAL_MACHINE\Security\Shell\StartInfo\HideSettings change to 0

Monday, February 08, 2010

Getting SQLite to work in PHP (PHP5) on Windows Server

I just wanted to use the existing code....

But it seems PHP5 underwent a big change in "PDO" for SQLite.

I went around the houses looking at errors like "Class 'SQLite3' not found php" and " Fatal error: Call to undefined function sqlite_open()"

But... finally I found: http://djhweb.co.uk/sqlite1.htm

So I had to change the code:

$db = sqlite_open('filename',0666)

to 

$db = new PDO('filename');

Then:

$res = sqlite_query($db, $query, SQLITE_ASSOC);

to

$res = $db->query($query);

And:

$row=sqlite_fetch_array($res);

to

$row=$res->fetch(PDO::FETCH_ASSOC);

I might have got some of this wrong... but hopefully not!

If you hit "SQLSTATE[HY000] [14] unable to open database file" then that means you need to open up read/write permissions on the database directory.

Friday, February 05, 2010

Doing IE6 testing

You don't want to, but sometimes you have to

When you do, then IE6 testing can be quite easily done using IETester - fab - http://www.my-debugbar.com/wiki/IETester/HomePage

Sunday, January 31, 2010

Just in case I need to use PHPMailer again...

The important line was $mail->SMTPAuth = true.

Thanks to:
http://www.fasthostinghelp.com/send-mail-using-phpmailer-t98.html

$mail = new PHPMailer(); 

$mail->IsSMTP(); // send via SMTP 
$mail->Host = "mail.domain name"; // SMTP servers 
$mail->SMTPAuth = true; // turn on SMTP authentication 
$mail->Username = "Domain Email account"; // SMTP username 
$mail->Password = "password of an email account"; // SMTP password 

$mail->From = "From email account – from above mentioned domain"; 
$mail->FromName = "From Name here"; 
$mail->AddAddress("To Email account here ","Display name"); 
$mail->AddReplyTo("Reply to email account here ","Details"); 

$mail->WordWrap = 50; // set word wrap 

$mail->IsHTML(true); // send as HTML 

$mail->Subject = "Subject Line of the email"; 
$mail->Body = "Body part of the message – email details</b>"; 
$mail->AltBody = "Alternate part of the body"; 

if(!
$mail->Send()) 
{ 
echo 
"Message did not sent <p>"; 
echo 
"Mailer Error: " . $mail->ErrorInfo; 
exit; 
} 

echo 
"Message has been sent"; 

?>

Thursday, January 28, 2010

Writing a DNN skin - need to get parent tab name

John Mitchell to the answer:

http://www.snapsis.com/DotNetNuke/Support/tabid/560/aff/12/aft/5003/afv/topic/Default.aspx

Have you ever wanted to get at more than just <%= SkinPath %>in your skin?

Maybe you want to display the name of the currently Active Page?

<%=PortalSettings.ActiveTab.TabName %>

Or maybe you want to display the name of the Active Page's Root level Parent?

<%=PortalSettings.ActiveTab.BreadCrumbs(0).TabName%>

If you want the currently Active Page's immediate Parent Tab Name try this:

<%=PortalSettings.ActiveTab.BreadCrumbs(PortalSettings.ActiveTab.Level - 1).TabName %>

Thursday, January 21, 2010

When Visual Studio 2008 keeps crashing

It's happened to me before and it's so annoying

Visual Studio just crashes and crashes and crashes - and it's not so easy to work out what to do...

First try the log file:
http://blogs.msdn.com/saraford/archive/2008/11/27/did-you-know-there-s-a-way-to-have-visual-studio-log-its-activity-for-troubleshooting-366.aspx

Then try the reset commands... basically type /? on the command line and you get options like /resetskippkgs and /resetaddin and /resetsettings

I'll try anything - I just want to get on with work!

Friday, January 15, 2010

MonoTouch - if you can't see any Provisioning Profiles

If MonoDevelop can't see any Provisioning Profiles, but XCode can, then maybe just maybe:

Distribution identity is not shown in MonoDevelop project signing options

MonoDevelop 2.2 has a bug that causes it not to detect distribution certificates that contain a comma. Apreview build of MonoDevelop 2.2.1 is currently available that fixes this issue.



This worked for me!

Wednesday, January 13, 2010

UITabBarController (kind of) inside a Modal child view

I've been playing quite a bit with MonoTouch - love it

It won't be a long term solution I feel (I *think* Silverlight is coming to the iPhone soon!) but it is a good solution for me right now.

One of the problems I've had is trying to get a UITabBarController to work in a child View - basically I just can't work out how to do this in Interface Builder.

To work around it I tried this code instead - using a UITabBar and custom linking code rather than using the "full" UITabBarController.

public override void ViewDidLoad ()
{
base.ViewDidLoad ();
childOne.Text = "one";
childTwo.Text = "two";
mainView.AddSubview(childOne.View);
mainView.AddSubview(childTwo.View);
mainView.BringSubviewToFront(childOne.View);
tabbar.SelectedItem = tabitemOne;
tabbar.Delegate = new MyUITabBarDelegate(this);
}


class MyUITabBarDelegate : UITabBarDelegate
{
TabViewController tvc;
public MyUITabBarDelegate (TabViewController _tvc)
{
tvc = _tvc;
}
public override void ItemSelected (UITabBar tabbar, UITabBarItem item)
{
if (item.Tag == 0)
{
tvc.mainView.BringSubviewToFront(tvc.childOne.View);
//while (tvc.mainView.Subviews.Count() > 0)
// tvc.mainView.Subviews[0].RemoveFromSuperview();
//tvc.mainView.AddSubview(tvc.childOne.View);
}
else
{
tvc.mainView.BringSubviewToFront(tvc.childTwo.View);
//while (tvc.mainView.Subviews.Count() > 0)
// tvc.mainView.Subviews[0].RemoveFromSuperview();
//tvc.mainView.AddSubview(tvc.childTwo.View);
}
}
}



Some initial MonTouch links

Doing MonoTouch stuff - and really quite enjoying myself!

I'd better make it pay though....


The monotouch forums are very useful - lots of code snippets around!

Monotouch.info is a good place to look for links

If you want to write games using Cocos, then check out:

This is a super tutorial

Craig Dunn's blog contains some very helpful posts:

Another blog/tutorial

Not monotouch, but useful for that real deployment stage,,,

StackOverflow is always a good place:
e.g. look at this level of info for writing a file - http://stackoverflow.com/questions/1829954/write-to-a-file-in-monotouch

Not monotouch, but for testing apps, this looks interesting:

Monday, January 11, 2010

A really good guide to url rewrite rules

Coupling an indecipherable language (regex) with a few flags to achieve lots of unexpected effects...

http://articles.sitepoint.com/article/guide-url-rewriting

Mainly posting this here as I keep hitting snags with my Wordpress MU installation on IIS

Tuesday, January 05, 2010

Setting up wordpress MU to work with authenticated SMTP Mail Server


I really don't like having sendmail running on a webserver, but some features of WordPressjust don't work if it can't send email (user registration, for example). Still, WordPress offers support to send email through external SMTP servers instead if a local mailer.

In /wp-includes/pluggable.php around line 377, change

 	$phpmailer->isMail();

to

 	$phpmailer->isSMTP();

Then, in /wp-includes/class-phpmailer.php around line 155, set your SMTP host:

     var $Host        = "my.smtphost.com";

You may also need to set a username and password, and tell WP to attempt authentication. You'll see those in the lines below the hostname variable.

     var $SMTPAuth     = true;     var $Username     = "username";     var $Password     = "password";

On the other hand, you could do this via a plugin, perhaps even Callum McDonald's WP MailSMTP.


For my redfoxhosting hosted SMTP server, the settings were:
true
password

Easy (but took 4 go's to get right!)

Thursday, December 17, 2009

YQL, Pipes and beyond

I've recently fallen in love with Yahoo again

Inspired by Haayman (a runsat user) I've been using Yahoo pipes to manipulate the site RSS output into more human friendly form.

The latest bit of this is here: http://pipes.yahoo.com/runsaturday/osmfeed -


Inspired by http://blog.pipes.yahoo.net/2009/06/01/using-yql-execute-to-power-the-pipes-webservice-module/ this pipe just shows how developed the web is now...

- it gets data from runsat
- processes that data
- makes a call to YQL which then processes the data through this serverside javascript - http://www.slodge.com/yql/pipe5.xml (this converts a google maps API
- processes the data some more
- spits out some new RSS which can then be consumed by web pages - e.g. by http://hollybar.blogspot.com

Of course, all of this could also be seen as fragile - it relies on external web services, but these are all on Yahoo! - so not too fragile (I hope!).

The programmable web - I love it!

Sunday, December 13, 2009

More player code live on runsaturday

A "simple" player:









A player with side map and elevation/speed chart:



Tuesday, November 17, 2009

"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."

If you're working late at night and suddenly you start seeing lots of https issues concerning... "The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."

Then it might just be because your app is routing its requests via the excellent fiddler2 - in which case SSL will not be trusted :)


Monday, November 16, 2009

Hard disk thrashing on Vista

I've been struggling recently with far too much hard disk thrashing.

So I searched around for help, and I've no idea if their advice helps yet, but this article seemed at least well written:
http://bucarotechelp.com/computers/windowsts/95021801.asp?x=62&y=6&page=1

Let's hope it helps - because recently the hard disk action has been way too slow!

Super easy to use (and free) POP3 email client source code

Really good project!
http://www.codeproject.com/KB/IP/Pop3MimeClient.aspx?fid=341657

Super easy to follow walkthrough for creating a custom DNN scheduled task

Super easy to follow walkthrough for creating a custom DNN scheduled task -

Really good stuff

Wednesday, November 11, 2009

Visual Trace Route

Just found this on the web. It wasn't what I was looking for - but it's a cool toy - let's you see some cute tracert maps
http://www.yougetsignal.com/tools/visual-tracert/

Would be fabulous if they could actually use my tracert results rather than their results.

Tuesday, November 10, 2009

JSON and cross site scripting

Been doing quite a lot of JSON work recently.

Have hit the odd occasion where I've needed to get JSON data across domain boundaries.

To do this, the only way seems to be to make use of <script> tags rather than making use of simple (e.g. Jquery) xml/http get's.

Basically what you do is:

1. Define a callback method, e.g.:

function myCallback(data)
{
// do stuff
}

2. On the server, instead of returning JSON, return the JSON inside a callback call, e.g.:
myCallback({ "thing": 12 });

3. To make the ajax call, then add a script tag to the document head:
            var scriptBlock = document.createElement('script');
            scriptBlock.src = jsonUrlToCall;
            scriptBlock.type = 'text/javascript';
            document.getElementsByTagName('head')[0].appendChild(scriptBlock);

4. Actually, that's it!

Tuesday, November 03, 2009

Samsung Omnia 2... GPS - the only setttings that work

More about this another day...

But have wasted so much time on trying to get Samsung Omnia II to hook up to GPS today...

Whatever you do, don't change the default settings:

Go to setting --> General Setting --> GPS --> Connection 
GPS program port: com7
GPS hardware port:com9
Baud rate: 4800
Click on done.
Go to XTRA
Enable XTRA Server
Tick "ZWhen connected to PC via ActiveSync
Enable SNTP Server (Only when you have data plan)
Click done.

These settings work!


Some color code to make some javascript HTML colors darker

I needed to quickly produce some new darker colours for an array of html colors.

Using this:
http://blog.lotusnotes.be/domino/archive/2007-08-04-javascript-color-functions.html

I built this:
    <div id='outputLifeLine'>
    </div>
    <script type="text/javascript">
        var arr = [[-18, '#00ff00'],
        [-4, '#aaff00'],
... snip...
        [18, '#ff2200']];

        var G = {}, $ = function(a) { return document.getElementById(a) };

        G.color = {
            rgb: function(a) {
                var o = a.toLowerCase();
                return [parseInt(o.slice(0, 2), 16), parseInt(o.slice(2, 4), 16), parseInt(o.slice(4), 16)];
            },
            shade: function(a, b) {
                var v = [], i;
                for (i = 0; i < 3; i++) {
                    v[i] = Math.round(a[i] * b)
                    if (v[i] > 255) v[i] = 255
                    if (v[i] < 0) v[i] = 0
                }
                return v
            },
            hex: function(a) { var f = G.color._hex; return f(a[0]) + f(a[1]) + f(a[2]) },
            _hex: function(a) { return ('0' + a.toString(16)).slice(-2) }
        };

        var txt = '';
        var m = G.color;
        for (var i in arr) {
            var n = m.rgb(arr[i][1].substr(1));
            txt += "[" + arr[i][0] + ",'" + arr[i][1] + "', '#" + m.hex(m.shade(n, 0.6)) + "'],";
            txt += "<br/>"
        }
        var d = document.getElementById("outputLifeLine");
        d.innerHTML = txt;

</script>

And then ran it... Nothing special... but thought I'd share it!

Monday, November 02, 2009

The perils of Javascript - Number.MIN_VALUE

Just spent some time debugging a problem....

I had a filter set up in my new player code on runsat - and when the filter was disabled I was setting the filter limits to Number.MIN_VALUE and Number.MAX_VALUE.

When a calculation results in a number greater than Number.MAX_VALUE, it is assigned a value of Number.POSITIVE_INFINITY.

When a calculation results in a number less than Number.MIN_VALUE, it is assigned a value of Number.NEGATIVE_ INFINITY.


However.... this is complete "codswollop" - actually MIN_VALUE is an epsilon value - it's the smallest positive fraction allowed in javascript - so it's not negative - in fact it's almost (but not quite) zero.

Looking around loads of sites contain big info on this!

Yikes!