Again, I find myself going back to basics when trying to make my SenchaTouch2 Project work.  Today, I updated my framework to Sencha’s latest alpha release of the tools (p4).  I often make these examples because I’m trying to prove there is a SenchaTouch bug and usually find out it’s my bug somehow.  So, since I went to the trouble of making a simple example of two stand alone buttons that switch between tab pages, I thought I’d blog it.

Here is what we get ultimately.  When clicking on b1 or b2, the home and the contact tab are selected automatically (same as clicking on those two items in the tab bar).

One thing I find a little odd, is that to create the class, you say Ext.TabPanel and not Ext.tab.Panel. (OK, I just tested that and both work)

 

image

And, here is the code:

<!DOCTYPE html>

<!-- Auto Generated with Sencha Designer -->
<!-- Modifications to this file will be overwritten. -->
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>AgelessST2</title>
    <link rel="stylesheet" type="text/css" href="sencha-touch-2.0.0-pr3/resources/css/sencha-touch.css"/>
    <script type="text/javascript" src="sencha-touch-2.0.0-pr3/sencha-touch-all-debug.js"></script>
    
    <script type="text/javascript"  >

        Ext.setup({
            onReady: function () {

                var pan = Ext.create('Ext.TabPanel', {
                    height: 150,
                    defaults: {
                        styleHtmlContent: true
                    },
                    items: [
                        {

                            title: 'Home',
                            html: 'Home Screen'
                        },
                        {

                            title: 'Contact',
                            html: 'Contact Screen'
                        }
                    ]
                });

                var buttonPannel = Ext.create('Ext.Panel', {
                    layout: 'hbox',
                    items: [
                            {
                                xtype: 'button',
                                text: 'b1',
                                handler: function (button) {
                                    pan.setActiveItem(0);
                                }
                            },
                            {
                                xtype: 'button',
                                text: 'b2',
                                handler: function (button) {
                                    pan.setActiveItem(2);
                                }
                            }
                ]
                });

                Ext.Viewport.add({
                    fullscreen: true,
                    layout: 'vbox',
                    items: [buttonPannel, pan]
                });
            }
        });

      
    
    
    </script>
</head>
<body></body>
</html>
Hope this helps.

It was surprisingly difficult for me to build a very simple Carousel application with SenchaTouch 2.0 so I thought I’d make a short blog post with the example code in the hopes it saves someone else some time.  Basically, since this runs from the Sencha CDN, you should be able to paste this code directly into your web site as an html page and it should run directly.

The fact that you have to have an items array inside an items array is a little confusing as well as having to specify the height or nothing comes out.  I’m used to using flex: 1 to get the width right, but I had forgotten about height.

Here is what is created and the html and JavaScript code.

 

image

 

and the html:

 

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>SenchaTouch 2.0 Carousel Example From PeterKellner.net</title>
    <link rel="stylesheet" type="text/css" href="http://extjs.cachefly.net/touch/sencha-touch-designer-edition/resources/css/sencha-touch.css" />
    <script type="text/javascript" src="http://extjs.cachefly.net/touch/sencha-touch-designer-edition/sencha-touch-all-debug.js"></script>
    <script type="text/javascript">

        Ext.setup({
            fullscreen: true,
            onReady: function () {
                Ext.create('Ext.Panel', {
                    fullscreen: true,
                    height: 200,
                    items: [{
                        xtype: 'carousel',
                        height: 200,
                        items: [
                                {
                                    title: 'title card 1',
                                    html: 'card1',
                                    cls: 'card1'
                                },
                                {
                                    title: 'title card 2',
                                    html: 'card2',
                                    cls: 'card2'
                                }
                            ]
                    }]
                });
            }
        });
    </script>
</head>
<body>
</body>
</html>

HTH’s

One of the standard things we programmers do is to read static files from our project directory.  That is, say you put a json file such as /data/stats_data.json at the root of your Visual Studio 2011 PreRelease Developer Edition project and you want to read it and convert it to a JavaScript object using WinRT (JSON.parse(..)).  This post explains how to do that using the Metro App Development Framework with JavaScript.

 

