Friday, December 30, 2011

Using a Mac for Visual Studio 2010 Development

For most of my development career I have exclusively used PCs. Things have changed now. My main PC was over four years old, limited to 4 GB and was painfully slow to work on, I needed to upgrade. Since my platforms were Android, iOS and the web, I needed to buy a Mac.  I had already had a Mac Mini for iOS development and liked it. I decided to replace my main system with a MacBook Pro.

The machine itself is sweet. It is an early 2011, 15" MacBook Pro. I bought it from Amazon discounted since the newer machine had just been released. Since I am an Amazon Prime member, shipping was free. And as an added bonus, I was able to use my American Express card reward points for an additional discount of 70 dollars. I bought it with 4 GB of ram but did the upgrade myself to 8 GB and 256 GB SSD. The upgrade was super easy and only took about 30 minutes to do. I bought a kit from iFixIt.com.

The problem was the back-end. I do all of my server development in either WCF or ASP.NET MVC. I had no desire to abandon all of my Microsoft knowledge. Since Mac are also Intel based I decided to try creating a virtual PC using software. There are several virtualization apps available, some are even free. But after a long weekend of reading every review I could find, I bought Parallels Desktop 7. It ROCKS! It is an amazing piece of software. The number one thing I like about it is that it has a mode called coherence, which makes PC apps appear on the Mac desktop just like native apps. I can navigate through the Mac file system from the PC too. They also seemed to have thoroughly optimized it. It seems only a hair or two slower than using a PC.

On my home WiFi network, from my iPhone, Android Nexus One, iPhone Simulator, Android Emulator, or any browser, I am able to see my IIS 7.5 server created with Visual Studio 2010. I can publish with a button click locally or to my Discount ASP.NET hosted web site, all from my Mac. In my next post I will give details on how I set everything up.

Monday, December 19, 2011

Make Regular Expressions Not More Code

Currently I am bug hunting at work. Product and QA have identify a number of issues engineering needs to fix before we begin A/B testing of our new website design. For the last few months while our website was being made feature complete, I'd been working on both our iPhone and Android apps. They were updated to use some newly available server data and fix some outstanding issues. So I missed out on a lot of the changes made to the site. Now I am catching up on the code by fixing bugs and refactoring code.

While the code in general is not too bad, there were a few things that troubled me. The first of which was a general ignorance of regular expressions. Every developer should learn regular expressions in their languages of choice and learn them well. They save time, minimize space, and increase code clarity. Here is the original code:


zipIsValid: function (zip, notify) {
var isValid = true;
var validCharacters = "0123456789";

if (zip.length != 5) {
isValid = false;
}
if (isValid) {
for (var i = 0; i < zip.length; i++) {
temp = "" + zip.substring(i, i + 1);
if (validCharacters.indexOf(temp) == "-1") {
isValid = false;
}
}
}
if (!isValid && notify) {
window.alert("The ZIP code you entered is invalid. Please enter a valid ZIP code. ");
}
return isValid;
},

All the above only checks to see if a zip code is valid and if not may display an alert box if a flag is set. I replaced it with the following code:

isZipCodeValid: function (zip) {
var re = /^\d{5}$/i;
return  zip && zip.match(re) != null;
},

The replacement consists of just two lines: a regular expression pattern and a line to test the expression. IMHO, this code is far more maintainable than the code above, if you understand regular expressions, that is.

Also, I moved the warning display to its own method, since every method should do only one thing. And I renamed the method to make it more readable.

Monday, November 7, 2011

Android Developer Conference 2

I am currently at AnDevCon 2 in San Francisco. I arrived Saturday night so that I could do the pre-conference sessions which were great.

Big thanks to the conference planners and the Hyatt Regency for the amazing tasty lunch. I have gone to far to many developer workshops with just horrible food that it is nice that someone actually gave us something delicious.

Today sessions on: using Maven, pragmatic layouts, and creating android library projects, plus a keynote from a couple of developers from American Express.

Friday, September 2, 2011

Android Developer Lab - Los Angeles

