Posts
60
Comments
36
Trackbacks
18
December 2008 Entries
Conditions in Java

Conditions in Java are a true/false representation of some case.  Some of the most popular places to see conditions would be if statements,  for, while, do..while  loops or boolean variables can also be declared with some sort of condition.  Here we look over a short excerpt of some of the ways you might see conditions in Java.

Note: Comparing variables in Java require the use of operands, which are different then math expressions.  Equals (=) makes a variable equal to the equivalent of the left side of the equation.  Operands would be (==) meaning "equals" which will test whether the two are identical or note, (<=) "less than equals" which tests whether one value is less than or equal, (>=) "greater than equal", (>) "greater than", (<) "less than", (!=) "not equal", etc.

Additionally, if you tack on a ! to the beginning of a condition, it returns true if the condition evaluates false.  The best way to say this in English is NOT.  If I see an exclamation, I just speak the word "NOT" out loud.  here:

if (!condition) {...}

I would speak this aloud as "if NOT condition"...

Basic if statement:

if (condition) {...}

Often you will see the condition being something similar to "(i == 2)" or "(text.equalsIgnoreCase("hello"))".  The basic rule here is that the condition statement must represent some boolean expression.  A boolean is either true OR false, therefore a condition is always true OR false.

Basic for condition:

for (int i = 0; condition; i++) {...}

Notice here, our condition is the middle of the for statement.  The right hand side of a Java for statement is the control, the left hand side tells Java what to do after every iteration of the for loop, and the middle is a condition.  To read this aloud in English, I might say:

"for i = 0 to condition, i goes up by 1 each time through"

Basic while condition:

while (condition) {...}

Here it is important to realize that if your condition is false, the {...} will never be executed.  Also, if entering your while loop with a condition of true, and to avoid a forever loop, you must reach a point at which this condition can be false inside of your curls {...}.

Basic do...while condition:

do {...} while (condition)

In a do...while, your code will always be executed once.  When we reach the while, if the condition evaluates to true then we will execute the block of code again starting at the do.

Some examples of conditions:

(i <= 10), i.e.

for (int i = 0; i <= 10; i++)
{
    System.out.println("Hello: " + i);
}
 
//Outputs
//Hello: 1
//Hello: 2
//Hello: 3
//...
//Hello: 10

(text.equalsIgnoreCase("hello"))

