Posted by: robrobertson | January 18, 2012

JavaScript === (Triple Equals)

Coming across a “===” in some JavaScript today and wondered what the difference was between the normal equality operater (==) and this super version. JavaScript: The Definitive Guide differiantes the two as being Equality vs Identity. The ECMAScript Spec merely labels it as the “Strict Equals Operator”.

An interesting example is (“1″ == true )

Since the string “1″ evaluates to the integer 1 and the boolean true evaluates to the integer 1, the values are treated as equals.

(“1″ === true) is immediately evaluated to false since the string and boolean are different types.

Just in case you’re curious, here’s the comparison algorithm from the ECMA Spec, Section 11.9.6:

The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:

1. If Type(x) is different from Type(y), return false.
2. If Type(x) is Undefined, return true.
3. If Type(x) is Null, return true.
4. If Type(x) is Number, then
a. If x is NaN, return false.
b. If y is NaN, return false.
c. If x is the same Number value as y, return true.
d. If x is +0 and y is ?0, return true.
e. If x is ?0 and y is +0, return true.
f. Return false.
5. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and
same characters in corresponding positions); otherwise, return false.
6. If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
7. Return true if x and y refer to the same object. Otherwise, return false.

It definitely seems like a safer bet to control the conversion of your datatypes.

Posted by: robrobertson | January 17, 2012

BlackBerry Launcher Application

Tasked with customizing a third party app with our branding and without access to the source code, a launcher app is in order. This launcher app enables us to have a custom icon and also perform setup tasks on the device before the “real” app is invoked. It’s important to check if the application is already running before trying to create a new process instance or you will have unpredictable results. This is accomplished with the ApplicationManager by calling getVisibileApplications(). If there are no running instances, then you are free to create one using runApplication().

Enjoy the source code below!

private void launch(String applicationName) throws Exception
{
//Check if the application is already running.
ApplicationManager manager = ApplicationManager.getApplicationManager();
ApplicationDescriptor descriptors[] = manager.getVisibleApplications();

for(int i=0; i < descriptors.length; i++)
{
    if(descriptors[i].getName().equals(applicationName))
    {
         manager.requestForeground( manager.getProcessId( descriptors[i] ));
    	System.exit(0);
    }
}

//Find the application on the device and try to start it.
int moduleHandle = CodeModuleManager.getModuleHandle(applicationName);
ApplicationDescriptor[] appDescriptors = CodeModuleManager.getApplicationDescriptors( moduleHandle ); 

for(int i=0; i < appDescriptors.length; i++)
{
    ApplicationDescriptor descriptor = appDescriptors[i];
    try {
        int processId = ApplicationManager.getApplicationManager().runApplication( descriptor );
         if(processId > 0)
    	    System.exit(0);
    }
    catch (ApplicationManagerException e) {
    	throw e;
    }
}
//Couldn't find the application
throw new Exception(applicationName + " is not detected.");
}

The key to storing a file in your COD for deployment to the BlackBerry file system:  store it in the src folder. Then use the basic input and output streams for reading and writing.

/**
* Write out a file stored in the COD.
* @param filename - filename must start with /
* @param location - example: file:///store/home/user
* @throws Exception
*/
private void writeFile(String filename, String location) throws Exception
{
InputStream inputStream = null;
inputStream = getClass().getResourceAsStream(filename);

if(inputStream == null)
    throw new Exception("Unable to open input file: " + filename);

FileConnection fc = (FileConnection)Connector.open(location + filename);
if (!fc.exists()) {
    fc.create();
}
OutputStream outStream = fc.openOutputStream();
outStream.write(IOUtilities.streamToBytes(inputStream));
outStream.close();
fc.close();
}

Posted by: robrobertson | December 16, 2011

HTTP method MERGE not supported

Have an oData service that doesn’t support HTTP Merge for updates?

In the SaveChanges method of the DataServicesContent, add the parameter of SaveChangesOptions.ReplaceOnUpdate.  This will replace all the values of the object until your service supports the friendlier merge option.

service.SaveChanges(SaveChangesOptions.ReplaceOnUpdate);

Posted by: robrobertson | December 7, 2011

Enable RESTClient Addon for Firefox 8+

With Firefox’s rapid release cycle, add-on developers have a difficult time ensuring their code is up to date.  However, with a cool little tool  that only uses javascript, html, and css, we should be pretty safe to run under newer versions of Firefox.

