Amazing New Contextual Android App Advertising

I am never the one to advertise the advertising companies I use within my apps, but I came across one the other day and so far it is blowing away all competition!

Sign up today using referral vnk3h2y44w to get $100 and the best CPM rates available!

 

TapContext

TapContext.com is one of the easiest SDK I ever worked with.  I integrated my old apps into the new platform in less than 15 minutes.  It has a step-by-step tutorial to help everyone out.

On top of the easy-to-implement, the dashboard is as good or better than all other mobile advertising companies.  It gives you real-time updates on the number of installs, number of impressions for each type of ad, and the current earnings (as well as all other benchmarks such as CPM, EPC.  You can sort through all your apps and see which app is providing the most impressions, clicks, and CPM.  It provides real-time charts to quickly glance how today is measuring up to previous days.

Last, but certainly not least, it provides the best eCPM rates I have ever received in the well over 10 companies I have used in the past.  The CTR is much higher, and I am earning the most I have ever made in the past with mobile ads (more than 50x what I was earning using AdMob)!

Bonus

They are a brand new advertising provider, and they are currently offering $100 sign-up bonus by using the referral code: vnk3h2y44w.  Sign-up today! You won’t regret it.

I am not an employee of TapContext, nor an investor.  I am simply a user and looking to spread the word.

Building Custom Lists using ListView on Android Tutorial – Part 2

Looking for a new mobile advertising platform? Check out my blog post on the new solution I am using (or sign-up if you don’t want to read the post)

Overview

Now that we have a Custom ListView with 2 TextViews and a ImageView, we may want to be able to search and filter through this list.  For this tutorial, we will add an EditText above the ListView to so users can filter between state or flower names.  If you skipped the first part of the tutorial, you can find it here.

 

 

Changes to First Tutorial Code

Since we are now going to have a filtered list, we are going to need to make some changes to the code we have implemented in the first tutorial.  The first thing we are going to need to do, is add an EditText view on the main layout where users can put their search terms and add a TextWatcher on that object that will call our filter method on the custom Filter we will create.  The new onCreate method within our Activity will now look like this:

	private ArrayList list;
	private Context context;
	private StateFlowerAdapter adapter;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        context = this;
        list = readFile();
        ListView listView = (ListView) findViewById(R.id.stateList);
        adapter = new StateFlowerAdapter(context, list);
        listView.setAdapter(adapter);
 
        EditText searchText = (EditText) findViewById(R.id.searchText);
        searchText.addTextChangedListener(new TextWatcher(){
 
			@Override
			public void afterTextChanged(Editable arg0) {
				// Do nothing
			}
 
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// Do nothing
			}
 
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				adapter.getFilter().filter(s);
			}
 
        });

Notice that we needed to declare our adapter outside the onCreate method so we can use it properly within the anonymous TextWatcher class.  Now you may be thinking, how do I call filter function on my custom adapter default filter and it knows what I want to filter on? The answer is, it doesn’t, which brings us to our next item we need to complete.

 

 

Building a Custom Filter

For this tutorial (and probably for most of the projects you will have), I will build my filter class within my custom Adapter class.  The only reason you would ever want to separate it is when you will have a project that will have multiple adapters that will require the same filter.  In order to build a custom filter, we need to extend android.widget.Filter and override the performFiltering and publishResults functions.  The following is my custom Filter:

private class StateFlowerFilter extends Filter{
 
		@Override
		protected FilterResults performFiltering(CharSequence constraint) {
			FilterResults retval = new FilterResults();
			retval.values = items;
                        retval.count = items.size();
			if(constraint != null && constraint.toString().length() > 0) {
				constraint = constraint.toString().toUpperCase();
                                ArrayList filt = new ArrayList();
                                ArrayList tmpItems = new ArrayList();
                                tmpItems.addAll(items);
                                for(int i = 0; i < tmpItems.size(); i++) {
                                    StateFlower sf = tmpItems.get(i);
                                    if(sf.getState().toUpperCase().contains(constraint) || sf.getFlowerName().toUpperCase().contains(constraint)) {
                                        filt.add(sf);
                                    }
                                }
                               retval.count = filt.size();
                               retval.values = filt;
                           }
	                  return retval;
	        }
 
