Showing posts with label tutorial. Show all posts
Showing posts with label tutorial. Show all posts

Friday, 21 October 2011

What is OSSAMS?


As information security professionals, we conduct security assessments for companies. One of the biggest problems we have is after all the data is collected, how can we correlate the data accurately. So we decided to start a project to solve this problem, and we are calling it Open Source Security Assessment Management System (OSSAMS). OSSAMS is a framework for putting configuration files, security scan data files (like Nessus), and other data collected, during a security assessment or penetration test, into a RDBMS.


The framework is going to be designed in a fashion similar to Metasploit, SNORT, or other systems that allow the security community to create plugins for new tasks as needed. The primary goal of OSSAMS is to normalize the data, there by allowing the security professional to better assess the current state of security for an organization.
Completed:
acunetix, burp, grendel, nessus, netsparker, nexpose community, nikto, nmap, ratproxy, retina community, skipfish, sslscan, w3af, wapiti, watcher, websecurify, zap.
Roadmap:
Appscan, arachni, core impact, fierce, httprint, iss, languard, metasploit, ncircle, nexpose, n-stalker, ntospider, openvas, proxystrike, retina, saint, sandcat, webcruiser, webinspect, wsfuzzer…
Requires:
Python > 2.5;
Python-mysqldb; and
Lxml.
Download OSSAMS Alpha

Wednesday, 19 October 2011

Disable the Ubuntu 11.10 Guest Session


I am a bit of a security wonk and strongly dislike guest accounts so one of the things I have researched since loading up Ubuntu 11.10 is how to disable the guest account available on the login screen. In the past, with GDM, all that had to be done is an uninstall of gdm-guest-session. With Ubuntu 11.10 switching to lightDM this has changed. To remove the guest login option you have to modify /etc/lightdm/lightdm.conf.
original
[SeatDefaults]
greeter-session=unity-greeter
user-session=ubuntu
modified
[SeatDefaults]
greeter-session=unity-greeter
user-session=ubuntu
allow-guest=false
You can either reboot or restart the service.
sudo restart lightdm
Please note that restarting lightdm will end your session so do not do this with applications running. This will now remove the guest login as an option from the login screen. I hope this helps out anyone, who like me, is concerned about restricting access to their computer.

Monday, 17 October 2011

How to run windows games on Linux?


So, you just started using Linux, but found out that your favorite Windows games and applications do not have a Linux edition. What should you do then? Set up a separate computer just for Windows, or abandon Linux and go back to Windows. If you have the means, you can opt for the former, but the second option is not necessary.
Why? Well, you see, you can run many Windows games and applications directly in your favorite Linux distribution, without installing Windows. That magic is made possible by an application called Wine. (The name is recursive for Wine Is Not an Emulator.)
Running Wine is very simple. Because it is already in your distribution’s repository, all you need to do is install it using your distribution’s package manager. But installing it is just the beginning. You have to configure it.
But even that is easy because most people running Wine configure and manage it using a graphical frontend, of which there is just a few in active development. In this article, I will list the graphical interfaces that are still in active development.
Note that not all Windows programs will run on Wine, and even some that run will not do so without one or more minor or major issues that will need fixing.

There are four graphical interface still in active development. They are: Winetricks, PlayonLinux, WineGame, and Q4wine.
  1. Winetricks – This is the best of the frontends. It was a lot more fun to use than the others. Its most important feature is that it makes it easy to install trial or demo applications without you actually having the applications or games. It does that by downloading and installing selected applications from the program’s website. This is its startup interface.
    WineTricks
    And this is a partial list of available applications. Those that show “download” in the “Media” column are automatically downloaded and installed.
    World of Warcraft
    That was how I installed World of Warcraft (WoW). This is a screenshot from a test installation.
    World of Warcraft (WoW)
  2. PlayonLinux – Offers a simple to use interface, but does not have the automatic download-and-install feature of Winetricks. What it does have, however, is a very active community.
    PlayonLinux
  3. WineGame – This will probably not be in your distribution’s repository, but you may install it by following the instructions here. I did not have much success working with WineGame, but that should not stop you from trying it. The image below shows the main interface.
    Winegame
  4. Q4wine – This a Qt4 interface for Wine, and runs on Linux and FreeBSD, which likely means that it will also run on PC-BSD. Like PlayonLinux and WineGame, Q4wine did not work as well as Winetricks. A few of its features are:
    • Can work with different versions of wine simultaneously
    • Makes it easy to extract icons from PE files (.exe .dll)
    • Autostart icons support
    This image shows the startup view of Q4wine.
    Q4Wine Setup
    And this, shows the Programs tab. You may view more screenshots here.
    Q4Wine Interface

Google command line (GoogleCL)


Google command(GoogleCL) line allows you to use command line for the basic features: 

