ionShopping

ionShopping is a intuitive, clean and professional hybrid app, perfect for e-commerce, online shopping, etc. It is a completely functional template/starter for ionic developers to create a multi-platform shopping app with shopping cart, custom powerful push notifications, and a custom Admin panel to manage the orders, the list of products, the images, etc.

What am I getting?

When you download ionShopping you’ll obtain the source code of the ionic app and the angular dashboard admin panel, plus an awesome documentation that will walk you through the setup process, step by step, the firebase setup, the setup of the environment, etc. The process should be smooth, but if you encounter any issue with the setup of the project, it will be my pleasure to assist you via email, my email is on the documentation.

Features:

ionic app:
– Login (with email/pass and social login with facebook and google plus)
– Recover password
– Sign up
– Tabs system to provide a more clean experience to the user
– Product list (manageable from the admin panel)
– Items details section
– Awesome order system/Shopping cart + checkout with paypal integrated
– Call number native and send SMS from the landing page to contact the store
– Push notifications (with custom dashboard) for promotions with promo landing page
– Editable profile

Admin dashboard:
– Manage all the items, details, images, prices, etc from the amazing custom admin panel included
– Tracking Order (shopping cart), from the admin panel you’ll see and manage the status of the order (purchased, processing, delivered).
– Powerful and custom Push Notification system to send notifications to user with rich text and images, to inform or promote offers discounts, etc. You can run a promotion from an start date to an end date, you can also create and save notification to be sent in the future
– Technologies used on the dashboard: Angular 4, Cloud firestore

Ionic App screenshots










Admin dashboard demo

The admin dashboard source code is included with the ionic code

Try before you invest

Note:
The notification and the social login will only work on an emulator or a cellphone

Get it from here:
https://market.ionicframework.com/starters/ionshopping/

ionRestaurant

ionRestaurant is a intuitive, clean and professional hybrid app, perfect for Restaurant, Bar, Bakery, etc. It is a completely functional template/starter for ionic developers to create a multi-platform restaurant app with food ordering system (shopping cart), custom powerful push notifications, and a custom Admin panel to manage the orders, the menu, the images, etc.

What am I getting?

When you download ionRestaurant you’ll obtain the source code of the ionic app and the angular dashboard admin panel, plus an awesome documentation that will walk you through the all setup process, step by step, the firebase setup and the setup of the environment, etc. The process should be smooth, but if you encounter any issue with the setup of the project, it will be my pleasure to assist you, my email is on the documentation.

Features:

ionic app:
– Login (with email/pass and social login with facebook and google plus)
– Recover password
– Sign up
– Tabs system to provide a more clean experience to the user
– Restaurant Menu (manageable from the admin panel)
– Items details section
– Awesome order system/Shopping cart + checkout with paypal integrated
– About us + contact section (With maps, gps, call number native)
– Push notifications for promotions with promo landing page
– Profile editable

Admin dashboard:
– Manage all the menu, images, plates, prices, etc from the amazing custom admin panel included
– Tracking Order (shopping cart), from the admin panel you’ll see and manage the status of the order (purchased, processing, delivered).
– Powerful and custom Push Notification system to send notifications to user with rich text and images, to inform or promote offers discounts, etc. You can run a promotion from an start date to an end date, you can also create and save notification to be sent in the future
– Technologies used on the dashboard: Angular 4, Cloud firestore

Ionic App screenshots

Admin panel screenshots

Try before you invest

Note:
The notification and the social login will only work on an emulator or a cellphone

Get it from here:
https://market.ionicframework.com/starters/ionrestaurant

ionPushemPro

You can use this starter to create your application on top of it and send and receive notifications with your own admin dashboard backend.
If you are a freelance developer, you can offer the dashboard backend to your clients as a plus, when you develop applications like e-commerce, for restaurants, anything where you need to communicate to the users about new features, products, promotions, etc.

The admin backend source code is included with this starter

With this starter you will be able to:

  • Send notifications to individual users
  • Create user groups and send notifications to group of users
  • Create channels/topics for the ionic user to opt-in/out and receive notifications via channesl
  • There is an option for the ionic user to create local notification (this is a generic functionality you should adapt it to your own needs)
  • Firebase and social login (google and facebook) with the ability to update the user’s profile

Watch the following video for more info:

Live ionic demo

Note:
The notification and the social login will only work on an emulator or a cellphone

Get it from here:
https://market.ionicframework.com/starters/ionpushempro

Ionic CRUD Application with Cloud Firestore

ionic crud
In this tutorial we are going to create the most simplest ionic CRUD(Create, Read, Update and Delete) using Cloud firestore.

At the end of this tutorial you’ll be able to:
-Setup a firebase account.
-Configure firestore database permissions.
-Create an ionic app using ionic cli (command line tool).
-Create, Read, Update and Delete to a firestore database from an ionic app.

What is cloud firestore?

Lets set up a firebase account.

Go to https://console.firebase.google.com and login with your google account or create one.

Enter the name of the project and click on Add Firebase to your web app.

We are going to use this data later, this will allow us to connect to firebase.

Next step is to configure Cloud Firestore, follow the following steps in the image, and start in test mode for now, to keep it simple.

For more rules you can visit here: https://cloud.google.com/firestore/docs/security/rules-query

Before we get into the ionic part, lets see how a firestore database structure looks like:

This example was taken from the ionAppFull4Pro ionic starter.
In this example you can see that the firestore data model is based on collections and documents, and you can nest collection within documents:

for more details you can visit here https://firebase.google.com/docs/firestore/data-model.

Lets create the ionic CRUD project.

First, install Node.js. Then, install the latest Cordova and Ionic command-line tools in your terminal. Follow the Android and iOS platform guides to install required tools for development. For more info go here: https://ionicframework.com/getting-started.

npm install -g cordova ionic

Now lets create the ionic app

ionic start crud blank

When the cli finish to create the files, do:

 > cd crud
 > ionic serve

To go to the new folder created, then run “ionic serve” to make sure that everything when correctly. This is how it should looks like:

Now, open the source code on your favorite editor, I prefer VS code. The source code should look like this:

Run the following command to install firebase dependency:

npm install firebase --save

We need to configure firebase on our app, for this we are going to need the config variable from previous step.

  var config = {
    apiKey: "<your key>",
    authDomain: "<your key>",
    databaseURL: "<your key>",
    projectId: "<your key>",
    storageBucket: "<your key>",
    messagingSenderId: "<your key>"
  };
firebase.initializeApp(config);

Insert the config variable on the app.module.ts for that lest add the firebase dependency.

...
import * as firebase from 'firebase';

const config = {
  apiKey: "<your key>",
  authDomain: "<your key>",
  databaseURL: "<your key>",
  projectId: "<your key>",
  storageBucket: "<your key>",
  messagingSenderId: "<your key>"
};
firebase.initializeApp(config);

...

Go to the home.html and insert this code.

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Crud example
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
<ion-list>
    <ion-item>
        <ion-label floating>Message title :</ion-label>
        <ion-input type="text" value="" [(ngModel)]="model.title"></ion-input>
      </ion-item>            
      <ion-item>
        <ion-label floating>Message body :</ion-label>
        <ion-textarea   type="text" row="10" [(ngModel)]="model.text"></ion-textarea>
      </ion-item>
      <ion-item>
          <button type="button" (click)="addMessage()" ion-button full >Submit</button>
      </ion-item>
</ion-list>

  <ion-card>
    <ion-card-header>
      Swipe item to the left to delete or edit
    </ion-card-header>
  </ion-card>
  <ion-list>
    <ion-item-sliding *ngFor="let message of messages">
      <ion-item>
        <h3>title: {{message.title}}</h3>
        <p>body: {{message.text}}</p>
      </ion-item>
      <ion-item-options>
        <button ion-button color="danger" (click)="deleteMessage(message.$key)">
        <ion-icon name="ios-trash"></ion-icon>
        delete
      </button>
      <button ion-button color="success" (click)="updateMessage(message)">
          <ion-icon name="ios-create"></ion-icon>
          edit
        </button>
      </ion-item-options>
    </ion-item-sliding>
  </ion-list>

</ion-content>

We are using an *ngFor to generate all the items on the list, we are creating sliding items so we can set a button to delete the item.

We need to add the methods for the ionic CRUD operation (got it from the ionAppFull4Pro project).

  getAllDocuments(collection: string): Promise<any> {
    return new Promise((resolve, reject) => {
        this.db.collection(collection)
            .get()
            .then((querySnapshot) => {
                let arr = [];
                querySnapshot.forEach(function (doc) {
                    var obj = JSON.parse(JSON.stringify(doc.data()));
                    obj.$key = doc.id
                    console.log(obj)
                    arr.push(obj);
                });

                if (arr.length > 0) {
                    console.log("Document data:", arr);
                    resolve(arr);
                } else {
                    console.log("No such document!");
                    resolve(null);
                }


            })
            .catch((error: any) => {
                reject(error);
            });
    });
}

deleteDocument(collectionName: string, docID: string): Promise<any> {
  return new Promise((resolve, reject) => {
      this.db
          .collection(collectionName)
          .doc(docID)
          .delete()
          .then((obj: any) => {
              resolve(obj);
          })
          .catch((error: any) => {
              reject(error);
          });
  });
}

addDocument(collectionName: string, dataObj: any): Promise<any> {
  return new Promise((resolve, reject) => {
      this.db.collection(collectionName).add(dataObj)
          .then((obj: any) => {
              resolve(obj);
          })
          .catch((error: any) => {
              reject(error);
          });
  });
}

updateDocument(collectionName: string, docID: string, dataObj: any): Promise<any> {
  return new Promise((resolve, reject) => {
      this.db
          .collection(collectionName)
          .doc(docID)
          .update(dataObj)
          .then((obj: any) => {
              resolve(obj);
          })
          .catch((error: any) => {
              reject(error);
          });
  });
}

Add the methods used by the view to add, edit,list and delete items:

  loadData(){
    this.getAllDocuments("messages").then((e)=>{
      this.messages = e;
  });
  }

addMessage(){
    if(!this.isEditing){
    this.addDocument("messages", this.model).then(()=>{
      this.loadData();//refresh view
    });
  }else{
    this.updateDocument("messages", this.model.$key, this.model).then(()=>{
      this.loadData();//refresh view
    });
  }
  this.isEditing = false;
  //clear form
  this.model.title = '';
  this.model.text = '';
}

updateMessage(obj){
  this.model = obj;
  this.isEditing = true;
}

deleteMessage(key){
  this.deleteDocument("messages", key).then(()=>{
    this.loadData();//refresh view
    this.isEditing = false;
  });
}

Now you can run:

ionic serve

The result should be something like this:

You can download the full source code from here:
https://github.com/jomendez/ionic-firestore-crud-example

Happy coding!!

Ionic 2 google signin Error 10 with firebase

The mysterious Error 10

I hope this article helps to clarify and find a solution quickly to the Error 10 using ionic 2 framewrok with firebase sign in and cordova-plugin-googleplus. I was developing an Ionic 2 application “quiz dev” to create a playful platform for developers to practice and improve their skill through quizzes, based on the spaced repetition approach. I wanted to provide the user the ability to sing in into the application using their google account.

error 10

The issue

The point is, that I’ve spend 2 or 3 days trying to figure out the error 10 I was receiving once I deployed to the Android Play Store. I followed the official documentation of Ionic https://ionicframework.com/docs/native/google-plus/

I installed the cordova-plugin-googleplus and implemented the plugin (I going to skip high level details, for more information refer to the documentation provided here)
 

  this.googlePlus.login({
        'webClientId':'#############-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
        'offline': true
      })
          .then(res => {
             //logged in
              ...
          })
          .catch(err => {
              alert("There is an error " + JSON.stringify(err));
          });

 

After that, I signed my debug.apk following the steps here, this is the google official documentation, then I get the SHA-1 fingerprint certificate that is going to be needed to setup the firebase project, you can do it via cmd following these steps. The result is going to be something like this:
sha-1 fingerprint certificate

I had set up a Firebase project, following the steps here https://chriztalk.com/ionic-2-firebase-google-authentication/

The headache

At this point installing the application in my device in release or debug mode, everything was working properly. Then I decided to deploy it to the google android app store. When installing the app from the android app store I wasn’t unable to login with my google accounts, the previous code to handle the google sign in was entering in the catch section and showing an alert with error 10
 

 
          .catch(err => {
              alert("There is an error " + JSON.stringify(err));
          });

The solution

After spending hours and hours trying to figure out what the issue was, I realize that there is an option when you are setting up your application in the google app store that ask you if you want to sign your apk in the store. After you say yes it shows you a message like this:
google app store apk sign
 

the real solution is to go to Release Management/App signing section and get the SHA-1 fingerprint certificate and include it in your Firebase project
 
app signing google android app store

Go to your Firebase project configuration and add you SHA-1 fingerprint and it will do it
 
firebase add sha-1 fingerprint

Final thought

I really hoe this save you a lot of time of banging your head against the wall.

Here is a demo of the app, you can from android to ios here. The is the application in the android app store in case you are interested https://play.google.com/store/apps/details?id=com.evolutionsys.quiz&hl=en

ionAppFull4Pro Privacy Policy

Privacy Policy

Last updated: (1/29/2018)

Evolution Sys (“us”, “we”, or “our”) operates ionAppFull4Pro (the “Ionic starter and Admin dashboard”). This page informs you of our policies regarding the collection, use and disclosure of Personal Information we receive from users of the Software.

We use your Personal Information only for providing and improving the Software. By using the Software, you agree to the collection and use of information in accordance with this policy.

Information Collection And Use

While using our Software, we may ask you to provide us with certain personally identifiable information that can be used to contact or identify you. Personally identifiable information may include, but is not limited to your name (“Personal Information”).

Log Data

Like many Software operators, we collect information that your browser sends whenever you visit our Software (“Log Data”).

This Log Data may include information such as the pages/sections of our Software that you visit, the time and date of your visit, the time spent on those pages and other statistics.

In addition, we may use third party services such as Google Analytics that collect, monitor and analyze this type of information in order to increase our Service’s functionality

Communications

We may use your Personal Information to contact you with newsletters, marketing or promotional materials and other information…

Security

The security of your Personal Information is important to us, but remember that no method of transmission over the Internet, or method of electronic storage, is 100% secure. While we strive to use commercially acceptable means to protect your Personal Information, we cannot guarantee its absolute security.

Changes To This Privacy Policy

This Privacy Policy is effective as of (8/14/2017) and will remain in effect except with respect to any changes in its provisions in the future, which will be in effect immediately after being posted on this page.

We reserve the right to update or change our Privacy Policy at any time and you should check this Privacy Policy periodically. Your continued use of the Service after we post any modifications to the Privacy Policy on this page will constitute your acknowledgment of the modifications and your consent to abide and be bound by the modified Privacy Policy.

If we make any material changes to this Privacy Policy, we will notify you either through the email address you have provided us, or by placing a prominent notice on our website.

Contact Us

If you have any questions about this Privacy Policy, please contact us.

Quiz dev privacy policy

Privacy Policy

Last updated: (8/14/2017)

Evolution Sys (“us”, “we”, or “our”) operates quiz dev (the “Mobile App”). This page informs you of our policies regarding the collection, use and disclosure of Personal Information we receive from users of the App.

We use your Personal Information only for providing and improving the App. By using the App, you agree to the collection and use of information in accordance with this policy.

Information Collection And Use

While using our App, we may ask you to provide us with certain personally identifiable information that can be used to contact or identify you. Personally identifiable information may include, but is not limited to your name (“Personal Information”).

Log Data

Like many app operators, we collect information that your browser sends whenever you visit our app (“Log Data”).

This Log Data may include information such as the pages/sections of our App that you visit, the time and date of your visit, the time spent on those pages and other statistics.

In addition, we may use third party services such as Google Analytics that collect, monitor and analyze this …

Communications

We may use your Personal Information to contact you with newsletters, marketing or promotional materials and other information…

Security

The security of your Personal Information is important to us, but remember that no method of transmission over the Internet, or method of electronic storage, is 100% secure. While we strive to use commercially acceptable means to protect your Personal Information, we cannot guarantee its absolute security.

Changes To This Privacy Policy

This Privacy Policy is effective as of (8/14/2017) and will remain in effect except with respect to any changes in its provisions in the future, which will be in effect immediately after being posted on this page.

We reserve the right to update or change our Privacy Policy at any time and you should check this Privacy Policy periodically. Your continued use of the Service after we post any modifications to the Privacy Policy on this page will constitute your acknowledgment of the modifications and your consent to abide and be bound by the modified Privacy Policy.

If we make any material changes to this Privacy Policy, we will notify you either through the email address you have provided us, or by placing a prominent notice on our website.

Contact Us

If you have any questions about this Privacy Policy, please contact us.

Quick Introduction to VueJS

vuejs

What is Vuejs?

What makes VueJs special is the fact that was designed to be incrementally adoptable, the core is dedicated to the view layer only but you can combine it with other libraries in order to create great single pages apps. Is very versatile and flexible yet lightweight, there is also components that allows you to handle routes and AJAX requests, hence is able to provide high quality results from a little gadget to a more complex SPA.

Why chose Vue.js?

  • The documentation is so good that it is the only tutorial you will need to understand and be able to dominate Vue.js efficiently.
  • The Vue.js community is growing.
  • Solutions through libraries and plugins well supported.
  • The way Vue.js do the things allows you to produce great code, efficient as well as readable.

Comparison with other frameworks

Vue.js vs React

Similarities:

  • Uses a Virtual DOM
  • Reactive and composable view components
  • Focused on the core library, so global state management and routing are delegated to third libraries

Differences:

  • Vue.js offers better performance than React, As you can see here.
  • In React all the UI components are represented rendering functions using JSX. In the other hand Vue.js provides render functions, provides support for JSX and also as default offers declarative templates (very readable by the way).
  • The ecosystem around custom renders makes React a winner in this aspect.
  • In matters of CLI Vuejs got leverage because of the limitations of React in this area, related with the lack of configurations.
  • Before to start working with React you should be familiar with JSX and ECMAScript 6, because most of the examples out there uses It, in the other hand Vuejs is more simple, to get it running you just need a single script on your page.

Vue.js vs Angular 1
Similarities:

  • Vue.js in an early stage of development inspire in the Angular syntax (e.g. v-if vs ng-if).

Differences:

  • Vue.js is way much simpler than Angular 1. A newbie is able to write functional code in a day with Vue.js, with angular, the learning curve is more higher.
  • Angular 1 ‘forces’ you to build the app under a specific and non-so flexible structure. Vue.js in the other hand is more flexible and modular.
  • Vue.js enforces a one-way data flow between components while Angular 1 uses two-way binding between scopes.
  • Vue.js offers better performance than Angular 1 because Angular one uses dirty checking with a cycle digests this can affect the performance.

Vue.js vs Angular 2:

Similarities:

  • Performance is equal because both are very fast.
  • Both are well suited for Enterprise environments.

Differences:

  • Vue.js is more flexible than Angular 2 in terms of the app architecture. Angular has a well defined architecture, Vue.js is more simple.
  • In terms of learning curve, Vue.js is extremely low while Angular 2 is too steeper.

To see more comparison of VueJs and other frameworks, you can go here:
https://vuejs.org/v2/guide/comparison.html

Simple app example with Vue.js.

Let’s create an simple object in javascript

 
var example = {
message: ‘Hi Vue’
}

This is going to be the template

 
<div id="container">
{{message}}
</div>

Vue in action, binding the template with the object:

 
new Vue({
el: '#container',
data: example
})

Here is a working example

 
Let’s see an example making use of a Vue.js directive: v-for:

This is the html template:

 
<html>
 <head>
<script src="./vue/dist/vue.js"></script>
 </head>
<body>
 <div id="app-example">
 <p v-for="human in people">                        
 {{ human.name }}
 </p>
 </div>
</body>
<script src="./app/myapp.js"></script>
</html>

Binding the template with the data

 
var app = new Vue({
  el: '#app-example',
  data: {
    people: [
     {name: 'albert'}, 
     {name: 'john'}, 
     {name: 'justin'}
     ]
  }
});

Here is a working example:
 

More examples can be found here: https://vuejs.org/v2/guide/, the introduction guide to Vue.js is one of the best tutorials you’ll find.

Let’s see another example, this time we are going to create a custom filter to reverse the text:
 

Here is an example where I use more concepts like, filters, methods, computed, the code is commented but if you don’t understand the concepts and how it works you can visit the Vue official documentation, or see this video from Egghead:
https://egghead.io/courses/develop-web-apps-with-vue-js

Introduction to Reactive programming RxJs

 
Reactive programming is a general concept that you can find in any language, it is often associated with event driven UI, asynchronous programming with observable, where you can subscribe to events. Reactive Extensions (abbreviated Rx*) provides libraries for a wide variety of programming languages, including JavaScript (RxJS). RxJS it precisely that, an extension/library for JavaScript.
 
Reactive programming RxJs

  • What is Reactive programming RxJS?
  • But wait, what is an observable?
  • Anything can be a stream
  • Where can I use RxJs?
  • Try yourself
  • RxJS Observables vs Promises
  • RxJS integration with AngularJS.
  • Differences between RxJs and Knockout
  • Conclutions

What is Reactive programming RxJS?

Reactive programming RxJS or Reactive Extensions for JavaScript is a reactive streams library that can be used in the client-side in the browser or server-side with Node.js. to work with asynchronous data streams. From the perspective of JavaScript let’s analyze the last three words of the previous sentence: asynchronous – data – streams.
Asynchronous – Is the fact of calling a function and then register a callback when results are available, this way we are notified about the returning of that function and been able to continue with execution avoiding non responsive behavior in our page.
Data – Raw information represented by any data type: Number, String, Objects.
Stream – Data made available over time meaning that you don’t need the presence of all the information to start using it for example mouse clicks, user inputs, database queries or just the call to an API.

But wait, what is an observable?

Observable is a JavaScript implementation of the observer pattern (also known as ‘publish/subscribe’).
The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
It is mainly used to implement distributed event handling systems.

Anything can be a stream.

Taken from this great article of Gerard Sans.
Asynchronous data streams are a pretty old concept, it exists since Unix and take different names and behavior depending on the environment for example in Node.js they are called ‘streams’, ‘pipes’ on Unix and ‘async pipes’ on Angular 2.
reactive programming: programming is called reactive when you are working with Asynchronous data streams.
Using RxJS asynchronous data streams can be represented through Observables and manipulate those streams with different operators as if they were simple collections of data. Next section has some examples.

Where can I use RxJs?

Creating and subscribing to simple Observable sequences

First include rx.js file in your code, you can use a CDN https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.3/Rx.js:

<script src="rx.js"></script>

If using Node.js:

var Rx = require('rx');

Lets create a very simple example so you get the idea of how it works.
For this we are going to create a textarea (the stream acting as event generator) we are going to show to the user what we are writing in the textarea plus a fixed text (this is the reaction). This is going to looks like a data-binding between the textarea and the label.

<textarea></textarea>
  <p>
    <strong>Text:</strong>
    <code id="text"></code>
  </p>

 
const text = document.getElementById('text');
const area = document.querySelector('textarea')

const content$ = Rx.Observable
  .fromEvent(area, 'keyup') // each `keyup` throws an event on the stream
  // shows the content of the text area concatenated with the string ‘Fixed text’
  .map(e => e.target.value.trim() + ' Fixed text');

The suffix $ on the variable named ‘content’ it used to indicate that the variable is a data stream.
So, the data stream ‘content$’ will launch a new event each time the user inputs a new letter. The correct way to react to this constant stream of data is through the function “subscribe()” like this:

 
content$
  .subscribe(text => {
    console.log(`The textarea content is: ${text}`)
    text.innerText = text;//print the text.
  });

Now that we got the idea lets implement something more practical like a “word counter”, in order to obtain the amount of words, we need to update the stream and update the user interface to show how many words are written. To do this we need the function ‘map()’ which is one of the many operators provided by RxJS (a full list of RxJS operators can be found here):

 
content$
  .map(content => content.trim().split(' '))// make the string into an array of words
  .map(wordList => wordList.length)// count the array elements
  .subscribe(totalWords => {
     text.innerText = totalWords
  })

Each step is transformed into stream and return a modified object to the next step. Finally we are going to use the function ‘subscribe()’ where we indicate what is going to be the reaction, in this case, the reaction is to update the user interface to show the amount of counted words.

Try yourself (full code):

I recommend you to read this tutorial for better understanding of the subject:

The introduction to Reactive Programming RxJs you’ve been missing

What operator to use

 

RxJS Observables vs Promises

Promises is a concept from javascript async programming. Basically the Promises give an abstracted help to work with asynchronous matter’s inside the apps. The promise is the eventual result of an asynchronous data stream task. For better understanding read this and analyze the example code text taken from here:

“The primary way of interacting with a promise is through its then method, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled. You can create them very easily where the constructor has two functions, resolve and reject which resolves the value or rejects it for a given reason “

  • Observables are cancellable. Observable also has the advantage over Promise to be cancellable. If the result of an HTTP request to a server or some other expensive async operation isn’t needed anymore, the Subscription of an Observable allows to cancel the subscription, while a Promise will eventually call the success or failed callback even when you don’t need the notification or the result it provides anymore.
  • The main difference here is that Promises in order to be able of retry the call, the caller must have access to the original function that return the Promise. In the other hand Observables are cancellable and the API provides operators to retrieve them (‘retry’ function).
  • A Promise handles a single event when an async operation completes or fails.
    Note: There are Promise libraries out there that support cancellation, but ES6 Promise doesn’t so far.

RxJS integration with AngularJS.

You may write a custom helper function to integrate this two but as you also may expect this task is already done. A library called rx.angular.js is in charge of this interoperability. Let’s analyze an example of using DOM-events:
To be able of use DOM-events we are going to use Rx.DOM, an HTML DOM bindings for RxJS provided by rx.angular.js. The next code is a feature to detect the time of inactivity of the user.

 
mergedStreams = rx.Observable.merge(  // mergin all the events coming from the user
rx.DOM.keydown(document), // keystrokes
rx.DOM.click(document), // mouse click
rx.DOM.mousemove(document), //mouse move
rx.DOM.scroll(document), //scroll
rx.DOM.touchstart(document) // taps
);

var idleStream = mergedStreams
.bufferWithTime(5000) //operator bufferWithTimes to catch all the event in buffer
.filter(function(arr){ //to check when the sequence is empty to notice that user is gone.
return arr.length===0;
})
.subscribe();

For more examples of how to integrate AngularJs with RXJs visit here:

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/howdoi/angular.md

Differences between RxJs and Knockout

The main main difference is:
 
Reactive programming RxJs allows composing operations against asynchronous streams , like http web requests or events, and includes advanced scenarios like combining streams for example when both event A and event B occur, execute X code, but stop it if B occur again.
 
KnockoutJs is an MVVM (not MVC) framework, with it you can manage the state of yourUI with a model that maps it’s functionality. This allows your to separate the logic from the view and the UI state.

 

Steve Sanderson, creator of Knockout, explained the difference on his blog:

I’m very familiar with Rx for JavaScript, having recently used it heavily on a big project, and in fact aspects of the design of Knockout are made with my Rx experiences in mind.

The key difference between Knockout’s implementation of the observer pattern and Rx’s is that Knockout automatically infers the associations and dependencies between observable from regular procedural code without you having to specify them up front though a special functional API. I wanted Knockout to use regular procedural/imperative-style code as it’s more familiar and approachable for most developers.

Another difference is that Rx is optimized for composing streams of events without state. At first I was enthusiastic about this and its functional purity, but after some time it felt increasingly like I was jumping through awkward hoops and had to invent extra ways to simulate state to manage UI commands efficiently. That’s why, in Knockout, all observables can be treated as stateful – for example you can always read their latest value (which is cached, by the way – it doesn’t recompute until the underlying data changes).

Rx goes further than Knockout into advanced ways of composing event streams, whereas Knockout goes further than Rx into UI development, letting you bind its observable to HTML DOM elements and templates and manipulate them any way you want. Rx is great at what it does but turned out not be be exactly how I wanted to build rich UIs – hence the design of Knockout.

Conclutions

I hope this article can be used as a starting point to dive into reactive programming for javascript RxJs, I encourage you to keep researching and learning about it since the intend of this post is to introduce the concept and make a comparison with other libraries like KnockoutJs, etc.

ASP.NET Core 1.0

In this opportunity I will be writing about one of the most used (and newest) and functional server-side web application framework: ASP.NET Core. Before entering into the ecosystem of this tool allow me to give you some feedback that may be needed in order to have a better understanding of topics related with versions, features and releases (this one is quite new).

Asp.net core

What is ASP.NET Core 1.0?

ASP.NET Core 1.0 is, in short terms, the evolution of ASP.NET 4.6. If you are thinking that it is just a superior version of ASP.NET 4.6 take away that myth of your head because ASP.NET Core 1.0 is an entire new based-cloud applications framework written from scratch, with a new focus different from its predecessor.
Two of the most appreciated characteristics of this new framework are:
First it is open source (supported by Microsoft) meaning that you can find and download the code on GitHub , also contribute to the development of it, and second, it is cross-platform, so you can run it either in Windows, Linux or Mac OS.

Advantages and Disadvantages. Looking back to ASP.NET 5.

Good:

– Open source: as I mentioned before, this is a huge advantage and everybody loves it.
– Cross-platform: this is an obvious point, run it everywhere!.
– Modular design: the main stuff here is NuGet packages. Developers can use NuGet Package Manager to install libraries to extend the features of apps so now is easier to maintain the code due to the benefits of package-based software.
– MVC and WEB.API are together in one: Back in ASP.NET, MVC and WEB.API were based on different versions of the framework and because of this some differences related to namespace and classes were present and tend to confuse sometimes. Now arrives MVC 6, a unique collection of objects with a unique namespace (Microsoft.AspNet.Mvc), this standard simplifies the development process.
– Dependency injection: Before this was available as an ad-on but now it is built-in the framework, but still third party’s solutions like Autofac should be functional.
– Productivity: The keyword here is Kestrel, a lightweight web server incorporated by Microsoft as an alternative to developer’s who does not want to use heavy options to host development. With Kestrel you can run the site in OSX.
– Easier integration with client-side frameworks like AngularJS, KnockoutJS and Bootstrap.

Bad:

– Issues with documentation in certain way: When in May of 2016 the RC2 of ASP.NET Core 1.0 was released the documentation was ‘incompleted’ because a lot of topics were without text. Today this situation was patched but sometimes you can find some cases, take in count that ASP.NET Core 1.1 is out too. God bless StackOverflow! 😉
– Sometimes when you are searching for information maybe a little bit hard, because this framework had many names in the past, first vNext, next ASP.NET 5 and today ASP.NET Core, this is not helpful.
– Compatibles solutions between versions not always is the best. You can find a solution to a specific trouble but it may not work because maybe it was written to a previous version. Thanks to GitHub and open source this can be fixed eventually because there is always an alternative.

What about ASP.NET Core 1.1?

The .NET Core 1.0 was updated with some changes, you can see them all here in the release notes.

Some of them are:
– Improved middleware in all sense through the user interface.
– Improved deployment of ASP.NET core apps on Microsoft Azure, increased the cloud support.
– Now other hosting options are available, beside IIS.

Let’s see an example of code, in this case it going to be an URL Rewriting Middle ware: (this was taken from here, check it if you want to see more examples.)

“URL Rewriting allows mapping a public URL space, designed for consumption of your clients, to whatever representation the downstream components of your middleware pipeline require as well as redirecting clients to different URLs based on a pattern.”

 
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Rewrite;
namespace MyApplication {

public class Startup {

public void Configure(IApplicationBuilder app, IHostingEnvironment env) 
{

var options = new RewriteOptions()
.AddRedirect("(.*)/$", "$1") // Redirect using a regular expression
.AddRewrite(@"app/(\d+)", "app?id=$1", skipRemainingRules: false) // Rewrite based on a Regular expression
.AddRedirectToHttps(302, 5001) // Redirect to a different port and use HTTPS
.AddIISUrlRewrite(env.ContentRootFileProvider, "UrlRewrite.xml") // Use IIS UrlRewriter rules to configure
.AddApacheModRewrite(env.ContentRootFileProvider, "Rewrite.txt"); // Use Apache mod_rewrite rules to configure
app.UseRewriter(options);
}

// More Code

}

}

From .Net Framework 4.6 to .Net Core 1.0 :

asp.net core chart

This images illustrates the main changes with its predecessor. I recommend you to read this post to understand some considerations before migrating from .NET 4.6 to .NET Core 1.0 as well as strategies and advices from the author to achieve it. In case you are not sure about what solution suits you, and need to pick, this post can give you a clear understanding.

Other resources to learn more about ASP.NET Core

Tutorials

Microsoft Virtual Academy – Introduction to ASP.NET Core

Building your first ASP.NET Core MVC application

Building Your First Web API with ASP.NET Core MVC and Visual Studio