Thursday, 11 March 2010

Killing Flash CS3 / AIR Processes and avoiding the "debugger launch failed" message

To kill an AIR application launched for testing from Flash CS3 open the task manager and kill the process idl.exe.

When working within the Flash CS3 development environment, lightweight or utility windows spawned from an AIR application are not killed when the primary AIR application window is exited. In fact, they are not even killed when Flash CS3 is closed.

Further, as long as these lightweight/utility windows are open you will not be able to to test your application. There simply will be no result from pressing ctrl+enter. Launching the debugger will only offer the message, "debugger launch failed!" If any part of the AIR application is still running you simply will not be able to test your application. Hence, you must go to the task manager and kill idl.exe!

Embedding Font in CS3 Components (Avoiding Disappearing Button Labels)

When a CS3 Component (i.e. a Button) appears under a mask the text disappears.
To fix this we simply embed the font in the Component. Unfortunately, this isn't like embedding font in a normal programatically generated TextField instance.

How To Embed Font in CS3 Components
(I will use the Button component for this example.)

1.First, we must embed the font in the swf. There are 2 ways to do this:

◦If you wish, you may simply create a TextField off stage and embed the font in that TextField.

◦Or if you have taste, you will open the library and select “new Font” from the library panel menu. Now, create a font symbol in the library. I chose Arial and set the linkage identifier for the font symbol to “ArialFont” exporting it for ActionScript.
2.With the font embedded in the swf, we now need to embed it in our component.
There is only one way to do this. Assuming that our button is named button_btn your ActionScript will look like this:


// you may replace new ArialFont().fontName with the string “Arial” if you prefer. (If you did not create a Font Symbol you must use the string “Arial”)

var tf:TextFormat = new TextFormat(new ArialFont().fontName);
button_btn.setStyle("embedFonts", true);
button_btn.setStyle("textFormat", tf);
button_btn.label = "fox";

3.That's it. The Font is now embedded in the CS3 Component.

A Note about things that don't work: components do not have a “fontFamily” style. The only way to control the style of text in components is to create an instance of TextFormat and set the Button's “textFormat” style to that instance of TextFormat. Also, you cannot set a style directly on the TextField object in the button component. (The CS3 Button Component's TextField can be retrieved through it's textField property.) Setting the style directly on the textField causes a runtime error. Also, setting the textField's defaultTextFormat object does not have an effect, as it is overwritten by the components default styles. Finally setting the textField.embedFonts property to true does not have any effect.

ReferenceError: Error #1056: Caused by Declaring Stage Instances Private

If you declare a stage instance private you get the message: "ReferenceError #1056 Cannot create property my_mc on StageIntanceDeclarationsClass"

This error occurs when you uncheck the "Declare Stage Instances Automatically" checkbox in the "ActionScript 3.0 Settings" dialogbox and proceed to declare stage instances as private variables in the class associated with the containing MovieClip.

A Note on Inheritances and Declaring Stage Instances:
You cannot choose to simply always declare stage instances automatically without forging the use of inheritance in classes linked to MovieClip Symbols. If you have a class APrime which is derived from class A and APrime is linked to a MovieClip Symbol, all stage instances used in the base class A must be manually declared in class A. "Declare Stage Instances Automatically" only declares instances in the class linked to the MovieClip Symbol and does NOT make those references available to any base classes.

Example:
Assume that the class StageIntanceDeclarations is set as the class associated with a MovieClip which c0ntains the MovieClip my_mc. Then the following code will cause ReferenceError #1056 at runtime.

package{
import flash.display.MovieClip;
public class StageIntanceDeclarations extends MovieClip
{
//Private Causes ReferenceError #1056
private var my_mc:MovieClip;
function StageIntanceDeclarations()
{
}
}
}

The output is as follows:
ReferenceError: Error #1056: Cannot create property my_mc on StageIntanceDeclarations.
at flash.display::Sprite/flash.display:Sprite::constructChildren()
at flash.display::Sprite$iinit()
at flash.display::MovieClip$iinit()
at TestStageIntanceDeclarationsBase$iinit()
at flash.display::Sprite/flash.display:Sprite::constructChildren()
at flash.display::Sprite$iinit()
at flash.display::MovieClip$iinit()

To avoid this error simply declare my_mc as public:
public var my_mc:MovieClip;

Sound and NetStream bytesTotal is zero until the entire file is loaded in IE

The bytesTotal property only returns the total number of bytes after the sound or video file has completely loaded in both IE and Safari. However, in Firefox bytesTotal will return the total number of bytes in a sound or video file as soon as the file begins to load.

Further the loadProgress, ProgressEvent.PROGRESS, event of the sound object does not fire as it should in Internet Explorer and Safari. Adobe makes no mention of this in their documentation! To show load progress in browsers other than Firefox the bytesTotal/getBytesTotal properties cannot always be used. You may need to have the total bytes loaded from XML or elsewhere.

Magna Cum Laude Complete!

Today, final grades posted assuring that I will graduate Magna Cum Laude with a Bachelors of Science in Computer Science.
(Suma Cum Laude is not offered by Western Washington University, making Magna Cum Laude the highest academic honor awarded.)

Its has been 3 years since I graduated from junior college with a Presidents Medal across degrees in digital media communications and an associate of arts. During the years at WWU, I spent my time delving into advanced physics, mathematics, and computer science exploring the underlying academics on which our interactive arts are founded.

flash.media.Microphone.rate What are the acceptable bit rates (bitrates)?

Adobe appears to have forgotten to publish the acceptable values for the flash.media.Microphone.rate property in the ActionScript 3.0 edition of their documentation.

The Adobe documentation on the rate (bitrate) property is limited to the following,
“The rate at which the microphone is capturing sound, in kHz. The default value is 8 kHz if your sound capture device supports this value. Otherwise, the default value is the next available capture level above 8 kHz that your sound capture device supports, usually 11 kHz. “

But, what If you want a rate (bitrate) other than 8 or 11 kHz ? If you are looking for the acceptable bit rates look no further. I dug this out of a tech note.

Sampling rate
Approximate data rate
5
5.512 kHz
1378 bytes/sec, or 11.025 K bits/sec
8
8.000 kHz
2,000 bytes/sec, or 16 K bits/sec
11
11.025 kHz
2756 bytes/sec, or 22.05 K bits/sec
22
22.050 kHz
5,513 bytes/sec, or 44.1 K bits/sec
44
44.100 kHz
11,025 bytes/sec, or 88.2 K bits/sec

Maximum AS3 (FileReference) file upload size 100MB or more?

From the adobe docs we can can not be sure that flash supports file uploads larger than 100MB. In my testing I have found no limit. I would be very interested in hearing about the client os/flash version, and server used by anyone who has found a file so large that it would not upload.

Here is what Adobe docs say:
"Although Flash Player has no restriction on the size of files you can upload or download, the player officially supports uploads or downloads of up to 100 MB. You must call the FileReference.browse() or FileReferenceList.browse() method before you call this method. "

However, in another area on the same page adobe points out the following:

"Note: In the initial version of ActionScript 3.0, the [file] size property was defined as a uint object, which supported files with sizes up to about 4 GB. It is now implimented as a Number object to support larger files. "

So it appears that Adobe also believes uploads larger than 4GB are possible but will not stand behind it.

Both quotes are from this page:
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/FileReference.html

Sunday, 28 February 2010

Creating Hello World application with Silverlight 3.0 with Visual Studio 2010

Silvelight is latest buzz in Microsoft.NET Technologies. Silverlight enable us to create rich user interface for the web based application. Let create a simple application to understand how Silverlight application works.
We will start creating application with file menu –> New Project –>Silverlight application a dialog for silverlight application will open like following.

Once you create a Silverlight application a new dialog will open to create a website which will host Silvelight application like following.

This website are used for hosting Silvelight application. Please note that Silverlight application can also run with simple html file also. After clicking on Ok it will create a simple project like following in solution explorer.
Now let's Create a simple button and on clicking on that button will print “Hello World” on screen.With Silvelight used Microsoft new UI Language called XAML which used to define the object in the SilverLight.
Once we create a silvelight application which will create a MainPage.xaml and MainPage.xaml.cs file for the same. It will create by default XAML like following.


