Pages

Friday, 15 November 2013

Rendering result in desire format making ajax call to local method in Rhomobile

Introduction:
While developing application, we sometimes need to make ajax call to local methods so that we can render the updated data without refreshing the whole page. We can achieve this using RhoMobile. If we need, we can call local method and get the data using JavaScript ajax call and finally render them into the current view without reloading it.

Description:
We can get desired format of output, using the advance use of ‘render’. If we need to render some data in different format like STRING, JSON, XML, following are the different ways to do the job.

Method 1 : Render as String
def get_string
   render :string => ‘This is a sample line’
end 


Continue reading

Wednesday, 14 August 2013

How To Authorize A Virtual Directory In Your Application In IIS

When we create any virutal directory in IIS, normally we follow the below steps:
1. Give the Alias name
2. Give the physical path
3. Click OK.

No doubt, the above steps will create the virtual directory of your application successfully and you will not get any issue while running
the application ; but it can give some major issue at runtime.
For example:
* Not able to load css
* Not able to log in to the application
* Not able to access particular files
* 401.3 access denied issue, and so on.

The only solution to the above issues is : Authorize the application in IIS.

After creating the virtual directory, we are not checking the authentication and authorization settings.
Click on the button "Test Settings", you will find that the site is authenicated properly but it needs authorization.

You can look into the below image for details:


Now our aim is to remove the waring symbol from the Authorization Test and we need to convert this into green check mark.

To provide authorization to the application, delete the previously created virtual directory and create the new one with the following stpes:

1.Give the Alias name
2. Give the physical path of your application
3. Click on "Connect As" button.
4. Click on radio button "Specific User" and then click on "Set".
5. Give the Username and password of your machine, confirm the given password and Click on "OK".
6. And finally Click "OK" to add the virtual directory.

Now, check the Authorization and Authentication settings by clicking "Test Settings" button.


Refer the below screen shot, all are marked as green. That means now your application is authorized and authenticated properly.


By doing this settings, we can resolve the above discussed issues as well as we can get rid of a major issue that we normally face, that is folder sharing issue.

Few days back, we have faced this problem. My client has shared one of the folder present inside the project directory and we were unable to access the files present within the shared folder. Though we were unaware about the folder sharing, it will take a day to find out the cause. Finally we got the issue and after doing some R&D, we found the solution.

We have deleted the application virtual directory and re-create it by giving the proper connection settings and after sharing the folder also, our application runs like magic.

Submitted By: Snehanjali Sahoo, Coldfusion Developer, Mindfire Solutions

Sunday, 11 August 2013

Capturing Image using Camera API in Rhomobile & Uploading it to Server

In this post, we will see how to capture the image using Camera API of Rhomobile and store it to app base path so as to gain permission to later upload it to server. We will see the way to store the details of the image on the rhom ( sqlite database ), then later upload the file to server on the time of sync process.

Capturing Image Using Device Camera:
As described on the previous post, A Deep Look Into Camera API of Rhomobile, we need to use take_picture method to capture the photo.

Below is the code to capture the photo from device camera.

    def take_picture

      album_id = @params['album_id']  
      camera_option = { 
                        :camera_type => “main”, 
                        :color_model => “RGB”, 
                        :enable_editing => false, 
                        :flash_mode => 'auto',
                      }
      Camera::take_picture(url_for(:action => :camera_callback, :query=> { :id => album_id }), camera_option)

    end


Here after the Camera API captures the photo, it will be redirected to the callback method with parameters as described in callback_params. The callback_params will be having an additional parameter 'id' that we send with the callback method.

Storing the Image:
On the callback method, we need to store the image details on the local database and store the image file to the base app path.

def camera_callback

  # Storing the image details to local db
  file_name = @params['image_uri'].to_s().split("/")[2]
  image = Image.new()
  image.image_uri = @params['image_uri']
  image.album_id = @params['id']
  image.filename = file_name.to_s
  image.created_at = Time.now.utc
  image.updated_at = Time.now.utc      
  image.save   

  # Store the image file to base app path
  file_blob_path = File.join(Rho::RhoApplication::get_blob_path(@params['image_uri']))
  file_content = File.binread(file_blob_path)
  file_real_path = File.join(Rho::RhoApplication::get_base_app_path(), file_name)
  f = File.new(file_real_path, "wb")
  f.write(file_content)
  f.close

