Showing posts with label error. Show all posts
Showing posts with label error. Show all posts

Wednesday, 31 October 2018

Invalid File Handle - Movie Downloads Beware!

Invalid File Handle - Movie Downloads Beware!

By Strictly-Software

Recently I downloaded a film, Con Man (2018), however when I try to do anything with the file such as open, run, copy, move or delete it I get a Windows "Invalid File Handle" error message.

I did some research and found that on certain file systems such as NTFS, CDFS, exFAT, UDFS, FAT, and FAT32, there are some reserved file names that you should never use which causes this error. One of these is con. Others include: PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9.

I checked the filename of the movie and the person had only named it Con.Man.2018.1080p.mp4, meaning that Windows saw the filename as Con preventing me doing anything with this file.

At the moment it is permanently stuck on my file system as I cannot remove the files containing folder either.

I did have a copy of this file on a USB stick however which I could remove, obviously due to the different format of the USB disk drive. If I had used uTorrent to download the file directly to the USB drive instead of first to a folder on my Windows drive I wouldn't have had this issue.

I am basically looking for ways to remove this file as I cannot rename it to something else, either from Windows or the Command Prompt, to enable deletion.

I saw someone suggest renaming the file to \\.\Con.xxx but this does not work as I cannot get a file handle to rename it in the first place.

Therefore this is more of a warning write up than a "How To Guide", although you can be sure I will update this when I find a solution.

So if you are downloading files such as movies to your computer be careful and check the filename first and if you are using a tool such as a Torrent downloader ensure the downloaded file name is changed to something an NTFS or FAT type disk can handle, or download it straight to a USB drive with a different disk format which will allow file deletion.

For more information you can read this MSDN article, called "Naming Files, Paths, and Namespaces".

It states: Do not use the following reserved names for the name of a file: CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9. Also avoid these names followed immediately by an extension; for example, NUL.txt is not recommended.

I will update this when I get a solution.

Thursday, 22 August 2013

Handle jQuery requests when you want to reference code that hasn't loaded yet

Handle jQuery requests when you want to reference code that hasn't loaded yet

As you should be aware it is best practise to load your JavaScripts at the bottom of your HTML for performance and to stop blocking or slow load times.

However sometimes you may want to reference an object that is not yet loaded higher up in the page.

If you are using a CMS or code that you cannot change then you may not be able to add your event handlers below any scripts that maybe needed to use them. This can cause errors such as:

Uncaught ReferenceError: $ is not defined 
Uncaught ReferenceError: jQuery is not defined

If you cannot move your code below where the script is loaded then you can make use of a little PageLoader function that you can pass any functions to and which will hold them until jQuery (or any other object) is loaded before running the functions.

A simple implementation of this would involve a setTimeout call that constantly polls the check function until your script has loaded.

For example:


PageLoader = { 
 
 // holds the callback function to run once jQuery has loaded if you are loading jQuery in the footer and your code is above
 jQueryOnLoad : function(){}, 

 // call this function with your onload function as the parameter
 CheckJQuery : function(func){
  var f = false;

  // has jQuery loaded yet?
  if(window.jQuery){
   f=true;
  }
  // if not we store the function if first time in loop otherwise and set a timeout
  if(!f){
   // if we have a function store it until jQuery has loaded
   if(typeof(func)=="function"){    
    PageLoader.jQueryOnLoad = func;
   }
   // keep looping until jQuery is in the DOM
   setTimeout(PageLoader.CheckJQuery,200);
  }else{
   // jQuery has loaded so call the function
   PageLoader.jQueryOnLoad.call();    
  }
 }
}


As you can see the object just holds the function passed to it in memory until jQuery has been loaded in the DOM. This will be apparent because window.jQuery will be true.

If the object isn't in the DOM yet then it just uses a setTimeout call to poll the function until it has loaded.

You could increase the length of time between the polls or even have a maximum limit so that it doesn't poll for ever and instead after 10 loops returns an error to the console. However this is just a simple example.

You would call the function by passing your jQuery referencing function to the CheckJQuery function like so.