<UserControl x:Class="MySilverLight.MainPage"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"mc:Ignorable="d"d:DesignHeight="300" d:DesignWidth="400"><Grid x:Name="LayoutRoot" Background="White"></Grid></UserControl>Here grid will be act as container like as we are using content pane in our asp.net application. Which can host the another objects like button text and other objects. Now I am creating a simple hello world button via adding following xml between <Grid> and </Grid> tag.

<Button x:Name="HelloWorldButton" Content="Push to print Hello World on Screen " Height="25" Width="250"></Button>

Here x:name is name of button and content is text that will display on button,width will specify width of button and height will specify height of button. It will create a simple button like following in the design layout of silverlight application as following.

Now let add a text block object which will print the Hello world text on the screen after clicking button with following XAML.

<TextBlock x:Name="Mytextbox" Text="Print Text" Height="25" Margin="75,197,92,78"></TextBlock>Which will create a text block just below the button like following. Here margin will define the margin from four side just like html. Text block will behave just like label in asp.net application

After that Let’s add a add a click event to button via modifying existing XAML like following .
<Button x:Name="HelloWorldButton" Content="Push to print Hello World on Screen " Height="25px" Width="250px" Click="HelloWorldButton_Click" ></Button>
It will create a click handler for the button we have added after then we can add code to print Hello World!! to event handler we have just create like following.

private void HelloWorldButton_Click(object sender, RoutedEventArgs e){ Mytextbox.Text = "Hello World!!!";}Now compile and run the application it will open a browser and once you click the button it will print a hello world!! text like following.

Delete all cookies and session in asp.net

Cookies are one of most important features of web application. From where we store little information on client side in one of my project we need to delete all cookies and as you can not delete cookies from server side so we have to expire them manually. Here is the code for that.

string[] myCookies = Request.Cookies.AllKeys;
foreach (string cookie in myCookies){
Response.Cookies[cookie].Expires = DateTime.Now.AddDays(-1);
}

Same way we can delete all session for following code.

Session.Abandon();

How to import your tweets into Google Buzz.

Social networking is a important feature for any person for professionally ass well as personally. You can stay in touch with your friends,colleague and other peoples thanks to social networking sites. Google Buzz is a counter part of twitter from Google. you can post anything on that and you don’t have limit of 140 characters just like. But now there are lots of social networking site available like Face book,Twitter,Orkut,LinkedIn and now Google Buzz and updating your profile and other things on every social networking site is a tedious job.So, I decided to synchronize my twitter account into Google Buzz. Adding your twitter account in Google Buzz is very easy. First open your Gmail Account and then click on Buzz it will redirect you to your Google Buzz screen. Then click on connected sites and following skin will appear.

Click on add it will ask your twitter name just put your twitter name and that’s it you have done with it. Your tweet will appear in Google Buzz depends on traffic from 1 min to 1 hour.

Sunday, 31 January 2010

EJB timers and the Transactions

EJB timers are transactional. If Transaction rolled back the timer creation is also rolled back. Similarly, if a bean cancels a timer within a transaction that gets rolled back, the timer cancellation is rolled back. Here the timer's duration is reset as if the cancellation had never occured.

System vs Application exceptions

System Exception: Problem with the services that support the application. It is usually Extension of EJBException. EJB Container might destroy the bean which threw the System exception. If thrown then the Transaction will be rolled back

Application Exception: Error in the business logic. Transaction will not be rolled back

MDB class requirements

•The class must be annotated with @MessageDriven annotation if it does not use the deployment descriptor.
•The class must be public
•The class cannot be defined as abstract or final
•It must contain public constructor with no args
•It must not define the finalize method
It is recommended, but not required, that a message-driven bean class implement the message listener interface (MessageListener)

Clients cannot call MDB directly, there is no interface.

MessageDrivenContext can be injected to the MDB as it provides a setRollbackOnly method

If we used @MessageDriven then we can specify the mappedName that specifies the name of the JNDI name of the destination from which the bean will consume messages. @ActivationConfigProperty can used for more complex MDB configuration

Entity class requirement

•Must be annotated with @Entity
•Must have public or protected no-arg constructor.
•Class must not be declared final. No methods or persistent instance variables must be declared final.
•If an entity is passed by value as detached object, such as through remote session bean interface, then the class must implement java.io.Serailizable
•Entity may extend both entity and non-entity classes, and non-entity classes may extend entity classes
•Persistent instance variable CANNOT be public (can be either private, protected or package)

Classes of security threats

•Accidental threats: Happens by human mistake
•Intentional threats: Human can open security hole in the system
•Passive threats: Only reading data, without changing the state of this data
•Active threats: Reading and changing the state of data

AdvantagesThree-Tier Architecture

•Changes in the user interface or the application logic are largely independent from one another, allowing the application to evolve easily to meet the new requirements
•Network bottlenecks are minimised because the application layer does not transmit extra data to the client; instead it transmits only what is needed to handle a task.
•When business logic changes are required, only the server has to be updated, in two-tier architecture, each client must be updated when logic changes.
•The client is insulated from database and network operations, the client can access data easily without having to know where data is or how many servers are on the system
•Database connection can be pooled and thus shared by several users, which reduces the cost of per-user licensing
•The application layer can be written in standard third- or fourth-generation languages, such as Java or C, with which the organisation's in-house programmers are experienced.
•The organisation has database independence because the data layer is written using standard SQL, which is platform independent

Architecture Terminologies

Availability: The degree to which a system is accessible. The term 24x7 describes the total availability. This is usually coupled with the performance

Reliability: The ability to ensure the integrity and consistency of an application and its transactions

Manageability: The ability to administer and manage the system resources to ensure the availability and performance of a system with respect to the other capabilities.

Flexibility: The ability to address architectural and hardware configuration changes without a great deal of impact to the underlying system

Performance: The ability to carry out functionality in a timeframe that meets the specified goals.

Capacity: The ability of the system to run multiple tasks per unit of time

Scalability: The ability to support the required availability and performance as transactional load increases.

Extensibility: The ability to extend the functionality

Validity: The ability to predict and confirm results based on a specific input of user gesture

Reusability: The ability to use a component in more than one context without changing its internals

Security: The ability to ensure that information is not accessed or modified unless done so in accordance with the enterprise policy

Principle of Least Privilege: Each system component or process should have the least authority necessary to perform its duties

Architectural Terminologies II

Abstraction: The use of symbol for something used repeatedly in a design. It's a component that hides details. Its a term of something that is factored out of a design so it can be used repeatedly
Surface Area: List of methods that are exposed to the client. The way in which components interact with each other in a defined way. The greater the surface area, the more ways a change in one component can effect another
Boundaries: The area where two components interact
Brittleness: The degree to which small changes will break large portions of the system. Software breaks before it bends.
Legacy Lock-in: Sometimes the brittleness is very high in the system, so this leads to the system gets locked in its legacy and reject any changes.
Capabilities: Non-functional observable system qualities including:

•Scalability
•Manageability
•Performance
•Availability
•Reliability
•Security

Friction: How much interaction occurs between two components. Friction is measured in terms of how a change in one component affects both component
Layering: Is the Hierarchy of separation

The role of Architect

•Architect visualises the behavior of the system.
•Architects create the BluePrint of the system.
•Architects define the way which the elements of the system work together and distinguish between functional and nonfunctional system requirements.
•Architects are responsible for integrating nonfunctional requirements into the system

Blueprint: type of paper-based reproduction usually of a technical drawing, documenting an architecture or an engineering design. More generally, the term "blueprint" has come to be used to refer to any detailed plan.

Benifits of using Design Patterns

•Help to quickly focus on solutions if the pattern was recognised
•Studying patterns can help inspiring developers to come up with new and unique ideas
•Provide common language for design discussions
•Provide solutions to real-world problems
•Their format captures knowledge and documents best practices for a domain
•They document discussions and the rationale that lead to the solution
•They reuse the experience of the predecessors
•They describe the circumstances (when and where), the influences (who and what) and the resolution (how and why)

Definition of Design Patterns

Solutions for recurring problems in a given context. They try to bring together and document the core solution to a given problem. They are identified and documented in a form that's easy to share, discuss and understand. They are useful problem-solving documentation for software designers and are used repeatedly to help solve common problems.

Documentation for the Design Patterns should provide a discussion on the difficulties and interests of surrounding the problem

Tuesday, 19 January 2010

JQuery: expandir y colapsar un div

