Share your knowledge and create a knowledgebase.

Archive for May, 2008



XPath is a language that allows you to address parts of an XML document, making XSLT transformations practically necessary. It also makes it an invaluable tool for managing XML data in applications such as Web applications.

Microsoft provides XPath functionality through the selectSingleNode() and selectNodes() methods on DOM nodes and documents. However, PHP uses functions that provide XPath functionality through contexts. In the following example, I’ll show sample XML data and PHP code to grab different parts of the XML document. I’ll also explain how the PHP code works.

In the example code, I use the following XML data to provide the functionality. (Note: This code was developed and run successfully using PHP 4.3.4, Windows XP, and IIS 5.1.)

<?xml version="1.0"?>
<x:root xmlns:x="http://www.someplace.com">
<x:row>
<x:dog
color="yellow">Marmaduke</x:dog>
<x:cat>Garfield</x:cat>
</x:row>
<x:row>
<x:dog color="white">Snoopy</x:dog>
<x:cat>Heathcliff</x:cat>
</x:row>
<x:row>
<x:dog color="gray">Spike</x:dog>
<x:cat>Sylvester</x:cat>
</x:row>
</x:root>

This XML data contains a few elements and some attributes including a namespace declaration — some basic XML. This results in varied queries for me to test.

<?php
$sxml = '<?xml version="1.0"?>
    <x:root xmlns:x="http://www.someplace.com">
        <x:row>
            <x:dog color="yellow">Marmaduke</x:dog>
            <x:cat>Garfield</x:cat>
        </x:row>
        <x:row>
            <x:dog color="white">Snoopy</x:dog>
            <x:cat>Heathcliff</x:cat>
        </x:row>
        <x:row>
            <x:dog color="gray">Spike</x:dog>
            <x:cat>Sylvester</x:cat>
        </x:row>
    </x:root>';
 
$xml = domxml_open_mem($sxml);
 
$xpc = xpath_new_context($xml);
xpath_register_ns($xpc, "x", "http://www.someplace.com");
 
$nodes = xpath_eval($xpc, "//x:row/x:dog[@color='yellow']/text()");
foreach ($nodes->nodeset as $node) {
    print $node->content . "\n";
}
 
$nodes = xpath_eval($xpc, "//x:row/x:dog");
foreach ($nodes->nodeset as $node) {
    print $xml->dump_node($node) . "\n";
}
 
$nodes = xpath_eval($xpc, "//x:cat/child::text()|//x:dog[@color='white' or
@color='gray']/text()");
foreach ($nodes->nodeset as $node) {
    print $node->content . "\n";
}
 
$xml->free();
?>

First, I create a local variable to hold the XML string. This information could have been passed in as part of a POST HTTP request. However, for this example, I’m going to include it in the code. The next step is to create a DOM Document by using the domxml_open_mem() function. This function creates a DOM Document object in memory from a valid XML string. It accepts one parameter: the XML string. Another way to accomplish this is to store the XML in a separate file and use the domxml_open_file() function to load the XML from a file. This function takes one parameter: the filename of the XML file.

Once I create the DOM Document object, I can create an XPath context with this object through the xpath_new_context() function, which takes one parameter: the current DOM Document object. This context is used to evaluate the XPath expression and is also used to register namespaces, if needed. Since my XML includes a namespace, I register the namespace with the xpath_register_ns() function. This makes it possible to create XPath queries using prefixes. The xpath_register_ns() function takes three parameters: the XPath context, the prefix, and the namespace, respectively.

Now I can run XPath queries. This is done with the xpath_eval() function, whose first parameter is the XPath context and second parameter is the XPath expression. The function returns an array of DOM Nodes. In my code, I step through the nodeset and produce some form of output.

In the first XPath example, I grab all the x:dog text elements under the x:row nodes, where the ‘color’ attribute equals ‘yellow’. This is where the XPath expression in PHP differs slightly from an XPath expression using MSXML. I include the ‘/text()’ part of the expression to return the text nodes only. With MSXML, you access the text node with the ‘text’ property. Using the ‘content’ property on the returned text node, I can get the content of the text node.

In the second example, I grab all the x:dog elements under the x:row nodes. However, I use the dump_node() method on the DOM Document object to print out the complete XML of the appropriate node. The dump_node() method accepts one parameter: the DOM Node of which you wish to dump the contents.

In the last example, I grab all the x:cat text nodes and all the x:dog text nodes where the ‘color’ attribute is ‘white’ or ‘gray’. Once again, I step through the nodeset and print out the content of each text node. Finally, I free up the DOM Document object.


May 15, 2008 Author: Ashish | Filed under: PHP, XML

Sometimes you just need to know what country your site visitors are coming from—for example, if you’re trying to implement geo-targeted advertising. This article will show you how.