		@Override
		protected void publishResults(CharSequence constraint, FilterResults results) {
			filteredItems = (ArrayList)results.values;
			notifyDataSetChanged();
			clear();
			Log.d("Filter", "Starting to publish the results with " + filteredItems.size() + " items");
			for (int i = 0; i < filteredItems.size(); i++){
				add(filteredItems.get(i));
			}
			Log.d("Filter", "Finished publishing results");
			notifyDataSetInvalidated();
	}

As you can see in the performFiltering function, we are setting the CharSequence to all caps therefore our search will not be case sensitive.  Anytime the state name or the state flower contains CharSequence passed in, we add it to the FilterResults.  Note that the performFiltering method is automatically called when we call the filter method on our filter object.  Recall that we called filter on the inside the onTextChanged method from our Activity.  After calling the performFiltering function, the results are then passed into the publishResults method automatically.  It is within this method that we set our new filteredItems variable equal to the results’ values property (which holds our ArrayList<StateFlower>).

Now that we are properly filtering and storing the filtered results into this new filteredItems variable, we need to update the getView method of our adapter to utilise this new variable (so we will draw the views of the filtered items instead of all items).  This is simple enough, we just need to replace all occurences of the variable items in getView, with the new variable filteredItems.  See below for the new getView method:

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View List;
		if(convertView==null){
			List=new View(context);
			LayoutInflater mLayoutinflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			List=mLayoutinflater.inflate(R.layout.state_item, parent, false);
		}
		else{
			List = (View)convertView;
		}
		TextView nameText = (TextView)List.findViewById(R.id.stateNameTextView);
		nameText.setText(filteredItems.get(position).getState());
		TextView flowerText = (TextView) List.findViewById(R.id.stateFlowerText);
		flowerText.setText(filteredItems.get(position).getFlowerName());
		ImageView flowerImage = (ImageView) List.findViewById(R.id.stateFlowerImage);
		flowerImage.setImageResource(filteredItems.get(position).getImageResId(context));
		return List;
	}

Almost there, we just need to set the filteredItems equal to items in the constructor as well so before any filtering is done, we have the full list.

public StateFlowerAdapter(Context c, ArrayList&lt;StateFlower&gt; items) {
  super (c, R.layout.state_item);
  this.items = items;
  filteredItems = items;
  context = c;
}

Let’s go ahead and run our program and enter a word to filter on.  Did we get our desired results?  No! This is because we are calling the getFilter method on our adapter within the onTextChanged method, but we did not put in our custom getFilter method to use the new Filter we have just created.  The last and final step is to override that getFilter method within our adapter class to return a Filter of type StateFlowerFilter like so:

	@Override
	public Filter getFilter() {
		if (filter == null){
			filter = new StateFlowerFilter();
		}
		return filter;
	}

We obviously will need to declare a variable filter in as a class variable, and then we are all set.  Run the program and see filtering in action.

Final Thoughts

Now that we have a completely working filter, play around with the performFiltering method and customize what to be filtering on.  If you wanted to play jokes on a user, do an opposite filter that will return everything the user didn’t want.

By building and utilizing custom ListViews and custom Filtering, you can take your Android project to the next level.  You will be able to produce much more user-friendly and professional looking apps that will impress your user-base.  We no longer need to stick with a simple list of Strings within our List, but instead can display any combination of built-in Views provided by Android SDK (TextView, EditText, ImageView, CheckBox, etc.).  We can go from needing 2 or more screens to do simple tasks (such as rating an item), to doing it all within the same View!

Thanks for reading, and please let me know if you have any questions.

Likes the tutorial? Show it by donating to the site. All donations are made to Maryland Special Olympics:

Building Custom Lists using ListView on Android Tutorial – Part 1

Looking for a new mobile advertising platform? Check out my blog post on the new solution I am using (or sign-up if you don’t want to read the post)

Overview