JQuery es una de las librerias más importantes surgidas en los últimos tiempos. Han surgido múltiples herramientas que la utilizan y su uso es cada vez más frecuente. En snipplr nos muestran como hacer un sencillo efecto para expandir y colapsar un div. He añadido un poco de CSS para que sea más visual y he cambiado alguna cosa más y el ejemplo queda de la siguiente forma:

Cambiar propiedades CSS con JQuery

JQuery nos ofrece varias formas de manipular nuestros CSS de forma dinámica. Lo primero que tenemos que conocer es la forma de acceder a los distintos elementos que conforman nuestra página web. Esto lo podemos hacer con el extenso juego de selectores que nos ofrece JQuery: Selectores CSS, XPath, de Formulario,... Los más utilizados y con los que nos podremos manejar en la mayoría de ocasiones son:


Una buena práctica a la hora de definir una página web es que cada id sea único. En el caso de que hubiera más de un elemento con el mismo id, el selector devolvería el primer elemento coincidente a través de la arquitectura DOM.

Como comentaba anteriormente, existen bastantes más selectores, pero con estos y con una buena planificación de nuestro HTML nos puede ser más que suficiente. Jugando con esto y con unos cuantos métodos para CSS podemos empezar a modificar el aspecto de nuestra web dinamicamente.








Cambiar fondo

Wednesday, 13 January 2010

What Does Google Apps for Your Domain Actually Do?

Dear Lifehacker,

I've been looking into Google Apps for Your Domain, which sounds cool, but I'm confused about what it is and why you'd use it. If I sign up for Google Apps for Your Domain, is Google actually becoming the host for my domain, or just providing a bunch of services for it? What's the advantage to using GAppsFYD versus just vanilla Gmail and the rest? I have my own domain name that I use for my primary email address and my web site.

Google Apps for Your Domain is pretty cool for folks with their own domain names who want to manage a bunch of email/calendar/homepage users for it. To answer your question, GAppsFYD does not become your domain host, but it does provide a bunch of services, like Gmail, Google Calendar, a Start Page (a la iGoogle), Google Docs, Google Talk, etc. The difference between GAppsFYD services and free vanilla Google services is what you'd expect: your domain.

For instance, if your domain is thesmithfamily.org, using GAppsFYD, you could set up a bunch of users who get Gmail, GCal, a personalized start page, and chat all with usernames like john@thesmithfamily.org, lisa@thesmithfamily.org. Your users would log in to a Google hosted control panel (which you can customize with a thesmithfamily.org logo), and all their email would get sent with their custom domain email as the From: address.

A note about Google Maps

Implementation
Like many other Google web applications, Google Maps uses JavaScript extensively. As the user drags the map, the grid squares are downloaded from the server and inserted into the page. When a user searches for a business, the results are downloaded in the background for insertion into the side panel and map; the page is not reloaded. Locations are drawn dynamically by positioning a red pin (composed of several partially-transparent PNGs) on top of the map images.

A hidden IFrame with form submission is used because it preserves browser history. The site also uses JSON for data transfer rather than XML, for performance reasons. These techniques both fall under the broad Ajax umbrella.

[edit] Extensibility and customization
As Google Maps is coded almost entirely in JavaScript and XML, some end users have reverse-engineered the tool and produced client-side scripts and server-side hooks which allowed a user or website to introduce expanded or customized features into the Google Maps interface.

Using the core engine and the map/satellite images hosted by Google, such tools can introduce custom location icons, location coordinates and metadata, and even custom map image sources into the Google Maps interface. The script-insertion tool Greasemonkey provides a large number of client-side scripts to customize Google Maps data.

Combinations with photo sharing websites, such as Flickr, are used to create "memory maps". Using copies of the Keyhole satellite photos, users have taken advantage of image annotation features to provide personal histories and information regarding particular points of the area.

[edit] Google Maps API
Google created the Google Maps API to allow developers to integrate Google Maps into their websites with their own data points. It is a free service, and currently does not contain ads, but Google states in their terms of use that they reserve the right to display ads in the future.[10]

By using the Google Maps API, it is possible to embed the full Google Maps site into an external website. Developers are required to request an API key,[11] which is bound to the website and directory entered when creating the key. The Google Maps API key is no longer required for API version 3. Creating a customized map interface requires adding the Google JavaScript code to a page, and then using Javascript functions to add points to the map.

When the API first launched, it lacked the ability to geocode addresses, requiring users to manually add points in (latitude, longitude) format. This feature has since been added for premier.

At the same time as the release of the Google Maps API, Yahoo! released its own Maps API.[12] The releases coincided with the O'Reilly Web 2.0 Conference. Yahoo! Maps, which lacks international support, included a geocoder in the first release.

As of October 2006[update], the implementation of Google Gadgets' Google Maps is simpler, requiring only one line of script, but it is not as customizable as the full API.

In 2006, Yahoo! began a campaign to upgrade its maps to compete better with Google and other online map companies. Several of the maps used in a survey were similar to Google maps.

Google Maps actively promotes the commercial use of its API. Some of its first large-scale adopters were real estate mash-up sites. Google performed a case study[13] about Nestoria, a property search engine in the UK and Spain.

More about Google Maps

Satellite view
Google Maps provides high-resolution satellite images for most urban areas in the United States (including Hawaii, Alaska, Puerto Rico, and the U.S. Virgin Islands), Canada, and the United Kingdom, as well as parts of Australia and many other countries. The high-resolution imagery has been used by Google Maps to cover all of Egypt's Nile Valley, Sahara desert and Sinai. Google Maps also covers many cities in the English speaking areas. However, Google Maps is not solely an English maps service, since its service is intended to cover the world. The highest-resolution images are in some Japanese cities, such as Tokyo.

Various governments have complained about the potential for terrorists to use the satellite images in planning attacks.[4] Google has blurred some areas for security (mostly in the United States),[5] including the U.S. Naval Observatory area (where the official residence of the Vice President is located), and previously[citation needed] the United States Capitol and the White House (which formerly featured this erased housetop). Other well-known government installations, including Area 51 in the Nevada desert, are visible. Not all areas on satellite images are covered in the same resolution; less populated areas usually get less detail. Some areas may be obscured by patches of clouds.[6][7]

With the introduction of an easily pannable and searchable mapping and satellite imagery tool, Google's mapping engine prompted a surge of interest in satellite imagery. Sites were established which feature satellite images of interesting natural and man-made landmarks, including such novelties as "large type" writing visible in the imagery, as well as famous stadia and unique geological formations. As of November 2008[update], the U.S. National Weather Service also now uses Google Maps within its local weather forecasts, showing the 5 x 5 km "point forecast" squares used in forecast models.[8]

Although Google uses the word satellite, most of the high-resolution imagery is aerial photography taken from airplanes rather than from satellites.[9]

See also: Coverage details of Google Maps
[edit] Directions
Google Maps directions work:

Contiguously in North America: Alaska* (excluding the Panhandle), Canada* and the continental United States*
Contiguously in South America: Argentina, Brazil* and Chile*
Contiguously in Europe: Andorra, Austria*, Belgium*, Bulgaria, Croatia*, Czech Republic*, Denmark* (excluding the Faroe Islands), Estonia, France*, Finland*, Germany*, Greece*, Gibraltar, Hungary*, Ireland, Italy*, Latvia, Liechtenstein*, Lithuania, Luxembourg*, Monaco*, The Netherlands*, Norway*, Poland*, Portugal* (excluding the Azores and Madeira), San Marino, Slovakia*, Slovenia, Serbia*, Spain* (including the Canary Islands but excluding Ceuta and Melilla), Sweden*, Switzerland*, Turkey*, Ukraine, United Kingdom* and Vatican City (i.e. all of Europe excluding Albania, Belarus, Bosnia and Herzegovina, Cyprus, FYR Macedonia, Iceland, Malta, Moldova, Montenegro, Romania, Russia and Serbia).
Contiguously in Southeast Asia: Singapore*, peninsular Malaysia* and Thailand*
In certain noncontiguous countries and regions: Australia*, China*, India*, Indonesia (Bali, Java and Sumatra only), Israel (and parts of the West Bank), Hawaii*, Hong Kong*, Japan*, Macau*, New Zealand*, Puerto Rico*, Russia* (Moscow area only), Sabah*, Sarawak*, Taiwan*, South Africa* and the US Virgin Islands*.
^ = not all roads are featured in this country, so directions are very limited.

* = has directions and places of interest.

Look what is Google Maps