String text = "HELLO";
if (text.equalsIgnoreCase("hello")
{
    System.out.println(text + " equals hello, ignoring case");
}
//Output:
//HELLO equals hello, ignoring case
 
(!text.equalsIgnoreCase("hello"))
String text = "HELLO1";
if (!text.equalsIgnoreCase("hello")
{
    System.out.println(text + " NOT equals hello, ignoring case");
}
//Output:
//HELLO NOT equals hello, ignoring case

 

Here we have looked at conditions and loops.  Please feel free to leave additional questions in the comments section here.

Technorati Tags:
posted @ Tuesday, December 30, 2008 1:02 PM | Feedback (0)
Java Variable Declaration

When declaring variables in Java, there are certain pointers you will want to remember.  It may be natural to declare same type variables on the same line.  This is not proper programming technique as it decreases readability.  So what are Java variables?  Variables are a type or instance of an Object in Java.  For the easiest examples we can use int, String, char, double, etc as examples.  So here is how we do it:
Declaring an integer in Java (int):

int i;

Which is the same as:

int i = 0;

Breaking this down, the "int" means that this variable is an integer (a number without decimal). "i" is the variable name.  When using this variable later, we will refer to it as "i".  The default value is 0 for all integers which means you do not have to declare this (optional).  The "= 0" is the initial value of "i".  Again, if you want the default value, leaving off "=0" is acceptable for Integers.  Generally this rule is not appropriate with double, String or char.

Declaring a double in Java (double):

double x = 0.0;

Note that if you do not declare an initial value, doubles act more like integers.  If that is the intended behavior, an integer should be used.

Declaring a String in Java (String):

String text = "";

String text = new String(); //Produces the same result as above

This declares the initial string as a blank string. Please note that you can not use this variable until you have made it something other than a null object, so the '=""' would be the absolute minimum for a Java String value.

Notice the similarity between the second in this line

String and ObjectName (later in the post).  String is an Object in Java, a collection of chars.

Declaring a char in Java (char):

char letter = 'a';

If you are having issues declaring characters in Java, please note the single tics around the character in the reference.  Characters in Java do not use double quotes,  so watch out for this.

Declaring other Objects in Java (Objects):

ObjectName obj = new ObjectName();

I will go into this in a later post as well, but this is a basic object instance.  The new ObjectName() is calling the default cunstructor, i.e. public ObjectName() {...}.

For today, we have gone over variable declaration in minor form.  I see this error often while teaching introduction courses and feel that this may help some of those with issues surrounding the basics of declaring basic variables in Java.

Technorati Tags:
posted @ Tuesday, December 30, 2008 12:11 PM | Feedback (0)
Tips When Flying

Flying can be a very convenient way to travel long distances over short periods of time.  For instance, if you want to go from Seattle to St. Louis, there are a ton of options.  I have a lot of family in Richmond VA and amazingly there is a direct flight from Virginia to St. Louis respectively (RIC) to (STL) and back.  Recently, there was a family member that (while attempting to pinch pennies) grabbed a flight that was indirect to save 20 dollars (per round trip) for two flights.  So basically, $20 per trip * 2 trips, which is $40.  What was the catch?  They had one stop for 220 and non-stop for 240.  They of course chose the one-stop option which left them stranded in Detroit (ice storm, delay, etc.).  They ended up having to fly to Raleigh and catching transportation on the ground from there (90+ miles).  It was an entire day to do this.  To make a long story short, they could have driven much faster from here to there (and cheaper) to avoid this mayhem.  What are some other things they could have done?  Gone direct!  Pay the extra $40 dollars and go direct!  So here are my tips.

  1. When at all possible, purchase a direct flight.
  2. Second option is to purchase a continuing flight (where the flight stops, but the traveler doesn't need to get off of the plane).
  3. If option 1 and 2 isn't available, try to separate your lay-overs enough to minimize missing a connection.  30 minutes is NOT enough, so make it at least 1.5 hours.  Most of the time, this makes for some downtime; but it is a lot less convenient than sitting in an airport overnight or ALL DAY because you were stuck in transit.
  4. If you do get stuck and it is the airlines fault, do NOT let them tell you there is nothing they can do.  Be polite, but demanding and you will get some benefit for the inconvenience.
  5. Finally, devise a back up plan before you leave to figure out what you may do IF you actually miss a connection.  Don't leave your options only to the airline that has messed up your schedule; see what other airlines may be able to connect you (American can cross-reference South-West, and vice-versa).  If you do this research ahead of time, it may make for a better chance at making your destination in a more timely manner.

These tips are basic, and while there is not always a direct flight there may be options to minimize your frustration.  The one thing to remember is that being a mad, angry jerk is never the answer to your frustrations.  Polite and demanding is a better way to get what you want.

posted @ Monday, December 29, 2008 2:17 PM | Feedback (0)
To All, a Merry Christmas

I wanted to take a minute and mention to anyone that reads my Blog a wonderfully Merry Christmas.  Soon, Santa will be coming by and filling many kids trees with Christmas presents (if he hasn't already) around the globe.  While things may get tense tomorrow (maybe you didn't get what you want, or he got more than she did, or whatever), it is important to remember the significance of what tomorrow really is.  It is a time to celebrate with your families (so close your browser now), celebrate life as we know it here on Earth, afforded to us by one man many years ago in the Lord, Jesus.  This is his birthday, and lets show him how much we love him by getting together with someone else and saying a prayer in his name thanking him for all that we have to celebrate (in his name) today, and God bless.

I need to get in the sack now so Santa can come by.  It is 1:38 my time and I am thankful that he is running late.

posted @ Thursday, December 25, 2008 1:39 AM | Feedback (0)
Err to Readability or Speed

Here is my question of the week.  For those of you that don't know me, I program in CSharp professionally and I teach Java at the University level.  Recently I have been torn between two facts:

  1. Code for maintainability, in which even the average Joe could probably go in and figure out what is going on.
  2. Code for speed, where it is often confused because I want it to go really fast; who cares about Overpaid Joe?

I am a big fan of both.  I love fast, reliable, well written, maintainable code.  So is there a fall off in speed or performance when I program?  Given the fact that I am programming in Java and C#, then I guess there is.  After all, if I wanted the fastest, wouldn't I use C or C++?  If I really sit down to think about it I think I want to be able to code stuff fast, with a scalable fall back on speed (libraries are good).  I want code that is maintainable and easy to read, since I even forget what I was doing 3 or 4 days later (err. Poor Documentation?).  I want Object Oriented for the much needed data abstraction and awesome organization.

I hope ASP.NET MVC deadens the CF crowd.  I really don't think it belongs in the Enterprise world.  CF is a bear to deal with, and all of the XML type syntax...

posted @ Tuesday, December 16, 2008 12:35 AM | Feedback (0)
String Extension CSharp

For those wondering what extension methods are:  they are an easy portable way to extend functionality of a class that you are using.  I have used them to extend HtmlHelper in .Net MVC (See the post where I create a submit button using these Extension Methods on HtmlHelper), I have also used them to automate some of the overhead of using the Microsoft AJAX ControlToolkit with MVC.  Past that, there are many other "Code Practices" that could make knowing these very easy.  I was just toying with (for practice) creating extension methods because I really want to understand this in full.  This is a small example of it in a Console application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace StringExtensionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
 
            Console.WriteLine("Input "
                +"String to print backwards: ");
            var demo = Console.ReadLine();
 // Regular string calling the extension method (Below)           
            Console.WriteLine(demo.Reverse());
 
            Console.ReadLine();
        }
    }
 
    public static class StringExtension
    {
        public static string Reverse(this string str)
        {   //Just reverse the string however you want.
            var Holder = "";
            for (int i = str.Length - 1; i >= 0; i--)
            {
                Holder += str[i];
            }
 
            return Holder;
        }
    }
 
}