For many projects, a list item needs to contain more than simply a single String.  This tutorial, which will contain 2 parts, will go over how to make a ListView with custom items that contain more than simply a String.  The tutorial will cover building the ListView from scratch (part 1) and then building a custom filter to search through the ListView.  The tutorial will use a simple example of displaying the state flowers for each state, and an image on the side of each flower.  All images and information obtained for this tutorial were obtained by Wikipedia article on the 50 States Flowers (http://en.wikipedia.org/wiki/List_of_U.S._state_flowers).

If you have any questions, please don’t hesitate to leave them in the comment section below.  I am very busy, so please do not get upset if it takes me a couple days to review and respond to your comments.  Thanks.

 

 

Starting the Project

Now that we have an idea of what we want, let’s jump in.  Create a new project in Eclipse.  I will skip these steps and assume that you have already created several projects before.  Once we have the project created, add the images supplied in the .zip file to one of your drawable-*dpi folders.  Add the states_flowers.txt to your assets folder (if you don’t have an assets folder, create one).  Now we are all set with the content portion of the tutorial.

Reading in the Content

It is always good practice to have Models (always remember MVC, Model-View-Controller) for any data items we wish to program.  For this tutorial, I created a model StateFlower which is shown here:

package com.justcallmebrian.stateflower;
 
import android.content.Context;
 
public class StateFlower {
	private String state;
	private String flowerName;
	private String flowerImage;
 
	public StateFlower(String state, String flowerName, String image) {
		this.state = state;
		this.flowerName = flowerName;
		flowerImage = image;
	}
 
	public String getState(){
		return state;
	}
 
	public String getFlowerName(){
		return flowerName;
	}
 
	public String getImageString(){
		return flowerImage;
	}
 
	public int getImageResId(Context context){
		return context.getResources().getIdentifier("com.justcallmebrian.stateflower:drawable/" + flowerImage, null, null);
	}
}

 

 

Content.tar
As you can see, it is a simple class that will hold the data needed for the application.  Once we have that, we need to read in the data, and store it into some sort of Array (I used ArrayList for simplicity).  Although, the reading of the file will probably be better situated in a Controller object, I included it in the main Activity class for simplicity.  The following code will read in the file:

    public ArrayList readFile(){
    	ArrayList retval = new ArrayList();
    	BufferedReader br = null;
		try {Log.d("Reading File", "Opening states_flowers.txt");
	    	br = new BufferedReader(new InputStreamReader(context.getAssets().open("states_flowers.txt"))); //throwing a FileNotFoundException?
	    	Log.d("Reading File", "Opened states_flowers.txt");
	        String word;
	        while((word=br.readLine()) != null) {
	        	String[] tmp = word.split(",");
	        	StateFlower newFlower = new StateFlower(tmp[0], tmp[1], tmp[2]);
	        	retval.add(newFlower); //break txt file into different words, add to wordList
	        }
	        Log.d("Reading File", "Retrieved " + retval.size() + " states");
	    }
		catch (FileNotFoundException fnfe) {
			fnfe.printStackTrace();
		}
	    catch(IOException e) {
	    	e.printStackTrace();
	    }
	    finally {
	    	try {
	    		if (br != null)
	    			br.close(); //stop reading
	    	}
	    	catch(IOException ex) {
	    		ex.printStackTrace();
	    	}
	    }
    	return retval;
    }

Now we just need to call this method in the onCreate of the function of your Activity.  Also, the function uses a Context variable that needs to be set before entering the method: “context = this;” will also need to be declared in the onCreate (see onCreate method under Building Custom Adapter section below).

Now if we run the application, we should see in the logs that all 50 states were read in (readFile is using Log.d to write to LogCat).  Uh-oh, FileNotFoundException?!?!  Before you throw your computer across the room, this is simply because you need to set the assets folder as a source folder for the project.  To do this, right-click on assets, and then click on Build Path->Use as Source Folder.  Try running again.  Woohoo! It read in the file, now let’s move to actually displaying some results to the screen.

Building Custom Adapter

Since we are building a Custom Layout, it makes sense that we will need a custom adapter to view each line item.  To do this, we first need to describe (via xml) the layout of each line item (although this can be done in code, it is much easier to just use an xml layout).  Right click on layout under res, and choose New->Other.  Choose a Android XML Layout and give it a name (I named mine state_item.xml).  The following my xml file in it’s entirety:

 

This gives us a look of the State string on top of the flower name, with the image of the flower to the right.

Now that we have the layout, let’s build the Adapter.  Create a new class that extends ArrayAdapter<StateFlower>.  Since we will need the Context on which it is drawing, we need to include it in the constructor.  I also included the ArrayList<StateFlower> as well (although if I used a Controller, I would not have had to do this, since I would be able to obtain it from my controller).  There are three important functions to override here: getCount, getItem, and getView.  All of these are depicted below:

	@Override
	public int getCount() {
		return items.size();
	}
	@Override
	public StateFlower getItem(int arg0) {
		return items.get(arg0);
	}
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View List;
		if(convertView==null){
			List=new View(context);
			LayoutInflater mLayoutinflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			List=mLayoutinflater.inflate(R.layout.state_item, parent, false);
		}
		else{
			List = (View)convertView;
		}
		TextView nameText = (TextView)List.findViewById(R.id.stateNameTextView);
		nameText.setText(items.get(position).getState());
		TextView flowerText = (TextView) List.findViewById(R.id.stateFlowerText);
		flowerText.setText(items.get(position).getFlowerName());
		ImageView flowerImage = (ImageView) List.findViewById(R.id.stateFlowerImage);
		flowerImage.setImageResource(items.get(position).getImageResId(context));
		return List;
	}