<script>
PageLoader.CheckJQuery(function(){
 $("#myelement").bind('click', function(e) { 
  // some code
  alert("hello");
 });
});
</script>


It's just a simple way to overcome a common problem where you cannot move your code about due to system limitations but require access to an object that will be loaded later on.

Tuesday, 14 May 2013

Handling unassigned local variable errors with struct objects in C#

Handling non assigned struct objects in C#

If you have ever used structs and had use of unassigned local variable errors from your editor i.e Visual Studio then there is a simple solution.

The problem comes about because the compiler is not clever enough to realise that the struct object will always be initialised when used.

This is usually because the struct object is initialised within an IF statement or other code branch which makes the compiler believe that a similar situation to the "unreachable code" error has been detected.

As the compile cannot definitely tell that the struct object will always be initialised when it gets used it will raise a compile error.

In Visual Studio it will usually show up with a red line under the code in question with the error message "use of unassigned local variable ..."

Here is a simple example where the struct object is populated with a method and starts off in the main constructor method unassigned.

However because of the nature of the code and the fact that on the first loop iteration oldID will never be the same as currentID (as oldID starts off as 0 and currentID as 1) then the IF statement will always cause the this.FillObject method to run on each iteration.

Therefore the myvar variable which is based on a struct called myStructObj will always get populated with new values from the loop.

However the compiler cannot tell this from the code and will raise the "use of unassigned local variable myvar" error when I try to pass the object as a parameter into the this.OutputObject(myvar) method which just outputs the current property values from the object.
public class Test
{

 /* example of a method that believes the struct object won't get assigned even though due to the if statement it always will */
 public void Test()
 {

  myStructObj myvar;
  int oldID = 0; 

  /* just a basic loop from 1 to 9 */
  for(int currentID = 1; currentID < 10; currentID++)
  {
   /* as the oldID starts as 0 and currentID starts as 1 on the first loop iteration we will always populate the struct object with values */
   if(oldID != currentID)
   {
    /* populate our struct object using our FillObject method */
    myvar = this.FillObject(currentID, "ID: " + currentID.ToString());

    oldID = currentID;
   }

   /* try and parse our struct to a method to output the values - this is where we would get our red line under the myvar parameter being passed into the OutputObject method e.g. "use of unassigned local variable myvar" */
   this.OutputObject(myvar);
  }

 }

 /* Simple method to output the properties of the object to the console */
 private void OutputObject(myStructObj myvar)
 {
  Console.WriteLine(myvar.prop1);
  Console.WriteLine(myvar.prop2);
 }

 /* Simple method to populate the struct object with a string and integer value for both properties*/
 private myStructObj FillObject(string val1, int val2)
 {
  myStructObj myvar = new myStructObj();

  myvar.prop1 = val1;
  myvar.prop2 = val2;

  return myvar;
 }

 /* my struct object definition - using non nullable types */
 public struct myStructObj
 {
  public string prop1;

  public int prop2;
 }
}

Solution to use of unassigned local struct variable

The solution is to either to always initialise the object before you start the loop or to just use the default keyword to ensure your struct object variable is always set-up with default values.

Example Fix

myStructObj myvar = default(myStructObj);

This will get rid of those annoying red lines and use of unassigned local variable errors.

If your struct object is a value type then it calls the default constructor and if it's a reference type you will get a null that you can then test for before using it.

Simples!

Saturday, 24 March 2012

Logging and Suppressing JavaScript errors

Logging JavaScript errors to a file by overwriting the window.onerror method

Sometimes you may have intermittent JavaScript errors that you cannot re-produce or maybe you just want to be able to log JavaScript errors for later viewing. Or maybe you just want to suppress them so that end users don't see them.

By using the useful and also dangerous feature of being able to overwrite core JavaScript functions and objects you can utilise this to your advantage by overwriting the window.onerror method.

The window.onerror method takes 3 parameters which are:

  • message : the error message
  • url: the URL of the file that raised the error message
  • line: the line number that the error occurred on.


