Category Archives: Web Development

ASP.net MVC: Expecting element ‘root’ from namespace ”.. Encountered ‘None’ with name ”, namespace ”.

ASP.net MVC Expecting element 'root' from namespace ''.. Encountered 'None' with name '', namespace ''.

While walking through an ASP.net MVC3 app, I noticed that Ajax calls resulted in nothing happening. Debugging in Visual Studio, I noticed a SerializationException at the following code:

public override void OnActionExecuting(ActionExecutingContext filterContext) {
....
object o = new DataContractJsonSerializer(RootType)
.ReadObject(filterContext.HttpContext.Request.InputStream);
}

The JSON response from the Ajax was supposed to be read here, but it was failing. It was a runtime exception, “SerializationException was unhandled by user code.” Turns out InputStream wasn’t being read from the beginning of the stream, so the JSON couldn’t be deserialized properly.

Resetting the position in the current stream to the beginning should make it readable again:

public override void OnActionExecuting(ActionExecutingContext filterContext) {
....
//move current position in the stream back to the beginning
filterContext.HttpContext.Request.InputStream.Position = 0;
object o = new DataContractJsonSerializer(RootType)
.ReadObject(filterContext.HttpContext.Request.InputStream);
}

SQL Server: A network-related or instance-specific error occurred while establishing a connection to SQL Server

I spent pretty much all today wiping a desktop, and installing Windows 7, Visual Studio, and SQL Server Express 2010 on it. Talk about some form of hell.

The WIndows 7 install went fine, The Visual Studio install went fine. The SQL Server Express install went fine. Thought I was in heaven.

Yeah, right.

So I fire up SQL Server Management Studio and this is what I see:

Makes sense, I hit the Connect button. After about 5 seconds, I see get an error:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 – Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 2)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=2&LinkId=20476

Of course the information is correct, I’m on my local box, how can you not connect to it? Bah.

Turns out, I got the server name wrong. It should be either <MACHINENAME>\SQLEXPRESS or .\SQLEXPRESS.

Then it all works like magic.

PHP: money_format and setLocale in Mac OS X vs Ubuntu

I had started working on a PHP project on my Macbook, which is running OS X Snow Leopard. With MAMP installed, I started plugging away. One of the requirements of the project was to display prices. Most users of the site would be in the US, so it was determined the currency should show up like $123.45.

On the Mac,

setlocale(LC_MONETARY, 'en_US');

worked perfectly fine.

To get the application ready, we decided to try it out on a test environment running Ubuntu 9.10 (don’t ask why its running Ubuntu 9.10).

Oddly, currency showed up like 123.45, without the dollar sign.

We thought maybe the ‘en_US’ locale wasn’t installed on the machine. To check, we did:

testme@meg:~$ locale -a
C
en_AG
en_AU.utf8
.
.
.
en_US.utf8
en_ZA.utf8
en_ZW.utf8
POSIX

Oops, in Ubuntu, its ‘en_US.utf8′. Doing a

setlocale(LC_MONETARY, 'en_US.utf8');

now allows money_format to work properly.

Magento Fix: Voted Polls Disappear from Sidebar

Working on a Magento 1.4.2 CE instance today, the client said they had set up polls earlier this week, but now they disappeared from the sidebar. Trying to replicate it, I noticed that there is a “Disallow Voting in a Poll Multiple Times from Same IP-address” under System->Web->Polls. I assumed if you set that to No, the polls would stay in the sidebar, showing the results even if a visitor voted.

Testing it out myself, thats clearly not how it works.

Digging around in the code, in the Mage_Poll_Block_ActivePoll constructor

            // get random not voted yet poll
            $votedIds = $pollModel->getVotedPollsIds();
            $pollId = $pollModel->setExcludeFilter($votedIds)
                ->setStoreFilter(Mage::app()->getStore()->getId())
                ->getRandomId();

So, to figure out which polls to display, Magento figures out which polls the user voted in already, and ignores them. If there is only one poll, and the user voted, they won’t see any polls.

There are a couple of options here. Either set $votedIds to an empty array or comment out most of getVotedPollsIds. getVotedPollsIds doesn’t seem to be used anywhere else, so I decided to comment it out by first copying app/code/core/Mage/Poll/Model/Poll.php to app/code/local/Mage/Poll/Model/Poll.php, and making sure getVotedPollsIds returns an empty array.

See more of my Magento posts.

Magento: PHP Fatal error Undefined class constant ‘TYPE_CONDITION’ Abstract.php on line 296

This is what happens when you don’t pay attention. I was working on a project that started out when Magento 1.4.1.1 was the latest stable version. There is a bit of development left, but I decided to upgrade the install to 1.4.2 via subversion. I go get some coffee, come back, and assume the upgrade is done.

Then I try to load the homepage, and I get a blank screen. Eh, ok. Time to display errors by commenting the following line in index.php.

ini_set('display_errors', 1);

Lets see what the logs say:

PHP Fatal error:  Undefined class constant ‘TYPE_CONDITION’ in /home/dev/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php on line 296

