Wednesday, January 8, 2014

Create OAI and Canonical User using .NET code


There are some tasks which we can’t achieve using the cloud formation scripts for all those we can always use the server side code to do that either JAVA or .NET.

If you're using Amazon S3 for your origin, you can use an origin access identity to require users to access your content using a CloudFront URL instead of the Amazon S3 URL.
Manually it’s very easy to create the OAI and link it to the S3 bucket, but when we want creating bucket and distribution using the Cloud formation scripts we need to create the OAI user using the server side code. Reason for this OAI creation will take time when we are running the piece of server side code for the same.

In Cloud formation script we can execute the exe file (server side code) which first generates the OAI user and then we can link it to the scripts. Below I have pasted the server side code for OAI creation.
These are the steps we need to follow when we want to automate the bucket and distribution creation using Cloud formation script.


Steps to follow:

  1. First Create the OAI user using the .NET/Java code and store the OAI id in some file.
  2. Once the ID is created pass the ID as parameter to the cloud formation script.



Script:
aws cloudformation create-stack --stack-name projecttemplate --template-body file://project.json --parameters file://Data.json

  1. project.json : Will have the Script to create bucket and distribution
  2. Data.json: Will have the parameter like OAI ID or any other variable such as bucket name etc.


  

.NET Source Code : To create the OAI User and store it in some JSON file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Amazon.CloudFront;
using Amazon.CloudFront.Model;
using System.Collections.Specialized;
using System.Configuration;
using Amazon.CloudFormation.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data;
using System.IO;

// Require AWS SDK for .NET http://aws.amazon.com/sdkfornet/

namespace AWS_Test
{
    class Program
    {
        static string accessKeyID = ConfigurationSettings.AppSettings["accessKeyID"].ToString();
        static string secretAccessKeyID = ConfigurationSettings.AppSettings["secretAccessKeyID"].ToString();

        static string configComment = ConfigurationSettings.AppSettings["Comment"].ToString();
        static string configCallerReference = ConfigurationSettings.AppSettings["CallerReference"].ToString();
        static AmazonCloudFrontClient cfClient = null;

        static void Main(string[] args)
        {


            using (cfClient = (AmazonCloudFrontClient)Amazon.AWSClientFactory.CreateAmazonCloudFrontClient(accessKeyID, secretAccessKeyID))
            {

                Console.WriteLine("Create CloudFront Origin Access Identity");
                CreateCloudFrontOAI();

                Console.WriteLine("Get CloudFront Origin Access Identity");
                GetCloudFrontOAI();

                Console.WriteLine("Finish");
            }

            Console.WriteLine("Press any key to continue...");
            //Console.Read();
        }