Therefore it is very easy to create your own window.onerror function to take these values and then make an AJAX call to a server side page which logs the JavaScript error details to a file or database or even sends an email.

Also by overwriting the window.onerror function we can suppress JavaScript errors if we chose to.

Maybe if we are debugging a script and don't want the error console constantly filled up or maybe some of our users are still using Windows 98 and use IE 4.

If we are using unobtrusive JavaScript that builds layer upon layer of functionality starting with the lowest common denominator e.g HTML, then adding JavaScript functionality if they have it, Flash if they have it and so on then we may want to just suppress these JavaScript errors in old browsers.

To suppress a JavaScript error you just need to return true.

This example uses jQuery seeing that is so popular but any AJAX library can be used. The point is that you are taking the error parameters and logging them somewhere useful.

I have used a little JavaScript wrapper object to set some system properties like a config object to define whether error logging is on or off and whether or not to suppress errors in older browsers. 

The code to define which browsers to suppress in can be left to you but I have done a simple test for document.getElementById which means browsers like IE 4 and NN4 won't get errors raised.


// Log JS errors to a file - file is overwritten each day only use when debugging a particular page/site

// Set up our global config options to decide whether to log JavaScript errors and whether or not to suppress them. A simple false/true could suffice but we might want to test for old browsers or certain features. If the browser doesn't support document.getElementById it's a pretty old browser!
GlobalSettings = {
 SystemName : "Strictly-Software",
 Version : 2.0.1,
 LogJSErrors : true,
 SuppressJSErrors : (document.getElementById) ? false : true
}

// override the onerror object
window.onerror = function(msg, url, line)
{   
 // does our global system want to log errors - this could be a Client or Serverside setting
 if (GlobalSettings.LogJSErrors)
 {  
                // using JQuery to post a GET request to a page that logs the error details
  $.get("logJSError.php", { message: msg, errorlocation: url, lineno: line } );
 }
 

 // do we still raise the error or for old browsers which might have a lot of errors do we try and supresss them? Use our global config options again.
 if(GlobalSettings.SuppressJSErrors){  
  // return true to suppress the error so its not raised to the console.
  return true;
 }else{
  // return false to raise the error to the console.
  return false;
 } 
}

Then all you need is to define your server side page logJSError.php (or whatever language you are using) to collect the error data from the request and do whatever you want with it e.g log it somewhere for later viewing.

Remember whilst being able to overwrite functions that already exist is good in certain situations like this and the Lazy Function scenario but it can also cause you severe debugging nightmares like the one I discovered when using the common addEvent naming convention for cross browser adding of events.

Therefore be careful especially when overwriting core JavaScript features but also use them to your advantage when possible.


Friday, 16 March 2012

WordPress - New Post page not loading and missing category list


Missing Categories and slow load time for New Post on Wordpress

I just had a weird issue with Wordpress in that everytime I tried to open a new post to write an article the page would hang forever and when it eventually loaded no categories would appear in the list on the right.

The categories were definitley there so I don't know why they weren't loading.

However I went through all my plugins and disabled some and updated others and I stumbled across what seems to the solution.

I had two SEO plugins installed - SEO  Ultimate and Yoast SEO for Wordpress.

I liked Yoast for the on-page SEO and Google term searching and I liked SEO Ultimate for the ability to edit .htaccess files and robots files as well as all the other reports (e.g 404) and other features.

However when I disabled SEO Ultimate the page suddenly worked. It loaded quickly and the categories all appeared in the sidebar.

I have no idea if these two SEO plugins were clashing or causing the problems I was experiencing but disabling the SEO Ultimate plugin seemed to fix the problem for me.

So if you have a similar issue and have both SEO plugins installed try disabling one or the other just to see if that fixes it for you as well.

Thursday, 10 November 2011

Error copying tables importing or exporting the Geography or Geometry data type in SQL 2008

Error importing and exporting the Geometry and Geography data types in SQL 2008

Today I had to make some work live that involved copying a database containing UK Postcodes and their related geo-location data to another SQL 2008 server.