The big thing to notice here, is that the View for each line item to be displayed is contained within getView (duh!).  We create a LayoutInflater with the resource id of the layout xml we created earlier, and then we get and set the attributes of each StateFlower based on the position (index) of the view the list is trying to draw.

OK, now we got our Adapter, so we can go ahead and click Run and see the results?  Not quite yet.  We still haven’t set the ListView in our main layout to the adapter we just created.  To do this, we simply need to use the setAdapter method and it takes care of the rest.  Below is my whole onCreate method for my Activity:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        context = this;
        list = readFile();
        ListView listView = (ListView) findViewById(R.id.stateList);
        listView.setAdapter(new StateFlowerAdapter(context, list));
    }

That’s it! You’ve done it. Click run and see the results of your finished work (or you can just look at the screenshot):

Custom ListView Android

Pretty simple, yet it sure beats the Default ListView of with just the name of a State!

Final Thoughts

I have separated the project files into two files, the content (images and states_flower.txt) and the code.  I did this for the sole purpose of letting people try to work from start to finish on building their own custom List View on their own instead of just taking prewritten code and compiling it.

Ready for custom filtering? Look at the second part of the tutorial: Building Custom Lists using ListView on Android Tutorial – Part 2

Again, if you have any questions and/or comments, please let me know.  I am always willing to help!

Likes the tutorial? Show it by donating and helping a great cause. All donations are made to Maryland Special Olympics:

Content.tar
Code.tar

Armando Galarraga’s One-Hitter

I have been reading several people comments on what should come of this call. These people are completely irate (which they should be as a fans of baseball) about the call Jim Joyce made in the ninth inning, however, I do not believe there should be a reversal of the call simply because the human element is part of baseball. Bad calls are made daily all around baseball (and all other sports as well). Most don’t affect the game to much, some bring huge swings into the game, and some, like this one, change history. Every one knows that Armando pitched a perfect game, including Jim Joyce, but the scorecard still reads 1 hit and that’s the way it should stay. If this call occurred in the first inning, it would probably make 10 seconds on ESPN, but since the call was made as the last out, it will be the most talked about call for the next couple of weeks.

Many people believe Bud Selig should reverse the call, stating that it was the last out and the only affected would be Donald (the one who was the beneficiary of the hit). I do not believe that any calls should be reversed for any reasons after it has been made. If we want perfect officiating, we can move to more advanced computerized umpiring. The technology exists where the umpiring can be all computerized so calls will be made correct 100% of the time and completely rid the game of human umps.

As far as Jim Joyce is concerned, I don’t think he will ever be able to umpire again. Not because he will get fired (because he definitely won’t and really doesn’t deserve to be fired), but because he will always be second-guessing his calls from now on. It will take a while for him to gain back his confidence when making calls.

This post probably pissed many people off, so let’s hear it. Tell me why out of all the bad calls made in the history of the MLB, why this one should be reversed? At least we can agree on knowing this game will certainly go down in MLB history (whether Bud Selig reverses the call or not).

Using AlarmManager to Schedule Activities on Android

Looking for a new mobile advertising platform? Check out my blog post on the new solution I am using (or sign-up if you don’t want to read the post)

 