By way of background, this post was motivated by two threads I had with a great support helper on the MSDN forums named Jeff Sanders.  The links are here:  Thread 1  and Thread 2.

image

 

First, let’s look at the basic empty project by creating a Blank Application as follows:

 

image

 

Then, drop some JavaScript into a new data directory which is what we plan on reading into our JavaScript.

 

image

 

Now, let’s add some code to the default.js file and one function called ReadAllDataFile that actually does the heavy lifting.  Add to the default.html just one div tag in the body so we can prove we did something good, and run it.  Below is the project that has all this in it.

Link To Download Project:  

 

And the explanation for the code pasted to the bottom with line numbers now (though it’s pretty self explanatory).  If you feel the urge to cut and paste the code, you will get annoyed with my line numbers. I’d suggest grabbing the zip file of the project from above and using that code for pasting purposes.

    • Line 57 simple is the code that executes when the app launches. All it does is call our function ReadAllDataFile with the local path to the file we want.
    • Lines 4 and 5 get the location of our project. Remember, out deployment is actually copied some place totally different and packaged for running.  It is not running in our local directory so it’s important that whatever file you reference be a part of your solution.
    • Lines 7 and 8 basically create a “promise” which when the file is accessed, will return and execute the anonymous function we are passing it (starting with ..(function(stream) {…).
    • Line 15 completes after the promise to read the file.
    • Line 19 should actually be enough, but I found that some json files have wide characters in them causing it to crash.  The workaround is to read the bytes and convert them while stripping out the higher order characters.  Remember, this is a simple example, you may want those high order characters.
    • Lines 36 and 37 grab the population of the state of New York (my home state) from the JSON file.
    • Line 40 displays it on the web page as follows:

image

(Tablet Simulator Screen Shot With Result Above)

default.js:

   1:  // read the file you want
   2:  function ReadAllDataFile(fileNameInLocalTree) {
   3:      
   4:      var package = Windows.ApplicationModel.Package.current;
   5:      var installedLocation = package.installedLocation;
   6:   
   7:      installedLocation.createFileAsync(fileNameInLocalTree, Windows.Storage.CreationCollisionOption.openIfExists).then(function (dataFile) {
   8:          dataFile.openAsync(Windows.Storage.FileAccessMode.read).then(function (stream) {
   9:              var size = stream.size;
  10:              if (size == 0) {
  11:                  // Data not found
  12:              }
  13:              else {
  14:                  var inputStream = stream.getInputStreamAt(0);
  15:                  var reader = new Windows.Storage.Streams.DataReader(inputStream);
  16:   
  17:                  reader.loadAsync(size).then(function () {
  18:   
  19:                      //var contents = reader.readString(size); // fails with multibyte error if bad data (see legislators.getList.json)
  20:   
  21:                      // allocate the full array so readBytes can insert it in full
  22:                      var array = new Array(size);
  23:                      reader.readBytes(array);
  24:                      
  25:                      var newString = "";
  26:                      for (var i = 0; i < array.length; i++) {
  27:                          // only printable characters (include spaces because could be part of names) (very rough here)
  28:                          // http://www.csgnetwork.com/asciiset.html
  29:                          if (array[i] >= 32 && array[i] <= 126) {
  30:                              var c = String.fromCharCode(array[i]);
  31:                              newString += c;
  32:                          }
  33:                      }
  34:   
  35:                      
  36:                      var result = JSON.parse(newString);
  37:                      var newYorkPopulation = result.NY.P001001;
  38:   
  39:                      // output to the screen
  40:                      document.getElementById('outputhere').innerHTML = "New York Population: " + newYorkPopulation;
  41:                      
  42:                  });
  43:              }
  44:          })
  45:      });
  46:  }
  47:   
  48:  (function () {
  49:      'use strict';
  50:      // Uncomment the following line to enable first chance exceptions.
  51:      Debug.enableFirstChanceException(true);
  52:   
  53:      WinJS.Application.onmainwindowactivated = function (e) {
  54:          if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
  55:              
  56:              // start of my insert code            
  57:              ReadAllDataFile("\data\\states_data.json");
  58:              // end of my insert code
  59:          }
  60:      }
  61:   
  62:      WinJS.Application.start();
  63:  })();

 

Hope this Helps!  Remember, these are pre-beta bits so things could change when production comes a long.  Feel free to add comments to this post and let me know if it stops working. 

 

Background

The new Windows 8 Developer environment is seriously under documented at this point in it’s product life.  Microsoft released a “Developer Preview” at the Build Conference in September, than has not done any noticeable updates or improvement on those bits.  The Video’s online from build are very helpful because you can go through them in slow motion and see how to make things work.  In this article, I’m going to go through the steps necessary in a lot of detail to build a simple list read-only list viewer of US Congress legislators in California.  At the end, we’ll have something like the following working:

 

image

(actual tablet from build running the app)

 

and the completed solution from Visual Studio 2011 (it’s always nice to have source)

 

Getting Visual Studio 2011 Going To Create The Project

First, launch Visual Studio 2011 and give the standard File/New Project choice and chose JavaScript / Windows Metro Style / Fixed Layout Application as follows:

image

 

Notice, there are two files we will primary work with, default.js and default.html.

 

image

The default.html is a very classic html page with just the standard html doctype, some JavaScript includes, a style sheet and a simple div container.  The default.js is actually what gives this page life.

One thing you’ll quickly discover if you have done much web development before (particularly JavaScript) is that unlike XAML in Visual Studio, there is no design view.  This shouldn’t be an entire surprise because in Microsoft’s ASP.NET MVC, there also is know design view for html files.  However, there is a really big difference here that I don’t see people pointing out clearly enough.  I’m going to say it twice for emphasis.  When you run your Metro App, there is no IE Debug, Firebug or Chrome Developer Tools to look at what are running (OK, I’ll spare saying it again, but this is really critical).  The way most of us do web development that depends on a lot of JavaScript is to launch the application in the browser, then dive into the browser’s debugger and do all there debugging from there (that is by running the Visual Studio project outside the Visual Studio debugger.

Blend to the rescue! (more like fire, and without Expression Blend, the house would burn down).  When you right click on the HTML file (as shown below) and open in blend, you will now see the page as if it were being run.  I’ve noticed that if I load my JavaScript data stores from local arrays, those actually render, but if I try to pull data from a live data source they do not.  I’m guessing that’s my misunderstanding for how to do it, rather than a product short coming.

 

image

 

Putting Down the ListView in HTML

Let’s get down to some real work here.  First, let’s open the default.html and put down a listview.  Before though, let’s look at what the template gives us (it’s very simple and boring).

<body>
    <div data-win-control="WinJS.UI.ViewBox">
        <div class="fixed-layout">
            <p>Content goes here</p>
        </div>
    </div>
</body>

We’ll add all our stuff to the “Content goes here”.  Fist, let’s add the listview control as follows:

<div id="listview"
   class="flipView"
   data-win-control="WinJS.UI.ListView" 
   data-win-options="{dataSource: itemDataSource, itemRenderer: personTemplate,
       layout: {type: WinJS.UI.GridLayout, maxRows:2}}"
     style="margin: 15px 15px 15px 15px; left: -3px; top: 10px; height: 100%;width: 100%">
</div>

and the template itself:

<div id="personTemplate" data-win-control="WinJS.Binding.Template">
<div style="width: 100%;height: 100%">
<div style="margin: 15px 15px 15px 15px">
    <img data-win-bind="src: govtrack_id convertGovTrackIdToImgTag" 
        alt="Databound image" />
    <h3>
        Rep <span class="content" data-win-bind="innerText: firstname">
         </span>&nbsp;<span class="letter"
            data-win-bind="innerText: lastname">
         </span>
    </h3>
</div>
</div>
</div>

Remembering that any style that begins with data- is ignored by html and can be handled by the program for doing template type stuff, you see here that we have a windows control declared which is based in the WinRT runtime (WinJS.UI.ListView).  We also have options set declaratively here in the data-win-options.  All those can be set in the default.js file which is often easier because the intellisense helps us.

Explaining the options is as follows:

    1. datasource:  defined in the default.js and is what we refer to this listview’s data source with
    2. itemRenderer: next, I’ll explain this. It points at the div that has the actual rendered template
    3. layout: just says what kind of layout. in our case, GridLayout.
    4. style: should really be set in a class but I got a little lazy since I’m not so good at the CSS stuff

And, don’t forget to update your depencies (namespaces for all your c# folks out there).  Here are the ones you need to replace in your html file.

    <script type="text/javascript" src="WinJS/js/base.js"></script>
    <script type="text/javascript" src="WinJS/js/ui.js"></script>
    <script type="text/javascript" src="WinJS/js/binding.js"></script>
    <script type="text/javascript" src="WinJS/js/controls.js"></script>
    <script type="text/javascript" src="WinJS/js/res.js"></script>
    <script type="text/javascript" src="WinJS/js/animations.js"></script>
    <script type="text/javascript" src="WinJS/js/uicollections.js"></script>
    <script type="text/javascript" src="WinJS/js/wwaapp.js"></script>

 

 

JavaScript File Update

Finally, let’s update the JavaScript file.  First, we need to create a simple array that we will databind to.  Then, we need to associate that array with the itemDataSource and finally execute.  The only thing tricky we have here is a Converter that takes an Id and build an image src tag for the image control itself.  Notice that the converter is called convertGovTrackIdToImgTag.  It takes in a govTrackId and returns the full blown URL to tick in the image url.

All the source is below.

Hope this helps!

 

 

convertGovTrackIdToImgTag = WinJS.Binding.converter(function (govTrackId) {
    var retUrl = 'http://www.govtrack.us/data/photos/' + govTrackId + '-50px.jpeg';
    return retUrl;
});


var itemDataSource = {};

(function () {
    'use strict';
    // Uncomment the following line to enable first chance exceptions.
    Debug.enableFirstChanceException(true);

    //allLegislatorsCreateFile();


    WinJS.Application.onmainwindowactivated = function (e) {
        if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {

            var items = [];
            var itemsFresh = [{
                firstname: "Barack",
                lastname: "Obama",
                govtrack_id: "400629"
            },
            {
                firstname: "Adam",
                lastname: "Smith",
                govtrack_id: "400379"
            },
            {
                firstname: "Adrian",
                lastname: "Smith",
                govtrack_id: "412217"
            }];
            items.push(itemsFresh[0]);
            items.push(itemsFresh[1]);
            items.push(itemsFresh[2]);

            itemDataSource = new WinJS.UI.ArrayDataSource(items);
            WinJS.UI.processAll();
        }
    }
    WinJS.Application.start();
})();

Yet another great meetup with the ExtJS San Francisco Group (though not meeting in San Francisco this time).  ExtJS has moved it’s main office and developers out here to Palo Alto, California and volunteered to host our meetup.  They provided pizza and beer and I’d say it was our most successful event so far! 

http://www.meetup.com/The-San-Francisco-ExtJS-Meetup-Group/calendar/12527913/

Most of the ExtJS team stayed until after 9.  The team introduced themselves to start the event, then we got presentations of all kind of cool upcoming technologies from ExtJS that we promised not share because it was top secret. ;)

I’ve posted more pictures to FaceBook at the following URL:  Click Here  I believe you will have to create a facebook account if you don’t have one to view them.  It would be great if everyone can Tag themselves so next time we will all know each other.

Abe invited us all back so I’m sure we will have the chance to all see each other again.  Here are a couple shots, including the rock band at the end of he meeting starring Tommy.

PeterStartingMeeting

(above picture courtesy of Mats)

(more…)

We are in the process of “speeding up” our ExtJS application.  I’m just finally figuring out the rules of the road for doing this.  Here are a couple of rules I believe to be true

  • Combine and Minify All JavaScript
  • Combine All CSS that are in the same directory (because of relative paths)
  • Put the CSS above the JavaScript includes

We are using a library http://atashbahar.com/post/Combine-minify-compress-JavaScript-files-to-load-ASPNET-pages-faster.aspx and it’s working well for us.  This project does a nice job of calling a minifier, gzipping and caching.

Hoe this helps!

Cutting to the chase, I choose Vladimir Bodurov’s Color Formatter!

For the past year or so, I’ve been working on a project that uses Microsoft’s ASP.NET MVC for providing data to our pure JavaScript application.  That is, there are no web forms, no dynamic HTML generation, just 100% JavaScript running on the client.  I’m using a library called ExtJS which gives us high quality “forms like” user interactions and MVC for getting the data.  That is, the Application looks like this:

image

The data retrieval URL used by the JavaScript look like:

(more…)

For the past year or so, I’ve been spending part time learning JavaScript.  My reason has been we use ExtJS extensively in my company and it’s written in JavaScript.  ExtJS is very object oriented so any book that tries to present JavaScript in an OO fashion is a big help.

(more…)

Programmatically setting JavaScript into an ASP.NET page is very straight forward when you do it in code.  That is, in my case, I simply put it in the Page_Load event of the page and have it load from there.  I’m currently working on an ExtJS project that requires me to show some details on a page that I want to show with JavaScript.  I’ve nicely modularized all the JavaScript into a name space so the code that I want to include on my ASP.NET Page looks like the following:

<script type="text/javascript" language="javascript" >
    ASPWeb.newsGrid.loadTypeId = 229490;
    ASPWeb.newsGrid.init();
</script>

(more…)

 

My guess is 75 people showed up at Dolores Labs last night for this meetup.  It lasted about two hours and had about 6 great presentations.  Douglas Crockford kicked it off with a discussion on upcoming security models around new versions of JavaScript followed by several other presentations that included a Google engineer showing cool Google Labs projects, several JavaScript frameworks and other very cool things.  Dolores Labs is down a small alley where I was sure I was lost.  Marked 83A was a non descript door with two flights of stairs. Then, a roomful of engineers, lots of ethernet connections, beer and pizza.  What else could we ask for.

Below are some fun pictures I took. Not sure if it does justice to the fun that was had.

Many thanks to Matt Humphrey for organizing the event.  Job well done!!!

 

IMG_1353 IMG_1354

 IMG_1356 IMG_1357

 

Come hear about how to see ExtJS integrated with ASP.NET for awesome Membership and Profile Management!  I will speaking at the Microsoft Office at a meeting of Bay.Net Users Group.

http://www.baynetug.org/DesktopModules/DetailXEvents.aspx?ItemID=378&mid=49

ASP.NET: Membership with Profile and High Performance ExtJS JavaScript Interface

When: 

Wednesday, 5/20/2009 at 6:30 PM

Where: 

Microsoft Office, 835 Market Street, Suite 700, San Francisco

Event Description

In this session, we will demonstrate building a super rich JavaScript interface to the standard ASP.NET Membership and Profile services. That is, built into ASP.NET are wonderful providers that allow you to validate and store user credentials typically to a database. It also lets you store other information such as pictures, first and last names, as well as anything else you may want to store. In this session we will build a highly performing, 100% JavaScript UI to maintain hundreds of thousands of users. As part of this solution, techniques for using REST based services to access this information will be presented. Once you see this, it will be hard to ever use web forms again.

I’m doing two sessions at VS-Live in June.  Both sessions are in the asp.net track. One is on High Speed performance in ASP.Net, and the other is on using ExtJS (a brilliantly fast rich JavaScript library).  Hope to see you there!

Here are the descriptions:

VM1

Build Blazingly Fast ASP.NET Apps with 100% Clientside UI ExtJS

Peter Kellner

Intermediate

Need a web application that has the responsiveness and interactivity of a forms app but still looks and feels like a web? One of the best kept secrets (at least to the Microsoft community) is ExtJS. It’s a different paradigm then we are all use to, but the results are spectacular. Take a look at this url and you will see as well as learn how to do this yourself. The hardest part is shuttling the data back and forth. A lot of this session will be talking about how to do a real world app that does this. Once you go this way, you’ll be gone from serverside forms for almost ever.

(more…)

Mats Bryntse, a great web developer and ExtJS expert has written a very cool utility that let’s you see how well the different JavaScript frameworks play with each other.  Specifically, he looks at many of the most popular frameworks and calculates how many globals each one uses.  This is important because if you happen to have multiple frameworks in your application (which is completely reasonable to do), you may have problems.  The URL is as follows and must be run in Firefox).