The first method is the main() method.  This just simply does things using the console window.  The second is the custom Reverse() method that I call to reverse the string.  As you can see, this is a really powerful feature and much easier to implement here than any other languages I have seen.  There were lots of warnings around the web that indicate that you should be very careful not to over do this when using these Extension methods in CSharp.   Here is a picture for anyone that is wondering how this should work.

12-12-2008 3-25-24 PM

posted @ Friday, December 12, 2008 3:26 PM | Feedback (0)
Today's Interesting Readings

Welcome to my technical readings.  I may not post everything I run across but would most certainly try to post some of the more interesting posts for your reading enjoyment.  So here they are, enjoy them.

  1. Google's Native Client - the following article was an interesting read on Google's new Native Client NaCl.  I continued reading several discussion forums on it and feel that this is amidst of a political battle.  I think that if anyone can take on something that has that many implications then Google is probably the right company.
  2. Facebook Connect Live Sites - If you want a good laugh, scroll down to Vimeo; they have a solution from what looks like an issue on the site.  I think it is funny that they list this site as one of them being it doesn't work.  I wonder if I were to put my site up with a whole bunch of bad API calls if they would recommend and fix them for me whilst advertising it for me too!
  3. I looked for the 3rd, but have reached the end of the internet!
posted @ Wednesday, December 10, 2008 6:55 PM | Feedback (0)
This Was a Journey

In this, my first real personal blog, I will say that I am extremely impressed with what I have been able to do with ASP.NET, Subtext and a few other technologies here and there.  One of the biggest accomplishments here is how easy it is to post blogs and how well the performance of the website has done to this moment.  Thanks for paving this road you guys over at Subtext