Sometimes, it may be necessary for your android app to complete a task sometime in the future.  In order to do this, you must schedule an activity (can also be a service) to be run using Android’s AlarmManager.  This post will show:

  • How to set up a receiver for the scheduled event
  • How to create an activity from this receiver
  • Using the AlarmManager and the created classes to successfully receive and process a scheduled event

Want the code? Get the source for only $1.49 (50% off). Click the button below to buy now:

Creating a BroadcastReceiver

The first thing you will need is a receiver to receive the event.  There are several key aspects to have for the receiver to work properly.  First create a class that extends BroadcastReceiver and override and implement the necessary onReceive(Context context, Intent intent) method.  The following is a basic example using a Toast message:

package com.justcallmebrian.alarmexample;
 
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import android.os.Bundle;
 
public class AlarmReceiver extends BroadcastReceiver {
 
 @Override
 public void onReceive(Context context, Intent intent) {
   try {
     Bundle bundle = intent.getExtras();
     String message = bundle.getString("alarm_message");
     Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
     Toast.makeText(context, "There was an error somewhere, but we still received an alarm", Toast.LENGTH_SHORT).show();
     e.printStackTrace();
 
    }
 }
 
}

In the previous example, we are simply just printing out the message supplied by the String passed in under the name of alarm_message.  For those who are not familiar with Toast, it is basically a short and quick message given to the user.  Here you can find more information on Toast.

 

 

Besides actually creating the class to receive the event, you must also declare it within AndroidManifest.xml.  The following is the line that should be added before the closing of the application tag (before </application>).

 

Basically this states that the class AlarmReceiver is available and will start a private process.  Once that is done, your BroadcastReceiver is ready to go.

Setting up an Event using AlarmManager

In order to receive an event, you obviously must schedule the event.  There are three ways of scheduling an event (a one time event using the set method, a repeating event using the setRepeating method and finally using the setInexactRepeating).  This tutorial will cover the one time alarm using the set method.  For more information regarding the other events, you can view AlarmManager. The following code snippet will get the AlarmManager and set an event to occur 5 minutes from the current time:

 // get a Calendar object with current time
 Calendar cal = Calendar.getInstance();
 // add 5 minutes to the calendar object
 cal.add(Calendar.MINUTE, 5);
 Intent intent = new Intent(ctx, AlarmReceiver.class);
 intent.putExtra("alarm_message", "O'Doyle Rules!");
 // In reality, you would want to have a static variable for the request code instead of 192837
 PendingIntent sender = PendingIntent.getBroadcast(this, 192837, intent, PendingIntent.FLAG_UPDATE_CURRENT);
 
 // Get the AlarmManager service
 AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
 am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);

This code snippet basically obtains a new Calendar object and adds 5 minutes to it.  An Intent is created with the AlarmReceiver which we created earlier.  The more important piece of the code is setting the FLAG_UPDATE_CURRENT flag.  Without this flag, the message being passed as an Extra will be lost and not obtained by the receiver.

With these code snippets you should be able to create and run some tasks in the BroadcastReceiver.  However, sometimes you may wish to start a new activity (or service) on the alarm event.  In order to do this, you would want to have the AlarmReceiver create and start the new Activity.

Starting an Activity from BroadcastReceiver

Starting an activity within a Receiver has an extra flag that is needed.  We will change the previous onReceive for AlarmReceiver to get this done:

 @Override
 public void onReceive(Context context, Intent intent) {
   try {
     Bundle bundle = intent.getExtras();
     String message = bundle.getString("alarm_message");
 
     Intent newIntent = new Intent(context, AlarmActivity.class);
     newIntent.putExtra("alarm_message", message);
     newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     context.startActivity(newIntent);
    } catch (Exception e) {
     Toast.makeText(context, "There was an error somewhere, but we still received an alarm", Toast.LENGTH_SHORT).show();
     e.printStackTrace();
 
    }
 }

Now you would only have to create the new AlarmActivity as you would do any other Activity.  Don’t forget to include the newly created activity in the AndroidManifest.xml file.

Want the code? Next 1000 people will get the source for only $1.49 (50% off). That’s the whole project (source, resources, xml files, etc) for only $1.49. Click the button below to buy now:

Likes the tutorial? Show it by donating and helping a great cause. All donations are made to Maryland Special Olympics:

Just Another “Fire Jerry Manuel” Post

There are so many fire Jerry Manuel post’s out there so I decided to throw up my own reasoning on why Jerry Manuel is not right for the Mets.