The table contained a list of all UK Postcodes as well as their longitude and latitude and a GeoLocation column that was based on the new SQL 2008 DataType Geography.

However when I tried to use the Import/Export wizard to copy the data I got to the Review Data Type Mapping page and was met with the following error message.


Found 1 unknown column type conversion(s) You are only allowed to save the package.


Import Geography Error Screenshot

Viewing the full error details revealed that the problem was down to SQL not understanding the Geography data type in the table I wanted to export.


The full error message details are below:



[Source Information]
Source Location : (local)
Source Provider : SQLNCLI10
Table: [dbo].[Country]
Column: CountryGeography
Column Type: geography
SSIS Type: (Type unknown ...)
Mapping file (to SSIS type): C:\Program Files\Microsoft SQL Server\100\DTS\MappingFiles\MSSQLToSSIS10.XML

[Destination Information]
Destination Location : (local)
Destination Provider : SQLNCLI10
Table: [dbo].[Country]
Column: CountryGeography
Column Type: geography
SSIS Type: (Type unknown ...)
Mapping file (to SSIS type): C:\Program Files\Microsoft SQL Server\100\DTS\MappingFiles\MSSQLToSSIS10.XML

[Conversion Steps]
Conversion unknown ...
SSIS conversion file: C:\Program Files\Microsoft SQL Server\100\DTS\binn\DtwTypeConversion.xml


First of all I checked that the database compatibility mode was set to 100 (SQL 2008) and not 90 (SQL 2005) and once I had confirmed both databases were the correct format I checked the mapping conversion XML file on the server I was doing the import from.

This XML mapping file is located at the following path C:\Program Files\Microsoft SQL Server\100\DTS\MappingFiles\MSSQLToSSIS10.XML.

On opening the file I could see that there was no mention of the geography OR geometry data types which explained why the DTS package wizard could not carry out the operation.

To fix this I copied one of the other similar data types (varbinary) and re-inserted it into the file twice before changing the names to Geography and Geometry.

You can just copy and paste the following XML into the file.


  <!-- geography -->
  <dtm:DataTypeMapping >
    <dtm:SourceDataType>
      <dtm:DataTypeName>geography</dtm:DataTypeName>
    </dtm:SourceDataType>
    <dtm:DestinationDataType>
      <dtm:SimpleType>
        <dtm:DataTypeName>DT_IMAGE</dtm:DataTypeName>
      </dtm:SimpleType>
    </dtm:DestinationDataType>
  </dtm:DataTypeMapping>




  <!-- geometry -->
  <dtm:DataTypeMapping >
    <dtm:SourceDataType>
      <dtm:DataTypeName>geometry</dtm:DataTypeName>
    </dtm:SourceDataType>
    <dtm:DestinationDataType>
      <dtm:SimpleType>
        <dtm:DataTypeName>DT_IMAGE</dtm:DataTypeName>
      </dtm:SimpleType>
    </dtm:DestinationDataType>
  </dtm:DataTypeMapping>


Save the MSSQLToSSIS10.XML file and you should now be able to import or export a table that contains the datatypes geography and geometry.

If for some reason after editing the file it still doesn't work, try the following:

  • restarting the SQL Server service on the server you are running the export/import wizard from.
  • restarting your own SQL Server Client Tools.
  • If you are running a 64bit version of Windows 7 like I am then you might need to also edit the same file in the 32 bit Program folder e.g C:\Program Files (x86)\Microsoft SQL Server\100\DTS\MappingFiles\MSSQLToSSIS10.XML.

Tuesday, 12 July 2011

Firefox 5.0 Firebug 1.8 Memory Leak Problem

Firefox 5.00 with Firebug 1.8.0b5 on Windows 7 64 bit causes Memory Leak

I came across a problem with Firefox 5.0 and Firebug 1.8.0b5 today that basically leaked memory like an open oil well and hung my PC every time I tried to open up a basic popup window from a page using Javascript.

My PC is running the following:

Windows 7 - Dual Core - 64 Bit
Firefox.exe *32 - version 5.0
Firebug 1.8.0b5