You may notice that there are already 8 blogs turned on (several of them were) posted from a previous weblog but ported using Live Writer (and how simple it was).  I guess the entire reason that I have chosen to use Subtext is because I read Haacked saying that they were going to move this to ASP.NET MVC and that is where I would like to start volunteering what little expertise I may have towards helping their team complete the 3.0 upgrade endeavor.

What I plan on gaining from my experience is pretty simple:  I want experienced feedback on what I develop, I want to develop with the best, I want to join the best, and finally I would hope to learn more than I am currently.  Let's hope that they pick up on this and I guess to start I will start writing some documentation.

What was the personal note again? 

posted @ Tuesday, December 09, 2008 8:02 PM | Feedback (0)
ASP.NET HTML Extension (Submit Button, Reset Button & Button)

I sat down reading one of Stephen Walther's blogs and noticed that he mentions a way to create extensions and talks about ordered lists and unordered lists.  At the top, he had mentioned something that I had taken interest in.  He said that a potential use is for a Submit Button, so when I couldn't find something that had already been created out in the world I decided to write my own.

Some of the considerations I looked at while making this include:

  • The easiest method possible
  • Least amount of code
  • Want to do all Submit, Reset and plain Button HTML Extension Methods
  • Wanted each method to have the ability to add JavaScript and/or additional attributes in a manageable and easy way
  • Wanted it to be bloggable and easy to understand

First things first.  Here is the web page that I started off reading to get a basic understanding of what I was doing, Thanks to Mr. Walther.

Design Decisions, I put the helper into a folder called Utils and named it HtmlExtension since effectively what I am doing is extending the HTML functionality that is already built in the System.Web.Mvc.Html methods.  I decided to import it at the top of the .aspx page because there is only one page (with any buttons) right now in the current system I am writing.

  1. Right Click your project name
  2. Select Add -> New Folder
  3. Name the Folder whatever you would like (I used Utils)
  4. Right Click on New Folder
  5. Select Add -> Class
  6. Name the class (I used HtmlExtension)
  7. Add the following code
    • using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;
      using System.Web.Mvc;
      using System.Text;
      using System.ComponentModel;
       
      namespace Names.Util
      {
          public static class HtmlExtension
          {
              // Methods
              public static string Button(this HtmlHelper helper, string value)
              {
                  return ("<input type=\"button\" value=\"" + value + "\" />");
              }
       
              public static string Button(this HtmlHelper helper, string value, object htmlAttributes)
              {
                  return ("<input type=\"button\" value=\"" + value + "\"" + HtmlAttributes(htmlAttributes) + "/>");
              }
       
              private static string HtmlAttributes(object htmlAttributes)
              {
                  StringBuilder builder = new StringBuilder();
                  foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(htmlAttributes))
                  {
                      builder.AppendFormat(" {0}=\"{1}\" ", descriptor.Name, descriptor.GetValue(htmlAttributes));
                  }
                  return builder.ToString();
              }
       
              public static string ResetButton(this HtmlHelper helper, string value)
              {
                  return ("<input type=\"reset\" value=\"" + value + "\" />");
              }
       
              public static string ResetButton(this HtmlHelper helper, string value, object htmlAttributes)
              {
                  return ("<input type=\"reset\" value=\"" + value + "\"" + HtmlAttributes(htmlAttributes) + "/>");
              }
       
              public static string SubmitButton(this HtmlHelper helper, string value)
              {
                  return ("<input type=\"submit\" value=\"" + value + "\" />");
              }
       
              public static string SubmitButton(this HtmlHelper helper, string value, object htmlAttributes)
              {
                  return ("<input type=\"submit\" value=\"" + value + "\"" + HtmlAttributes(htmlAttributes) + "/>");
              }
          }
       
      }
  8. Then add the import to your .aspx page
  9. <%@ Import Namespace="Names.Util" %>

     

That's it.  To reference your  new extensions, use

<%= Html.SubmitButton("Button Name") %>

 

To use attributes on your new Buttons, try

<%= Htme.SubmitButton("Button Name", new { onclick="SomeJavaScriptMethod()" } ) %>