oogle Maps (for a time named Google Local) is a basic web mapping service application and technology provided by Google, free (for non-commercial use), that powers many map-based services, including the Google Maps website, Google Ride Finder, Google Transit, and maps embedded on third-party websites via the Google Maps API. It offers street maps, a route planner for traveling by foot, car, or public transport and an urban business locator for numerous countries around the world. According to one of its creators (Lars Rasmussen), Google Maps is "a way of organizing the world's information geographically".

Google Maps uses the Mercator projection, so it cannot show areas around the poles. A related product is Google Earth, a stand-alone program for Microsoft Windows, Mac OS X, Linux, SymbianOS, and iPhone OS which offers more globe-viewing features, including showing polar areas.

How to use Google Maps - Part 4

You'll want to download the sample file and replace the following parameters to match your own map settings:


•Just duplicate the title here•defines the GPS coordinates the map will center in on when you click the "Display Points" link - just choose a central waypoint for the area your map covers.
Next, let's zero in on what one waypoint looks like, and what changes you'll need to make for each of your points:



Here's what you'll need to edit for each waypoint:

•— For ordering and differentiating your waypoints, change id="A" to correspond alphabetically to the order in which you wish to place your waypoints. The third point would be id="C" and so on. Note that you can include any number of waypoints on your map, but Google only provides 10 default marker images: A through J.
•— Replace this with the latitude and longitude data generated from your GPS. Note that for small projects like this it is simpler to track and add these points manually, but if you're handy with Perl you can auto-generate a lot of this XML from a list of coordinates. More info here.
•— As with the first bullet point, replace "markerA.png" with the approproate letter to correspond with your waypoint's order in the map: markerB.png, markerC.png, and so on — up to J, past which you'll have to make your own markers to link to.
•— Replace with your own title for this waypoint.
•101 E. Green St., Ithaca, NY— This defines the address displayed underneath the title in the popup balloon that results from clicking your waypoint. It is also the basis for getting driving directions to or from this point, so you can use the nearest real street address if you want to have this functionality in your map.
•http;//media.weblogsinc.com/common/videos/barb/googlemaps/1library.jpg — this defines the URL of the image or video file you wish to link to, or any other URL you wish to link to from this waypoint. (note: replaced : with ; to prevent url autolink in this example)
•picture — this will be the text that gets linked in the popup balloon; picture, movie, or link will be common terms here.
•http;//www.google.com/search?q=tompkins+county+public+library+ithaca — You can add more than one URL reference to each waypoint. This second URL is the one that gets linked from the "1 more" link in the popup balloon. Change it to whatever additional link or file you wish to link to.
•parked here! — This defines the "sub-head" descriptive text you see under the waypoint title in the right-hand pane of the map.
To add another waypoint to the map, just cut and paste everything starting from the opening tag until after the end of the closing tag from your first waypoint, then modify the same bits of data as detailed in the list above for this new waypoint. The entire collection of waypoints lives sandwiched in between the opening bit of code:



And the closing tiny bit of code:



Still with me? That is the bulk of the magic behind the annotation. When you've finished stringing together all your waypoints and have nestled them between the opening and closing bits, save the resulting final file as your_map.xml or similar. Then, upload that XML file to whatever web host you've chosen. After this, you should be able to load up the following URL in your Greasemonkey-enabled Firefox browser:

http://maps.google.com/?loc=http://yourhost.com/path/to/your/files/yourmap.xml