This problem has only started occurring since my latest upgrade and I narrowed it down to Firebug by disabling each plugin one by one.

I can replicate the problem on one particular page quite easily which has a link with a simple javascript: window.open(url) function that opens up a little static html page.

When I now click the link the popup opens full size rather than the dimensions set 400px * 400px and there is nothing on the page - just a blank screen. Viewing the source shows nothing at all.

This page used to work fine before the update.

It still works on all other browsers Chrome, Safari, IE (6 to 9) and it still works in Firefox 5.0 on 32 bit machines so I am not sure whether it's a 64 bit problem or not.

Viewing my Task Manager window I can open Firefox and I can get my Firefox to use beyond 1GB of memory and 50% CPU (the whole of one of my two processors) with only one single window and tab open all within 5 minutes.

Earlier today it was using over 3GB of memory!

Another clue is the fact that the error console is permanently full of these error messages:

attempt to run compile-and-go on a cleared scope
resource://firebug_rjs/console/errors.js
line 156

Hitting clear just fills up the whole of Firebug's console log instantly with the same message.

The only way I have found to solve this problem is to disable Firebug and not use the "Restart Firefox" link as this seems to just ramp the memory up without shutting the process down first.

I usually have to kill the process through Task Manager as clicking the close button doesn't do anything the majority of the time.

If anyone else has similar problems please let me know.


Saturday, 22 May 2010

Problems with LINUX, Apache and PHP

LINUX Apache Server stopped serving up PHP pages

By Strictly-Software

When I logged into my hosted LINUX web server earlier tonight I was met with a message saying I should install a number of new packages.

I usually ignore things like this until it gets to a point where someone forces me to do purely for reasons that will shortly become obvious.

The packages were the following:
  • apache2.2-common
  • apache2-mpm-worker
  • apache2
  • usermin
  • libapt-pkg-perl
  • apt-show-versions
  • webmin
  • webmin-virtual-server
I have no idea what most of them do but they had been sitting around for a long time waiting for me to install them and tonight was the night. These are always nights I dread!

Shortly after doing the updates I noticed that my WordPress sites had stopped working and all the PHP files were being served up as file attachments with a content type of application/x-httpd-php instead of being parsed, executed and then delivered as text/html.

At first I thought it was something to do with the SQL performance tweaks I was doing but I soon remembered about the updates and I went off hunting the web for a solution.

It's nights like these that make me wish I was back doing carpet fitting, finishing the day at 3 pm and then going down the pub. Much more enjoyable than spending Friday nights scratching my head wondering what the hell I had done to bring down my websites at 3 am.

To cap off the nightmare I had just spent ages writing a detailed message to post on an APACHE web forum only for my session to timeout and then for the site to refuse to log me in.

They then decided to block me for failing 5 login attempts in a row. Obviously I couldn't get back my message so I was pretty pissed right now!

For some reason APACHE had stopped recognising PHP file extensions and I still don't know what had happened under the covers but after a long hunt on Google I came across the solution.

The libapache2-mod-php5 module had somehow disappeared so I had to re-install it with the following lines:

sudo apt-get purge libapache2-mod-php5
sudo apt-get install libapache2-mod-php5
sudo a2enmod php5
sudo /etc/init.d/apache2 restart
I also added the following two lines to /etc/php5/apache2/php.ini

AddHandler application/x-httpd-php .php
LoadModule php5_module modules/libphp5.so
I then cleared my browser cache and low and behold my site came back.

Maybe this info might come in handy for anyone else about to upgrade packages on their server or serve as a reminder of what happens when you try to behave like a sysadmin and have no real idea what your doing!

It also should make you glad that we live in the days where a Google search can provide almost any answer you are looking for. I doubt I would have owned, let alone found, a book that would have been of any use at 3am on a Saturday morning.

So despite all their snooping, minority report advertising and links to the alphabet agencies they are good for something.

Sunday, 25 October 2009

Google Chrome Unresponsive

Googles Chrome Browser Raising Page Unresponsive Errors