GoogleCL brings Google services to the command line.
We currently support the following Google services:
  • Blogger
  • $ google blogger post --title "foo" "command line posting"
  • Calendar
  • $ google calendar add "Lunch with Jim at noon tomorrow"
  • Contacts
  • $ google contacts list Bob name,email > the_bobs.csv
  • Docs
  • $ google docs edit "Shopping list"
  • Finance
  • $ google finance create-txn "Savings Portfolio" NASDAQ:GOOG Buy
  • Picasa
  • $ google picasa create "Cat Photos" ~/photos/cats/*.jpg
  • Youtube
  • $ google youtube post --category Education killer_robots.avi

Saturday, 15 October 2011

Play with Cakephp's find query


CakePHP allows you to use your own "find-types" for the Model::find() methodology. Those of your who are familiar with the find() method know that there are currently four types in the core: 'list', 'all', 'first' and 'count'. However, sometimes it is nice to specify your own type so you can have a call like this:
$this->Comment->find('pending');
So how would you go about implementing this? Correct, you would overwrite the find() method in your model and provide the default functionality if there is one of the default types used. Let's have a look at how you could implement this pending find from above:
class Comment extends AppModel {
  var $belongsTo = array('User');

  function find($type, $queryData = array()) {
    switch ($type) {
      case 'pending':
        return $this->find('all', array(
          'fields' => array('User.email', 'User.first_name', 'User.last_name', 'Comment.name')
          , 'conditions' => array(
            'Comment.active' => 0
            , 'Comment.blocked' => 0
          )
          , 'contain' => array('User')
        ));
      default:
        return parent::find($type, $queryData);
    }
  }
}
So this is actually not very difficult code, but it is very powerful. You could specify different sets of conditions, fields, orders, groups by's and containments just by adding a new entry to the switch statement. Please note that there is no break needed within the switch as we return home.
Let's add some code for finding pending users that were invited by the currently logged-in user. This is what we could use in the controller:
$this->Comment->find('pending', array('created_by_id' => User::get('id')));
Now for the model we would need to add some code that tracks if $queryData['conditions'] is set, and use that as well in conjunction with the conditions specified in our find type. While we are at it, let's also add some code that would handle fields, order, group, recursive and contain statements:
class Comment extends AppModel {
  var $belongsTo = array('User');

  function find($type, $queryData = array()) {
    $defaults = array(
      'conditions' => null
      , 'fields' => array()
      , 'order' => null
      , 'recursive' => null
      , 'contain' => null
    );
    $queryData = am($defaults, $queryData);

    switch ($type) {
      case 'pending':
        return $this->find('all', array(
          'fields' => am(
            array('User.email', 'User.first_name', 'User.last_name', 'Comment.name')
            , $queryData['fields']
          )
          , 'conditions' => am(array(
            'Comment.active' => 0
            , 'Comment.blocked' => 0
          ), $queryData['conditions'])
          , 'contain' => am(array('User'), $queryData['contain'])
        ));
      default:
        return parent::find($type, $queryData);
    }
  }
}
With some default values we can happily use our custom find type alongside dynamic conditions inserted by our controllers. If you think this am() stuff is overkill, you could as well just provide another find type:
$this->Comment->find('pending-created-by-logged-in-user');
class Comment extends AppModel {
  var $belongsTo = array('User');

  function find($type, $queryData = array()) {
    switch ($type) {
      case 'pending':
        return $this->find('all', array(
          'fields' => array('User.email', 'User.first_name', 'User.last_name', 'Comment.name')
          , 'conditions' => array(
            'Comment.active' => 0
            , 'Comment.blocked' => 0
          )
          , 'contain' => array('User')
        ));
      case 'pending-created-by-logged-in-user':
        return $this->find('all', array(
          'fields' => array('User.email', 'User.first_name', 'User.last_name')
          , 'conditions' => array(
            'Comment.active' => 0
            , 'Comment.blocked' => 0
            , 'Comment.created_by_id' => User::get('id')
          )
          , 'contain' => array('User')
        ));
      default:
        return parent::find($type, $queryData);
    }
  }
}
... well you get the idea. By the way, do you notice how useful using a static functions like this User::get() methods are for fetching properties and data from the currently logged in user? More on that later.

Thursday, 13 October 2011

Ubuntu 11.10 (Oneiric Ocelot) tweaks



Some of those tweaks still work but since this is a new version, there are new things that need tweaking so I've decided to make a new post with some popular old tweaks as well as some new ones.

Read on!



Tux

General tweaks (for both GNOME Shell and Unity)



Change themes, fonts and more with GNOME Tweak Tool


GNOME Tweak Tool

In Ubuntu 11.10 Oneiric Ocelot you can only switch between the default GTK themes by default. Also, there's no built-in GUI to easily change fonts or icon themes. But you can do this using GNOME Tweak Tool:
sudo apt-get install gnome-tweak-tool

Once installed, GNOME Tweak Tool should show up as "Advanced Settings" in the menu. Besides changing fonts or themes, GNOME Tweak Tool can also be used to enable/disable GNOME Shell extensions, tweak the desktop, various windows behavior or GNOME Shell.



No screensaver in GNOME 3.2


Screensaver

GNOME 3 doesn't have a screensaver, just a black screen. If you want to use a screensaver, you can use Xscreensaver - install it using the following commands (this will also remove gnome-screensaver):

sudo apt-get remove gnome-screensaver
sudo apt-get install xscreensaver xscreensaver-gl-extra xscreensaver-data-extra

Then search for "Screensaver" in the menu and tweak its settings to your needs.

To add Xscreensaver to startup, open Startup Applications and add "xscreensaver -nosplash".


Let's also make the lock screen work (CTRL + ALT + L):
sudo ln -s /usr/bin/xscreensaver-command /usr/bin/gnome-screensaver-command

To be able to watch a movie properly, also install Caffeine:
sudo add-apt-repository ppa:caffeine-developers/ppa
sudo apt-get update
sudo apt-get install caffeine python-glade2

To revert the changes (go back to the black GNOME Screensaver screen):
sudo apt-get remove xscreensaver xscreensaver-gl-extra xscreensaver-data-extra
sudo rm /usr/bin/gnome-screensaver-command
sudo apt-get install gnome-screensaver



Nautilus search


Partially fix annoying Nautilus behavior that doesn't let you properly search by typing when there are a lot of files/folders: in Nautilus, select View > Statusbar.



Install Syanptic


Synaptic

Synaptic is not installed by default in Ubuntu 11.10 and while Ubuntu Software Center got many new features, it still can't do everything Synaptic can. Install Synaptic back using the following command:
sudo apt-get install synaptic



Disable Overlay Scrollbars


no overlay scrollbars

If you don't like the overlay scrollbars, you can remove them using the following command:
sudo apt-get remove overlay-scrollbar liboverlay-scrollbar3-0.2-0 liboverlay-scrollbar-0.2-0
Then, restart your computer (performing a logout only may not be enough).

To revert this change, install the packages back:
sudo apt-get install overlay-scrollbar liboverlay-scrollbar3-0.2-0 liboverlay-scrollbar-0.2-0
And restart your computer.



Missing features: web apps and file previewer


Two missing GNOME 3.2 features in Ubuntu 11.10 Oneiric Ocelot (for both Unity and GNOME Shell) are the web applications and Sushi quick previewer.


Epiphany web app

The first requires Epiphany 3.2.0 which is available in the WebUpd8 GNOME 3 PPA:
sudo add-apt-repository ppa:webupd8team/gnome3
sudo apt-get update
sudo apt-get install epiphany-browser

Sushi file previewer

And the second - Sushi file previewer -, is available in the official Ubuntu repositories:
sudo apt-get install gnome-sushi




Longer battery life


Jupiter

I don't know if the kernel power bug is real or not, but many users have reported that using Jupiter or a tweak we've posted a while back, their laptop/netbook battery life increased. Install Jupiter using the following commands:
sudo add-apt-repository ppa:webupd8team/jupiter
sudo apt-get update
sudo apt-get install jupiter

If you have an EeePC, also install the following package for SHE support:
sudo apt-get install jupiter-support-eee

As for the other tweak, see this post: Linux Kernel Power Issue / Overheat Workaround.



No more Sun/Oracle Java


The "sun-java6" package is no longer available in the official Ubuntu 11.10 Oneiric Ocelot repositories due to the removal of the JDL license. Java 7 won't be in Oneiric either, but you still have 3 options:

- Install OpenJDK:
sudo apt-get install openjdk-7-jre

- Or Oracle (previously Sun) Java 6 from the LFFL PPA:
sudo add-apt-repository ppa:ferramroberto/java
sudo apt-get update
sudo apt-get install sun-java6-jdk sun-java6-plugin

- Or manually install Java 7 (JDK) in Ubuntu 11.10 Oneiric Ocelot.



GNOME Shell tweaks


Fix ALT + F2


Fix alt f2 GNOME Shell

ALT + F2 doesn't work by default in GNOME Shell under Ubuntu 11.10 Oneiric Ocelot. To fix it, open "System Settings" and under Keyboard > Shortcuts > System, click "Disabled" next to "Show the run command prompt" and press ALT + F2 - this should set ALT + F2 for running the command prompt.



Easily change GNOME Shell themes


To be able to easily change the GNOME Shell theme, besides GNOME Tweak Tool you'll also need the User Theme extension, available in the WebUpd8 GNOME3 PPA:
sudo add-apt-repository ppa:webupd8team/gnome3
sudo apt-get update
sudo apt-get install gnome-shell-extensions-user-theme

Then use GNOME Tweak Tool to activate the theme.

For more extensions, see: Official GNOME Shell Extensions Available In The WebUpd8 GNOME 3 PPA For Ubuntu 11.10.



Move icons from Message tray (bottom tray) to the Top Bar


GNOME SHell icons top bar

Some might find the notification area icons showing up in the Message Tray (at the bottom of the screen, hidden by default) annoying or confusing. But you can move the icon on the Top Bar using an extension:
sudo apt-get install git-core
cd
git clone https://github.com/rcmorano/gnome-shell-gnome2-notifications.git
sudo cp -r gnome-shell-gnome2-notifications/gnome-shell-gnome2-notifications@emergya.com /usr/share/gnome-shell/extensions/

Then press ALT + F2 and enter "r" to restart GNOME Shell.

Important: this extension shows up as disabled in GNOME Tweak Tool because of an error in the extension code. Despite this, the extension still works!



No shutdown menu entry


Alternative status menu gnome shell extension

By default, there's no shutdown entry in the status menu and you must press and hold ALT to be able to shutdown your computer when using GNOME Shell. But this can be changed by installing Alternative Status Menu extension which adds "Power off" and "Hibernate" to the status menu, visible at all time (and not just when pressing the ALT key). Install it:

sudo add-apt-repository ppa:webupd8team/gnome3
sudo apt-get update
sudo apt-get install gnome-shell-extensions-alternative-status-menu

Then use GNOME Tweak Tool to enable the extension.



Fix Nautilus menu being displayed under the GNOME Shell top bar when using transparent GNOME Shell themes


Nautilus menu under gnome shell top bar

If you use a transparent GNOME Shell theme such as Zukitwo, the Nautilus menu shows up behind the top bar. You can fix this either by removing global menu (see below, under "Unity tweaks") or by disabling Nautilus from handling the desktop using GNOME Tweak Tool (under "Desktop", set "Have file manager handle the desktop" to off):

tweak tool handle desktop

Disabling Nautilus from handling the desktop means you won't have any icons on the desktop anymore. If this is a big deal to you, remove AppMenu (Global Menu) - but you won't have a global menu in Unity anymore (though that shouldn't be a big issue if you don't use Unity anyway).

To install GNOME Tweak Tool, see the first tweak in this post.



Unity tweaks



Configure Unity (autohide, etc.)


CompizConfig Settings Manager UNity settings

Unity 3D can be configured through CompizConfig Settings Manager, but CCSM isn't installed by default so let's install it:
sudo apt-get install compizconfig-settings-manager

Using CCSM you can configure the Unity Launcher reavel mode and timeout, the Unity Launcher autohide (autohide, dodge windows, dodge active windows or disable autohide), various keyboard shortcuts, the new ALT + TAB switcher behavior, blacklight mode, panel and launcher opacity, launcher icon size and more.

A few quick stuff I for one always tweak using CCSM (open CompizConfig Settings Manager and click the "Ubuntu Unity Plugin"):

To disable launcher autohide: on the "Behavior tab" under "Hide Launcher", select "Never".

To disable mounted devices from showing up on the Unity Launcher: on the "Experimental" tab, under "Show Devices" select "Never".

By default, applications that usually take 75% of the screen are maximized automatically on start. To change this automaximize value, on the "Experimental" tab, look for "Automaximize value" - tweak this to whatever value you want.





Configure Unity 2D


Dconf editor

Some Unity 2D settings as well as other tweaks can be performed using "dconf-editor", part of the "dconf-tools" package. Install it using the following command:
sudo apt-get install dconf-tools

Then press ALT + F2 and enter: "dconf-editor" to launch it. You can find the Unity 2D settings under com > canonical > unity-2d.




Re-enable the systray (notification area)


Systray

You no longer need to whitelist Qt applications but you may still need the systray for other applications such as Shutter, Jupiter, etc. You can whitelist the systray using the following command:
gsettings set com.canonical.Unity.Panel systray-whitelist "['all']"

Then log out and log back in.




Disable Global Menu (AppMenu)


Disabled global menu ubuntu

Don't like the global menu? Get the menu back in the application window instead of using a global menu on the top panel:
sudo apt-get remove appmenu-gtk3 appmenu-gtk appmenu-qt

Then, restart your computer (performing a logout only may not be enough).

You can also disable the global menu without removing any package. See HERE.

To revert the changes, install these packages back:
sudo apt-get install appmenu-gtk3 appmenu-gtk appmenu-qt

And restart your computer.




Use a global menu for LibreOffice


Global menu libreoffice

By default, LibreOffice doesn't come with a Global Menu but you can manually install it:
sudo apt-get install lo-menubar

If you experience any issues with it, simply remove it:
sudo apt-get remove lo-menubar


Disable the user switcher indicator


No user switcher indicator

The user switcher indicator (or Me-User-Indicator or whatever is called) can be useful if multiple users log in on your computer but if it's just one user, you can get more space by disabling it. Presuming you've already installed the "dconf-tools" package: press ALT + F2 or open a terminal and enter:
dconf-editor

user switcher

Then navigate to apps > indicator-session and uncheck the box next to "user-show-menu", then restat Unity (ALT + F2 and enter "unity --replace") or log out and log back in.



Something went wrong! How do I reset Unity or Compiz?


You can easily reset Unity or Compiz using the following commands (be careful when using these commands and only use them if you really have to!):

- to reset the Unity launcher icons:
unity --reset-icons

- to reset Unity:
unity --reset

- to reset Compiz:
gconftool-2 --recursive-unset /apps/compiz-1
unity --reset


Using a different "shell"


By default, Ubuntu 11.10 Oneiric Ocelot uses Unity 3D (with Compiz). If you don't like it, you can try a different interface, while still using GNOME:


Unity 2D
Unity 2D

Unity 2D is installed by default and is used as the fall-back mode for computers that can't run Unity 3D. To use Unity 2D, log out and select "Ubuntu 2D" in the login screen:

Ubuntu Unity 2D




GNOME Shell
GNOME Shell

GNOME Shell is not installed by default but you can easily install it from the official Ubuntu repositories:
sudo apt-get install gnome-shell

Once installed, log out and select "GNOME" from the login screen:

GNOME SHell session




Classic GNOME 3 session
Classic GNOME 3 session

You can also use the GNOME 3 classic session. Install it using the following command:
sudo apt-get install gnome-session-fallback

And select "GNOME Classic" from the login screen:

Classic GNOME

When a hacker deletes all your mails


 Many people are concerned about hacked e-mail accounts (even celebrities), but what about when several years worth of your digital file cabinet are deleted, say, by a malicious intruder?
That happened to Deb Fallows six months ago, and her husband, author James Fallows, wrote a riveting account of their ordeal for The Atlantic that makes for fascinating reading.
His words of advice are: use strong, unique passwords on important important online accounts; take advantage of Google's two-step verification service; and back up our cloud-based data on our own. Oh, and act fast. Deleted messages are purged from the Trash folder after about a month.

In a nutshell, someone somehow got a hold of his wife's Gmail password and sent scary "Mugged in Madrid" messages to her contacts (including ex-Google CEO Eric Schmidt, who sent a "terse" e-mail to the author with the subject line of "Deb's e-mail has been hacked"), diverted her incoming messages to an outside account and pretended to be her in e-mail exchanges with concerned and or dubious friends and family. The hacker then deleted six years worth of correspondence. Poof!
Google initially was only able to retrieve a fraction of the deleted data and said the rest were not recoverable and that Google "will not be able to respond to any further e-mails on this case." That's when being a prominent writer with the likes of Schmidt in your address book comes in handy.
Fallows dashed off an e-mail to a top Google engineer to the effect of: "You (Google) cannot be serious about this. You cannot entice people into relying on your services, and be so cavalier about the risks they are exposed to. Can you?"
Suffice it to say his connections and persistence pay off. But his resulting crisis of faith in cloud computing drives him on a journey into the bowels of the Googleplex where he seeks reassurance that we're not fated for digital disaster.
"How could big tech companies offer cloud services to hundreds of millions of people without better guarding their data against catastrophic loss?"

Wednesday, 12 October 2011

JQuery Template Engines and JSON Services


Introduction

This article will present a model for development of pure client-side applications where all the processing logic is implemented using jQuery and information is presented to the user directly on the client side using JavaScript View engines. In this application model, there is no server-side code except the Web Services that provide data. The only communication between the client side and the server-side code is done using AJAX calls that provide data and all the processing is done in the client-side code. This model is most suitable for JavaScript plugins but can be applied in pure JavaScript applications.
JavaScript view engines are a new and interesting concept in web development. Classic web application development uses the same logic when pages are shown to the user - content that should be shown in the client’s browser is generated on the server side, and HTML, CSS, JavaScript, and other content is sent to the browser and presented to the user. If we take a look at the standard Model-View-Controller model, applications take data from some persistent storage (Model), perform some processing (Controller), and pass data to some rendering component (View) where the model is rendered. Regardless of what technology is used on the server-side (ASP.NET, J2EE, PHP), this logic is more or less applied in all application frameworks.
The logic behind this approach is an assumption that we have powerful and scalable servers, farms, clusters, or clouds on the server-side that can handle any number of requests, and that the client browser is weak and should not have a lot of processing. However, knowing that client computers have become more powerful and that browsers are getting faster, you might consider moving some logic to the browser. If you are using jQuery, processing logic is encapsulated in jQuery plugins that perform actions in the browser. JavaScript view engines introduce a new concept in web application development. Using JavaScript view engines, you can generate the view directly in the browser instead of on the server. If JavaScript view engines are used, server-side components (Controllers) send JavaScript objects represented in JSON notation (these JSON objects are Models), and these objects are rendered in the browser (in this case, the browser is a View component). The communication between the client-side code and server-side code is performed via AJAX calls. There are lot of JavaScript view engines such as jQuery template, Pure, noTemplate, jsTemplate, Populate that can be used to transform JSON to HTML – in this article, we will use the loadJSON plugin.
The general usage of the client-side view engines will be shown in the following example. I will assume that the following JavaScript is sent from the server and used as a model on the client side:
var data = {
            "Name":"Emkay Entertainments",
            "Address":"Nobel House, Regent Centre",
            "Contact":"Phone"
} 
This JavaScript object can be directly generated from the server-side, returned via a Web Service call, or loaded via some AJAX call. To show this object in the browser, we would need to have some kind of template – the following template can be used with the loadJSON plugin:
<div id="data">
    <h1 id="Name"></h1>
    <label for="Address">Address:</label>
    <span id="Address"></span>        
    <label for="Contact">Contact by:</label>
    <span id="Contact"></span>
</div>
In this template, we have classes that match properties on the JavaScript object by name. The jQuery loadJSON plugin matches the JavaScript object with classes, ID, and names of the HTML elements and loads the JSON object into the template using the following call in the JavaScript code:
("#data").loadJSON(data); 
The result of this call is a template populated with the information from the JavaScript object. An example is shown below:
<div id="data">
    <h1 id="Name">Emkay Entertainments</h1>
    <label for="Address">Address:</label>
    <span id="Address">Nobel House, Regent Centre</span>        
    <label for="Contact">Contact by:</label>
    <span id="Contact">Phone</span>
</div>
More details about the loadJSON plugin can be obtained on the plugin site. I have described how JavaScript View engines can be used with ASP.NET MVC applications in the “Using JavaScript View Engines in the ASP.NET MVC” article, where I describe how you can generate a list, display details, populate a form used for editing, or generate a hierarchical report. If you want to see how JavaScript view engines can be used, you might take a look at this article. In this article, I will present a new concept of usage of JavaScript engines – integration with third party applications directly in the browser.

Background

JavaScript View engines enable you to create fully functional client-side applications without server-side code that generates HTML. If you are using JavaScript View engines and AJAX, you can make queries to the Web Services that return response that can be handled on the client side. If you have some public Web Service that provides information via JSON format, you can create pure JavaScript code that calls this service and use JavaScript view engines to generate content directly in the browser window. The concept of using Web Services from the client-side code is shown in the following figure:
application-conceptual-model.png
Although everything is done on the client side, you will need to have a web server where the page will be placed and loaded in the browser using a standard HTTP GET or POST request. The web server should return an initial HTML of the web page. Once the page is loaded, the application that works with the JavaScript view engines can take all the necessary information from the Web Services. Using AJAX calls, you can send requests back to the server or even to third party services, take a response, and show it in the browser window using JavaScript view engines. If AJAX calls are sent to the original server, a standard JSON object will be returned; however, if AJAX calls are sent to the other servers, JSONP protocol should be used (you can find more information about the JSON/JSONP AJAX calls below).
As you can see, once the page is loaded in the browser, AJAX is the basic communication protocol between the client and server.
In this article, we will use Bing Maps as a public service, and we will see how to create a pure JavaScript application that calls Bing Maps using AJAX calls, take JSON response, and show it in the page. For converting JSON to HTML, we will use the loadJSON plugin but any other view engine can be used instead. If we use the MVC model to describe the application structure, in this type of application, we have the following components:
  1. Model - The model represents the information structure taken from the remote service. In this example, the model is a JSON object retrieved from the Bing Maps Web Service. The information in the model objects will be shown to the user in the browser.
  2. Controller – In this application model, the controller is also moved to the client-side. The Controller has functionalities implemented in JavaScript using the jQuery library that reacts on the client events, takes model data from the services, and sends them to the view engine.
  3. View is the JavaScript view engine that generates the HTML based on the JSON model. In this example, the loadJSON plugin is used as the view engine.
As you can see, this is the application model for a fat-client application where both the controller and view are implemented as JavaScript components. In this code example, we will create a JavaScript application with the following features:
  1. It will enable the user to search locations by keyword - the results will be shown in the list and on the map.
  2. The user will be able to position any result in the center of the map.
  3. The user will be able to adjust the zoom level of the map.

Bing Maps REST API

Bing Maps provide a set of Web services you can use to search addresses, generate maps, display routes between two points, etc. The only thing you need is a BingMaps key you can get on the Microsoft Bing Maps site (it is free). Once you have a key, you can send various queries to the BingMaps server. Bing maps provides both SOAP and REST Web Services. In this example, we will use the REST web services provided by the Bing Maps because they can be easily integrated with JavaScript code (SOAP Web Services are better for server-side calls). Examples of some requests you can send to the Bing Maps REST Web Services are:
  1. If you want to find objects on the address or using a keyword, you can open the following URL: http://dev.virtualearth.net/REST/v1/Locations/US/WA/98052/Redmond/1 Microsoft Way?o=xml&key=BingMapsKey
  2. You can also get the map of an area using the following call: http://dev.virtualearth.net/REST/v1/Imagery/Map/Road/47.619048,-122.35384/15?mapSize=500,500&pp=47.620495,-122.34931;21;AA&pp=47.619385,-122.351485;;AB&pp=47.616295,-122.3556;22&mapVersion=v1&key=BingMapsKey
As mentioned above, the only thing you need is a Bing Maps key that should be placed instead of the BingMapsKey in the examples shown above. I will not describe the details of the Bing Maps REST API but you can find more information at this link where you can find more examples.
Instead of Bing Maps, you can use any other public service - the only prerequisite is that the service supports the JSONP protocol.

Calling Services using AJAX Calls

Once you know what you can get from the external Web Service (Bing Maps in this case), you will need to make AJAX calls to this service. jQuery provides an easy way to send AJAX requests to the server-side page using the following code:
$.ajax({
        url: "<<URL>>",
        success: function (data) { }
 }); 
Instead of <<URL>>, you should place the real address of the web page or Web Service you want to call, and if the request succeeds, a success function fill be called.
This works fine when you make AJAX calls to the same server where your page is loaded, however, if the URL is on third party sites, the browser blocks the call. In most browsers, cross-site AJAX calls are not allowed and the result of the AJAX call will be an empty string. However, there is a way to perform cross-site AJAX calls if you are using the JSONP protocol. An example of the jQuery call to the URL using JSONP is shown in the following listing:
$.ajax({
        url: "<<URL>>",
        dataType: "jsonp",
        jsonp: "jsonp",
        success: function (data) { }
 });
If the server-side application accepts JSONP calls, a success functional will be called even if this is a cross-side call. You can find more information about creating JSONP requests on the jQuery site. The Bing Maps service allows the JSONP protocol so it can be used in this example.

Loading the Response into the Page

Once you perform an AJAX call and get a JSON object from the server-side, you can load it into the template using a JavaScript view engine (loadJSON plugin in this example). As described above, if you have a template that matches the JSON structure, you can load it easily into the page using the following code:
$("#template").loadJSON(data); 
This code should be placed in the success handler of the AJAX call. Once the JSON object is loaded into the page, you can attach the event handlers to the elements and perform additional AJAX calls to get new information if needed – without any server-side code.
In this section, basic concepts of usage of JavaScript view engines with third party public services is described. In the following section, an example of how you can create simple Bing Maps application with pure JavaScript logic is shown.

Using the Code

This example shows how you can use the loadJSON plugin to generate a simple Bing Maps interface. Note that this is just a case study that shows how you can use JavaScript view engines to integrate third party data – if you need a Bing Maps interface, it would be better to use some existing component such as Bing Maps JavaScript control or some jQuery Bing Maps plugin.
In this example, I will create a simple application that enables you to search for location based on query, display results in the HTML list and map, and enable some simple interaction with map (setting the center of the map, zoom-in, and zoom-out). The displayed results are shown in the following figure:
bing_maps_app.png
In the list and map are displayed all locations that match the search condition; the coordinates of the locations are paced in the links, and when you click on the link, the selected location will be placed in the center. You can see a live version of this application on the loadJSON demo page. The following sections describe the model, view, and controller code used to implement this example.

Model

As it is described above, model is JSON object returned by the Bing Maps service. In the following listing is shown JSON code returned by the Bing Maps service when query that returns location is executed:
{ 
  "brandLogoUri" : "http://dev.virtualearth.net/Branding/logo_powered_by.png",
  "resourceSets" : [ {
        "resources" : [ { 
              "name" : "Regent Street, London NW10 5",
              "point" : { "coordinates" : [ 51.528781000000002,-0.216583] }
            },
            { "name" : "Regent Street, London W1S 2",
              "point" : { "coordinates" : [ 51.511755000000001,-0.139491]  }
            },
            { "name" : "Regent Street, London W4 3",
              "point" : { "coordinates" : [ 51.488630999999998,-0.28262900000000002] }
            }
         ]
      } ]
}
Within the resources array is placed list of location objects that contains name of the location and point where location is placed. Point contains coordinates object that has latitude and longitude information. This information structure will be loaded using the view engine.

View

View is responsible for user interface and if you are using JavaScript view engines this is pure static HTML. In this example, we need a form where user can enter address and run a search. This is HTML code shown in the following listing:
<div id="searchDiv">
    <label for="searchBox">Search: </label>
    <input id="searchBox" /><button id="search">Search</button>
</div>
When the user performs a search, JSON results returned from the Bing Maps service will be loaded into the template. The structure HTML template matches the structure of JSON object. HTML template used in this example is shown in the listing below:
<div id="data" style="display:none">
 <img src="#" id="brandLogoUri" />
 <div id="copyright"></div>
 <div id="slider"></div>
 <img src="#" id="searchmap" />
 <ol class="resourceSets">
  <li class="resources">
   <span class="name"></span>
   <span class="point">
    (<a href="#" class="coordinates">
     <span rel="0"></span>,<span rel="1"></span>
    </a>)
   </span>
  </li>
 </ol>
 <a href="BingMapsSearch.html">New search</a>
</div>
In the HTML structure can be found empty elements with classes brandLogoUrl, name, and coordinates where JSON properties will be loaded. Elements with classes resourceSet and resource are placed just to match the structure of the JSON object. In the element with the class “point” are placed two elements with rel attributes 0 and 1 where first and second element of the coordinates array will be placed. In this structure can be loaded elements from the JSON object that represents a model. JSON object will be loaded into the template using a following JavaScript call:
 $("#data").ladJSON(data); 
Variable data will be returned as a response from the Bing Maps ajax call.

Controller

Controller is implemented on the client side as a set of JQuery event handlers. In this application, controller has the following functions:
  1. Finding a location that matches search query and displaying results in the list and map
  2. Setting some of the locations returned in the center of the map
  3. Zooming in and out map

Finding locations based on query

When user enters an address in the searchBox text box and presses the search button, AJAX call is sent to Bing Maps with a query and an authentication key. When the request is successfully completed, result of the AJAX call is loaded into the template, search form is hidden, and template is shown. In addition, center of the map is set and map is shown. Code for this action is shown in the following listing:
$("#search").click( function () {
  $.ajax({
                        url: "http://dev.virtualearth.net/REST/v1/Locations",
                        dataType: "jsonp",
                        data: {
                            key: key,
                            q: $("#searchBox").val()
                        },
                        jsonp: "jsonp",
                        success: function (data) {
    $("#searchDiv").hide();
    $("#data").loadJSON(data).fadeIn("slow");
    center = $($(".point .coordinates")[0]).text();
    showMap();
                        }
                    });
});
In the AJAX call is sent value entered in the searchBox text input so Bing Maps service can return locations that match this search query. The most important processing is placed in the success handler. When request is successfully completed search box is hidden, JSON results are loaded into the template and shown in the page, coordinates of the first point are found and set as a center of the map, and function for showing a map is called (this function fill be described later). Variable center is globally defined variable that is used in all functions described in this section.
Setting the position of the map 
In this example, when user clicks on the any link containing coordinates, selected location is placed as a center of the map. In the links with class "coordinates" are loaded coordinates of each location, so when user click on any of these links text will be set as center of the map as it is shown in the following listing:
  $("a.coordinates").live("click", function(event){
   center = $(this).text();
   showMap();  
  });
Once the center variable is set, map is refreshed using a showMap() method. Variable center is the same one that is used in the previous function.

Adjusting zoom level of the image

In this example application, the user is able to change the zoom level of the map. Changing the zoom level is enables using a JQuery UI slider where user can change value of zoom level between 1 and 19. Code for setting JQuery UI slide is shown in the following listing:
        $( "#slider" ).slider({
            value:12,
            min: 1,
            max: 19,
            step: 1,
            slide: function( event, ui ) {
                zoom = ui.value;
                showMap();
            }
        }); 
Slider is placed in the empty DIV with an id "slider" and it is initialized as a JQuery UI slider control with value ranges from 1 to 19 (these are set as zoom levels). When a slider value is changed in the slide event handler zoom value is set to the current value of the slider and map is shown again. Variable zoom is defined as a global variable.

Utility function for showing the map

The last part of JQuery code is a utility function that shows a map. Function is shown in the following listing:
function showMap(){
        var pushpins = "";
        var i = 1;
        $("a.coordinates").each(function(){ 
                               pushpins += "&pp="+$(this).text()+";;"+(i++); } );
        $("#searchmap").attr("src", 
            "http://dev.virtualearth.net/REST/V1/Imagery/Map/road/"+center+"/"+
            zoom+"?mapSize=600,400&ml=TrafficFlow&mapVersion=v1&key="+
            key+pushpins);
    }  
This function takes all coordinates from the links and format pushpins that will be placed on the map. Global variables center and zoom are set in the previous functions. Map is shown when src attribute of the image is set to the URL that returns image with pushpins from the Bing Maps server.

Conclusion 

I have shown in this article how you can use JavaScript view engine to create pure JavaScript components that use third party services (Bing Maps in this example). View engines enable you to move all processing to the client side and this is perfect if you are creating UI components such as JQuery plugins that should generate HTML based on the JSON data. View engines enable you to easily handle generating HTML and to focus on the logic of your plugin or client-side code.
Shown here are the basic concepts of creating fat-client JavaScript applications or plugins using JQuery, making cross-site calls to the external sites, and generating view on the client side using the loadJSON JavaScript view engine. This new application model is different from a classic server-side model where everything is generated on the server. Knowing that client computers get more powerful with more faster browsers that can handle lot of JavaScript processing, it is reasonable to consider moving some processing to the client side if this would improve performances of overall application.
Although it is shown here how Bing Maps service can be integrated in your site, this is not a guideline for using Bing Maps. If you want to integrate Bing Maps into your site, you should use something like a Bing Maps AJAX Control, Version 7.0. You will use code described in this article if you want to create your own plugins or maybe if you need simper or customized look of the Bing Maps control.
To see how this works, you can either download the code example or go to the live demo page.