Archives

Web Development – The Basics

· Tech · ,

Back-end, front-end, multitier architecture, client-server model, MVC? If you’re familiar with web development, you’ve probably heard some of these terms. I’ve put together a small ebook (PDF) with the basics in web development. The ebook is a collection of articles from Wikipedia.

Web Development – The Basics

Parse: Uploading files to the cloud (.NET SDK)

· Tech · , , , ,

Parse API/SDK is very well documented but in some cases it’s good to see some examples from the community itself. In this post I’ll describe how easy it is to upload files with Parse using the .NET SDK.

This code is divided in three methods:

 

readFileToMemory

public static byte[] readFileToMemory(string _filePath)
{
	byte[] buffer;
	var filePath = _filePath;
	FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
	Console.WriteLine("READING FILE...");
	try
	{
		int length = (int)fileStream.Length; // get file length
		buffer = new byte[length]; // create buffer
		int count; // actual number of bytes read
		int sum = 0; // total number of bytes read
		// read until Read method returns 0 (end of the stream has been reached)
		while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
			sum += count; // sum is a buffer offset for next reading
	}
	finally
	{
		fileStream.Close();
	}

	return buffer;
}

 

uploadFileToParse

public static async Task uploadFileToParse(byte[] buffer, string fileName)
{
	//Upload file
	byte[] data = buffer;
	ParseFile file = new ParseFile(fileName, data);
	Console.WriteLine("UPLOADING FILE...");
	await file.SaveAsync();
	
	//Link file with object
	var jobApplication = new ParseObject("JobApplication");
	jobApplication["applicantName"] = "Joe Smith";
	jobApplication["applicantResumeFile"] = file;
	Console.WriteLine("SAVING OBJECT...");
	await jobApplication.SaveAsync();
	Console.WriteLine("FINISHED - press enter to exit");
}

 

Main

public static void Main(string[] args)
{
	ParseClient.Initialize("Your App Id", "Your .NET Key");
	string filePath = @"Filesimage.jpg";
	string fileName = Path.GetFileName(filePath);
	byte[] buffer;
	
        buffer = readFileToMemory(filePath);
	uploadFileToParse(buffer, fileName);
	Console.Read();
}

 

GitHub: get repo here

Google API + AngularJS: The first step – Authenticate and display data!

· Tech · , ,

In one of my previous posts I created a tiny ToDo-app with AngularJS and Parse. In this post I’ll be using the same concept however this time I’ll be using AngularJS with the Google Task API. In this particular example I’ll be demonstrating how easy it is to authenticate and display your tasks. The prerequisite for this example is that you already have a GMail account. This example is divided in two parts,

1) Set up the Google Task API for your application

2) Wire up the Google Task API with your ToDo-app.

 

Part 1: Set up Google Task API for your application

1. Go to Google Developers Console – this is where you’ll administrate, among other, Google API access and credentials

https://console.developers.google.com/project

2. Create a new Project.
3. Go to the newly Project and enable Google Task API.
4. Before we can start accessing the API, we need to first generate an ID. Go to Credentials:

a) Create Client ID
Under AUTHORIZED JAVASCRIPT ORIGINS put the URL of the webserver you’re working with;

– ex if you’re developing locally: http://localhost:5050

Under AUTHORIZED REDIRECT URI, put the URL for the callback;

ex: http://localhost:5050/callback.html

6. Once the credentials are ready, the next step is to form the URL you’ll be call to Google. This URL contains information such as what data your application is requesting from Google, what the redirect URL is, and what is your client id. An example of the URL might look something like this:

https://accounts.google.com/o/oauth2/auth?

scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Ftasks+

https%3A%2F%2Fwww.googleapis.com%2Fauth%2Ftasks.readonly+profile&

redirect_uri=http://localhost:57657/Index.html&

response_type=token&

client_id=< YOUR CLIENT ID HERE – see step 4.a >

 

7. Your application is now ready to access the API. Go to the URL you just formed – you should see something like this:

google task auth

You can administrate your 3rd party application list here: https://security.google.com/settings/security/permissions

 

Now, let’s wire it up with AngularJS!

 

Part 2: Wire up the Google Task API with your ToDo-app

1. For this ToDo-app we’ll be using the same architecture as in my previous post.

2. Let’s first define app.js:

'use strict';

// Declare app level module which depends on filters, and services
var todoApp = angular.module('todoApp', []);

//URLs
todoApp.constant("GOOGLE_VALIDATE_TOKEN_URL", "https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=");
todoApp.constant("GOOGLE_TASK_API_URL", "https://www.googleapis.com/tasks/v1/lists/%40default/tasks?access_token=");
todoApp.constant('GOOGLE_AUTH_URL', 'https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Ftasks+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Ftasks.readonly+profile&amp;redirect_uri=http://localhost:57657/Index.html&amp;response_type=token&amp;client_id=759474991499-j0tip3nsv9q0ee6tvv02jber6afsrqrk.apps.googleusercontent.com');

2. Once we have the core building block of the app ready, let’s start of with the Service. The Service has two core features:

1. For every page load the Service validates the token (if there are any) and also checks if you’re coming from a callback URL from Google – the token will then be displayed in the URL as a access_token parameter.

2. A getTasks method that calls the Google Task API and recieves the tasks.

todoApp.service("IgService", function ($http, $q, $location, GOOGLE_VALIDATE_TOKEN_URL, GOOGLE_TASK_API_URL) {

var d = $q.defer();
var token = localStorage.token;
var URL = $location.path();
var validated = false;

//Check for callback URL
if(URL.indexOf("access_token") != -1){
localStorage.token = URL.substring(URL.indexOf("=") + 1, URL.indexOf("&amp;"));
token = localStorage.token;
}

//Validate and parse token
$http.get(GOOGLE_VALIDATE_TOKEN_URL + token)
.success(function (result) {
validated = true;
}).error(function (error) {
validated = false;
});

//Get Google Tasks
this.getTasks = function () {
if (validated) {
$http.get(GOOGLE_TASK_API_URL + token)
.success(function (result) {
d.resolve(result);
}).error(function (error) {
console.log(error);
});
return d.promise;
}
}
});

This is how the token is generated and received from Google:

tokenflow

3. The next step is to put the Controller together; call the Service to retrieve the Google Tasks and then expose the data and Google Authentication URL to the view.

todoApp.controller("IgCtrl", function ($scope, IgService, GOOGLE_AUTH_URL) {
//Get tasks
$scope.tasks = function () {
IgService.getTasks().then(function (result) {
$scope.models = result.items;
});
};

//Auth URL
$scope.GoogleAuth = GOOGLE_AUTH_URL;
});

 

4. The last step is to then put the data to the view in the HTML.

&lt;!doctype html&gt;
&lt;html lang="en" ng-app="todoApp"&gt;
&lt;head&gt;
&lt;meta charset="utf-8"&gt;
&lt;title&gt;ToDo&lt;/title&gt;
&lt;link rel="stylesheet" href="css/bootstrap.min.css" /&gt;
&lt;link rel="stylesheet" href="css/app.css" /&gt;
&lt;/head&gt;

&lt;body ng-controller="IgCtrl"&gt;

&lt;div class="container" align="center" style="width:500px"&gt;
&lt;div class="row"&gt;
&lt;div class="col-md-6"&gt;
&lt;a href="{{GoogleAuth}}"&gt;
&lt;h4&gt;Google Auth&lt;/h4&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;div class="col-md-6"&gt;
&lt;a href="" ng-click="tasks()"&gt;
&lt;h4&gt;Get Google Tasks&lt;/h4&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/br&gt;&lt;/br&gt;

&lt;table class="table table-striped"&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Title&lt;/th&gt;
&lt;th&gt;Done&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr ng-repeat="model in models | orderBy: 'updated'"&gt;
&lt;td&gt;{{model.title}}&lt;/td&gt;
&lt;td&gt;
&lt;input type="checkbox" ng-model="model.status" ng-checked="model.status == 'completed'"/&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/div&gt;

&lt;!--SCRIPTS--&gt;
&lt;script src="lib/jquery.min.js"&gt;&lt;/script&gt;
&lt;script src="lib/bootstrap.min.js"&gt;&lt;/script&gt;
&lt;script src="lib/angular/angular.min.js"&gt;&lt;/script&gt;
&lt;script src="js/app.js"&gt;&lt;/script&gt;
&lt;script src="js/controllers/IgCtrl.js"&gt;&lt;/script&gt;
&lt;script src="js/services/IgService.js"&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

And that’s all! Your view should look something like this:

todo google API

GitHub: get the repo here!

Bower – finally a “NuGet” for the web

· Tech · , ,

I’ve always been a huge fan of NuGet and the great features it offers. It is an elegant way to keep your libraries and dependencies in sync and up to date. But have you ever wondered if there’s a similar tool for the web? The answer is yes; it’s called Bower! Bower is a web package manager you can download from Node Package Manager (NPM). It is important to highlight that NPM is a package manager for Node whilst Bower is a package manager for the web. The beauty of Bower is that you have one central place for all your dependencies and libraries in contrary to the traditional way where you have to manually download and link your scripts into your HTML.

In this example I’ll take an existing project without Bower and show how the project will look like after we use Bower. Before we start, make sure you have Node installed.

The file structure for the existing project is:

 

1. Open Node Package Manager console and enter following command. The -g parameter tells NPM to install Bower on a global scope which means you can access Bower wherever you may be inside the command line. I personally install all my packages globally!

npm install -g bower

2. Once Bower is installed you’ll need to initialize Bower in your project. This means setting up JSON-file with settings such as where your packages will be installed and which dependencies you have installed. In this case we’ll install Angular and Bootstrap.

bower install bootstrap --save
bower install angular --save

Note that in order to include all your dependencies in your config file, you need to add the –save parameter. The great thing about the config file is that if you manage to mess up your dependencies file structure, you can easily erase all files and folders and start over again by typing:

bower install

3. The new file structure and reference for the project looks now something like this:

File structure:

 

Index.html

&lt;!doctype html&gt;
&lt;html lang="en" ng-app="igApp"&gt;
&lt;head&gt;
&lt;meta charset="utf-8"&gt;
&lt;title&gt;ToDo&lt;/title&gt;

&lt;!--OLD REFERENCE --&gt;
//&lt;link rel="stylesheet" href="css/bootstrap.min.css" /&gt;

&lt;!--NEW REFERENCE --&gt;
&lt;link rel="stylesheet"href="app/bower_components/bootstrap/dist/css/bootstrap.min.css" /&gt;
&lt;/head&gt;

&lt;body ng-controller="IgCtrl"&gt;

&lt;!--OLD REFERENCE--&gt;
//&lt;script src="lib/angular/angular.min.js"&gt;&lt;/script&gt;

&lt;!--NEW REFERENCE--&gt;
&lt;script src="app/bower_components/angular/angular.min.js"&gt;&lt;/script&gt;
&lt;script src="js/app.js"&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

Creating your first REST API service using Parse

· Tech · , , , ,

Parse is a great cloud service with lots of features, one them being Parse Cloud Code. Let’s say you have some business logic that you don’t want expose to the public – that’s where Parse Cloud Code comes in. It is basically a dead simple way to create your own API back-end service using nothing but JavaScript. In this example I’ll be using AngularJS to test the API service. Before we start make sure to create a Parse account, at least created one app and to have the latest Parse Console app.

 

1. Open ParseConsole.cmd and enter following command. This command line creates a folder with three subfolders (cloud, config, public). During the creation, you’ll be prompted to enter email, password and to choose app :

parse new FirstCloudCode

2. Go to the cloud folder and open main.js. Here you’ll find an already defined API service called hello. Erease all of the text and type the following code:

Parse.Cloud.define("randomNum", function(request, response) {
var min = parseInt(request.params.min);
var max = parseInt(request.params.max);

var number = Math.floor(Math.random() * (max - min + 1) + min);

response.success(number);
});

This API service receives two parameters (min and max) – generates a random number between min and max number.


3. Once you’ve defined your first Parse Cloude Code, you’ll need to upload/deploy it to your Parse app using the ParseConsole.cmd. Make sure that you’re inside the root folder (see step 1). Enter the following code:

parse deploy

4. Your first REST API service is now ready. Let’s try it out using AngularJS. Before we start with the code, make sure to collect your Parse Application ID and Parse REST ID from your Parse App.

We have created following files with following code:

ParseService.js

&lt;/pre&gt;
&lt;pre&gt;parseApp.service("ParseService", function ($http, $q) {
//Values
var ParseURL = "https://api.parse.com/1/functions/randomNum";
var appID = "&lt;INSERT APP ID&gt;";
var restID = "&lt;INSERT REST ID&gt;";
var defer = $q.defer();

//Set up header values
$http.defaults.headers.common['X-Parse-Application-Id'] = appID;
$http.defaults.headers.common['X-Parse-REST-API-Key'] = restID;
$http.defaults.headers.common['Content-Type'] = "application/json";

//Call Parse Cloud Code
this.genRandomNum = function () {
$http.post(ParseURL,
{
"min": "1",
"max": "150"
}
).success(function (result) {
defer.resolve(result);

}).error(function (error) {
defer.reject(error);
});
return defer.promise;
}
});&lt;/pre&gt;
&lt;pre&gt;

ParseCtrl.js

&lt;/pre&gt;
&lt;pre&gt;parseApp.controller("ParseCtrl", function ($scope, ParseService) {
ParseService.genRandomNum().then(function(results){
$scope.number = results.result;
});
});&lt;/pre&gt;
&lt;pre&gt;

Index.html

&lt;/pre&gt;
&lt;pre&gt;&lt;!doctype html&gt;
&lt;html lang="en" ng-app="parseApp"&gt;
&lt;head&gt;
&lt;meta charset="utf-8"&gt;
&lt;title&gt;ToDo&lt;/title&gt;
&lt;/head&gt;

&lt;body ng-controller="ParseCtrl"&gt;
&lt;h1&gt;RANDOM NUMBER = {{number}}&lt;/h1&gt;

&lt;!--SCRIPTS--&gt;
&lt;script src="lib/angular/angular.min.js"&gt;&lt;/script&gt;
&lt;script src="js/app.js"&gt;&lt;/script&gt;
&lt;script src="js/controllers/ParseCtrl.js"&gt;&lt;/script&gt;
&lt;script src="js/services/ParseService.js"&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;&lt;/pre&gt;
&lt;pre&gt;

A tiny ToDo-app built with AngularJS and Parse

· Tech · , , , ,

Are you new to AngularJS and the cloud service Parse? I’ve put together a small example demonstrating the beautiful simplicity yet powerful parts of AngularJS and Parse.

Here’s how my ToDo app is built up (click on the image below):

Arkitektur

 

Get the code here: https://github.com/mesic/ToDo-app_AngularJS-ParseJS_SDK

As a next step, maybe need to host your AngularJS project somewhere? Check this post out:)