Sometimes you just need to know what country your site visitors are coming from—for example, if you’re trying to implement geo-targeted advertising. That’s where a tool like MaxMind’s GeoIP comes in—it lets you easily extract geographic data from your visitor’s IP address.

MaxMind makes available both commercial and free databases; the commercial ones are extremely precise and can get as fine-grained as the user’s city, while the free version can only identify the country of origin. We’ll use the free version in this article. If you need more detailed information, such as the remote client’s city and state of origin, you will need to purchase a more detailed database from MaxMind.

Getting started
To use it, you’ll have to first download the GeoIP Free Country file and extract it into a directory in your Web server. Then you’ll have to pick which language API to use with the database file. For simplicity, we’re going to use the pure PHP version because it doesn’t require any additional configuration or Apache modules. Remember to read the license terms before installing these on your Web site to ensure you are in compliance.

The code below demonstrates the basics of using the module (geoip.inc) to access the GeoIP Free Country database (GeoIP.dat). The example assumes both the PHP include and the country database file are in the same directory as the PHP file itself. You’ll have to change the paths as needed if this is not the case in your installation.

<?php
 
// include functions
include("geoip.inc");
 
// read GeoIP database
$handle = geoip_open("GeoIP.dat", GEOIP_STANDARD);
 
// map IP to country
echo "IP address 62.149.130.132 located in " . geoip_country_name_by_addr($handle, "62.149.130.132") . " (country code " . geoip_country_code_by_addr($handle, "62.149.130.132") . ")";
 
// close database handler
geoip_close($handle);
 
// print compulsory license notice
echo "&lt;p&gt; -- This product includes GeoIP data created by MaxMind, available from http://maxmind.com/ --";
 
?>

The sample code is pretty straightforward. After including the GeoIP PHP function library, the first step is to open the GeoIP database file with the geoip_open() function. This function accepts two arguments: the path to the database file and the type of database.

We then use the handle returned by the call to geoip_open() to obtain the two-letter country code and human-friendly name corresponding to the given IP address, via the geoip_country_code_by_addr() and geoip_country_code_by_name() functions, respectively. Both functions accept two arguments: the handle returned by geoip_open() and the IP address to resolve.

Once the required information is obtained, we close the database file with a call to geoip_close(). Simple as that.


May 15, 2008 Author: Ashish | Filed under: PHP

Developers often cringe when they have to create reports, but there are numerous options available with .NET to simplify the process. Tony Patton offers you a look at .NET’s various reporting options.
Data is the lifeblood of the enterprise and almost every application you develop will tap data in some manner. With all that data, users eventually want to view it in a report.

Many novice developers foolishly tackle reporting by creating custom forms—but this legwork is not necessary, as there are plenty of options with .NET for creating reports by dragging and dropping or a custom object model. In addition, reporting solutions offer additional functionality like PDF generation and charting that is hard to duplicate with custom code. .NET’s choices include readily available options, third-party products, and open source solutions. Let’s take a closer look at the reporting options available with .NET by category.

Readily available reporting options
I was very excited when I first encountered .NET with Visual Studio .NET. My enthusiasm stemmed from the inclusion of Crystal Reports within the environment. That’s right, no more purchasing and installing the product (although a standalone version is still available). My excitement was quickly extinguished as I tackled my first product utilizing Crystal Reports functionality. Its documentation is arcane and getting everything working properly is a bit mind-numbing. As time as passed, a few books have appeared on the subject and there are numerous Web resources as well. One in particular that I would recommend is Crystal Reports .NET Programming by Brian Bischof.

While Crystal Reports is readily available, the Microsoft Office Suite is seemingly everywhere as well. You may utilise Excel or Word functionality in a Windows client application or use the Office Web Components for browser clients. The different applications are readily accessible via your .NET code. Or, your enterprise may opt for another suite such as StarOffice or OpenOffice. Whatever the product, you can take advantage of it in your application. If these products are not a viable option, there are plenty of third-party products available.

Third-party products
Here is a sampling of third-party .NET reporting solutions. Free trial versions are available for most products, so you can give it a test run before making a commitment. Of course, there are open source options available as well.

  • ActiveReports for .NET: A managed implementation of the popular ActiveReports engine and report viewer. It provides complete code integration with the Visual Studio .NET environment. It supports both Web and Windows clients and allows exporting to PDF, Excel, RTF, HTML text, and TIFF images. The documentation is thorough and the drag-and-drop interface is straightforward.
  • ComponentOne Studio for .NET: It includes two tools: the report component, which generates Access-style database reports, and its companion Report Designer for report layout. It also includes tools for migrating Crystal Reports to their environment.
  • OOReport.NET: This product provides reports for Web-based clients. It also includes controls for assembling repots.
  • Visual Reports: This may be used with pre-.NET Visual Studio projects. It also includes an interactive report designer for proper layout. Report properties and such are accessed via COM interface.
  • Windward Reports: This product facilitates report design and creation via Microsoft Word. Open source reporting options

