Pages

Sunday, October 27, 2013

Removing Turbolinks from Rails 4

If you don't want to use Turbolinks with your Rails 4 application, it's easy! Just do this:

  1. Remove the gem 'turbolinks' line from your Gemfile.
  2. Run bundle install
  3. Remove the //= require turbolinks from your app/assets/javascripts/application.js
  4. Remove the two "data-turbolinks-track" => true hash key/value pairs from your app/views/layouts/application.html.erb

Done!

Reference: Removing Turbolinks from Rails 4

Monday, February 4, 2013

Implementing Android Push Notifications using Urbanairship (GCM) client Lib

Hello friends,
This is about how to Integrate Push Notification service of Urbanairship client(GCM) in Android App.
I didn't find a good blog for Urbanairship integration in Android for using Google's GCM service. Processes dictated in Urbanairship docs are good but not much clear for new developers.

As we know rather than using GCM lib. directly prefer to use Urbanairship services which are pretty simple.
If you want to read about GCM here you go with Google GCM doc.

I will explain complete process from start to end the way I did and it's working.

If you have your project ready to integrate lets start.
Steps:

1. First of all register your Android project on Google API site. If you visiting site first time, get to see below window(You need to use your gmail account to login).



Clicking on create project will lead to new page, on left hand side drop down menu select "Create Project". Provide name of your project. It will bring you on dashboard where you get the details of your project.
From there save the 12 digit "Project Number" (e.g. 933568175224) you'll need it later.
Go to Services on left hand side turn on "Google Cloud Messaging for Android".

2. Now to use Urbanairship client(GCM) you have to Register on Urbanairship.
After logging in go to "Create New App" fill details properly, for Android device add package name (e.g. com.android.gcmtestproject) and check Push enable.
This process leads to a details page where you'll receive Application Key, App Secrete we are going to use it in airshipconfig.properties file, we'll get back to this later.

As result of above two steps your registered with Google API and Urbanairship.

3. Now you need Urbanairship lib for integration so Downlaod latest zip (click to download zip 1.0MB). In that you'll get Urbanairship lib and a sample application to demonstrate the process.
Just copy that urbanairship.2.0.0.jar and paste to your android projects /lib/ folder. Add this jar file to your projects build path.

GCM Early Access Urbanairship this doc page dictates you everything but I'm explaining in detail.

4. Create airshipconfig.properties file in /assets/ folder now add following lines in it.


As you noticed in above code we commented productionAppKey and productionAppSecret because we are not deploying it to market when you do so remove comment and add both field values.

5. Setting up your AndroidManifest.xml file with the necessary receivers, services and permissions to start receiving push notifications. You can also find AndroidManifest.xml in sample project from urbanairship.zip that you downloaded.