He brings absolutely no fire.  He always seems like he is about to fall asleep every game.  His style of managing clearly isn’t working with this bunch of guys.  Only ten games into the season and the team already looks unmotivated and it just feels they are just going through the motions.  There has been several terrible baserunning miscues already this year, with the most important one being Tatis getting thrown out at the plate for the last out of the inning with David Wright up.  This is just fundamental baseball here, never even chance a third out at the plate with a good hitter up unless you are 100% positive you will make it.  Did Tatis get benched at least a game for this?  No, Jerry just said “oh well” and starts him at first base the following day.  I am not a fan of managers yelling at the players, but sometimes it is called for so they learn.

Jerry makes some of the most interesting lineup choices.  Gary Matthews Jr. is getting the majority of the playing time in CF?  Are you kidding me?  Angel Pagan is a much younger player in the prime of his career.  Both players have split the position starting 5 games each, but why even have Gary Matthews Jr. play that much?  Not anything against Gary Matthews Jr., but Pagan in my opinion is a better fielder and a more reliable bat in the lineup, not to mention 8 years younger and has many potential years ahead of him.  I believe he also relies too heavily on pitch counts when deciding whether to take a pitcher out.  Never in my life have I seen a manager take out a pitcher who was as dominant as Oliver Perez was tonight to be taken out because he gave up a infield single and a sacrifice bunt in the seventh inning.  Sure he threw 97 pitches, but at least you can let him try to finish out the 7th with the shutout in tact instead of bringing in a couple of no-name relievers that end up hitting a man, walking a man and then giving up a grand slam (giving up by Raul Valdes, a pitcher who was signed as a free agent and is playing in his first year in the MLB).  It is not just tonight that this has happened, any time a pitcher nears that 100 pitch count (no matter what the circumstances are) he will get pulled.  Johan Santana was pulled mid-inning so many times last year that ended up costing him the win, and sometimes gave him a loss because the bullpen just didn’t get the job done.

Lack of fundamental knowledge (or at least lack of playing fundamental baseball).  The National League is much different than the American League and stealing bases and bunting is a big part of the NL game.  So many times I have seen nobody out and a runner on second, and instead of bunting the man over to third, Jerry will opt to let him swing away, usually leading to an out and no advancement.  There is no manufacturing of runs under Jerry Manuel, instead its all about scoring on hits alone.

And finally, actual win-loss percentage is terrible.  They are not playing the way a team with the 5th highest payroll should be playing (2nd highest last year).  A lot of this can be directed towards the players, but I feel it is the manager’s job to get them fired up and excited to play day in and day out.  Jerry Manuel and his laid-back behavior does not do this and most of these players seem they don’t care if they win or not.  Jerry Manuel’s record with the Mets so far is 128-137.  That’s right, under 500 winning percentage.  I don’t know many managers who can keep his job for as long as he has (even though it has only been one full season) with that kind of performance and the amount of talent on the team.

So who is my favorite choice to replace Jerry if (I mean when) he gets fired.  The one that comes to mind that every Mets fan will love to see is Bobby Valentine.  I know there is a lot of bad blood between the Wilpons and Bobby V, but bringing back Valentine (that is if he wants to come back after the way he was treated the first time) will mean a lot to the fans of the Mets.  It will bring excitement back into Citi Field and hopefully will transfer to the players.  There’s no denying that Valentine was successful with the Mets.  Look at the starting lineup he brought to the World Series in 2000:  Benny Agbayani, Edgardo Alfonso, Mike Piazza, Todd Zeile, Robin Ventura, Bubba Trammell, Jay Payton and Kurt Abbott.  Side-to-side comparison, the 2010 Mets are a much better team on paper, yet playing no where near the same level that team played.  If I was the Wilpon family, I would say bury the hatchet and go after Bobby Valentine, for the sake of Mets fans everywhere.

In any case, do us all a favor and get rid of Jerry Manuel before it is too late.

Detroit, MI and the Frozen Four

Frozen Four

I spent the past weekend in Detroit to watch RIT’s first game at the Frozen Four.  It was a bit disappointing to see them lose 8-1 against the Wisconsin Badgers, but it was a great experience.  Throughout the weekend, I heard many people stating that RIT showed that they don’t belong in the Frozen Four, but I completely disagree.  RIT beat the Denver, second ranked team in the nation, and the University of New Hampshire to make its way to the Frozen Four.