http://mankz.com/code/GlobalCheck.htm

Here is an example result:

(more…)

http://www.meetup.com/The-San-Francisco-ExtJS-Meetup-Group/

As many of you know, I’m learning the JavaScript library ExtJS.  It’s basically a very rich development api that allows you to make totally awesome client side control 100% in JavaScript.  It has control that include Grid, Dropdown, Calendar, Image, Drag and Drop, Toolbars, etc.  With ExtJS, you can in a very straight forward way, make interfaces that look like the following:

image

(more…)

As I’m learning ExtJS I plan on publishing the things I figure out.  For those that don’t know, ExtJS is a very rich JavaScript library that gives you all kinds of capabilities that work cross browsers.  Trees, Grid’s, Panels, Layouts and all kind of stuff.  For an idea of the kinds of things you can do, check out the demos at there site at this URL:  http://extjs.com/deploy/dev/examples/samples.html.

It’s pretty amazing the kinds of things that can be done with just client side JavaScript.  At the core of ExtJS are some very useful JavaScript methods.  In order to take advantage of the more sophisticated features, it’s helpful to know the basics first.  In this article, I plan on going through a simple example that will ultimately product html that looks like the following.

image

(more…)

For my current project, I’m focused on delivering the fastest and best user experience possible for our web site.  To deliver this, it is necessary to really focus on delivering client side code.  After doing a bunch of research, the very clear answer to me is to use a Library called ExtJS combined with a very nice integration tool suite for the .net called Coolite. It’s basically a very rich interactive JavaScript library that is extremely customizable.  To that end, I’m taking a week training class from ExtJS.  We’ve had our first day which has focused on CSS and JavaScript basics with an eye towards the patterns used in ExtJS.

(more…)

I’ve been working on a project lately that requires a lot of JavaScript, and if any of you are like me, you’ve had trouble learning the language well.  Over the years, I’ve taken several runs at it but have not been successful.  Sure, I could always to basic stuff, but it seemed that when ever I need to do anything useful, I just could not figure it out.  Well, times have changed.  Mostly based on my need to know the language, I am really starting to feel good about the language. I’m understanding scoping, I can throw functions and arrays around as well as actually do useful stuff.

(more…)

I’ve just started my journey into the land of JavaScript for real and am learning things most of you already know.  For example, as the Silicon Valley Code Camp coordinator and web site author, I just recently decided to add a Virtual Earth Map showing attendees and speakers (see the home page).  I wrote a simple web response handler that returns all the data in JSON so I could plot the data.  Then, after a couple searches on the web, I found a way to send a request to the service asynchronously and get the result. The code looks something like this:

(more…)

I’m just starting out using WCF in an application for the first time.  I’m using Visual Studio 2008 sp1 and created an asp.net web site from the standard create project wizard.  I then created a simple AJAX–enabled WCF Service as follows:

image

I then added some code to the service that looks like the following (using MapPath):

(more…)

© 2012 PeterKellner.net. All Rights Reserved