Today I have just come across an intermittent problem with the latest version of Google Chrome 3.0.195.27 which has meant that the browser opens correctly but then freezes when trying to load any page including the homepage.

I first had this problem this morning and thought it was down to a slow connection but all my other browsers worked fine. After a while of spinning around Chrome pops up a little pop up box saying that a page (unnamed) has become unresponsive and you can either close it or wait. Choosing either option does nothing at all.

I have scanned my system with multiple virus checkers and all seems fine.

I have also re-installed Chrome three times now. The first time I re-installed the program run okay up until I rebooted later on then the same problem came back. Now I am just getting the unresponsive messages on starting up the browser.

I don't know what the problem is and I also haven't got a solution yet so if anyone has similar issues please let me know. I can still access the web with FireFox, IE, Opera and Safari but I tend to use Chrome for all my pure web surfing so I would really like this browser back working well as I have really got to love using it over the last year.

Wednesday, 30 September 2009

The database owner SID recorded in the master database differs from the database owner SID recorded in database

Problems with database ownership SID values

I recently came across a problem which I have had a couple of times now which seems to be related to database backups in SQL Server 2005.

I was carrying out a manual backup of a database on the production server which was taking a very long time. During this process I came across another problem which needed solving quickly and I couldn't wait until the backup had finished before trying to resolve the issue which was caused by a report called from one database trying to access data from another. It was raising the following error message:

The server principal "XXXXX" is not able to access the database "XXXX" under the current security context.
The solution to this problem is to enable the database that needs to be accessed as Trustworthy with an SQL statement like this:

ALTER DATABASE strategies_jobboard SET TRUSTWORTHY ON
So I ran this statement to fix the reporting issue and I had some hesitations about doing this as I didn't know whether the combination of the backup and the lock on the Database would cause any issues and low and behold just after running this statement I started receiving the following errors:

The database owner SID recorded in the master database differs from the database owner SID recorded in database 'XXXX'. You should correct this situation by resetting the owner of database 'XXXX' using the ALTER AUTHORIZATION statement.
Now this is an error I have come across before when a database has been created on one server by restoring a backup taken from another server and the database owners differ. To prove that the problem is in fact differing SID's I ran the following two SQL statements.

--To get owner SID recorded in the master database for the current database
SELECT owner_sid FROM sys.databases WHERE database_id=DB_ID()

--To get the owner SID recorded for the current database owner
SELECT sid FROM sys.database_principals WHERE name=N'dbo'

They should return you SID values in the format of a GUID e.g

0x010500000000000515000000BF76FC16EA335FE078A67D48FB030000

Now if the two SID's differ which they did in my case it means that you need to reset the database owner so that both values are the same. To do this you can run another ALTER statement and pass in the owner value you want to use e.g
ALTER AUTHORIZATION ON Database::XXXX TO [domain\user]


Once I had run this code the problem was fixed. Now I am pretty sure the issue was down to a combination of the backup running at the same time as the code to change the TRUSTWORTHY statement as I had no errors before that SQL was run and as soon as I had executed it the errors started shooting into my inbox.

However I tried to replicate this problem on a development server by running some backups and executing the same SQL but I couldn't re-create the problem. Maybe there was something else in the mix I was unaware of but I thought I would post the solution to the problem anyway in case others have a similar situation arise.

Friday, 4 September 2009

Useful Bookmarks to overcome IE 8 / Firebug

Two useful bookmarks to aid web development

Over the last month I have been moaning a lot about IE 8 and Firebug and have started working without these two developer tools that have had started causing me problems such as:

-Very slow load times on certain sites or pages (IE 8 dev toolbar / Firebug)
-Hanging of the browser and maxing out CPU (50% on a dual core) (IE 8 / Firebug)
-Errors related to other scripts or add-ons (Firebug)

I have just found another issue to add to the list which is that when Firebug is enabled my Google Adverts are not loading on the following site: www.hattrickheaven.com with the following errors being reported (copied from firebugs console)

cannot access optimized closure

gadgets is undefined