end

Upload the image to server:
During the sync process, we need to upload the record and the image file to server as follows,

def image_upload_to_server
  images = Image.find_by_sql("select * from Image where filename is not null")
  unless images.eql?(nil)
    images.each do |image|
      # Get the image real path
      image_path = File.join(Rho::RhoApplication::get_base_app_path(), image.filename)
      data = Rho::AsyncHttp.upload_file(
                  :url => "#{@@url}/photo/upload?album_id=#{image.album_id}",       
                  :filename => image_path,
                  :headers => {}, 
                  :body => ""
                )
    end
  end
end
That's all, the image is now uploaded to the server.

A Deep Look Into Camera API of Rhomobile

In this post, we will go through the available methods for Camera API in details using Rhodes. This post will just explain the methods and uses of the Camera API from ruby excluding the rho-element javascript API.

Camera Permission:
In order to use the device camera, we need to get the permission by defining the capabilities in build.yml file.

    capabilities: 
       - camera

This denotes the Rhomobile build stage to add respective access permissions to the application keeping the platform and required settings on focus.

Available APIs:
Rhomobile provides the listed APIs to interact with the Device Camera.
      1. get_camera_info
      2. save_image_to_device_gallery
      3. take_picture
      4. choose_picture

Camera Options:
The APIs (take_picture & choose_picture) takes a hash as options for extra configurations, if we need to set.

 camera_option = {
  camera_type  =>  “main”,
  desired_width  => “640”,
  desired_height => “480”,
  color_model => “RGB”,
  format => “png”,
  enable_editing => false,
  flash_mode => “auto”,
  save_to_shared_gallery => true
 }


Lets go through each options in details,
         1. camera_type :
            Possible values are “main” or “front”.
            Default is “main”.
    2. desired_width :
        The value to be in px.
        Default is the maximum possible camera width.
    3. desired_height :
            The value to be in px.
            Default is the maximum possible camera height.
    4. color_model :
            Possible values are “RGB” or “Grayscale”.
            Default is “RGB”.
    5. format :
            Possible values are “png” or “jpg”.
            Default is “jpg”.
    6. flash_mode :
            Possible values are “on” | “off” | “auto” | “red-eye” 

            | “torch”.
            Default is “auto”. This option is for Android only.
    7. enable_editing :
            Posible value Boolean true / false.
            Default is true. This option is for iPhone only.
    9. save_to_shared_gallery :
        Possible values are Boolean true | false.
        Default is false. This option is for iOs only.

How to use APIs:
  1. get_camera_info 

    This method takes parameter ( camera_type ) and returns the
    hash value with width and height as numeric value and returns NIL if camera_type is not supported.
          camera_info = Camera::get_camera_info(camera_type)
    
    
    camera_info will be something like 
          { width => 640, height => 480 } | NIL

  1. choose_picture

    This method is used to select the image file from the gallery or sdcard. This method takes two parameters callback_method and camera_option.

          Camera::choose_picture(callback_method,camera_option)
    

    The callback_method (“/app/camera/callback_method”) will be 
    called after the operation completes, with parameter as hash 
    described in callback_params.

  1. take_picture
     This method is used to open the camera view and snap a photo.
     This method takes two parameters callback_method and 
     camera_option as like above one.

  •       Camera::take_picture(callback_method,camera_option)
    

     The callback_method will be called after the operation
     completes, with parameter as hash described in callback_params.

  1. save_image_to_device_gallery
    This method is used to store the generated or created image file to device gallery. This method takes parameter as the image path.

  •      
         image_path = Rho::RhoApplication::get_blob_path(image_uri)
         Camera::save_image_to_device_gallery(image_path)
    

    The image_uri will be the uri of the image in the 
    callback_params.

Camera Callback Parameters:
The callback method with be called by POST method, and the passed parameters are:

  •      
    
        {
         status => “ok”,
         image_uri => “some uri”,
         message => “”,
         image_format => “jpg”,
         image_width => 640,
         image_height => 480
        }
    
    