Well, what exactly is the code throwing this error? In Abstract.php:

        if (!empty($conditionSql)) {
            $this->getSelect()->where($conditionSql, null,
Varien_Db_Select::TYPE_CONDITION);
        } else {
            Mage::throwException('Invalid attribute identifier for filter ('.get_class($attribute).')');
        }

        return $this;
    }

How can Varien_Db_Select::TYPE_CONDITION not exist? I looked at my Varien/DB/Select.php and there was no TYPE_CONDITION. Then I looked at Varien_Db_Select in the Magento docs, and it was there. Weird.

Then I looked back at the terminal which was doing Subversion update, and noticed that there was an error. Apparently my Internet connection had died and the update didn’t complete. Ugh.

After restarting the Subversion update, I look at Varien_Db_Select:

class Varien_Db_Select extends Zend_Db_Select
{
    const TYPE_CONDITION    = 'TYPE_CONDITION';

    const STRAIGHT_JOIN_ON  = 'straight_join';
    const STRAIGHT_JOIN     = 'straightjoin';
    const SQL_STRAIGHT_JOIN = 'STRAIGHT_JOIN';

There it is.

Moral of the story. Make sure your updates actually complete before making such an assumption.

Ubuntu 10.04 & Node.js – wscript:138: error: could not configure a cxx compiler!

Wanting to learn more about node.js, I grabbed the latest stable branch of the source code and tried to install it on my Ubuntu 10.04 dev box. Simply doing a ./configure returned the following:

nali@nali-desktop:~/dev/nodejs/node-v0.2.6$ ./configure
Checking for program g++ or c++          : not found
Checking for program icpc                : not found
Checking for program c++                 : not found
/home/nali/dev/nodejs/node-v0.2.6/wscript:138: error: could not configure a cxx compiler!

Oh oops, no compiler has been installed. There are a couple different ways to proceed: (1) either install only the packages needed, or (2) wuss out and install build-essentials which will load all the necessary packages and some extra ones for general development. I prefer to wuss out, so I do:

nali@nali-desktop:~/dev/nodejs/node-v0.2.6$ sudo apt-get install build-essential

After all that installs, I try ./configure again, only to get:

Checking for program g++ or c++          : /usr/bin/g++
Checking for program cpp                 : /usr/bin/cpp
Checking for program ar                  : /usr/bin/ar
Checking for program ranlib              : /usr/bin/ranlib
Checking for g++                         : ok  
Checking for program gcc or cc           : /usr/bin/gcc
Checking for program ar                  : /usr/bin/ar
Checking for program ranlib              : /usr/bin/ranlib
Checking for gcc                         : ok  
Checking for library dl                  : yes
Checking for openssl                     : not found
Checking for function SSL_library_init   : not found
Checking for header openssl/crypto.h     : not found
/home/nali/dev/nodejs/node-v0.2.6/wscript:195: error: Could not autodetect OpenSSL support. Make sure OpenSSL development packages are installed. Use configure --without-ssl to disable this message.

Bah, the SSL packages haven’t been installed yet. Do a:

nali@nali-desktop:~/dev/nodejs/node-v0.2.6$ sudo apt-get install libssl-dev

And then you can do a ‘make; sudo make install; make test’ to get it all running.

ImageMagick: Batch Crop and Rename Files

There are many better ways to do this, but here is one method if you need to do a quick and dirty jobs of cropping and renaming a bunch of files in a batch with ImageMagick.

Quick little background. Even though I’ve got a Macbook, if I have to look at code, I’m usually on a desktop thats running Ubuntu 10.04. We host client sites on servers running Ubuntu 10.04, so its best to write code in that environment. So today, after finishing up code for a Magento site, I needed to upload a set of fabric swatches that would be used with configurable products. The client provided images for the fabric swatches, but they were all different sizes. All I needed was a 60x60px selection of each image and the filenames to be something descriptive with the image size.

Of course, this can be done pretty easily in Photoshop. I’m sure there is some plugin for it, but you can record an action, and run it against a batch of files. The problem was that I didn’t want to hop on my Macbook just to crop and rename files.

Since I was on an Ubuntu machine, my first gut reaction was to fire up Gimp and see if I could do it. Turns out there is a plugin called David’s Batch Processor that pretty much does that. Ubuntu has the plugin in the repository, just search for ‘gimp-plugin-registry’ in Synaptic. Gimp also supports scripting, but the scripting language is Scheme-like, and I didn’t want to recall knowledge from freshman year in college to do this.

Then I remembered ImageMagick. While ImageMagick has a GUI for image manipulation, its got a powerful CLI that lets you do pretty much anything you want to do. So no need to open up a big honkin’ application just to do some basic cropping and renaming.

So save the following code in the directory of the files you want cropped and renamed and run it:

#!/bin/bash
width=60;
height=60;
x_offset=10;
y_offset=5;
filelist=`ls | grep '.jpg'`
for image_file in $filelist
do
  preextensionfilename=`convert $image_file -format "%t" info:`
  convert $image_file -crop ${width}x${height}+${x_offset}+${y_offset} \
    ${preextensionfilename}_${width}x${height}.jpg
done

Most of this should be pretty self-explanatory. Up top we define what sizes we want the images to be cropped to and from where in the image we want to crop. Then we grab a list of all the files we want to crop, and grab the filename before the extension (to be used for saving the new files). The convert command is what actually does the cropping and saving the files with the new names, in this case, something like oldgold_60x60.jpg.

The script is most definitely not robust, but hopefully it will be a good starting off point for some.

Magento: syntax error, unexpected T_NAMESPACE, expecting T_STRING

Isn’t it fun hunting down bugs? Today, I noticed a community Magento extension that I was trying out would only partly output what it was supposed to. Digging into the Apache error logs, I see this:

PHP Parse error:  syntax error, unexpected T_NAMESPACE, expecting T_STRING in /home/foo/magento/app/code/community/bar/ProductPageShipping/Model/Session.php on line 26

The problem code was

class Qux_ProductPageShipping_Model_Session extends Mage_Core_Model_Session_Abstract
{
    const NAMESPACE = 'productpageshipping';