Your URL is similar to ours (http://maps.google.com/?loc=
http://media.weblogsinc.com/common/videos/barb/googlemaps/ithaca_walk.xml) but replacing the URL after the "?loc=" with your own XML file. It is the combination of Greasemonkey and the Google maps user annotation script that add this function to Firefox to feed an external XML file to Google maps — although there are other methods of achieving the same goal, this way is very simple.

Click the "Display Points" link and Google maps should zoom in to whatever you listed as your center point, as described above. Then, follow along on your own annotated map tour courtesy of Google maps.



Going further
This is just the tip of the iceberg of what can be done with hacking Google maps. Work up a script to import and convert your GPS data automagically from the output of your GPS. If you're handy with javascript, you can add all sorts of dynamic actions such as panning and following into your maps. Or, include your custom Google map on your own web page. You can get your custom maps working in other browsers besides Firefox, as well — we just chose the Greasemonkey method as being easy enough to do even if you've no experience with XML. For other ideas, try hunting around in the GoogleMapsHacking wiki.

And of course, don't forget to post a link to your hacked Google map!

How to use Google Maps - Part 3

To host video, and to host our XML file, you'll need access to a web server that allows you to FTP upload files. If you already have a web site or a blog that allows you to upload files, you're set - you can upload all media and your XML there. Otherwise, there are still free web hosting services out there you can use in a pinch for making a few of these maps. Ye olde Angelfire is still kickin' it as a free service with 20MB of space. Yes, you have to navigate a minefield of opt-out checkboxes to get there but it takes all of about five minutes to set up a free account and upload your XML file, which you can safely link to from Google maps without incurring the evil spector of the sponsored ads (we tested this to be sure!). You could host some images and video there, as well, if you're only making one or a few maps. Or, ask around and get recommendations of other free web hosts — most are evil, but if you don't give them any real metadata about yourself you should be able to emerge unscathed.

Now, you've made and uploaded your media files to wherever they may roam. You'll need to know the fully-qualified URL of any media file you wish to link to, as well as your (coming next) XML file. That's as good a sequeway as any — let's dive in to the meat of this project: creating our XML file.

If you've seen HTML, XML looks pretty much the same: parameters surrounded by opening and closing tags. We'll show you an example of how to make two different waypoints, one with an associated image and one with associated video, and show you the minimal rest of the document structure. You can download the following example waypoints file by right-clicking and saving it to disk, then modifying it to make your own map. It includes one waypoint with an associated image and one with an associated video, matching the first two stops on our Ithaca map.

Here's what the entire XML file looks like with only one waypoint — all the stuff between the tags defines the waypoint. The stuff before and after is just the "shell" of the entire document.

How to use Google Maps - Part2

Getting started
Before we get in to how it's done, let's look at the results. Fire up Firefox and install the Greasemonkey Firefox plug-in that allows you to inject some dynamic behavior into viewed web pages; you'll have to restart Firefox for it to take effect. Relaunch Firefox, and install the Google maps user annotation script by simply clicking right-clicking on the link (CTRL-click for one-button mouse Mac users) in this sentence and choosing "Install user scripts..." Then, load up the URL of our annotated Ithaca map in a new tab so you can switch back to this how-to easily. Click on the "Display Points" link, and you'll zoom in to our annotated Ithaca walk.



This map works like any other Google map, except for the fact that we've created it ourselves and added media to it. You can click on a waypoint to get more information, or generate driving directions to and from points as usual. When you click on one of our points, you'll notice it will have either a picture or a movie link associated with it:



The best way to follow the map tour is to right-click (CTRL-click Mac) and open the media file in a separate browser tab, because following a link and clicking the back button will break the script and revert the map back to its default state, from which you'll have to click the "Display Points" link and start all over again. If you right-click the "movie" link in the above example, you'll see a 30 second 360-degree video we took from the center of the Ithaca Commons. If you right-click on the "1 more" link it will open a tab with a Google query ("Ithaca Commons") we've also linked to — you can add links to any URL on the web, not just your media files. Load up a waypoint with a "picture" link, right-click on it and you'll see an image we shot at that location.

Now that we've seen what we're about to create, let's get started.

We'll leave the finer details of collecting your media files and waypoints up to you — that's the easy part. Just gather your GPS and camera and have at it, or take your images and geolocate them later using Geocode.com if you prefer that method. Similarly, we'll let you handle the editing and preparation of your images and video files, and start in at the nitty-gritty stage.

You'll need a place to host your media files and the XML file we're going to create that specifies your map data. If you already have a Flickr account, you can host images there, and if you don't have one, we highly recommend it as a value-added image hosting service. You can host up to 100 images for free, and link to them from elsewhere.

How to use Google map - Part1

One of the great things about Google maps is it has its roots in XML. To translate for the non-web developers out there, it basically means Google maps are user hackable. This how-to will show you how to make your own annotated Google map from your own GPS data. Plus, you'll be able to tie in images and video to create an interactive multimedia map. We'll walk you through the steps we took to generate an annotated map of a walk we took recently through our hometown, now that it's actually starting to get warm enough to want to walk about!



Background
I saw this post by Jon Udell, in which he does a screencast of an annotated walking tour through Keene, NH. Screencast goodness aside, I wanted to figure out how he made the map and how to simplify the process so that the non-web geek could attempt it without too much trouble. The geekiest bit will be where we edit our XML file, but you can essentially think of it just like editing a plain old text file — it looks like garbledy-gook, but it's not actually rocket science. If you're new to web development or new to XML, don't worry — we'll walk you through it as best we can. Ready? Let's dive in!



Materials
•GPS device. Though, technically, you can even do without this if you don't have one — unless you're travelling off the beaten path, you can use Geocode.com to convert the nearest street address to latitude and longitude data.
•Digital camera, if you wish to capture media for your map.
•Computer of any flavor that will run Firefox.
•A place to store your files online; we'll talk more about this later. If you have access to a web server, you're all set. Otherwise, we'll give some suggestions about free hosting options.
•The Firefox browser.
•The Greasemonkey Firefox plug-in
•The Google maps user annotation script.
•Text editor to edit your XML file; plenty of free options across operating systems. We use the free TextWrangler on our Mac, and jEdit on our Windows PC.

Wednesday, 6 January 2010

FOSDEM 2010 Encuentro Europeo Desarrolladores

Nueva edición de la reunión anual de los creadores de proyectos libres de código abierto.

FOSDEM o Free and Open Source Software Developers European Meeting, es uno de los encuentros de desarrolladores de software libre y open source más importantes celebrados en Europa.

En la edición 2010 volveremos a contar con charlas rápidas, conferencias, salas para desarrolladores, stands de proyectos como Fedora, Debian, Ubuntu, FreeBSD, Mozilla, OpenOffice, Haiku, que den cuerpo a un nuevo encuentro anual.

A 35 días de la celebración de FOSDEM 2010 aun no dispone de un programa cerrado por lo que cualquier interesado podrá ir conociendo las novedades que vayan saliendo desde www.fosdem.org.

La décima edición de FOSDEM tendrá lugar el próximo 6 y 7 de febrero en Bruselas(Bélgica). El encuentro sigue siendo gratuito y no necesita de registro previo.

Notepad++ 5.6.4, listo para descarga

Última versión del editor gratuito de código fuente para multiples lenguajes de programación.

Notepad++ 5.6.4, es la última versión del editor gratuito de código fuente con soporte para sistemas Windows.

Este sencillo entorno de desarrollo ha lanzado en apenas dos semanas dos nuevas versiones de su editor basado en C++ que permite extenderse mediante plugins.

Notepad++ 5.6.4 incorpora respecto a la versión anterior, corrección de errores y pequeñas mejoras como una nueva característica de conversión de una codificación de caracteres localizada a UNICODE.

Interesados pueden acceder a la descarga de Notepad++ 5.6.4.

Hojas resumen Adobe Flash

Recopilación de diferente documentación de consulta rápida de la tecnología de Adobe para la creación de animaciones vectoriales

Flash es una de las tecnologías más comúnmente utilizadas para añadir dinamismo a la Web, que permite la creación de animaciones vectoriales y contenidos multimedia. Flash a través de complejas técnicas de compresión consigue la máxima optimización (poco peso) y el menor consumo de recursos lo que lo convierten en interesate para ser usadas en aplicaciones y páginas web.

Además de guías de referencia y atajos de teclado de Flash para sistemas Windows y Mac, también han sido recopiladas hojas resumen ActionScript, el lenguaje de programación usado en aplicaciones web animadas realizadas en el entorno Adobe Flash.

•Atajos de teclado Flash CS4
sistemas windows
sistemas mac

•Guias de referencia Flash cs3
sistemas windows
sistemas mac

•Guías de referencia ActionScript 3.0

GIMP lanza versión 2.6.8

El editor de imágenes libre, gratuito y multiplataforma que pertenece al proyecto GNU, publica una nueva actualización.

Gimp 2.6.8 (GNU Image Manipulation Program), es la nueva versión del popular programa de código abierto pensado para el diseño gráfico y que se constituye como una de las mejores alternativas a Photoshop.

Además de su completa funcionalidad para la creación y manipulación de gráficos, retoque de fotos e imágenes, GIMP permite descargar complementos, con los que aumentar su capacidad, ampliar el número de pinceles, efectos....

Gimp 2.6.8 es una versión que mejora el rendimiento y en la que se corrigen errores encontrados en ediciones anteriores. Aquellos interesados en repasar los bugs solucionados que GIMP 2.6.8 trae, pueden acceder al siguiente listado.

Si quieres a aprender a manejar esta herramienta de edición de imágenes gratuita puedes acceder a un manual en castellano.

Descarga GIMP 2.6.8.

PDT 2.1, editor gratuito PHP basado en eclipse

PHP Development Tools (PDT) interesante distribución del entorno de desarrollo integrado Eclipse, para la creación de aplicaciones web con PHP.

22/12/2009 - PDT es un IDE basado en la plataforma Eclipse, pero que incluye extensiones para dar soporte al lenguaje de programación PHP con el que simplificar la vida a los desarrolladores de este lenguaje de programación.

Esta aplicación actualmente en su versión 2.1 dispone entre sus principales características de:

•Soporte para PHP 5.3
•Solución de bugs de las versiones anteriores
•Resaltado, asistente y autocompletado de código.
•Integración con las herramientas y soporta de los estándares de Eclipse
•Soporte para el debug incremental del código de PHP
•Extensos frameworks y APIs que permiten a los desarrolladores extender PDT

La próxima versión, PDT 2.2, se espera para el 23 de junio de 2010. Podemos encontrar completa información de PHP Development Tools (PDT) desde www.eclipse.org.

Moonlight 2.0 final disponible

La implementación open source de la tecnología Silverlight de Microsoft a sistemas Linux dispone de una nueva versión estable.

Moonlight es la implementación de código abierto con la que agregar funciones multimedia como reproducción de vídeos, gráficos vectoriales, animaciones, y de entorno de desarrollo, a las plataformas SUSE Linux Enterprise Desktop 11, openSUSE 11.x, Ubuntu 9.10, and Fedora 12, así como a otras distribuciones Linux (requieren construir Moonlight desde el código fuente).

El nuevo Moonlihgt 2.0, basado sobre Mono 2.6, Cairo y GTK+, implementa todas las funciones de Silverlight 2 como mejoras para vídeo, audio, streaming y soporte para codecs de código abierto e incluye algunas funciones de Silverlight 3, como Moonlight Ogg y codificadores para Vorbis y Dirac.

Moonlight 2.0 admite gran variedad de lenguajes de programación como IronRuby, IronPython, Visual Basic o PHP.

Junto a este anuncio Microsoft y Novell han indicado que amplían su acuerdo de colaboración para introducir soporte para Moonlight en las versiones de Silverlight 3 y 4.

Interesados pueden acceder a más información y descarga de Moonlight 2.0 desde www.go-mono.com.

PHP 5.2.12 disponible

El equipo de desarrollo del lenguaje de programación PHP anuncia la disponibilidad de la nueva versión 5.2.12.

PHP 5.2.12 se centra en mejorar la estabilidad de la rama 5.2.x con solución a más de 60 errores.

Entre los errores solucionados por la nueva actualización de este lenguaje gratuito, multiplataforma para la creación de páginas web dinámicas, encontramos algunos relacionados con la seguridad que pueden ser aprovechados por un atacante remoto.

Interesados en conocer con más detalle los bugs solucionados con este lanzamiento pueden acceder a www.php.net.

Desde PHP, se recomienda a todos los usuarios de PHP 5.2, que se actualicen a esta nueva versión.

Mas información acerca de PHP 5.2.12 desde www.php.net e instalación desde www.php.net/downloads.php.

Komodo Edit

Editor de texto multiplataforma y gratuito para programadores con herramientas avanzadas para edición de código en diversos lenguajes, gestión de proyectos, etc.

Plataforma:
Todas
Idioma: Multilenguaje
Licencia: Freeware
Tamaño: 33,8 MB
Web: http://www.activestate.com/komodo_edit/


Komodo Edit es un editor de código fuente bastante avanzado y extensible. No se limita sólo a proveernos de las diversas herramientas habituales de los editores populares para programadores, sino que va más allá, proporcionando algunas de las utilidades típicas de los entornos de desarrollo profesionales o IDEs. Además, incorpora un sistema de complementos o add-ons similar al que conocemos por el navegador Firefox, que hace que todavía podamos disfrutar de diversas otras utilidades que seguro agradeceremos.
La verdad es que si queremos editar código fuente en lenguajes de programación orientados para la web, Komodo Edit es una de las opciones más interesantes. Primero porque es multiplataforma, lo que da soporte tanto a usuarios de Windows como los de otras plataformas como puede ser Mac o Linux. Otra de las principales ventajas de Komodo IDE es que se ofrece con la misma licencia que el navegador de la fundación Mozilla, Firefox, por lo que sobra decir que es un producto de código libre y por tanto, gratuito para cualquier uso.

Komodo Edit es, por decirlo de una manera sencilla, el hermano menor de otra herramienta de la misma compañía, ActiveState, llamada Komodo IDE. Siendo que Komodo IDE es una herramienta comercial, de pago, con diversas posibilidades aun más avanzadas y útiles para los desarrolladores profesionales como el debugging. Komodo Edit, a pesar de ser una herramienta con funcionalidad limitada a las tareas de edición de código, es bastante potente y suficiente para la mayoría de los programadores ocasionales. Por eso, sin llegar a las complejidades típicas de un entorno de desarrollo integrado (IDE), Komodo Edit ofrece muchas de las herramientas que más sirven de ayuda en los editores para programadores.

Algunas de sus principales funcionalidades son las siguientes:


•Resaltado y coloreado de código fuente, con soporte para casi todos los lenguajes que podemos utilizar al construir una página web, como PHP, JavaScript, CSS, HTML, Python, Ruby, Perl, etc.
•Multi-documento, que permite abrir y editar varios archivos al mismo tiempo.
•Auto-completado de código con los típicos menús contextuales, que aparecen a medida que vamos escribiendo los programas.
•Revisión de sintaxis en vivo, que nos proporciona información sobre los errores que podemos realizar en la sintaxis de los lenguajes de programación soportados, a medida que vamos realizando los scripts.
•Vista previa de HTML, para poder ver las páginas web que estamos realizando dentro del propio editor.
•Gestión de proyectos, con la posibilidad de navegar por las carpetas de nuestro sistema, en lo que llaman "live folders".
•Posibilidad de conexión con servidores remotos para editar código directamente sobre el archivo publicado en un servidor, por medio de FTP, SFTP, SSH.
•Posibilidad de extender el programa, con diversos complementos o add-ons creados por terceras personas, como ocurre con el navegador Firefox y sus extensiones.
La lista de funcionalidades está a la altura de los mejores editores para programadores, aunque faltan algunas de las cosas más útiles de los IDE, como el mencionado debugger. Pero dejando a un lado este detalle, cabe señalar que todavía se puede ampliar bastante el grado de posibilidades del programa a partir de las extensiones. Echando un vistazo rápido a las extensiones disponibles, podremos encontrar muchas que sin duda nos resultarán muy interesantes, como ampliación de la compatibilidad con distintos lenguajes de programación, integración de APIs y librerías de código dentro de las funciones reconocidas y de las ayudas contextuales, para diversos frameworks Javascript como Mootools, jQuery, Js-Core, ExtJs... o frameworks PHP como el conocido Cake PHP.
Entre las cosas que se echan en falta es un explorador de archivos remoto. Podemos navegar nuestro disco duro, en los directorios que tengamos asociados al proyecto activo, pero no podemos navegar un directorio en un servidor remoto, por FTP. Podemos, eso si, abrir cualquier archivo remoto para editarlo online. Incluso podemos asociar un directorio remoto a un proyecto, a través de "Project - Import from filesystem" pero las actualizaciones en este caso se quedan sólo en local y necesitaríamos sincronizar con el sistema de archivos remoto. No obstante, a través de las extensiones de Komodo Edit, tenemos la posibilidad de suplir un esta carencia con el add-on Remote Drive Tree, con el que podemos obtener un navegador de archivos en el servidor remoto, como si fuera un explorador de Windows.

Como decíamos, existen muchas extensiones muy útiles. El proceso de instalación y búsqueda es similar a Firefox y se puede realizar desde el menú de "Tools - Add-ons" de Komodo Edit. Sin duda, muchas de las necesidades que podamos encontrar, previamente las han encontrado otras personas y han sido resueltas por medio de los complementos y gracias a ellos, este editor de código se convierte en uno de los más recomendables, dentro de la oferta en programas de código libre y gratuitos.

Puedes ver lo que dicen los usuarios de Komodo Edit en la Wiki.

Eliminar el index.php de las direcciones de CodeIgniter

Todas las URLs de CodeIgniter tienen un index.php que si lo deseamos podemos eliminar usando un archivo htaccess.

Lo cierto es que las direcciones de CodeIgniter son bastante amigables a buscadores, pero todavía pueden serlo más. Esto es algo que vamos a ver en este artículo de DesarrolloWeb.com.
En el artículo anterior, sobre las características de las URL de CodeIgniter, ya explicamos varias cosas que conviene saber acerca de componer direcciones para las páginas de nuestras aplicaciones PHP. Como se decía en ese artículo, todas las solicitudes a páginas de una aplicación web en CodeIgniter pasan por un archivo index.php que está en la raíz del framework. Este index.php se encarga de redirigir, o enrutar, la solicitud a través del controlador que se esté invocando (que se indica en el primer segmento después del nombre del dominio).

Así pues, por defecto las URL de CodeIgniter tienen un formato como el que sigue:

http://pruebas.com/index.php/empresas/editar/1

Pues bien, si deseamos eliminar el index.php de esta URL, para simplificar la dirección, hacerla todavía más amigable a buscadores y también más entendible por los seres humanos, podemos utilizar un archivo .htaccess.


Nota: En DesarrolloWeb.com hemos hablado en repetidas ocasiones acerca de los archivos .htaccess, explicando lo que son y cómo podemos utilizarlos para crear automáticamente URLs amigables a buscadores, sin que tengan que existir físicamente los archivos en el servidor. Recomendamos la lectura del manual Editar htaccess para crear direcciones URL amigables http://www.desarrolloweb.com/manuales/htaccess-para-urls-amigables.html para obtener una información de referencia.
Así pues, podríamos conseguir que nuestras direcciones no tuvieran siempre el mencionado index.php y quedasen con una forma similar a esta:

http://pruebas.com/empresas/editar/1

Para ello existirían diversos métodos y según nuestro dominio de los archivos .htaccess y de las expresiones regulares, así como de la configuración de Apache, podremos implementar una u otra. Nosotros en este artículo vamos a explicar un modo que está disponible en la propia guía de uso de CodeIgniter, que hemos probado y resulta sencillo y efectivo.

Se trata de utilizar un método de trabajo con .htaccess que llaman "negativo", donde todas las URLs son redirigidas a través del archivo index.php, a no ser que tengan una forma determinada que no queramos que se redireccione.

Por ejemplo, una URL como esta:

www.loquesea.com/empresas

Se redirigiría a una URL como esta otra:

www.loquesea.com/index.php/empresas

Pero esa redirección se haría de manera transparente al usuario y al navegador que nos visita. Es decir, el procesamiento de la página se hace a través del index.php, pero nosotros no llegamos a percibir que en el servidor se ha llevado a cabo esa redirección, quedando la URL en la barra de direcciones siempre sin el index.php.

Ahora bien, hay determinadas direcciones que no vamos a desear que se redirijan, como puede ser una hoja de estilos CSS. Es decir, podemos tener en nuestro servidor un archivo como este:

www.loquesea.com/css/estilos.css

Y en ningún caso queremos que se procese a través del index.php, sino que directamente se devuelva el archivo CSS que hay en esa ruta. Este es el caso en el que se utiliza el método "negativo" del htaccess, a través del comando "RewriteCond" (condición de redirección). Este caso obvio también lo tendríamos, por ejemplo, en archivos como el robots.txt o aquellos donde podamos tener librerías de código Javascript.

Código htaccess para eliminar el index.php de CodeIgniter
Así pues, podríamos tener un archivo .htaccess en la raíz de la instalación del framework, que suele ser también la raíz del dominio donde estamos trabajando, con un código como el que sigue:
RewriteEngine on
RewriteCond $1 !^(index.php|css|js|images|robots.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

Esto diría que se redirijan todos los archivos que se soliciten a este dominio, menos los que contengan el propio index.php, css, js, images o robots.txt.

La redirección se hará a través de la misma URL, pero agregando "index.php/" después del nombre del dominio y antes de lo que haya justo después de ese nombre de dominio.


Nota: si tuviéramos CodeIgniter instalado en un subdirectorio de nuestro dominio, por ejemplo, en el subdirectorio "carpeta", la regla de redirección "RewriteRule" cambiaría un poco:
RewriteRule ^(.*)$ /carpeta/index.php/$1 [L]

Ahora, sólo nos faltaría decirle a CodeIgniter que, al componer URLs para los enlaces entre las distintas páginas de nuestra aplicación web PHP, no coloque el index.php, pues no lo necesitamos. Esto lo podemos hacer desde el archivo de configuración principal, que están en: system/application/config/config.php
Simplemente tendríamos que editar la variable de configuración "index_page", poniéndola a la cadena vacía.

$config['index_page'] = "";

Este no sería necesariamente el único método. Por ejemplo, en la Wiki oficial de Codeigniter explican un modo distinto de conseguirlo, aunque bastante más complejo: http://codeigniter.com/wiki/mod_rewrite/

URLs en CodeIgniter

Detalles sobre las URLs que genera CodeIgniter para las páginas de las aplicaciones, que siempre son amigables a buscadores.

Uno de los puntos que debemos conocer antes de empezar a trabajar con CodeIgniter es sobre cómo son las direcciones URL que utiliza este popular framework PHP para cada una de las páginas de las aplicaciones PHP que creemos utilizándolo. La verdad es que es un punto que realmente resulta transparente para nosotros, puesto que las URL se generan automáticamente a medida que vamos programando el sitio web, pero está bien comentar algunas cosas importantes.
Éste es un artículo del Manual de CodeIgniter que estamos publicando en DesarrolloWeb.com, por lo que para entenderlo habrá que leer alguno de los artículos previos a éste.

URLs amigables a buscadores
Uno de los puntos fuertes de este framework PHP es que las URL se presentan siempre en un formato amigable a los buscadores. Esto quiere decir que cualquier motor de búsqueda puntuará positivamente, a priori, las direcciones de las páginas. Del mismo modo, las direcciones tendrán una forma fácil de entender y recordar por los seres humanos.
En DesarrolloWeb.com, en los manuales de posicionamiento y promoción en buscadores hemos hablado repetidas veces acerca de las URL amigables, pero para el que no lo sepa, estas son URL que no suelen ser puntuadas bien por los buscadores:

www.midominio.com/articulos.php?id=32
www.midominio.com/articulos.php?nombre=miarticulo

Si lo vemos, tenemos una página, articulos.php, que se le pasan distintos parámetros. Pero los buscadores muchas veces interpretan que es la misma página. Bueno, en realidad no tiene más importancia, porque con CodeIgniter las URL tienen mucha mejor arquitectura, con formas como estas:

www.midominio.com/articulos/muestra/32
www.midominio.com/controlador/funcion/parametro

Las diferencias saltan a la vista, tanto para nosotros humanos como para motores de búsqueda como Google. Y lo bueno es que nosotros no tenemos que hacer nada para conseguir este tipo de direcciones.


Nota: Hay un pequeño matiz que comentaremos más tarde en este artículo y es que en principio todas las URL en CodeIgniter tienen el nombre de una página llamada index.php, pero esto es algo que podemos hacer desaparecer si sabemos configurar el framework.
Query String desactivado
En CodeIgniter en principio está desactivada la posibilidad de envío de variables a través de la URL, lo que se conoce en inglés como Query String. Es decir, que direcciones en las que se envían variables a través de las URL, que decíamos que eran poco amigables a buscadores, no funcionarán.
Si se desea, se puede hacer que CodeIgniter reconozca las variables enviadas por la URL, pero como en principio el sistema de URLs amigables a buscadores que implementa el framework está pensado para poder evitar el problemático Query String, su uso está desactivado.

Segmentos de la URL y el modelo - vista - controlador
Cada una de las partes de la URL de las aplicaciones creadas con el framework sirve para identificar qué controlador, del ya explicado Modelo - Vista - Controlador de CodeIgniter, se va a hacer cargo del procesamiento de la página, así como de la función que se invocará y los parámetros que se le enviarán a la misma. Por ejemplo:
aplicacioncodeiginter.com/facturacion/editarempresa/5610

•aplicacioncodeiginter.com es el nombre del supuesto dominio donde tenemos CodeIgniter instalado.
•facturacion es el nombre del controlador que se encargará de procesar la solicitud.
•editarempresa es el nombre de la función que habrá dentro del controlador y donde estará el código que ejecute y genere la página. Aunque para ser correctos, como el controlador está en programación orientada a objetos, en vez de función, deberíamos llamarle método.
•Por último, 5610, es el parámetro que se le pasa a la función editarempresa, que servirá en este caso para que editarempresa sepa cuál es la empresa que se desea editar. Si queremos o necesitamos enviar varios parámetros a esta función, y no sólo el identificador de la empresa a editar, podremos colocarlos a continuación, separados por barras.
Nota: Esto quizás resulte ahora un poco complicado, porque todavía no tenemos una idea definida sobre cómo son los controladores, pero dentro de poco lo veréis todo más claro.
CodeIgniter pone a nuestra disposición una clase para trabajar con URLs llamada URI Class y una librería llamada URL Helper que contienen funciones para trabajar fácilmente con URLs y datos enviados en las mismas. En estas librerías hay funciones tan interesantes como site_url() que sirve para que el propio CodeIgniter cree una URL dentro del sitio a partir de un parámetro que le pasemos. Otro ejemplo es base_url(), que simplemente devuelve la URL raíz donde está nuestra aplicación CodeIgniter.
Todo pasa por index.php
En CodeIgniter existe un index.php que está en la raíz del framework que se encarga de las funciones de enrutamiento hacia el controlador que se debe encargar de procesar la solicitud. Por ello, de manera predeterminada en CodeIgniter veremos que las URLs incluyen el nombre del archivo index.php. Este comportamiento se puede configurar.
En el próximo artículo explicaremos cómo eliminar este index.php en las URLs de CodeIgniter, algo que simplificará las direcciones.

Añadir un sufijo a las URL
Otro de los detalles que podemos hacer con CodeIgniter, que pueden personalizar aun más nuestras direcciones URL, es añadir un sufijo, que nosotros deseemos, al final de todas las URL que formen parte del framework. Por ejemplo, podríamos desear que todas las URL acaben en .html o en .php, o como queramos. Esto se puede hacer a través de los archivos de configuración del framework.
La idea es que una URL como esta:

http://dom.com/index.php/blog/post/cualquier-articulo

Pase a ser una dirección como esta otra:

http://dom.com/index.php/blog/post/cualquier-articulo.html

Para esto editamos el archivo de configuraciones generales: system/application/config/config.php y tenemos que buscar la variable url_suffix y colocar el valor que deseemos, por ejemplo:

$config['url_suffix'] = ".html";

Modelo - Vista - Controlador en CodeIgniter

Explicamos la arquitectura de desarrollo llamada Modelo - Vista - Controlador, que utiliza CodeIgniter y otros frameworks PHP.

Seguimos ofreciendo capítulos introductorios en el Manual de CodeIgniter de DesarrolloWeb.com, en esta ocasión vamos a explicar estilo de programación que tenemos que seguir cuando desarrollemos nuestras aplicaciones web en CodeIgniter.
El Modelo, Vista, Controlador es típicamente utilizado para la creación de aplicaciones web y no sólo CodeIgniter lo implementa, sino también otra serie de frameworks de desarrollo web, en PHP u otros lenguajes. Es interesante porque separa en varios grupos las complejidades de las distintas partes que componen una página web, como la vista y la lógica, así como el acceso a la base de datos.

Quizás lo que más nos fuerce a cambiar nuestros hábitos de programación en PHP es el hecho de tener que basar nuestros scripts en este modelo de programación, que seguramente resultará novedoso para la mayoría de los lectores de este manual, porque fija un nuevo estilo de desarrollo de aplicaciones, que nos obliga a separar código fuente según su ámbito. Sin embargo, como decíamos anteriormente, estas nuevas costumbres de codificación también nos ayudarán a que nuestros programas sean mejores y disfruten de varias ventajas como ser más organizados, extendibles y entendibles por otros desarrolladores, reutilizables, con más fácil mantenimiento, etc.

Para los que no lo conocen, el Modelo - Vista - Controlador (en inglés Model - View - Controller) es un patrón de desarrollo o un estilo de arquitectura de software que separa el código fuente de las aplicaciones en tres grupos:

Modelo:
Todo el código que tiene que ver con el acceso a base de datos. En el modelo mantendremos encapsulada la complejidad de nuestra base de datos y simplemente crearemos funciones para recibir, insertar, actualizar o borrar información de nuestras tablas. Al mantenerse todas las llamadas a la base de datos en un mismo código, desde otras partes del programa podremos invocar las funciones que necesitemos del modelo y éste se encargará de procesarlas. En el modelo nos podrán preocupar cosas como el tipo de base de datos con la que trabajamos, o las tablas y sus relaciones, pero desde las otras partes del programa simplemente llamaremos a las funciones del modelo sin importarnos qué tiene que hace éste para conseguir realizar las acciones invocadas.

Vista:
La vista codifica y mantiene la presentación final de nuestra aplicación de cara al usuario. Es decir, en la vista colocaremos todo el código HTML, CSS, Javascript, etc. que se tiene que generar para producir la página tal cual queremos que la vea el usuario. En la práctica la vista no sólo sirve para producir páginas web, sino también cualquier otra salida que queramos enviar al usuario, en formatos o lenguajes distintos, como pueden ser feeds RSS, archivos JSON, XML, etc.

Controlador:
El controlador podríamos decir que es la parte más importante, porque hace de enlace entre el modelo, la vista y cualquier otro recurso que se tenga que procesar en el servidor para generar la página web. En resumen, en el controlador guardamos la lógica de nuestras páginas y realizamos todas las acciones que sean necesarias para generarlas, ayudados del modelo o la vista.


Nota: Esto quiere decir, en la práctica para el caso de CodeIgniter, que según sea el ámbito donde estemos codificando, tendremos que escribir las líneas de código de cualquier página web en tres grupos de archivos distintos. En una aplicación estándar podremos tener varios modelos (por ejemplo, para cada una de las entidades distintas de la base de datos), varias vistas (una o varias para cada página o sección) y varios controladores (para cada página o sección de la web). Luego veremos dónde tenemos que guardar los archivos de cada uno de estos tres grupos.
Durante el desarrollo con CodeIgniter será muy recomendable seguir las normas del diseño Modelo - Vista - Controlador (MVC), pero realmente el framework es bastante flexible y permite que, si lo deseamos, no sigamos el desarrollo atendiendo a dicha arquitectura. En este caso, podríamos tener simplemente controladores y dentro de ellos realizar todas las acciones de acceso a la base de datos directamente, sin hacer llamadas al modelo, o escribir texto en la salida sin utilizar las vistas. Obviamente, esta opción no aprovechará las ventajas de separación de código entre presentación, lógica y modelo de base de datos, pero si vemos que nos resulta muy complejo el MVC, podemos dejarlo de lado.
En el caso que no utilizemos los modelos, no ocurrirá ningún efecto negativo en el desempeño del framework, pero en el caso de las vistas, si no las utilizamos y escribimos salida directamente desde el controlador, como por ejemplo con sentencias echo de PHP en en código de los controladores, perderemos algunas de las ventajas que CodeIgniter realiza por nosotros para procesar la salida antes de enviarla al usuario. Esto lo detallaremos más adelante.

Nota: Como sabemos, o podremos imaginar, separar la vista o presentación de la lógica de los programas es una ventaja importante, ya que ayuda a mantener un código más sencillo, reducido y con mayor facilidad de mantenimiento. En principio puede parecer un tanto complejo el hecho de manejar varios archivos con códigos distintos, pero a medio plazo nos vendrá muy bien separar el código de cada parte de nuestra aplicación. Nos evitará muchos de los problemas que a veces tenemos en desarrollos PHP, donde en un mismo archivo tenemos mezclado código en varios lenguajes como HTML, CSS, SQL, con el propio código PHP para generar la lógica de nuestro negocio.

Entender el flujo de aplicación de CodeIgniter

Explicamos el flujo de la aplicación de CodeIgniter, que será recomendable conocer antes de empezar tu aplicación web PHP con este framework.

En DesarrolloWeb.com hemos empezado a publicar una línea de artículos sobre el framework PHP CodeIgniter, que es uno de los más sencillos, versátiles y apropiados para la mayoría de desarrolladores y proyectos. En este artículo vamos a comentar algunas de las cosas, más bien teóricas sobre el proceso de desarrollo y producción de aplicaciones con CodeIgniter.
Recordemos que ya se presentaron unas características generales de CodeIgniter y que estuvimos ofreciendo una guía para la instalación del framework PHP, que resulta bastante sencilla, como podréis ver dado que CodeIgniter es apropiado para la mayoría de los entornos donde necesitemos ejecutar aplicaciones con programación en PHP.

Como cualquier herramienta o librería para el desarrollo, CodeIgniter define una serie de pautas de trabajo que necesitaríamos conocer antes de ponernos a escribir líneas de código. Si queremos utilizar este framework hay muchas cosas no podremos hacer tal como, quizás, estemos acostumbrados en el pasado con PHP. Así pues es muy importante saber unas cuantas cosas antes de empezar a ver ejemplos simples o explicar el proceso de desarrollo de una aplicación web más compleja. De hecho, la mayor complejidad de empezar a usar CodeIgniter es justamente la necesidad de cambiar nuestros esquemas y costumbres de desarrollo, pero esto también posibilitará que empecemos a pensar "a lo grande" y que los objetivos de aplicaciones avanzadas sean más fácilmente alcanzables.

Flujo de aplicación de CodeIgniter
En CodeIgniter existe un procedimiento para atender una solicitud de página del cliente. Este proceso se realiza internamente por el propio CodeIgniter y de manera transparente para nosotros. Durante el proceso participan varios módulos como el enrutamiento de la solicitud, la caché interna, etc. Está bien conocerlo de antemano, aunque algunas de las cosas aun no las entendamos con lo que hemos visto hasta el momento en este manual.
Conviene prestar atención sobre la siguiente imagen, tomada de la documentación de CodeIgniter, donde hemos traducido simplemente algunos nombres de los módulos que participan.

En resumen, para que se pueda entender el flujo de aplicación que implementa CodeIgniter, puedes seguir los siguientes puntos:

1.Toda solicitud de una página a partir de CodeIgniter comienza en un index.php que hay en la raíz del framework.
2.Luego se realiza un filtrado de la URL para saber cuál es elemento que tiene que procesar esta página.
3.Si la página se había generado antes y está en la caché de CodeIgniter, se devuelve el archivo de la caché ya generado, con lo que se ahorra procesamientos repetidos. La caché se puede configurar y si lo deseamos, incluso deshabilitar.
4.Antes de continuar con el proceso se realiza un tratamiento de seguridad sobre la entrada que tengamos, tanto de la información que haya en la URL como de la información que haya en un posible POST, si lo hemos configurado así.
5.El controlador adecuado realiza el procesamiento de la solicitud. CodeIgniter decide el controlador que debe procesar la solicitud en función de la URL solicitada.
6.El controlador comunica con una serie de módulos, los que necesite, para producir la página.
7.A través de las vistas adecuadas, el controlador genera la página, tal cual se tiene que enviar al navegador.
8.Si la página no estaba en la caché, se introduce, para que las futuras solicitudes de esta página sean más rápidas.
Algunos de estos módulos, como la caché o el enrutamiento, funcionan de manera transparente para nosotros. Algunos otros, como los controladores, modelos y vistas, los tenemos que programar por nuestra cuenta y localizan cada una de las partes de nuestro programa que, al estar sepadadas nos ayudan a organizar también nuestro código. También tenemos a nuestra disposición diversas librerías, ayudantes (helpers) y plugins ya escritos en CodeIgniter con numerosas clases y funciones muy útiles para el desarrollo de aplicaciones web.
Uno de los puntos más básicos, pero no por ello menos útiles, de CodeIgniter que explicaremos dentro de poco, es el múdulo de entutamiento (routing) que permite que cualquier URL que se solicite al servidor se ejecute en el controlador adecuado. La URL se analiza y los datos se procesan y aseguran antes de enviarlos al controlador adecuado, en el que simplemente tendremos que codificar sus diversos métodos.

En el siguiente artículo estudiaremos el Modelo - Vista - Controlador, que implementa CodeIgniter como arquitectura para el desarrollo.