Here is one example that shows how I use it.  In the index.aspx page, I have this:

<%= Html.SubmitButton("GO", new { onclick="TryThis();"} ) %>

The corresponding view source on the produced Html page shows:

<input type="submit" value="GO" onclick="TryThis();" />

I actually threw this together real fast and see quite a bit of room for improvement.  Let me know what you think or if you decide to use this.

 

Technorati Tags: ,,
posted @ Tuesday, December 09, 2008 5:21 PM | Feedback (2)
Facebook, Twitter & LinkedIn Updated

I recently updated the information contained in these "sites".  It is semi-annoying to have to go into each and everyone of them to update everything every time anything changes.  Are there any aggregator services out there that can keep all of my information in Sync I wonder.  Anyway's, here are the links to my profiles.

 

Jeff Ancel's LinkedIn

Jeff Ancel's Twitter

posted @ Tuesday, December 09, 2008 3:16 PM | Feedback (0)
Subtext and Tagcloud (Tag Cloud?!)

Well I am becoming a big fan of Subtext as far as a personal blogging system.  I have yet to look at what I am going to do for my commercial adventure, though I am sure there is more to come on that.  For those that are wondering, I am trying to figure out the easiest way to have full control of my content and maintain a blog VERY Easily.  Subtext seams to be the right approach so that is what I use here.  I was looking for a solution to my Tag Cloud endeavor though. 

How do I enable and set a tag cloud through this interface? 

Well the answer came on the second day and it was as easy as clicking the Insert Tags from the insert menu on the right hand side of Live Writer (See Pic).  This automatically configures and adds your Tag Cloud for you to your blog.  The most important thing is that it works fabulously and it is extremely easy to add tags.  I just wish Live Writer would allow a clickable list of recent Tags for clickable inserting since most of my blogs are about similar things.

12-8-2008 4-25-39 PM

Technorati Tags: ,,,
posted @ Monday, December 08, 2008 4:27 PM | Feedback (1)
ASP.NET MVC Return User to Previous Link when Registering

So I was playing around with the Login and Sign up links in ASP.NET MVC with the Membership Provider included. I really liked it (and it was easy to understand how to use the Login feature of ASP.NET Memberships). You simply send the user to /Account/Login/?---Return path goes here---. To do this, I used this code here:

/Account/Register/?ReturnUrl=<%= HttpUtility.UrlEncode(Request.FilePath.ToString()) %>#comments

One of the issues with this is that I want the users to be able to sign up as well and be returned to the previous page. This serves many purposes. First and foremost, it’s a blog and the user may not want to navigate back to the section in which they wanted to comment OR perhaps they don’t even know. So I dove in to see if I could produce this behavior which I did with little or no problem.