In above manifest file just replace com.urbanairship.push.sample with your projects package name (here I've com.android.gcmtestproject).

6. Enabling Push: By default, push is disabled in the client library. So, for testing purposes, enabling push service on start up.
Client library automatically starts push upon takeOff.
Add following lines to your projects application’s onCreate method.


7. Get APID: The APID is a unique identifier that ties together an application/device pair on android. You can use this ID to target pushes to specific devices using the Urban Airship API. Once an APID is created, it will persist the application until it is either re-installed, or its internal data is cleared.
Add following lines to your projects application’s onCreate method.


8. Now write IntentReceiver class which extends BroadcastReceiver. In it's onReceive() do the following

get action from intent:

When action is ACTION_PUSH_RECEIVED or ACTION_NOTIFICATION_OPENED then you can extract data from intent and pass it to another activity. When action is ACTION_REGISTRATION_FINISHED you can get APID through following code.


I described APID in step 7.

Note this APID as we'll use it to send push notifications from Urbanairship and don't forgot to add IntentReceiver to your manifest file.

So, these are the steps pretty simple. Your app is now ready to receive Push notifications from Urbanairship.

For testing that push notification on device is working or not go to https://go.urbanairship.com. Log in
then on left hand side in your App's Details window click on Push then click on "Send Broadcast" as we created IntentReceiver class which is BroadcastReceiver so we receive fired intent.
Or click on "Testing Push Notifications".

Note while sending and receiving Push notification you have to log in from your Google account on Android device to receive Pushes.

A little prob. as we know that GCM is not completely replaced for C2DM and on Urbanairship Early Access is available.
I got response mail from Urbanairship support team i.e. "GCM early access requests filled much faster than expected and new activations have been halted. So we have to wait till release."

If you're not receiving Push notifications then send an email to Urbanairship(support@urbanairship.com) with following details.

Subject should be specific.

Account Type is : Pro
Application name : GCMTestApplication
Application Key : dqzp7LmjTRG65cZBfUhMxw

Message


Then Urbanairship support team replies you with case no. and they try to clear it ASAP, and then your application can receive push notifications.

How to prevent browsers from caching a page in Rails

This took me forever to figure out, so I hope I’ll be able to save someone a few hours of annoyance someday.

Serendeputy is always recalculating, and I needed to make sure that the browsers wouldn’t cache the page when someone clicked off and then hit the back button. This is how I was able to do it.

in application_controller.rb

I just tested this out, and it works on Safari and Firefox on the Mac, and IE7, Firefox and Chrome on the PC.

Hope this helps.

Sunday, February 3, 2013

Paperclip - Rails

Below is a page for a product in an e-commerce application. We’d like to add an image of the product to this page and modify the admin system so that an image can be uploaded when a product is created or modified. In this episode we’ll show you how to use a plugin called Paperclip to do this.

The product page for our application.

Paperclip makes adding attachments to a model simple. We’re going to use it to add a field to our Product model so that each product can have an image.
Paperclip is installed in the same way as any other plugin. From our application’s directory we can install it from Github.


Updating The Model

Now that we have Paperclip installed we can run its generator to add an attachment field to the Product model.


The generator takes two arguments. The first is the name of the model, in our case our Product model, and the second is the name of the model’s new attachment field. The generator will create a migration that will add four new fields to the model.


The four new fields added by the Paperclip generator.

We’ll then need to run rake db:migrate to update the products table in the database.

The next step is to update the model code. We need to use has_attached_file to tell it the name of the attachment field we specified when we ran the migration.


Modifying The Views


The form that creates or updates a product will need a file upload field adding to it.


As well as adding a file_field to the form we need to modify the form_for so that the form will accept file attachments. This is done by adding :multipart => true to the :html hash, which will add the attribute enctype="multipart/form-data" to the form’s opening tag.

Of course there’s no point uploading images if we don’t then show them, so we’ll need to make a change to the show view. To add the image we just need to add an image_tag to the page. Our Product model will now have a photo object as a property with a url method that will give us the correct path to the image.


That done we can edit a product, add an image to it and see the results.

The product's page now shows an image.

It’s worked! Our product now has an image, but it’s a bit too big. While we could make sure that we only upload pictures of the correct size, it would be easier if we could resize the images on the server and with Paperclip there’s a way to do just that.

Resizing Images


The has_attached_file method that we added to our Product model takes a number of options. One of these is styles which allows us to define different sizes for our image. To create a thumbnail for each image we just need to define a style and specify the size.


With the new style added, Paperclip will now generate a thumbnail of each image that fits within 150x150 pixels. The greater than sign at the end tells Paperclip to keep the aspect ratio of the picture so that it isn’t distorted when its resized. Note that to enable resizing you’ll need to have ImageMagick installed on your server.

To display the resized image in the product’s show view we’ll have to change the image_tag so that the url points to the smaller version.


If we pass the style to the url method the appropriate image will be returned. The smaller image is only generated when an image is uploaded, so to resize our picture we’ll have to edit our product and upload the file again. Once we’ve done that our product’s photo will now appear at the thumbnail size we specified.

The product page now shows the image at the correct size.

Setting Paperclip’s Path


By default Paperclip will store attachments in a system directory under our application’s public directory.


Paperclip creates its own hierarchy to store attachments, creating directories based on the the id of the product and style we set in the model. Most of the time the default directory is fine, but if we want to store the images elsewhere then we can change it.

To store the images elsewhere we just add two more options to the has_attached_file method, url and path.


The url and path shown above are the defaults that Paperclip uses. The url is specified relative to the public directory and there are placeholders in the string for the name of the attachment field, the model’s id and the style. There are similar placeholders in the string for the path. We want to store our images in an assets directory, so we’ll change the url and the path to suit.


Any images we upload now will be stored in the assets directory rather than in system/photos.

Validating Attachments


One final useful part of Paperclip is that it can validate the attachments that are uploaded. To validate the photos that are uploaded we could add validators like these to our Product model:


With the validators above we’re checking that an attachment has been uploaded, that it is no bigger than five megabytes in size and that it is either a JPEG or PNG image. Using these we can validate an attachment as easily as any other form field. One thing to take care with if you’re checking the content type is that Internet Explorer can report different MIME types from other browsers. For example it can treat JPEG files as image/pjpeg rather than image/jpeg.

Note: This topic is taken from RailsCasts and shared here so that you can discuss any problems that you may face during implementing Paperclip into your project. You can go to RailsCasts for more details on this topic.

Prevent the Browser from Caching an ASP Page

Most ASP books and articles state that you need to set the Response. Expires property to 0 or -1 to prevent the end user's browser from caching an ASP page. However, this is only partially correct, because in order to work correctly for all browsers brands and versions, you also need to add a special Pragma HTTP header, and to disable any caching by a proxy. This is the ASP code you should put on top of your page to achieve the desired behavior:


Prevent Page Caching in JSP

It is possible to keep the browser from caching a JSP page response. The following hints added to the response header seem to prevent most modern browsers from pulling pages out of cache when the same URL is "hit":


The same effect can be achieved by using meta tags in the HTML header:


The Cache-Control header was added in HTTP 1.1, while the other two were also present in HTTP 1.0.

Creating Arrays in Java

Arrays are objects in java, and for that we create them using new operator.

For primitive data types:

For non-primitive data types:

Once you specify the size of array, you can't change it later.

Assigning values to arrays:

For primitive data types:

For non-primitive types:

It will create objects in the heap and assign it to the the array elements.

To copy one array to another one you can use arraycopy method from System class:


It will copy values from index 1 of myStrings to copiedStrings. So copiedStrings will look like this.


Wednesday, January 30, 2013

How to use the Application object of Android


We know there is an Application class in the Android api and according to the class name it's used for global settings or running entrance. What does it to do for an application? I will dive into it along with some examples in this blog post.
In the Android reference it describes the Application class: "Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml'stag, which will cause that class to be instantiated for you when the process for your application/package is created."
So you can create your own subclass of Application like this:


And specify its name in your AndroidManifest.xml's tag


The Application class is mainly used for some Application level callbacks and for maintaining global Application state.

Application level callbacks

  • onConfigurationChanged( ) Called by the system when the device configuration changes while your component is running.
  • onCreate( ) Called when the application is starting, before any other application objects have been created.
  • onLowMemory( ) This is called when the overall system is running low on memory, and would like actively running processes to tighten their belts.
  • onTerminate( ) This method is for use in emulated process environments. It will never be called on a production Android device, where processes are removed by simply killing them; no user code (including this callback) is executed when doing so.

Maintaining global Application state

Sometimes you want to store data, like global variables which need to be accessed from multiple Activities - sometimes everywhere within the application. In this case, the Application object will help you.
For example, if you want to get the basic authentication data for each http request, you can implement the methods for authentication data in the application object.
After this,you can get the username and password in any of the activities like this:


And finally, do remember to use the Application object as a singleton object: