Google+ Peter Bromberg's .NET Blog | All posts by admin

Peter Bromberg's .NET Blog All Things Programming

Using Firebase With Angular, Authentication, and MVC

26. July 2013 10:50 by admin in Angular, Firebase, Jquery
 

Firebase lets you create fully interactive apps with just frontend code. Stop thinking about servers and databases and focus on your application logic and your customers.

Apps built with Firebase respond immediately to data changes as they occur, bringing a whole new level of interactivity to your users.

Data stored in Firebase is directly accessible from the client. This means you can build dynamic, data-driven websites without worrying about servers or server code.

Firebase also supports authentication via a number of providers including Persona (BrowserID), Facebook, and Twitter.  Here is a demo “ToDo” MVC app using firebase as the back end.

First, the login page:

<!DOCTYPE html>
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta charset="utf-8">
  <title>Firebase Simple Login</title>
  <link rel="stylesheet" href="http://firebase.github.io/firebase-simple-login/css/reset.css">
  <link rel="stylesheet" href="http://firebase.github.io/firebase-simple-login/css/text.css">
  <link rel="stylesheet" href="http://firebase.github.io/firebase-simple-login/css/960.css">
  <link rel="stylesheet" href="http://firebase.github.io/firebase-simple-login/css/style.css">
  <script type="text/javascript" async="" src="js/ga.js"></script><script type="text/javascript" src="js/prettify.js"></script><style type="text/css">
                                                                                                                                                                                     </style>
</head>
<body onload="prettyPrint();">

  <div class="header">
    <div id=loggy class="ribbon"></div>
  </div>
&nbsp;<div class="container_12">

    <div class="grid_12">
      <br>
      <div class="box">
        &nbsp;</div>
    </div>

    <div class="clear"></div>
    <div class="grid_4">
      <br>
      <div class="box">
        <fieldset>
          <legend class="bold">Supported Providers</legend>
          <div class="content">
            <p>
              Click any of the links below to log in.
            </p>
            <div class="example facebook">
              <div class="icon"></div>
              <div class="description">
                <h4>Facebook</h4>
                <p><a href="javascript:login('facebook');">Log In »</a></p>
              </div>
            </div>
            <div class="example persona">
                <div class="icon">
                </div>
                <div class="description">
                    <h4>Persona</h4>
                    <p><a href="javascript:login('persona');">Log In »</a></p>
                </div>
            </div>
            <div class="example twitter">
              <div class="icon"></div>
              <div class="description">
                <h4>Twitter</h4>
                <p><a href="javascript:login('twitter');">Log In »</a></p>
              </div>
            </div>
            <div class="example password">
              <div class="description">
              </div>
            </div>
          </div>
        </fieldset>
      </div>
    </div>
    <div class="grid_8">
      <br>
      <div class="box">
        &nbsp;</div>

    </div>

    <div class="clear"></div>
    <div class="grid_12">
      <img src="js/hr.png">
    </div>

    <div id="contact">
      <div class="clear"></div>
      <div class="grid_4 prefix_4 suffix_4 center">
        <br>
      </div>

      <div class="clear"></div>
      <div class="grid_5 prefix_1 center">
      </div>
      <div class="grid_5 suffix_1 center">
      </div>
    </div>
  </div>

  <script type="text/javascript" src="js/firebase.js"></script>
  <script type="text/javascript" src="js/firebase-simple-login.js"></script>
  <script type="text/javascript" src="js/include.js"></script>
  <script type="text/javascript">
    var href = document.location.href;
    // FirebaseSimpleLogin demo instantiation
    var firebaseRef = new Firebase("https://peterbromberg.firebaseio.com");
    var auth = new FirebaseSimpleLogin(firebaseRef, function(error, user) {
      if (error) {
        // an error occurred while attempting login
        alert(error);
      } else if (user) {
        // user authenticated with Firebase, redirect to the app
        window.location.href='ToDo.html?id=' +user.id;

      // Log out so we can log in again with a different provider.
      // auth.logout();
      } else {
        // user is logged out
      }
    });
    function login(provider) {
      auth.login(provider);
    }

  </script>
<iframe style="display: none;"></iframe><iframe src="js/lp.htm" style="display: none;"></iframe></body></html>

 

I am showing the facebook, Twitter, and Persona login options. The live demo I’ll send you to at the end only has Persona enabled,

but it is a fully working app. What I do is after getting the user authenticated, I suffix the firebase endpoint with their User Id,

which is usually your email as the path. This ensures that each user has their own data store and cannot see others’.

Next is the ToDoctrl.js script, which loads in the todo.html page that we are redirected to from above:

/*global todomvc */
'use strict';

/**
* The main controller for the app. The controller:
* - retrieves and persist the model via the todoStorage service
* - exposes the model to the template and provides event handlers
*/
todomvc.controller('TodoCtrl', ['$scope', '$location', 'angularFire', 'filterFilter',
    function TodoCtrl($scope, $location, angularFire, filterFilter) {
        //  this is mine, suggest you get your own free firebase url here: https://www.firebase.com/pricing.html
        var url = "'https://peterbromberg.firebaseIO.com/todomvc" + getQueryVariable('id');
        url = url.replace(',', '');
        var promise = angularFire(url, $scope, 'todos');

        $scope.newTodo = '';
        $scope.editedTodo = null;

        if ($location.path() === '') {
            $location.path('/');
        }
        $scope.location = $location;

        promise.then(function(todos) {
            startWatch($scope, filterFilter);
        });
    }
]);

function startWatch($scope, filter) {
    $scope.$watch('todos', function () {
        $scope.remainingCount = filter($scope.todos, {completed: false}).length;
        $scope.completedCount = $scope.todos.length - $scope.remainingCount;
        $scope.allChecked = !$scope.remainingCount;
    }, true);

    $scope.$watch('location.path()', function (path) {
        $scope.statusFilter = (path === '/active') ?
            { completed: false } : (path === '/completed') ?
            { completed: true } : null;
    });

    $scope.addTodo = function () {
        if (!$scope.newTodo.length) {
            return;
        }

        $scope.todos.push({
            title: $scope.newTodo,
            completed: false
        });

        $scope.newTodo = '';
    };

    $scope.editTodo = function (todo) {
        $scope.editedTodo = todo;
    };

    $scope.doneEditing = function (todo) {
        $scope.editedTodo = null;
        if (!todo.title) {
            $scope.removeTodo(todo);
        }
    };

    $scope.removeTodo = function (todo) {
        $scope.todos.splice($scope.todos.indexOf(todo), 1);
    };

    $scope.clearCompletedTodos = function () {
        $scope.todos = $scope.todos.filter(function (val) {
            return !val.completed;
        });
    };

    $scope.markAll = function (completed) {
        $scope.todos.forEach(function (todo) {
            todo.completed = completed;
        });
    };
}

 

The rest is boilerplate Angular.js for the databinding. You can try out the demo here:

http://www.peterbromberg.net/firebase/index.htm

Be sure to login via Persona, as Facebook and Twitter authentication are not enabled on my demo. You can download a complete Visual Studio 2012 solution here:

FirebaseToDo.zip (263.07 kb)

My Grammar lived to be 100, but she never learnt to write worth a Dime

18. July 2013 15:45 by admin in General

Well, it's Dr. Dotnetsky, back with another of my little rants about one thing or another, all carefully gauged to get you to think. . . Professional programmers often need to write, either to produce articles, for documentation, presentations, or for more mundane tasks such as creating or answering email or newsgroup messages. So my rant this episode isn't directly about programming; it's more related to what happens between the neurons before you start writing any code. In a round-about way, it's actually more directly related to writing professional code than many people think.

What we put on paper or in the media  is a reflection of our own intellectual and creative maturity and abilities in the professional world. Make no mistake -- you may produce an authoritative article about XML, but if it contains any of the more common grammatical bloopers I'll enumerate below, intelligent readers will immediately--if only subconsciously-- call your integrity into question. 

For some reason it seems that intelligent people who understand programming appear to have left grammar school without ever  having been taught  to turn on Option Explicit and Option Strict in the language hemisphere of their brains… I've actually seen ASP.NET server controls with properties that the author titled "LooseFocus" (see below)!  Of course, if you do this consistently, your compiler won't throw any exceptions. But people with an above room-temperature IQ will be taken aback by your apparent lack of basic literacy in your own native language--ENGLISH!

While the Doctor often can be found engaging on this site in various types of slang, witticisms and other tricks that involve playing with words, he also knows how to write formally, too--and so should you. The list below is by no means complete, but if you can absorb it and get to the point where your internal "Debugger" watches for these, you at least will have a fighting chance, because these are the "short list" -- Dr. Dotnetsky's ALL TIME pet peeves, and you KNOW that Dr. Dotnetsky wouldn't play you wrong! Now here are the baddies:

accept vs. except: 
Accept is a verb meaning "receive," "admit," "take something willingly," as in "Bart Simpsonaccepted his Oscar nomination by thumbing his nose at the cameras."  Except is most often a preposition meaning "other than," "with the exclusion of," as in "All of the Oscar nomineesexcept Bart Simpson accepted the honor of being nominated with grace."

If the word you want describes the action of "receiving," "admitting," etc., use accept, not except.  Except is occasionally a verb also, meaning "leave out," "exclude," but far more often than not except is the preposition meaning "other than." Accept is always a verb, it is alwaysan action.

affect vs. effect: 
Affect is always a verb, most often meaning "to influence, or have an impact upon" as in"Drinking alcohol affects a person's judgment."  Effect can be a verb meaning "to bring about or to make happen," as in "The republican congress effected many new important tax reforms."  However, effect is used most often as a noun, meaning "result," "influence," or "impact," as in "Our massive security campaign has had some effect on the incidence of PC viruses, but not the dramatic effect that we had hoped."

If the word you want is a noun, something that might be counted numerically (side effects, e.g.), use effect, not affect.

its vs. it's: 
It's is always a contraction for "it is," and its always indicates possession, as in "It's (it is) a pitiful shame when a computer is abused by its owner."  You should have no trouble with these words. Since contractions are inappropriate in formal writing, there is never any instance when you should say it's in your formal work.

like vs. asas if, or as though: 
As a rule, 
like should not be used to introduce a clause.  "He don't love you like I love you" is incorrect; "He [doesn't] love you as I do" is correct.  Instead of saying, "She looks like she is going to be sick," say, "She looks as if she is going to be sick" or "She looks as though she is going to be sick." Unless you mean "has an affection for," "like" is a great word to avoid altogether. The very worst offender of all time is of course, "Like I said".  No, no, NO! It's "As I said", As I was saying, this one is a real doozy.

loose vs. lose: 
Loose is almost always an adjective meaning "not tight," as in "Since Alexandra has lost weight, her clothes are all loose on her."  Lose is a verb usually meaning "not to have in possession anymore," as in "Since Alexandra is behind on her payments, she may lose her car."  So, if your server keeps "loosing" Session State, you have more than one problem, Dude!

than vs. then: 
Than is always used in comparison, as in "Bill is taller than Bobby."  Then has many uses, but the most common are a) to indicate sequence, as in "First x occurred, and then y happened"; b) meaning "at that time," as in "I wasn't ready to settle down and get married then"; and c) meaning "in that case," as in "If I'm not home, then leave me a message." 

there vs. their: 
There generally indicates a specific location or direction; their indicates possession.

Since there usually indicates location--you can point there, you can distinguish between here and there--it usually answers the question "where?" Note that where and there, which both involve location, are spelled --ere: where & there.

to vs. too: 
To is a preposition; too is an adverb.

To generally indicates direction, as in "Bill was very intoxicated, so we took him to his room and put him to bed."  To often indicates the infinitive form of a verb, as in, "Bill was too inebriated to walk, so we had to carry him."

Too has two most common meanings: 1) also, in addition; and 2) excessively, more than enough.  For example, "Marcia, too [also], was too [more than enough] intoxicated to walk.  Her roommate had to put her to bed, too [also]."

Prepositions such as to are usually "smaller" words than adverbs, literally and in terms of grammar--prepositions are kinds of "connecting words": think of other common prepositions that are also "small" words of only two letters: "of," "at," "in," "on" and "by," for instance.  Adverbs such as too are more important to specific meaning within a sentence--they indicate how an action is done, or when, or how often, for instance. It makes a certain kind of sense that the more important "too," the adverb, is the longer word.  If you're unsure whether to use toor too, ask yourself whether the word is a preposition indicating direction ("to the house") or an adverb meaning also (I, too, was intoxicated) or excessively, more than enough (I was tooblitzed to walk).

Sight vs. Site:

Site is a noun:

  • The place where a structure or group of structures was, is, or is to be located: a good site for the school.
  • The place or setting of something: a historic site; a job site.
  • A website.

    Sight is also a noun, and has at least ten different accepted usages. However, the primary one is "The ability to see".   We use our sense of sight to view a web site. Got the "picture"?

Well! I hope this little exercise in grammar (she actually did live to be 100, the old bag!) was useful to y'all. Now where... Oh, Darn! My nice Stoli Martini, up with two olives, has gone and started to get warm!

Firebase and Angular Fire

12. July 2013 06:44 by admin in database, JSON

Firebase is a cloud database designed to power real-time, collaborative applications.

Add the Firebase library to your app and get access to a shared data structure; any changes made to that data are automatically synchronized with the Firebase cloud and with other clients within milliseconds.

Firebase apps can be written entirely with client-side code, update in real-time out-of-the-box, interoperate well with existing services, scale automatically, and provide strong data security.

https://www.firebase.com/how-it-works.html

 

GitHub Repo here:  https://github.com/firebase/angularFire

Display RSS Feed with JSONP and AJAX UI-blocking Loader

2. July 2013 08:38 by admin in ASP.NET, JSON

Here is a technique to display an RSS feed with the jQuery $ajax method, using Yahoo's YQL query API to retrieve the feed and return it as JSON:

<!DOCTYPE HTML>
<html>
 <head>
<title> Feed Demo with Ajax Loader </title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="Scripts/jquery.blockUI.js"></script>
  <script>
function stopUI() {
    $.blockUI({ message: '<img id="AjaxLoader" src="Images/ajax-loader.gif" />',
        css: {
            padding: '25px',
            margin: 0,
            width: '5%',
            top: '40%',
            left: '40%',
            color: '#000',
            textAlign: 'center',
            border: '3px solid #aaa',
            backgroundColor: '#efefef',
            cursor: 'wait'
        },
        overlayCSS: {
            backgroundColor: '#000',
            opacity: 0.2
        }
    });
    $('body').css('cursor', 'wait');
}
 
// REMOVE THE BLOCKED INTERFACE
function startUI() {
    $.unblockUI();
    $('body').css('cursor', 'default');
}
 
$(function() {
    stopUI();
     getFeed();
});
 
function getFeed()
{ 
    $.ajax({
// ajax request to yql public json url 
      url : 'http://query.yahooapis.com/v1/public/yql',
      jsonp : 'callback',
// tell jQuery that we need JSON format
      dataType : 'jsonp',
// tell YQL that what we want and to output in JSON format
      data : {
          q : 'select * from rss where url ="http://www.peterbromberg.net/syndication.axd"',
          format : 'json'
      },
// parse response data
      success : function(data) {
        $.each(data.query.results.item, function(i,data)
        {
var news_data =
"<div><a href='"+data.link+"'>" + data.title + "</a>" + 
          data.description +"</div>";
          $(news_data).appendTo("#news");
        });
 
      }    ,
      complete: function(){
          startUI();
          } 
    });
 
}
</script>
 </head>
 <body>
<div id="news"></div>
 </body>
</html>


The download includes the Ajax-loader image as well as the required jquery.blockUI.js javascript.


 

blockUi.zip (9.58 kb)