Since RESTClient is open source, we can head over to GitHub and download a copy of the source.  GitHub has a great feature to download the source as a zip.  Take this zip file and edit the contained file:  install.rdf   Simply change the maxVersion to 10 or so.

<RDF:Description RDF:about=”rdf:#$ll2uD1″
em:id=”{ec8030f7-c20a-464f-9b0e-13a3a9e97384}”
em:minVersion=”3.6″
em:maxVersion=”10.*” />

Save the file back into your zip.  Open up Firefox’s Add-on Manager and drag the zip file onto the Add-on Manager.

Your newly upgraded plugin is now available for your version of Firefox!

Posted by: robrobertson | January 4, 2010

IIS 500 with isapi_redirect.dll (incorrect function)

Having received a most un-useful HTTP Error 500 with an error code of 2147942401 and also Incorrect function (0×80070001), we started digging around different versions and the setup of our redirect.

The short story is to check and re-check your settings again.

One missing configuration value that is stored in the registry was enough to generate this strange error. The Apache Tomcat Connector – Reference Guide contains all the necessary steps to properly setup the redirects. The basic registry values to create are: extension_uri, log_file, log_level, worker_file, and worker_mount_file.

Posted by: robrobertson | November 4, 2009

Windows 2008 (IIS7): The installer was interrupted

When installing an MSI from a Visual Studio Web Project, a dreaded “The installer was interrupted before the Application was installed” message may appear. The Server Role, “IIS 6 Management Capability” is required for the MSI to register with the IIS 6 Metabase.

Posted by: robrobertson | June 15, 2009

Generate Dynamic iTextSharp PDF Documents from ASP.Net

Here’s two examples to dynamically create PDF’s using iTextSharps’ HTML Parser: in the browser and also a method to write the pdf to disk.

using System;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Xml;
using iTextSharp.text;
using iTextSharp.text.html;
using iTextSharp.text.pdf;

namespace Web
{
    public partial class iTextSharpDemo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Example HTML String
            string html = "<html><p align='center'>Hello World!</p><newpage />Hello 2nd Page!</html>";

            //Parse the HTML to PDF and Write PDF to disk
            WritePdf(html, @"c:\temp\share\mypdf.pdf");

            //Parse the HTML to PDF and write PDF bytes to browser via the outputstream
            MemoryStream m = CreatePdf(html);
            Response.ContentType = "application/pdf";
            Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length);
            Response.OutputStream.Flush();
            Response.OutputStream.Close();
        }

        protected void WritePdf(string html, string destination)
        {
            MemoryStream ms = CreatePdf(html);

            FileStream fs = File.OpenWrite(destination);
            fs.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
            fs.Close();
            ms.Close();
        }

        public static MemoryStream CreatePdf(string html)
        {
            MemoryStream m = new MemoryStream();

            try
            {
                Document document = new Document(PageSize.LETTER);
                PdfWriter.GetInstance(document, m);

                StringReader sr = new StringReader(html);
                XmlTextReader xtr = new XmlTextReader(sr);

                document.Open();

                HtmlParser.Parse(document, xtr);

                xtr.Close();
                document.Close();
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("Application", ex.Message);
                throw ex;
            }

            return m;
        }

    }
}

Posted by: robrobertson | March 30, 2009

Taking an ASP.Net Application Offline with an Outage Message

App_offline.htm is an easy, but not widely published, method to take your favorite ASP.Net Web Application offline and present a friendly outage message to your users. Simply create an outage message with your downtime info formatted in clear, readable html. Copy the file to the root of your website, and any requests will be redirected to this file.

Posted by: robrobertson | November 6, 2008

iTextSharp – 401 Error when parsing images!

When using the html parser to convert a web page into PDF and also using an image tag to an IIS server that has Integrated Authentication enabled, you will receive: The remote server returned an error: (401) Unauthorized.

The easy solution is to find the GetImage(Uri url) method and add the default credentials to the WebRequest after it is created. These can be found in the itextsharp.txt.pdf.codec namespace in the following classes: BmpImage, GifImage, and PngImage.

WebRequest wr = WebRequest.Create(url);
wr.Credentials = CredentialCache.DefaultCredentials;
isp = wr.GetResponse().GetResponseStream();

Since iTextSharp is Open Source, it was easy to download the code, isolate the error, and quickly add a line of code for the authentication. Now, it’s time to submit the change to the iTextSharp project on SourceForge.

Older Posts »

Categories

Follow

Get every new post delivered to your Inbox.