I was lucky enough to be invited to the Android Developer Lab, Los Angeles, that was held today. The focus of this event was honeycomb development. Google is well aware of the lack of apps for Android tablets and is presenting this lab in several cities hoping to encourage developers to build more apps. This was the first Google sponsored event that I attended. As a recovering C# programmer, I had attended an large number of Microsoft events, so I was curious to see if Google was a good host.

The event was held at the Sheraton Delfina Santa Monica Hotel. Things got off to a good start. I drove up to the hotel to ask where there was parking for the event and was politely told by the valet, that Google was providing valet parking for everyone. If you live in a city where parking is plentiful, you might not appreciate this, but in southern California, parking is always a problem and one that I didn't have to worry about.

The event was held at the penthouse level of the hotel. Excellent view and lots of space. I arrived early but there was already coffee, pastries, and fruit waiting. I grabbed a cup of java and joined some Google employees in a rambling discussion of tech.

The session got off to a bit of a late start but with LA traffic being always unpleasant, allowed more people to arrive without missing anything. The talks went fast and there was an enormous amount of information flying across the slides. Unfortunately the slides weren't available online, and there was no way I was going to be able take notes fast enough. So I just pulled out my favorite note taking tool, my Nexus One. It is much easier to snap photos than to write notes.

The first sessions covered some of honeycomb new programming paradigms focusing on fragments, in general, allow an activity to manage multiple view panes. We also discussed loaders, drag and drop, Renderscript, and more.

As a coder, I generally find non-coding session boring. A marketing session presented by Natasha Bock, became an exception to that. She gave a clear set of do's and don'ts for enhancing your apps standing in the marketplace. Explained how things like the editors choices are made. And did something that I always like to hear, ask for suggestions on how to improve things in the marketplace

After a fine lunch, we were given a quick introduction to Google TV. The next release which is coming soon will be compatible with Android 3.1 - not 3.2. IMHO - that not that big of deal since 3.2 was a minor upgrade anyways. More surprising was that the current crop of Google TV devices, like the Logitech Revue, will be capable of upgrading.

The final session was a developer lab. The goal of this session was to take a Android 2.1 app and turn it into a tablet app. In order to make sure that everyone had a tablet, they gave everyone in the room a brand new T-Mobile  G Slate with Google.

  • Premium Tablet Features
    • 4G and Wi-Fi capable
    • 8.9 High Definition Touch-screen
    • Dual 5MP Camera for 3D or HD Capture
    • Front Facing Camera for Video Chat
    • 32 GB Internal Memory
    • NVIDIA Tegra 2 Dual Core Mobile Processor


The lab was very fast paced and ran out of time. Luckily, all of the information in session was available online. It was interesting to watch the progression from Android 2.1 to Android 3.0. I planned to step through the session from beginning to end in the morning, to make sure that I have it all down.

Even without the free tablet, I would rate this event extremely high. It filled my head with a lot of new information and new ideas. I can't wait to get started and I will keep you all informed of my progress.

Monday, August 29, 2011

Changing Tab Background Color

At times things in Android are unbelievably easy. Especially if you have Eclipse's autocompletion function turned on. But occasionally you hit a baffling wall. We are currently re-skinning our Android app. Since the UI is nearly completely defined in resources, this has been amazingly easy to do, until an hour or two ago.

The specification sheet supplied to me by our UI guy uses something other than the default background colors in the tabs, both for the active and inactive tab. Anyone who has worked with tabs in Android already knows that they are one of the more clumsily implemented UI patterns. So much so that the Layout Editor can't accurately process them. For those who don't know, in order to create a tabbed layout, you combine a series of activities together into another layout which is called a Tab Host. The definition of the Tab Host is very strict. It must consist of an outer Tab Host with a Linear Layout inside and surrounding Tab Widget with the id of "tabs" and a layout with the id of "tabcontent".

All of the above won't actually render your tabs, you still must use code in the onCreate method of the activity  to add the activities of the tab views to the tab host. If you do everything right, you get a tabbed layout, if not, mostly likely you'll get an exception.