IG_EmbedCachedFlash is not a function

Which are coming from a file that is referenced by Googles Adsense http://ads.gmodules.com/gadgets/ifr.

I do know that there have been bugs in Googles Adsense code latley as I regularly get errors from ads.modules.com/gadgets/ifr. There were some errors the other day that prevented adverts from showing as well as any content loaded through Googles AJAX API in IE. If I view the same page in IE I do get a Invalid argument error (line 603, char 7) however the google adsense advert loads correctly.

However if I disable Firebug the adverts appear correctly in Firefox so I can only assume its a clash between Firebug and Googles code just like the error I reported the other month with the highlighter code I use on my blog.

The problems with both of these add-ons has meant that I have disabled both the IE developer toolbar and Firebug from appearing automatically on all pages. With Firebug I know that if I need it I can turn it on with ease and deal with the errors knowing that they are most likely caused by the tool itself rather than any other script. However with IE's developer toolbar its not so easy due to it causing my PC to hang the majority of the time its used.

I have found that going to Control Panel > Internet Options > Advanced > Reset does resolve the issue for a while until the problems slowly build up again over time and the browser with the developer toolbar becomes unusable.

Until IE resolve this issue I have resorted to using the following two bookmarklets to accomplish the two main tasks I use the developer toolbar and Firebug for.

The first is a bookmarklet that allows me to view the generated source code for a particular page:

javascript:(function()%7b%20function%20htmlEscape(s)%7bs=s.replace(/&/g,'&amp;');s=s.replace(/%3e/g,'&gt;');s=s.replace(/%3c/g,'&lt;');return%20s;%7d%20x=window.open();%20x.document.write('%3cpre%3e'%20+%20htmlEscape('%3chtml%3e\n'%20+%20document.documentElement.innerHTML%20+%20'\n%3c/html%3e'));%20x.document.close();%20%7d)();
Which if you unpack it breaks down as the following code:
javascript: (function () {
function htmlEscape(s) {
s = s.replace(/&/g, '&amp;');
s = s.replace(/>/g, '&gt;');
s = s.replace(/</g, '&lt;');
return s;
}
x = window.open();
x.document.write('<pre>' + htmlEscape('<html>\n' + document.documentElement.innerHTML + '\n</html>'));
x.document.close();
})();


And the following code which will generate a DOM inspector allowing you to highlight elements on your page and view its properties and child elements.


javascript:prefFile='';void(z=document.body.appendChild(document.createElement('script')));void(z.language='javascript');void(z.type='text/javascript');void(z.src='http://slayeroffice.com/tools/modi/v2.0/modi_v2.0.js');void(z.id='modi');

You can get these and other bookmarklets from the following site which is tailored for adding missing functionality to Google Chrome: http://www.nogeekyname.com/blog/google-chrome/extensions-for-google-chrome-bookmarklet-for-chrome/

Sunday, 5 April 2009

Problems with Firebug and raised errors

Firebug raising false errors or incorrect line numbers

I have noticed recently that Firebug seems to be giving me unhelpful error reports and it seems to be happening more and more. By unhelpful I mean in the way Internet Explorer used to when an error was raised with an invalid or incorrect line number. I always thought Firebug was pretty spot on for error reporting but it seems that within the last month or so I have been getting quite a lot of errors in the console that say the problem is in file X and on line 120 but in fact after stepping through the problem the problem is actually in file Z and on line 45. Sometimes the error details that are reported in the console do not correspond exactly to those in the standard error console and a lot of the time errors that appear in Firebugs console do not appear in the standard error console.


Possible Causes to spurious error messages

Conflict with Firefox Add-Ons

I have found problems in the past with certain Firefox add-ons that raise errors constantly or intermittently. One such add-on is the user-agent switcher which always raises a 
UserAgentButton is null error and another add on which is a brilliant add-on for Search Engine Optimisation called the SEO Toolbar keeps raising the following error s4fToolbar_cache is undefined.