The semifinal game was lost early on with too many penalties including a 5 minute major where Wisconsin scored two of their goals (with 5 on 3 action).  RIT is predominantly a defensive team and with such a team, it is hard mentally to swallow being down more than a couple of goals.  I liked that Coach Wilson was generous enough to put in both backup goalies so they can also get playing time in what was the biggest game of RIT hockey history.

The weekend was full of one-sided victories.  All three games were decided by at least 5 goals, which didn’t make much for very exciting and nail-biting hockey.

The Fans

I was actually surprised by the lack of support other teams’ fans were giving to their team.  It was shocking that the loudest fans during the Championship game were the RIT fans that were mocking the fans of both Boston College and Wisconsin.  It got to the point that Wisconsin fans actually came over to the Corner Crew asking for their help in between the second and third intermission.  It is sad that they needed to ask for help from a section of probably around 300-400 RIT fans to help cheer on the Wisconsin team that clearly had many more fans throughout the arena.  The RIT fans left such a presence in the championship game that it was mentioned during the ESPN broadcast and several media articles covering the game.  One of the biggest cheers that got the most laughter and applause from surrounding non-RIT fans was “That’s all right, that’s OK, you’re going to work for us one day!”.  Even towards the end of the game, several Boston College fans starting chanting RIT along with the Corner Crew.

The City Of Detroit

Definitely signs of tough times in Detroit with almost every other store was out of business.  While talking to some locals, they kidded around by saying “you should have seen 3 years ago, when everything was out of business.”  Even though there was many people affected by the downturn of the economy, they didn’t act it.  The streets were packed all day with Tigers fans (Detroit’s home opener was on Friday afternoon) and the city put together a festival across the street of Comerica Park with live music, vendors and games.  The people of Detroit love their sports which was evident by the many stores and street stands that sold sporting apparel and merchandise (those were practically the only stores that remained open besides bars and restaurants).

By far my favorite place in Detroit was this little strip known as Greektown which is made up of a bunch of Greek restaurants (I ate on this street for 4 of my meals).  The food there was fantastic and for a pretty decent price.  Greektown seemed to be the place to be no matter what time of day, and I recommend it to anyone traveling to Detroit.

Wine and Food Pairing – 3 Week Update

The app has been on the market for 3 weeks now, and I am impressed with the number of uses and downloads.  The number of downloads have been dramatically increasing the past couple of days, well over 100 downloads each day as opposed to the usual 50 downloads each day (after the first couple of days the downloads dropped).  Here are the stats for the ad-supported app as of earlier this morning:

1938 total downloads, 1641 active installs for an 84.67% active install rate.  I am very happy with the percentage of active installs as it shows how many people find the app useful and plan on using it in the future as opposed to a single use application.

The usage of the app has dramatically increased as well.  When the app first started, the average usage was 2 times per active user, but that is now up to 5.8 times per active user.  It was used the most yesterday at 906 times.  Today, the app has already been used 435 times, so it has a good chance of beating yesterday’s mark.

Keep the suggestions coming regarding future enhancements.

Software Patterns in Web Development

Over the last couple of years I have witnessed thrown together php code that is impossible to understand what is going on without spending hours reading through the code.  I get same response is given every time I ask why not separate into more readable and maintainable way: “It doesn’t matter as long as it works”.  That may be true for small, personal websites but the furthest from the truth when dealing with company websites that may have multiple developers and will get passed on long after the initial developer is gone.  By developing with the attitude as long as it works, it usually leads to more money wasted whenever a new feature or a bug fix needs to get done.  Here are some hints that can be easily done to help improve your site.

DatabaseController

Almost all dynamic and functional websites will connect to some form of a database in one way or another.  It is always a good idea to have a Controller object that deals with all connections to the database.  This subsystem (could be a single file or a group of files) that will act as a single connection point for all database queries that need to be run.  By abstracting out these functions into a separate file will allow for quick changing of database server and name as well as easy modification of all queries (since there will be no searching through all files to find the query).  It also provides aspects of reusability where the result set of one database query can be used in several parts of the web application.

The following is an example of a basic Database Controller written in php 5 (adds object orientation features) with a MySQL database:

<?php
class DatabaseController {
 
 private static $instance;
 private $conn;
 
 private function DatabaseController(){
   $conn = mysql_connect('localhost', 'user', 'password');
   if (!$conn){
     die ('Could not connect: ' . mysql_error());
   }
   mysql_select_db("mydb") or die (mysql_error());
 }
 
 public static function getInstance(){        
   if (!self::$instance instanceof self){            
     self::$instance = new DatabaseController();
   }
   return self::$instance;
 }
 
 public function getRegisteredUsers() {
   $retval;
   $query = "SELECT name, user_id from users";
   $result = mysql_query($query);        
   while ($row = mysql_fetch_array($result)){                
     $retval[$row['user_id']] = $row['name'];
   }
   return $retval;
 }
 
 public function registerUser($name){
   $name = mysql_real_escape_string<code>(</code>$name);
   $query = "INSERT INTO users (name) VALUES ('$name')";
   $result = mysql_query($query);        
 }
}
?>

This is a template that can be used for all database connections.  Obviously it would be smart to group functions together.

Separate Static Content

Another important aspect of web development is having the same look and feel for every page.  This is used heavily in major CMS (such as WordPress), but I am still shocked with the amount of sites where I see copy and paste jobs.  The idea here is to separate all the static content that should appear on all pages away from the actual body of the page.  For example, create files for the header, footer, sidebars, navigation, etc.  The benefits here obviously are maintainability.  Changing one file is much easier than modifying all files within the system.  This will not only save money when these parts need changing, it will also make the code easier to understand for a new employee trying to learn the system.

Error Handling

Error handling is key when developing a reliable and user friendly web application.  Within error handling, you would want to be able to catch errors before it becomes a problem, and have a way of the application to correct itself.  The other key part is to notify the end-user of the error.  Error handling can also include logging of particular errors (having a variety of error levels like low to severe).  Like all the other things talked about so far, abstracting out the error handling allows for quicker modifications for the future.

Database Injection Prevention

This is not a pattern in itself, but just something that I am amazed still happens on live sites.  For those who are unaware of what SQL Injection is, Wikipedia explains it well.  Always double check all input for validity before running an SQL query.  There is a pre-built function for PHP called mysql_real_escape_string which will take the supplied string and make it mysql safe by adding an escape character (‘\’) before certain string combinations including an apostrophe.  By simply calling this function on all input provided, it significantly decreases the chances of an SQL injection attack.

Final Words

The last thing I can provide advice about is to follow the software life cycle (Requirements -> Design -> Implement -> Test -> Maintain) for your web application.  Like all software projects time spent nailing down the specification of what needs to get done, and having a robust design will save more time and money in the future.

The Power of Extension Methods in C#

So one of the most underrated and unknown features of C# is what is know as Extension Methods.  “Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type,” straight from MSDN.  The following post will describe what these extension methods are, how to implement them, and when is the proper time to use these methods.

First off, Extension Methods are just as the name describes them: methods that are extension points off of existing classes.  The power of this is shown by the following example.  Say your team/company is using a physics engine API where all the classes are sealed (no inheritance is allowed).  Now as newer and faster algorithms come out, there is no need to throw away the whole API for the few changes.  Instead you can use Extension Methods to add these algorithms to their appropriate classes without having to modify the original code or subclass.

The actual syntax of Extension Methods can look scary and awkward at first.  Take the following example:

public static String ReverseSentence(this String str){
    String retval = "";
    String[] words = str.Split(' ');
    foreach (String word in words)
    {
        retval = word + " " + retval;
    }
    return retval;
}

The following shows how you can call this method on a String:

    String sentence = "This is an example of Extension Methods in C#";
    String reverseSentence = sentence.ReverseSentence();

This quick example just reverses the sentence. The first thing you may notice is that the method is static, however this method can be called on a String object itself. Also, there is a parameter in the method declaration (this String str), but nothing gets passed in when using the method. Even though you call this method on the instance variable, the compiler will generate it as a static call to ensure these extension methods do not have access to private variables in the extended class (which would be a huge security issue).

Frederik Kalseth shows a couple examples of extending DateTime class here.

I hope this was an informative tutorial and shows how powerful Extension Methods can be.  Feel free to leave comments and/or questions.