In the past, the term open source would never be uttered when discussing Microsoft-based development, but the .NET Framework’s acceptance and use of (some) standards has fueled several great open source solutions for .NET. And, reporting has a number of options.

Charting capabilities are provided by NPlot. One of the great features of .NET is the lack of adherence to one particular language, so you can use other products that are not .NET-based. While this may be beyond many .NET developers, open source solutions like the Java-based JasperReports can provide clean and simple reports.

Don’t overlook SQL Server
I would be remiss not to mention SQL Server’s Reporting Services. Microsoft describes it as “a comprehensive, server-based reporting solution designed to help you author, manage, and deliver both paper-based and interactive Web-based reports.” It is an excellent solution where SQL Server is readily available. It was first introduced as an add-on for SQL Server 2000, but it is also included with SQL Server 2005. It includes a report builder for simplifying report creation. SQL Server 2005 Reporting Services does not require Visual Studio .NET like its predecessor, but it may be utilised.

Make the data presentable
Where there is data there is a need to make sense of it, and reporting is one tool to aid users in this chore. Luckily, the .NET Framework includes various options ranging from the inherent Crystal Reports to open source alternatives. Your choices may depend on cost, but each product offers plenty of features to enhance your application.


May 14, 2008 Author: Ashish | Filed under: .Net

The .NET Framework provides enterprise services for building highly scalable solutions, but the implementation can be tricky. Learn when and where these services should be used.

One of the biggest mistakes architects can make when designing Enterprise Services is to assume that its sole purpose is to provide wrappers for existing unmanaged COM+ and MTS functionality. It’s a common assumption, given that the current Enterprise Services implementation provides little more than a managed interface to unmanaged COM+.

However, Microsoft views Enterprise Services quite differently. In its eyes, Enterprise Services is the replacement for COM+ and MTS. Going forward, Microsoft has two primary goals for new versions of the .NET Framework, starting with release 1.1 that’s due with Windows .NET Server 2003. First, all existing COM+ functionality will move to managed code. Second, all new distributed systems management functionality will be implemented in Enterprise Services in .NET. In fact, COM+ version 1.5 (released with Windows XP) will likely be the last version of COM+ available as an unmanaged release.

What is Enterprise Services?
Given Microsoft’s emphasis on Enterprise Services as its distributed systems development platform, you need to understand exactly what services Microsoft is talking about. Enterprise Services supports resource management in a distributed environment. This functionality includes support for distributed transactions, role-based security and packaging of objects, object pooling, just-in-time-activation (JITA), queued components, and loosely coupled events. When used together, these functions give architects the tools to implement a complete server application process model.

One of the most confusing aspects of Enterprise Services is when to use them. If your existing systems use COM+ extensively, you’ll naturally want to use Enterprise Services when porting your applications to .NET. But if you don’t use COM+ today, how do you get started and what’s the benefit?

Implementing transaction support
To understand how you can get started with Enterprise Services, let’s look at how you implement transaction support in three different scenarios: traditional distributed applications, Web services, and ASP.NET applications. It’s important to differentiate between how developers handle transactions in the COM+ world vs. .NET. In COM+, developers manually start a transaction and then check conditions to determine whether the transaction should be committed or aborted. But .NET lets you handle transaction commits and aborts automatically by using declarations exposed through attributes. In other words, you can think of distributed transactions as automatic or declarative transactions in .NET. (Developers still have the option of coding commits and aborts manually if they need that granular level of control.)

Traditional distributed applications
For a traditional distributed application, the developer needs to create a server object and then code the client to call the server object. Here’s a simple implementation of a server object implemented in C#:

View Code CSHARP
using System;
using System.EnterpriseServices;
[assembly : ApplicationName("TxDemo")]
 
[Transaction]
public class Account : ServicedComponent {
[AutoComplete]
public void Credit() {
// do some work
} }

We should note three important items from this sample. First, the statement, using System.EnterpriseServices; gives you access to attributes in the Enterprise Services namespace. Second, the Account class inherits from the existing ServicedComponent class, where it gets its ability to be managed by EnterpriseServices. Finally, the Transaction and AutoComplete attributes make objects instantiated from this class transactional. The AutoComplete attribute tells EnterpriseServices to commit the work done in the Credit function unless an error occurs, in which case it should abort. You still can catch exceptions and swallow them (i.e., not Throw them up the call stack) with AutoComplete committing the transaction.

Here’s the code required to use the Credit object from a client application:

View Code CSHARP
public Class AccountClient {
private void Transactions_Click() {
Account account = New Account();
order.Credit()
} }

Notice that the client has no idea that the server object uses transaction management.

Web Services
If your users need to consume resources managed by Enterprise Services but access them through a Web Services interface, you can expose those resources using parameters on the WebMethod attribute declaration. For example, the code below allows the WebMethod DeleteAuthor to create a new transaction before attempting to delete the author passed in by the user of the Web service:

View Code CSHARP
[WebMethod(TransactionOption=
TransactionOption.RequiresNew)]
public int DeleteAuthor(string lastName) {
//…
}

Any other business objects called by this WebMethod automatically inherit its transaction context as long as they are marked to either Support or Require a transaction.

ASP.NET applications
Using transactions from ASP Pages is simple, as well. You add a page-level directive like this:

View Code CSHARP
<%@ Page Transaction="Required" %>

The Required setting allows this page to initiate a new transaction if it’s not already participating in an existing one. Any components called by this page will participate in the same transaction context.

What’s the benefit of Enterprise Services?
Before we look at the benefit of Enterprise Services, let’s first consider the widely discussed downside: performance. It’s true that calling serviced components is slower than calling other objects. This is because creating context and crossing context boundaries imposes overhead on your applications. But calling serviced components hosted in library applications (these run in-process with the application) is nearly as fast as calling nonserviced components. Server applications have a higher call time due to crossing process or machine boundaries. You determine whether components run as library or server applications when you install them in COM+.

But here’s the real issue: In most real-world applications, the performance cost of the infrastructure required to support Enterprise Services is minimal compared to the cost of the actual work that the component does. Moreover, if you didn’t use the features provided by serviced components, your code will likely have to do additional work to get the same functionality.

So when should you use serviced components? In general, if your application architecture can benefit from the services (like guaranteed transactions) provided by Enterprise Services, serviced components are worth the performance cost. You should also consider the ease of development and future expansion benefits of developing with serviced components. Development is simpler with serviced components. If you use a SqlTransaction object or OleDbTransaction object to manage transactions, you’ll have to manage the transaction yourself. With Enterprise Services, you simply add a Transaction attribute to your object(s). Enterprise Services ensures that transactions managed between multiple objects happen logically and consistently. For example, you won’t have to add any special logic to determine whether an object is the root of a transaction.

Future expansion is easier to accomplish if you code systems using serviced components from the start. Suppose you create an order management system that includes inventory tables managed as part of the overall order transaction. What if, in the future, the inventory tables move to a separate database? What if the inventory object is moved to a remote server? What if one of the objects wants to dispatch to a transactional message queue? If you built the system with manual transaction management, you’ll have to rewrite it in order to make it work in a distributed environment. Had you built the system using Enterprise Services, you could make these deployment decisions without requiring changes to the underlying application.

It will take time to learn how to implement serviced components correctly. And you may not need to use them for many of your smaller applications. But employing their functionality correctly for distributed applications will pay off in the long term because they allow you to make deployment decisions without regard for design decisions you made during development.


May 14, 2008 Author: Ashish | Filed under: .Net

Schmap, publisher of over 200 free online travel guides, has opened access to their guides for iPhone and iPod Touch users by way of a remarkably nifty web application. The guides cover cities throughout the US, Europe, Australia, Canada, and New Zealand, and provide information on everything from the city’s historical background to the best places to get your drink on.

schmap.pngAs portrayed in the image, the web app utilizes the iPhone’s gyro sensors and a Safari specific JavaScript function to determine how the device is currently oriented, and swaps between two display modes accordingly. If the device is oriented vertically, points of interest are displayed as a simple list; if horizontal, the points are overlaid on a map of the area. This allows the user to jump back and forth between modes without having to dig through menus, and is an ingenious way to make the most of the available screen real estate.

In addition to the city guides available for many major cities, Schmap is working on implementing a local search feature to provide similar functionality for cities they haven’t charted out yet. While local search results obviously won’t be as in-depth as the custom written city guide entries, it provides enough to get by: the business name, street address, and phone number. It did a good job of finding coffee shops in my area, even pointing out a few I’d somehow managed to ignore. I was unable to get the local search to recognize any zip codes, so you may need to type out the city’s name for the time being.

My only dislike with the service thus far is the tiny size of some of the buttons. I definitely don’t have sausage fingers, yet I constantly found myself tapping just outside of the detection areas. This was especially true of the arrows at the top and bottom of the interface.

Overall, Schmap for iPhone/iPod Touch is an incredibly handy application, especially while traveling or getting to know a new area. I’d expect to pay a few bucks a month for the service; that it’s free is just the mega delicious icing on the cake.


May 14, 2008 Author: Ashish | Filed under: iPhone

Advertisement

Adsense