The problem with all of this is that somethings, most notably the background colors, are hard-coded into the tabs. Android will let you change the background color of the tab host in both XML and in code, but neither will actually change anything, nor produce an error. The reason for this is that the tabs are actually child elements of the tab host's tab widget. So changing their grand parent, has no effect on them. But don't worry, changing the tabs while clumsy, is easy to do.

First off, make sure that the activity of the Tab Host implements OnTabChangeListener.


implements OnTabChangeListener


Then within the class declare a couple of private variables to hold references to Tab Host and Tab Widget.


private TabHost tabHost;
private TabWidget tabWidget;

Within the onCreate method set the values for tabHost and tabWidget.


tabHost = getTabHost();
tabWidget = tabHost.getTabWidget();

Then set the tab change listener:



tabHost.setOnTabChangedListener(this);


And finally call the colorTabs method which will initially seed the tabs.

colorTabs();

Anytime the user switches tabs, we will need to set their background colors again. So we have to override the tab changed listener.



@Override
public void onTabChanged(String tabId) {
colorTabs();
}



Finally we get to the colorTabs method. Which simply pulls the colors for the active and inactive tabs from the colors.xml, then sets all of the tabs to the inactive color, before finding the active tab and setting it to the active color.


private void colorTabs() {
int inactiveColor = getResources().getColor(R.color.inactive_tab);
int activeColor = getResources().getColor(R.color.active_tab);

// set the inactive tabs
for (int i = 0; i < tabWidget.getChildCount(); i++) {
tabWidget.getChildAt(i).setBackgroundColor(inactiveColor);
}

// set the active tab
tabWidget.getChildAt(tabHost.getCurrentTab()).setBackgroundColor(activeColor);
}

And that is it. Now you can color your tabs to whatever color makes your UI guys happy.

Tuesday, April 26, 2011

Who "Likes" You Baby

received the following email from zhang na:


Hi, i met a trouble , i want to get the value
The total number of people who have liked your Page
but i try all the function , cannot get the lastest data , i used graph.facebook.com/appid//insights/page_fans/lifetime, but i get the old three days data
can you give me an example code ?



Here is my response:


Hi zhang na,

There is an easier way to get the count of the number of people who have liked your page, simply do a "GET" call to the Graph API with the id of the page. Facebook will return the current number of likes along with other public information. Unlike insights, no access token or permissions are necessary to access public information. The code below assumes you have included the Facebook JavaScript SDK on your web page:

function GetLikeCount() {
 var pageId = "19292868552";
 
 FB.api("/" + pageId, function (data) {
  var count = 0;
 
  if (data && data.likes) {
   count = data.likes;
  }
  alert("Page " + pageId + ", likes = " + count);
 });
}

I am always happy to answer questions, assuming of course, that I know the answer. Please post questions in the comments and I will answer as soon as I am able.

Thursday, April 14, 2011

Facebook's FQL Multi-Query


Introduction

At work, my team is currently developing a social media management application. I am focused now on displaying some data charts and tables. All of the code is client-side JavaScript. To populate the charts, we make calls to Facebook.

Facebook has a SQL like query language, FQL,  which allows you to request various data points about your pages, applications, etc. When you need a single data point like your page's total fans, you make a call to the method, fql.query to get your data. For a single data point this is great, but what if you are building a chart and need more than one data point? Making repeated calls to Facebook, will quickly begin to become tedious and slow. Luckily, Facebook has another method, fql.multi-query, which allows you to submit multiple queries at the same time and receive them back in a single result-set.

Submitting Data
Submitting queries to multi-query is only slightly more complicated than doing a single query. A single query request looks like:

var query = “SELECT metric, value FROM insights WHERE object_id=162705687107157 AND metric='page_fans' AND end_time=end_time_date('2011-04-01') AND period=period('lifetime')”;