    public function __construct()
    {
        $this->init(self::NAMESPACE);
    }
}

Doesn’t look problematic…unless you are running PHP 5.3. In PHP 5.3, namespace is a reserved keyword. Oops.

Renaming NAMESPACE to anything will work in this instance:

class Qux_ProductPageShipping_Model_Session extends Mage_Core_Model_Session_Abstract
{
    const HELLO_WORLD_NAMESPACE = 'productpageshipping';

    public function __construct()
    {
        $this->init(self::HELLO_WORLD_NAMESPACE);
    }
}

Tada!

See more of my Magento posts.

Magento Connect Manager: Cannot initialize channel://connect.magentocommerce.com/

MagentoI swear I can read. Seriously. No, I know some of you may not believe me, but I can. Yeah, sure. Lets go with that.

Wanting to investigate how a popular extension implemented certain functionality, I decided to install the extension on a new Magento dev environment:

Failed to download magento-community/Foo_Bar within preferred state "stable", latest release is version 1.0.2, stability "alpha", use "channel://connect.magentocommerce.com/community/Foo_Bar-1.0.2" to install
Cannot initialize 'channel://connect.magentocommerce.com/community/Foo_Bar', invalid or missing package file
Install Errors
Package "channel://connect.magentocommerce.com/community/Foo_Bar" is not valid

Immediately thought I had broken PHP or PEAR in my environment. Then at the root Magento directory, I tried:

./pear install magento-community/Foo_Bar

and got this error:

Failed to download magento-community/Foo_Bar within preferred state "stable", latest release is version 1.0.2, stability "alpha", use "channel://connect.magentocommerce.com/community/Foo_Bar-1.0.2" to install
Cannot initialize 'channel://connect.magentocommerce.com/community/Foo_Bar', invalid or missing package file
Install Errors
Package "channel://connect.magentocommerce.com/community/Foo_Bar" is not valid
PEAR ERROR: install failed

I nearly panicked at this point. I started checking file permissions, checking versions…yeah, general panic.

Of course, if you aren’t completely dim-witted like me and actually read the message, you’d see the problem:

Failed to download magento-community/Foo_Bar within preferred state "stable", latest release is version 1.0.2, stability "alpha"

Ohhh. Magento is configured to only accept stable extensions, and Foo_Bar is designated alpha.

Obviously, a quick fix. In the admin backend, go to System -> Magento Connect -> Magento Connect Manager -> Settings and change Preferred State to Alpha or whatever your extension is:

Magento Connect Manager Extension Alpha

See more of my Magento posts.

WordPress 3.0 Multisite Subdomain: Broken Image / Thumbnails

WordPressAfter upgrading nali.org from WordPress 2.9.X to WordPress 3.0, I set it up as multisite. Specifically, I wanted to set up a subdomain: stream.nali.org. Its basically for lifestreaming, but instead of using Tumblr or Posterous, I decided I’d just do it myself with the network/multisite feature of WordPress 3.0. Even though multisite existed in previous versions of WordPress, it was a separate code base. In 3.0, its part of the core functionality.

Having set up the stream blog, I tried uploading pictures for a post about The Original Pancake House. Uploading didn’t give me any errors, but all the thumbnails and images were showing the broken image placeholder.

Here is what happened with my setup: after setting up multisite by following the instructions at the Codex, I tried installing W3 Total Cache. W3 Total Cache required changes to the .htaccess. But W3 Total Cache really wasn’t working on the underpowered Rackspace instance I was testing (completely my fault).

So I decided to go back to the original .htaccess:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Oops. The multisite references are gone! Look what the Codex states, the .htaccess should be:

# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# uploaded files
RewriteRule ^files/(.+) wp-includes/ms-files.php?file=$1 [L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule . index.php [L]
# END WordPress

After making the changes, the thumbnails under Media might still be broken. Edit an image and hit save. The thumbnails should be recreated.

Atlanta Lions Club