        /// <summary>
        /// POST Origin Access Identity
        /// http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/index.html?CreateOAI.html
        /// </summary>
        static void CreateCloudFrontOAI()
        {
            try
            {
                CloudFrontOriginAccessIdentityConfig config = new CloudFrontOriginAccessIdentityConfig();
                config.Comment = configComment;
                config.CallerReference = configCallerReference;

                CreateCloudFrontOriginAccessIdentityRequest req = new CreateCloudFrontOriginAccessIdentityRequest();
                req.CloudFrontOriginAccessIdentityConfig = config;

                var res = cfClient.CreateCloudFrontOriginAccessIdentity(req);

                CloudFrontOriginAccessIdentity id = res.CloudFrontOriginAccessIdentity;
                String xml = res.ResponseMetadata.ToString();

                Console.WriteLine("OAI id:" + id.Id);
                Console.WriteLine("OAI S3CanonicalUserId:" + id.S3CanonicalUserId);
                Console.WriteLine(xml);

                writeinfile(id.Id);

            }
            catch (AmazonCloudFrontException cfEx)
            {
                Console.WriteLine("An Error, number {0}, occurred when create cloud distribution with the message '{1}", cfEx.ErrorCode, cfEx.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("UnknownError:{0}", ex.Message);
            }
        }

        /// <summary>
        /// GET Origin Access Identity
        /// http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/index.html?GetOAI.html
        /// </summary>
        static void GetCloudFrontOAI()
        {
            try
            {
                GetCloudFrontOriginAccessIdentityConfigRequest request = new GetCloudFrontOriginAccessIdentityConfigRequest();
                request.Id = "ORIGIN_ACCESS_IDENTITY_ID";

                GetCloudFrontOriginAccessIdentityConfigResponse response = cfClient.GetCloudFrontOriginAccessIdentityConfig(request);

                //String xml = response.XML;
                //Console.WriteLine(xml);

                Console.WriteLine("Etag: " + response.ETag);
            }
            catch (AmazonCloudFrontException cfEx)
            {
                Console.WriteLine("An Error, number {0}, occurred when create cloud distribution with the message '{1}", cfEx.ErrorCode, cfEx.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("UnknownError:{0}", ex.Message);
            }
        }

        /// <summary>
        /// GET Origin Access Identity List
        /// http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/index.html?ListOAIs.html
        /// </summary>
        static void ListCloudFrontOAI()
        {
            try
            {
                ListCloudFrontOriginAccessIdentitiesResponse response = cfClient.ListCloudFrontOriginAccessIdentities();

                String xml = response.ResponseMetadata.ToString();
                Console.WriteLine(xml);
            }
            catch (AmazonCloudFrontException cfEx)
            {
                Console.WriteLine("An Error, number {0}, occurred when create cloud distribution with the message '{1}", cfEx.ErrorCode, cfEx.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("UnknownError:{0}", ex.Message);
            }
        }


        /// <summary>
        /// function to update the json file with the OAIID value
        /// </summary>
        /// <param name="OAIID"></param>
        static void writeinfile(string OAIID)
        {
            string jsonString = string.Empty;

            StreamReader re = File.OpenText(ConfigurationSettings.AppSettings["filepath"].ToString() + "DevData.json");
            JsonTextReader reader = new JsonTextReader(re);
            JArray root = JArray.Load(reader);

            foreach (JObject o in root)
            {

                if (o.GetValue("ParameterKey").ToString() == "oaiid")
                {
                    o["ParameterValue"] = OAIID;
                }

                if (jsonString.ToString() == string.Empty)
                {
                    jsonString += o.ToString();
                }
                else
                {
                    jsonString += "," + o.ToString();
                }
            }

            jsonString = "[" + jsonString + "]";
            re.Close();
            System.IO.File.WriteAllText(ConfigurationSettings.AppSettings["filepath"].ToString() + "DevData" + ".json", jsonString);
        }
    }

}

References:



Thursday, July 25, 2013

PhoneGap 3.0 Setup

Setup Cordova 3.0


As all of you are aware that phonegap has released a new version 3.0, which has incorporated architectural changes in it. And some of the basic things like creating project, building project, adding platform supports, adding PhoneGap API and adding Custom plug-in to the project has changed.
Before you start the installation processes please go through this link: Adobe-phonegap-3.0-released

 

Steps to Configure Cordova 3.0


1.       Make sure you install node.js in Mac/windows machine.
2.       Once you have installednode.js , then open your command line and run the following:
C:\> npm install -g Cordova
3.       Once installation completes, you can invoke Cordova on command line for further help.

List of project command for Cordova


1.       To create a Cordova project
       $ cordova create my-app                                             # create a Cordova project 
2.       Usage of Cordova commands
       $ cordova [options] [commands]

Commands:
                                I.            create <path>        create a phonegap project
                              II.            build <platform>     build a specific platform
                            III.            install <platform>   install a specific platform
                            IV.            run <platform>       build and install a specific platform
                              V.            local [command]      development on local system
                            VI.            remote [command]     development in cloud with phonegap/build
                          VII.            help [command]       output usage information
                        VIII.            version              output version number

 Options:
                                I.            -V, --verbose        allow verbose output
                              II.            -v, --version        output version number
                            III.            -h, --help           output usage information


Examples:
                                I.            To Get the Cordova help type the following command in command line.
$ Cordova help

                              II.            To create Cordova project, first locate the project folder.
$ First redirect to you work space using the cd/ls commands
$ Cordova create FirstApp                                  #Create a Cordova project
$ cd FirstApp                                                         # Change the folder to app location


3.       Platforms Commands
      $ “Cordova platform [ls | list]” list all platforms the project will build to       $ “Cordova platform add <platform> [<platform> ...]” add one (or more) platforms as a build target for the project
      $ “Cordova platform [rm | remove] <platform> [<platform> ...]” removes one (or more) platforms as a build target for the project

4.       Plug-in Commands
      $ “Cordova plugin [ls | list]”   list all plugins added to the project
      $ “Cordova plugin add <path-to-plugin> [<path-to-plugin> ...]” add one (or more) plugins to the project
      $”Cordova  plugin [rm | remove] <plugin-name> [<plugin-name> ...]” remove one (or more) added plugin’s

5.       Build Commands
       $ “Cordova build”   will build added platform projects like iOS, android etc..
       $ “Cordova build  <android/ios etc..>” Will build the specific platform like iOS, Android ect


Project Directory Structure:



A Cordova application built with cordova-cli will have the following directory structure:

.cordova/
This directory identifies a tree as a Cordova project. Simple configuration information is stored in here (such as BlackBerry environment variables).
Commands other than `create` operate against the project directory itself, rather than the current directory - a search up the current directory's parents is made to find the project directory. Thus, any command (other than `create`) can be used from any subdirectory whose parent is a Cordova project directory (same as git).

merges/
Platform-specific web assets (HTML, CSS and JavaScript files) are contained within appropriate subfolders in this directory. These are deployed during a `prepare` to the appropriate native directory.  Files placed under `merges/` will override matching files in the `www/` folder for the relevant platform.

www/
Contain the project resources such as .html, .css and .js files. These are your main application assets. They will be copied on a `cordova prepare` to each platform's www directory.

config.xml
This file is what you should be editing to modify your application's metadata. Any time you run any cordova-cli commands, the tool will look at the contents of `config.xml` and use all relevant info from this file to define native application information. cordova-cli supports changing your application's data via the following elements inside the `config.xml` file:

platforms/
Platforms added to your application will have the native application project structures laid out within this directory.

plugins/

Any added plugins will be extracted or copied into this directory.


References


Monday, July 1, 2013

Hybrid Mobile Development

Introduction

In this article we will see how the different hybrid mobile approach supports for developing mobile application for multiple mobile platforms such as iOS, android and Blackberry etc. In this article I have targeted mostly used hybrid development framework available in market as of now. Hybrid mobile application basically is a power of HTML5, JavaScript and CSS3 as well as Native API for cross platforms.

Hybrid Mobile Development

Hybrid mobile apps combine aspects of the two, written in HTML5, CSS3 and JavaScript, but with access to device functions via a plug-in developed by mobile development framework. Hybrid apps make it possible to embed HTML5 apps inside a thin native container, combining the best (and worst) elements of native and HTML5 apps.

Hybrid Frameworks
There are lot of hybrid mobile development frameworks available in the market. We will see in brief some of the widely used frameworks.

PhoneGap/Cordova:

PhoneGap is an open source framework for quickly building cross-platform mobile apps using HTML5, Javascript and CSS. When we want to develop application for Android, iOS, Blackberry and windows phone etc, we need to have the understanding of all the languages that each of the platform uses. PhoneGap solves this by using standards-based web technologies to bridge web applications and mobile devices.
·         http://phonegap.com/

Dojo:

Dojo is a JavaScript framework, a collection of utilities written to ease development of client-side Mobile/Desktop applications. Dojo is one of several such libraries. It is composed of a collection of JavaScript functions that cover DOM operations to perform useful operations frequently needed by developers. It establishes a framework for defining modules of code and managing their interdependencies; it provides build tools for optimizing JavaScript and CSS, generating documentation, and unit testing; it supports internationalization, localization, and accessibility.

The Dojo Toolkit is organized as –
Dojo: Contains the core and most non-visual modules.
Dijit: Is a library of user-interface modules for widgets and layout.
Dojox: holds assorted modules not yet considered stable enough to include in dojo or dijit.
Util: includes build tools such as optimization, documentation, style-checking, and testing.

·         http://dojocampus.org/
·         http://www.classdojo.com/

Sencha Touch:

 JavaScript library or framework, specifically built for the mobile devices. It is fully based on web standards such as HTML5CSS3 and JavaScript. Sencha Touch we can integrate with the PhoneGap and easily create HTML5 based mobile apps that work on Android, iOS and BlackBerry devices, and produce a native-app-like experience inside a browser. Sencha touch has set of Control defined which we can use in the mobile development. All the controls are enabled with the touch events/features.


JQuery Mobile:

JQuery Mobile is a user interface framework based on jQuery that works across all popular phones, tablet and desktop platforms. JQuery is developed to meet the responsive web design (RWD) principles. JQuery mobile framework allows user to design a single highly-branded web site or application that will work on all popular Smartphone, tablet, and desktop platforms.

·         http://jquerymobile.com/


Hybrid Frameworks Comparison   



Hybrid Mobile App Pros and Cons

Pros

ü  Faster time to market.
ü  Hybrid app development enables seasoned developers with the knowledge of traditional technologies like HTML5 and CSS to build quality apps without having to learn native app development.
ü  A reduction in native coding usually results in more reusable code across platforms as the HTML5/JS/CSS code base can be utilized across platforms
ü  Maintenance costs are usually lower
ü  Targeting multiple platforms without writing multiple apps from scratch
ü  Not having to maintain multiple codebases in the future.

Cons

ü  There are several layers of abstraction that tend to slow down the application.
ü  It is a lot more difficult to debug a hybrid app than it is to do the same to a native app.
ü  It is not possible to use a lot of native features – especially the cutting-edge features that have just been released.
ü  Potential performance issues.
ü  HTML5 doesn’t work for everything.
ü  Native frameworks can provide advanced functionality that cannot always be easily replicated on the HTML5/CSS/JS side




Conclusion

The best choice would depend on the type of application you are developing.  For example, animation-intensive apps such as games or Device specific functionality would favour native apps, while hybrid applications may be better suited for simple and small apps or enterprise mobile apps because they provide multi-platform support.


The rule for Hybrid Development “Build once and deploy to multiple platforms”.