Plugging in a ReturnUrl so when a user signs up for the first time, they are returned to the page in which they clicked the sign up link.

  • From the page you are sending them to sign up from, put the above link into the href=”” field.
  • Change Login to Register, you should now have something that looks like: (note: the #comments is specific to my application)
    • <a href="/Account/Login/?ReturnUrl= <%= HttpUtility.UrlEncode(Request.FilePath.ToString()) %>#comments">Login </a>
    • Then browse to your account controller and find the method Register.
  • Modify the default line to bring in (string returnUrl) <- Goes inside of the currently empty parenthesis directly following the word Register.
ModifyRegister
  • Insert this before the return View()… if (!String.IsNullOrEmpty(returnUrl)) ViewData["ReturnUrl"] = returnUrl;
  • Just below that, you should see another Register, and you will also want to tack on , string returnUrl to the end of the variables that they are already passing in.
ModifyRegisterPostBack
  • The below picture shows you where you will want to insert the next if statement, and then one more step
RegisterPostBackIfStatement
  • Now navigate to Views/Account/Register.aspx and insert a hidden field (see below) somewhere inside the form tags of that page

In the above picture, the response write that you need is ViewData["ReturnUrl"].

RegisterFormChange

Now test it out and you should have a fully functional (and optional) returnUrl included in your Register module. I appreciate any “Code Reviews” in the way of comments, so if you found that this was useful, please feel free to leave comments here!

 

posted @ Saturday, December 06, 2008 11:29 PM | Feedback (3)
Using ASP.NET MVC Beta With GoDaddy

Well I was on the phone with GoDaddy (woohoo) after uploading my ASP.NET MVC Site that I had just created. The issue is that I created this at a time in which MVC requires SP1, or at least the libraries from SP1. So how do you get around it? Here is the error:

Could not load file or assembly 'System.Web.Abstractions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.

To skate the issue (GoDaddy wouldn’t upgrade their servers for just me, but I did ask), I used a technique that I ran across somewhere along the way. In my References folder of my project I focused on each and every (sure this wasn’t the best way to do it) DLL that was referenced and in the Properties window of that DLL I Changed “Copy Local” from False to True. Next time I refreshed, the website worked perfectly. Here are some of the websites that I ran across along the way. I am sure one of them, you will see a reference to this solution!

Technorati Tags: ,,,
posted @ Saturday, December 06, 2008 11:23 PM | Feedback (3)
Godaddy and Subtext Fairly Simple Install

So I decided to load Subtext for my personal blog.  I did it with Godaddy.  The entire Godaddy install for Subtext was fairly simple in that there were little or no modifications necessary to the setup and I was able to load Subtext into my base directory so there was no need for any base directory redirect or anything.  So here is what I did.  This post here will show you exactly what you need to do to get your blog running in GoDaddy.  Install Subtext on Godaddy.

1. Downloaded the latest install for subtext from their website.

2. Extracted the files to a location on my hard drive (the desktop).

3. Log in to Godaddy, I have a medium hosting account there (about 7 dollars a month).

4. Browsed to Hosting -> My Hosting Account.

5. Next to the account you want to install Subtext on, Click Manage Account.

6. Browse to Content -> IIS Settings.

7. Make sure Content Root is checked and Click the Advanced Icon above it.

12-6-2008 9-30-37 PM

8. Select Classic and then Ok. (It took about 30 minutes for this step to be completed on their side).

9. In the top again, select Databases -> SQL Server. (Install a database, make note of Username and Password).

After the steps above are no longer pending you are almost ready to go.

10. Get your connection string by clicking the icon in the picture (see below),

 12-6-2008 9-37-02 PM

11. Browse to the directory in which you extracted Subtext in earlier, Open the Web.Config in the root.

12. Use that information to fill in your connection string ( Please remove the square brackets when filling in [ ... ] ):

<add name="subtextData" connectionString="Data Source=[database host name];Initial Catalog=[Database Name];Uid=[Database User ID];Pwd=[Password]" providerName="System.Data.SqlClient"/>

13. Now use your favorite FTP Client to upload to GoDaddy.

After all of your files are loaded, browse to your web site and you are ready to setup your Blog. 

Technorati Tags: ,,
posted @ Saturday, December 06, 2008 9:54 PM | Feedback (0)
Using Windows Live Writer

So I redid my blog today, realizing that SubText would be releasing an MVC Version of the weblog, I decided that I would go ahead and get into it now.  It is most likely more powerful then my original blog that I wrote using ASP.NET MVC and I believe in typing as little as possible.  So there is one thing that I was extremely impressed with.  To get Subtext (2.1.x) to work with Live Writer, just:

  1. Point it at your blog's base directory
  2. Insert your Username and Password
  3. Click next or finish
  4. On the first publish, I put a small picture in it
  5. When you are prompted (after clicking publish), set up your FTP information
  6. Make a directory for your pictures
  7. Make sure your links point to that directory
  8. You are now off to the races

I was extremely impressed with the ease of this task.  Kudos to those that are doing Subtext.  They are definitely doing it right.

Technorati Tags: ,,
posted @ Saturday, December 06, 2008 9:08 PM | Feedback (0)
News
My Developer Notebook! This also happens to be my opinion place. Thanks for coming by.