FB.api({ access_token:accessToken, method: 'fql.query', query: query }, function (data) { // do something });

A multi-query request looks like:

var queries = {
d20110401:“SELECT metric, value FROM insights WHERE object_id=162705687107157 AND metric='page_fans' AND end_time=end_time_date('2011-04-01') AND period=period('lifetime')”,
d20110404:"SELECT metric, value FROM insights WHERE object_id=162705687107157 AND metric='page_fans' AND end_time=end_time_date('2011-04-04') AND period=period('lifetime')",
d20110407:"SELECT metric, value FROM insights WHERE object_id=162705687107157 AND metric='page_fans' AND end_time=end_time_date('2011-04-07') AND period=period('lifetime')",
d20110410:"SELECT metric, value FROM insights WHERE object_id=162705687107157 AND metric='page_fans' AND end_time=end_time_date('2011-04-10') AND period=period('lifetime')"}

FB.api({ access_token:accessToken, method: 'fql.multiquery', queries: queries }, function (data) { // do something });

The only things that change are the name of the method from fql.query to fql.multiquery and instead of query, we now have queries. Please note: queries is a property and not an array. A property in JavaScript is like a dictionary in other languages. So each entry is a key/value pair. The key of each query is used to identify its data in the result-set.

Retrieving Data
One challenge of using multi-query is in changing the returned result-set into more easily used data. Here is what the result-set looks like for the preceding queries::

resultset = {
[ { "fql_result_set" : [ { "metric" : "page_fans", "value" : "31" } ],
   "name" : "d20110401"
 },
 { "fql_result_set" : [ { "metric" : "page_fans", "value" : "31" } ],
   "name" : "d20110404"
 },
 { "fql_result_set" : [ { "metric" : "page_fans", "value" : "31" } ],
   "name" : "d20110407"
 },
 { "fql_result_set" : [ { "metric" : "page_fans", "value" : "31" } ],
   "name" : "d20110410"
 }
]};


The resultset neatly encapsulates all of the information asked for by the query. Please note: the keys of the request are now identified by the name keys of each fql_result_set. Unfortunately, this data is a bit cumbersome to work with. For displaying charts an array is much easier to use. So I wrote the following general purpose method to change the result-set into an array.

FilterData: function (data, processedData, criteria, name) {
 var prop, ptr, type;
 for (prop in data) {
   ptr = data[prop];
   type = typeof (ptr);
   if (type === "object") {
     // is this the field holding the desired data?
     if (ptr && ptr.metric && ptr.metric === criteria) {
       processedData.push({ metric: ptr.metric, value: ptr.value, name: name });
     } else {
       // search deeper into the object
       this.FilterData(ptr, processedData, criteria, name);
     }
   } else if (type === "string" && prop === "name") {
     // save the name of the current query
     name = ptr;
   }
 }
}


The FilterData method uses recursion to search through the JavaScript property, data. Each time it finds a match to criteria, it pushes a new value onto the array, processedData. The value pushed onto the array is a property consisting of: the name of the query, the name of the metric, and the value of the metric. This design allows the method to be able to search through result-sets which have more than one metric returned.

Summary
It is always a best practice to minimize the number of out of process calls your application makes. Facebook’s multi-query makes it easy to get all of the data you need in one call.

Saturday, April 9, 2011

Dynamic DOM Manipulation Using JavaScript and jQuery

I gave a talk to the Southern California .NET Developers Group on Wednesday, April 6, 2011. It was entitled, "Dynamic DOM Manipulation Using JavaScript and jQuery." I went deep into the subject, but I think I was clear. Through out the presentation, during the break, and afterwards, people asked the kinds of questions which let me know they understood the material. I am hoping to give the talk to another local group after I have tightened it up a bit.

April 6th at SoCal.NET Dev Group

Starting tomorrow, I will begin blogging on actual code development. My first blog will be on efficiently reading HTML input tags in JavaScript.

Sunday, March 27, 2011

Dynamic Web Pages Using JavaScript and JQuery

Hi All,

If you are in Southern California and would like to know more about developing dynamic web pages, think Facebook, I will be giving a talk on April 6, 2011 at the monthly meeting of the Southern California .NET Developers Group. More information on their website: http://www.socaldotnet.org/.