Lets go through each parameters in details,
         1. status :
             Possible values are “ok” or “cancel” or “error”.
    2. message :
        Some error message as string if the status is “error”.
    3. image_uri :
        The uri of the taken or choosen image.
    4. image_format :
        Possible values are “png” or “jpg”.
    5. image_width :
        Width of the image in numeric value.
    6. image_height :
        Height of the image in numeric value.

Thats all. We can now explore device camera with the above APIs.

Sunday, 21 July 2013

MVC Architecture & Oops in JavaScript using PhoneGap

Introduction:

In this post, we'll look into the creation of MVC architecture in JavaScript. Using MVC in PhoneGap applications makes them modularize, which is much helpfull during big projects and most of all, makes them easy & simple to handle and review during maintenance. Use of Oops concept, helps us making multiple instances of Model/Controller that can be used with multiple views, each having it's own scope.

Description:

First of all, lets have a look into the MVC Architecture. As we know Model creates the bridge between the database and the Controller, where as View manages the UI in associate with the Controller. So, the vital part is the Controller, which builds the passage between the Model and View, passing the data to & fro. The Controller contains all the logical codes that need to be done, and rest Model & View just contains the code required to manipulate the data.

Below is the basic HTML we need for showing the list view.

        <div id="wrapper">
            <div id="scroller">
                <ul id="container"></ul>
            </div>
        </div>


Now we need to create the MVC Architecture, so we will be having the following files,

    RecipeModel.js - It will manage all the database queries.
    RecipeView.js - It will make the UI changes to show the Recipe List.
    RecipeController.js - It will manage the data flow between View and Model.
   
So let's have go through the Model,

    RecipeModel.js
    ------------------
   
    var RecipeModel = function() {
       
     // Code to open database and retrieve records
     // from it.
       
  };
   
Now it's the time to code for Controller, let's see how.

    RecipeController.js
    ------------------
   
    var RecipeController = function() {
       
    // Get the model object
    this.model = new RecipeModel();
       
    // Code to get the list of recipes from model
       
  };
   
And finally, we will go for creating the View,

    RecipeModel.js
    ------------------
   
    var RecipeView = function() {
       
     // Get the controller object
     this.controller = new RecipeController();
       
     // Code to loop through the array and print the

     // recipes to the html
       
  };
   
That's all, we can now have the list of recipes listed on the UI. For a detailed code and reference follow my post here

Summary:

    Using MVC makes the flow go simple and concrete, all together making it quite easy during maintenace.


Sunday, 14 July 2013

Smooth Page Transition on Mobile Devices within Single Html Page

For the smooth page transitions for mobile devices, the basic concept is to make a div element of full width and height, and animate the inner div elements that should act like page.

Now let's discuss the required styling for the sections. The div element acting as page should be position absolute with full page display, and keep in mind to translate them to initial positions using the css3 translate3d property.

The first page will be animated form its original position to either left/right side with translate value of 100%. So we need four classes, one with the animations effects and other three with the translated values.

         /* Transitions Effects Styling */
         .page.left {
               -webkit-transform: translate3d(-100%, 0, 0);
               transform: translate3d(-100%, 0, 0);
         }
         .page.center {
               -webkit-transform: translate3d(0, 0, 0);
               transform: translate3d(0, 0, 0);
         }
         .page.right {
               -webkit-transform: translate3d(100%, 0, 0);
               transform: translate3d(100%, 0, 0);
         }


So now on the javascript code we just need to add these classes to the respective pages while animating, and yes, before going for this, we need to bind a function with the "webkitTransitionEnd"
event that will revert back the changes by removing the classes.

Finally, the navigation. This can be done by keeping track of the hash change and animating the required pages accordingly with loading the page templates onto the main div.  
     
      // Bind the hash change event
      $(window).on('hashchange', Route);



So here basically we need to write a function called "Route", that will manage the hash change event and detect the current hash and load the respective page.

That's all, just load the page and go through the transitions.

For a detailed view of this post please follow this link.