Both of these errors disappear once the add-on has been disabled or in the case of the SEO toolbar you can turn it off without having to restart your browser. I have quite a number of add-ons on my work PC and due to my experience of errors related to add-ons I wouldn't rule out some sort of clash that is generating incorrect error details. 


Syntax Problems

I have found that sometimes when there are compilation errors usually due to missing or incorrect brackets then the error can be reported incorrectly. If a function hasn't been closed correctly due to a missing bracket then the calling function can sometimes be identified as the erroring function. However a large number of the errors I am getting invalid details for do not meet this criteria.


Firefox or Firebug installations

Within the last couple of months I have had upgrades of both Firefox and Firebug so it maybe that some problem within the application is causing the invalid error details.

If anyone else has found similar issues recently with their Firebug installation it would be good to hear about it. As my colleagues also use Firefox and Firebug but without the various add-ons I have installed do not have these problems it means at the moment I am of the opinion the problem is most likely due to some sort of clash between add-ons as I cannot see such a problem not being spotted and resolved before any upgraded version of Firebug being released. I came to expect this sort of behaviour from IE and it was just understood by everyone that you couldn't get a proper error message when you needed one so its a tad annoying to say the least for me to start experiencing this issue with Firefox.

Saturday, 21 March 2009

Problems Upgrading to IE 8

Upgrading to Internet Explorer 8.0

There are plenty of sites already out there listing all the many bugs or "features" that IE 8 has brought to the table but so far the two main ones I have come across are:


Problems when FirebugLite is also running in IE 8.

I was getting a "Function Expected" error on line 1499 in the IsArray function. As a workaround I added the following line as the first line in the function e.g



IsArray:function(_object){
if(!_object) return false;



This prevents the error but the Firebug-lite console does not display correctly in IE 8 when the document mode is also IE 8. To get round this I set the document mode to IE 7 and then it works fine.

Remember IE 8 now has a console in the developer tools options for outputting custom debug messages plus its now got a great debugger tool with all the same features as Firebug so Firebug-Lite isn't really needed anymore. However it should still be possible to run the two side by side.


Issue with clip and rect function

I also found an "invalid argument" error when setting the clip properties using the rect function. The code was for a scroller and the original version that raised the error was:



this.canvas.style.clip = "rect(0 " + this.canvasWidth + " " + this.canvasHeight + " 0)";



The fix was to add "px" after the dimension values and separate the values with commas e.g



this.canvas.style.clip = "rect(0px, " + parseInt(this.canvasWidth) + "px, " + parseInt(this.canvasHeight) + "px, 0px)";



I have come across a few errors such as "null is null or not an object" (you don't say!) which have been simple fixes and have just required testing the values correctly before using them.

I am sure there are hundreds more errors and that many many hours will be devoted to fixing them all in a similar manner to the last 2 major releases of IE. However overall I am very happy that they seem to have caught up with Firefox and the others and have implemented a pretty decent developer tools section including a great debugger that actually gives you a useful error message for once. Plus I like the fact that the GUI hasn't changed very much in the way that IE 6 to IE 7 did and I do like the little touches like the accelerators.

However its a shame that with such a major release they couldn't have gone the whole hog and sorted their Javascript engine out to make that standards compliant as well as the CSS. Apparently they have rewritten the whole JS engine so now was as good a time as any to bite the bullet and do it and they would have made the whole web development community very happy if they had done so. Even with the rewrite their event model is still pretty shoddy and even if they wanted to keep with their intermediary event model (attachEvent, removeEvent, returnValue, srcElement etc) then they could have fixed those annoying little issues that people have spent thousands of development hours resolving such as the this keyword referring to the window and not the object in question and attaching event listeners in order rather than randomly.

It seems pretty likely that more and more companies will get to the point where developing for IE becomes too much work and stop supporting it. Market share of Firefox, Chrome, Safari and Opera are increasing all the time so it may not be that long until you find a lot of sites just redirecting to a Mozilla download page when you access their site in IE. If that does happen then it might be a shame to some people but Microsoft will only have themselves to blame and may find that they have missed a great opportunity with this release to prevent that from occurring.