Saturday, December 20, 2014

Use Javascript to upload csv file and chain replace method

Uploading the csv file was the easy part thanks to this code. (Just make sure you have appropriate code to display it since the author just uses console.log.)

Once the csv file was uploaded, my goal was to select certain rows and then, from those rows, select certain fields to display. We'll start with how the code to upload the csv file works.

Uploading the csv file:
Mounir Messelmeni's processData(csv) method takes the csv file you select as an argument and stores it in a variable as a string using split(). Once the string is appropriately split, the code then uses nested for loops to first split each record and then store each record as an element of an array. (You'll notice my code is slightly different regarding the separators I used.)

Regexp patterns
My problem was that I needed to access the individual fields within the records. That sounded a lot like accessing elements in an array, except I wasn't dealing with an array but an element in an array. Naturally, my first thought was to make each element its own array so I could access the fields as elements within the new array. You've probably already guessed the problem. When I created the new array and assigned an element to it, that didn't split anything up. I just had an array with one element.

I then considered separating each char and storing certain ones into an array and that array would then become an element in another array. That made me tired thinking about it. Plus, I still had the issue of figuring out how to target certain chars.

I also thought about saving the array element containing a record as a string, separating the string, and based on the separation, creating elements for an array. But I finally decided it was just easier to search for patterns. I am not claiming this is the best way, just that it is one way.

My code starts by storing lines.toString() in var x. I then create two patterns. (The csv file only contains 2 fields per record. For demonstrative purposes, text in both fields will be replaced.)

I also created an empty string, newstr which is then assigned the variable "x" with chained replace methods. The value of newstr becomes the value of the element with the id "list". I include an alert to show you the value of x before so you can compare that with the replace values.

The full code, including the csv file I used, is here.

Wednesday, December 17, 2014

Java command line

It's a basic concept, but it threw me at first. How do the command line and a Java program you wrote in an IDE interact?

First, the command line:
     a) Save your java file in a text editor as YourFile.java. Read this for more details.
     b) Get to the command line. If you're using Win8, for example, go to the Start menu and either type in "cmd" or use search and type in "command".
     c) On the command line itself, first change to the directory in which you saved your file. (See page I referred to above.)
     d) Set the path. The page referred to above addresses this but it didn't work for me. This is what worked for me. Proceed with caution.
     e) Compile by entering this at the command prompt - javac YourJavaFileName.java
     f) Run the interpreter by entering this at the next prompt - java YourJavaFileName command parameters
     ex. java InvestmentFile calculate .04 10 5000
    //calculate is the command;
   //.04, 10 and 5000 are the arguments

Entering the command: Just make sure the user knows which command to enter in the beginning and follow up in case they still enter the wrong thing.

if(user enters right command)
{//code}
else
{//tell them what to do or use a try-catch block instead}


Now, how do the parameters in the methods connect to the arguments on the command line?

Let's assume in the example above that .04 represents the interest rate, 10 represents the number of years and 5000 represents the amount invested.

Let's say you have a method that has these 3 things as parameters. Here is how you'd normally write the method:

public double calculateROI(double rate, int yrs, double money)
{
    //code
}
 But for the command line, here is how you write the method:
public double calculateROI(args[0], args[1], args[2])
{
    //code
}

Look familiar? Yes, finally, we see a point for those args in the main method.  Here is where exception handling comes in. If the first parameter in your method is the interest rate and, obviously, you want the first argument written on the command line to be the interest rate, you have to account for handling the error of someone not doing that. Otherwise, if the number of years is entered as the first argument, you clearly won't get the right result.

This isn't unlike dealing with parameters and arguments normally. Just make sure the user enters the arguments in the right order, after you've made sure they've entered the right command.


Monday, November 17, 2014

Xojo: Creating a report from a listbox

Initial disclaimers: The code presented here is not my own. My goal is to fill in some of the blanks when it comes to learning to create a simple report from a listbox in Xojo. There isn't a lot about Xojo out there and I feel the more information that is presented in various formats, the more likely people are discover the beauty of Xojo (formerly known as RealBasic or Real Studio).

Step 1:
Put something in the listbox! The code I used comes from here. I imported a csv file so I didn't need the code to write to the listbox, just to read it. As a result, I just skipped the write portion of the code. I also added a button called "Load" to the window and put this code under the Load action event.

Step 2:
Watch this video and read the Examples folder under Printing and Reporting. That's where the rest of my code came from. The Examples folder is in Xojo and you'll see it on the sidebar when Xojo first opens.

Step 3:
Under App, choose the appropriate window. Otherwise, you won't see anything. It's a small step and one I overlooked. I drove myself nuts trying to figure out why nothing was displaying as planned.

Step 4:
As one of my Xojo friends explained, if you have a Mac, you will be able to preview the report as a PDF. Pretty cool since that's mostly what you'll want to do - preview the pdf, email the pdf. But in Windows, that functionality isn't present and, unfortunately, it's still a work in progress in Xojo itself, although, high up on the to-do list. There are a couple of options, besides just literally printing out the entire report.
      a) Use the Dyna plugin but it's not free. However, if you're creating an app to make money and not just for fun, it might be worth the cost. Like the Xojo license, it's not unreasonably priced.
      b) Create your own pdf framework. This is outside my realm of knowledge.
      c) Use OneNote. It came with my laptop on Windows 8 and I accidentally discovered that while I can't view the report as a pdf, I can view it in OneNote and that has the same effect. This isn't the prettiest report but it gives you an idea of what you can do. You'll see the Address and Subdivision fields from the report that are the column headings here. ***Note that the DataFields in the Inspector should use the same name as the original fields. The CSV report I used named the fields, "Address" and "Subd" and those are the names in the DataFields. In the text property in the Inspector, you can enter whatever text you want.
You can see how I put all the code together in GitHub. If anyone feels it would be useful, I will write down step-by-step what  I did. It didn't seem necessary as I wouldn't have really added anything to the sources cited above. So unless I hear otherwise, Happy Reporting!



What I love about Xojo - Part 2: GUIs, Multiplatform, Databases

In the first part, I loved the fact that Xojo's online book explained caching. So simple yet so important and often overlooked by instructors. It made me think that the people behind Xojo really thought things through in the development process.

The other reason Xojo(fka RealBasic, Real Studio) is so lovable is that it makes difficult things simple.

While I have a thing for C#, creating GUIs in Windows Forms is a major pain. With Xojo, you drag and drop. Seriously, that's it. Drag and drop and go to the Inspector to set values for the properties. Then you can actually work on your code instead of spending a ton of time coding for the GUI. Listbox? No problem! Labels? No biggie!

Then there is the real reason for Xojo's existence in the first place - multiplatform. Do I love Apple? Not really. Am I planning to learn Objective-C? No. I'm a Windows kind of girl. But now I want to create an app for a friend who happens to use a Mac. What's the answer? Xojo. Write it in Xojo and it can be used on Windows, Linux or Mac. (If I ever find time to finish said app, I'll write about that.)

Last, but not least, the database. It's a mistake to think you can become a real programmer without loving the database life. SQLite is part of Xojo and you can actually create the database in Xojo using the insert menu. Feel free to do it programmatically, too.

I think Xojo is a great business solution for companies/individuals who have limited resources in terms of being able to write code for multiple operating systems and maintain that code. You do have to pay for the license to deploy your app, but you can build it for free to see how you like Xojo. The license is not unreasonably priced either. Check it out here.




Thursday, November 6, 2014

Java - equals vs. ==

Finally, I found an article that explains this in terms that are understandable.

In a previous post, my explanation for C# reference type vs. value type is the difference between your painting ,which is an original masterpiece, getting destroyed (no more painting for anyone) and your painting, which is a print, getting destroyed (more copies can be made).

However, I still had trouble understanding the concept that underlies the issue here of when to use equals method instead of the == operator.

Here's a synopsis of the article:

  1. == compares memory addresses.
  2. equals, as inherited from Object, does, too.
  3. If you want equals to compare data, then you have to override the equals method inherited from Object.
So that explains not only the difference (or similarity, as the case may be) between  == and equals. It also explains that what is being compared is either the address or the data. Hence, in the example in the article, A == C //false because they have different memory addresses. But A.equals(D), once the equals method is overriden, is true because the data is being compared. Thank you, Kurt Mammen!

Friday, September 26, 2014

What I love about Xojo - Part I - Caching and optimization

Caching - Have you even done a programming exercise, in any language, and done something like this?
      int x = array.length
      int average = 10/x

Have you wondered why you didn't just do this?
     int average = 10/array.length

Because they both work, but one requires more lines of code. Aren't we supposed to use as few lines of code as possible (within reason)?

The answer is explained in Xojo's book, Introduction to Programming, by Brad Rhine. On pages 89-90, Mr. Rhine explains that if you use a built-in function and you're using a loop, for example, the entire function has to run every time the loop iterates. If you assign the function to a variable, in other words, if you cache it, your app will speed up by accessing the value of the built-in function instead of running the function each iteration.

Seriously. To date, I've taken several programming classes and done some self-teaching and never has this been explained. See also this article that goes into a lot more depth.

Xojo gets the first thumbs up from me for explaining a common concept that should be explained in every intro class for any language.

Tuesday, September 9, 2014

Break out of a sentinel-controlled loop in Java/C#

The issue is the same in Java and C# . To exit a loop with a sentinel-controlled value, you need a break statement.

Example:
while(someValue != "Q"){
      //code for loop to execute while sentinel value not entered
      if(someValue.equals("Q"){
             break;//MUST USE THIS OR YOU WILL LOOP FOREVER
}

I think MSDN does a much better and simpler job explaining break. But I did manage to find some Oracle documentation that included code examples here.

In general, I am finding any documentation on Java to be spotty and not well written in the sense of not providing a substantive explanation with code examples. (Sorry to all the Java die-hards I offend.) In this case, you can see that MSDN uses one sentence to explain the break statement while the title of the Oracle documentation will make it difficult to even find this in a search using keyword "break".

The moral of the story: Java is a competitor to C# so they are very similar. If you can't find info on your Java issue, you might find it in MSDN and be able to apply it to Java.

Sunday, August 17, 2014

Python Classes and the__init__ method (not the _init_ method)

Can you tell the difference between "init"s in the title? It's hard to see and in some cases, impossible.

I was doing an exercise on Codecademy and it failed to mention one teeny, tiny thing. When you write the function/method/constructor "__init__" inside a class, you must use double underscores, not single. Otherwise, when you try to initialize your object, you'll get an error message.

On Codecademy, you can't tell the difference between single and double underscores by looking at the screen. Only because of StackOverflow did I figure out the problem. If you don't believe StackOverflow, check out MIT's Python MOOC as well.

So what is __init__? Codecademy refers to it  as a function and someone in StackOverflow differentiated between init as a method and a constructor. Call it whatever you want. In the Python documentation, it's referred to as a "special method" which initializes the object. In C#, that would be a constructor. 

Unfortunately, I could not find any other documentation to highlight the fact that double underscores are required. If you search for this problem, you'll see many people have been hindered by this issue. For now, I'll accept that this is the way it is and I'll append a note to this post if I ever find anything official on the matter.

Saturday, August 2, 2014

Python, floating points and range()

MIT's MOOC, "A Gentle Introduction to Programming Using Python" has just taught me that Python's range() does not like integers. Actually, it didn't teach me this at all. The reading discussed getting a range of random floating points and then testing that function to determine how many times each random number occurred. The reading didn't say anything about not being able to use range() with floating points. I figured that out when I tried it myself and it didn't work.

Then, as usual, I hopped over to StackOverflow which was full of suggestions that I perceived to be too unduly complex for the reading. Plus, most of the solutions involved integers in range(). This is precisely what I was trying to avoid.

I am completely new to Python but I continue with my mission of making the unnecessarily complex discernable to newbies. Keep that in mind when you read my solution below.

The reading I refer to is here. I don't use those examples. Here are mine:

#first, get some random numbers
import random #kindof like "using" in C#
randList = [] # we'll need this list soon; make it empty for now
def randomness:
          hi = 2.0
          lo = 1.0
          for i in range(10):   #this will print out 10 random numbers
                 x = random.uniform(lo, hi)
                 #generates random floating point between the lo and hi range
                 randList.append(x) # this adds the value in x to the list
           print randList
               
#test randomness() to see how many times each range of random numbers occur
def test(randList):
       count = 0
       for num in randList:
              if num < 1.5: #I want to see how many numbers less than 1.5 are generated
                     count += 1
       print ("There are/is"), count, ("occurrences of floating points less than 1.5.")

Call randomness() and then call test().

I will also post this in GitHub. More info on range() here.

Thursday, July 31, 2014

Why Republic Wireless and net neutrality matter

The Interstate Commerce Clause of the U.S. Constitution basically says that any commerce occurring between states falls under the umbrella of the federal government. This is an important point for a nation which takes states' rights so seriously. Keep in mind, too, the time period in which the Constitution was drafted and the level of interstate commerce at that point.

What can the feds do with the ICC?

Fast forward to the present day. The ICC is how the federal government can prohibit guns within so many feet of a school. Why? Because no gun is made entirely within one state and sold entirely within one state. Hence, the feds can control legislation relating to guns. The ICC is also how many cases are removed from state court to federal court when it is more favorable to the defendant who was sued in state court. What company uses paper made entirely in one state and sold entirely in the same state? Or software? Or office equipment? You get the picture.

The age of the Internet.

I'm a stay-at-home mom to 2 small kids. I can't afford to pay for daycare on top of tuition. So I can only pursue my techie dreams if I can take classes online. Wake Tech is ultra cheap, CodeAcademy introduced me to HTML/CSS/JS and MOOC gave me Python. The point is that we have access to more knowledge (and I don't mean the kind Perez Hilton brings us) than ever before. Access to knowledge = power. Constricting access = power for someone else.

Replace "We the People" with "Comcast/Time Warner Cable"...

...if these giant corporations can control internet speed based on who pays the ransom, then we are not a democracy. And I hope you don't think for one second their lobbyists aren't well paid to attempt to take control of Congress. So if the corporations tell us what we can read and what we can watch and what we can listen to because they have the money to bend Congress' ear...then "adijo" democracy.

It looks like we've won part of the battle,  but they'll be back for more.

Keep the faith, Republic Wireless.

So when a company like RW starts to make a dent in a market and make technology affordable for everyone, it's a big deal. Everyone says the desktop is dying. (Personally, I need a bigger screen for regular reading.) If that's true, outrageous phone bills for smart phones means a lot of people are priced out of accessing information.

This is not a thorough legal analysis, but it is something I believe in strongly. I'm all for making a profit and people who work hard and do a good job should be aptly rewarded. But individuals should not be controlled by corporations. They don't own the internet. They don't own information.

How we practice democracy will change with technology. Companies like RW can push us in that direction while simultaneously pushing back against the corporate giants that want to diminish democracy.

Wednesday, July 23, 2014

Making columns in a listbox in C#

Amended: There is a MultiColumn property I forgot to mention. It didn't work for me with the particular problem I had. Maybe that was my lack of skill. Maybe it was the problem. In any case, try MultiColumn and try my workaround. One of them should do the trick.

This post probably has a very limited audience made up of other students who, like me, are being forced to use Windows Forms and have not yet used WPF. Having not used WPF yet, I don't know if this helpful hint will help outside Windows Forms.

Here was my problem: I had a lab assignment in which I was required to make a GUI in Windows Forms. Random integers were to be created with a button click and the values displayed in a listbox with two columns. I suddenly realized I didn't know how to make columns in a listbox.  Very old versions of Visual Studio had a columns property but since I was using VS 2013, that didn't help. I also read somewhere that listview could be used but it was described as "quirky." I didn't have time for quirky.

So here's how to do it:

        Step 1: listBox1.Items.Add("Index     Values");
        Step 2: Make a for loop
        Step 3:  Inside the for loop, add the output underneath the column headings
                    from Step 1.
                    listBox1.Items.Add(string.Format("{0}           {1}", i, intArray[i]));

That's it. Pretend you're in a Console app but use listbox instead and you've got columns.

Monday, July 14, 2014

Convert string to a char array in C#

It's not complicated. You just have to know how to do it.

   public class ArrayChange
   {
       static char[] charArray;//declare before Main method
       public static void Main(string[] args)
      {
         Console.WriteLine("Enter your name: ");
         string input = Console.ReadLine();
         charArray = input.ToCharArray();
      }//end Main method
   }//end class

This first line, of course, prompts the user to enter a string. The second line stores that input in a string variable called "input". The third line converts input to a char array and stores it in the array called "charArray".

If you try to store the user input directly into a char array, you'll get a red squiggly line telling you that you cannot implicitly convert a string, which is the user input, into a char array. In other words, you can't just say that apples = oranges.

So your next thought is probably to do this:

Convert.ToCharArray(Console.ReadLine());

Good idea. Makes sense to me, but Convert class does not contain a ToCharArray method, just ToChar. So when you want apples = oranges, you need a middleman. In our case, that middleman is string input, which stores the user input as a string. Since strings are made of characters, we can just dump those characters into a char array as we did in the third line.




Saturday, June 28, 2014

Structs vs. Classes in C#

This MVA video does an excellent job of explaining the difference. This post is a short summary of the video.

The most important thing to understand is passing by reference versus passing by value. The example I use for explaining the difference between pass by reference and pass by value is this: You go to an art gallery and buy an original work of art. When you take it home, your 2-year-old scribbles all over it with crayon. The original work of art is forever changed. That's passing by reference. But if you were to buy a print of the original work of art which your 2-year-old then scribbles on, the original work of art is not affected. Although it may suck for you that you paid good money for a print which is now messed up, the original work of art remains intact and more prints can be made from it. That's passing by value.

If you've looked at structs before, you know that a struct looks and acts a lot like a class. But as is pointed out in the video, there are some major differences. So here is the promised summary of the video.

1. Structs are values types and classes are reference types. Thinking of my example above, this means that when changes are made, only a copy is changed and not the original values in a struct. But with a class, whatever values you change are changed within the class itself. The MVA video does a great job of demonstrating this by code. I copied the code and put it on GitHub so I could see the whole thing at once. I just got tired of rewinding and fastforwarding when I wanted to see something. Just remember, this is not my code but the code from the MVA video.

2. Structs are passed on the stack and classes are passed on the heap. When a copy of a struct is passed onto the stack, the whole data structure is passed. (This is also means structs should be smaller data structures than classes.) When a class is passed on the heap, a copy of the memory address is passed. While this makes the process more efficient than passing the entire data structure, it also means that the method receives a copy of the instance of the class and, thus, has access to change the class itself.

3. What is the stack and what is the heap? Here is a great article. I won't try to reinvent the wheel. Just read this.

4. What is with the hashtags? It just means you can specify a block of code, a region, like the struct, that can be collapsed while you look at other code. I added in the regions to the code on GitHub, so you can try it out there.









Monday, June 23, 2014

StringBuilder in C# - Tricky truncating with Length and Append

StringBuilder, unlike String, is a class that allows you to change the length of a string. If the length property is already set and a new string is created that is longer than the length, the length increases. If the new string is shorter than the property value already set, it decreases. The MSDN source code provides a more technical way of putting it. (See lines 464-467.)

Here's a simple example to demonstrate:

      StringBuilder example = new StringBuilder("Hello");
      //length changes from default value of 0 to 5 on creation of the object
      Console.WriteLine(example.Length);
      //output is 5

Using the append method, I add the string "Hello" onto an empty string.

      StringBuilder example = new StringBuilder("");
      //this is an empty string; length is still 0 
      example.Append("Hello");
      Console.WriteLine(example.Length);
      //output is still 5 

Using the append method, I add the string "Hello" onto a string containing only a space character.
      StringBuilder example = new StringBuilder(" ");
      //this is NOT an empty string
      //there is a space character in this string; current length is now 1 
      Console.WriteLine(example.Length);
      //output is 1
      example.Append("Hello");
      Console.WriteLine(example.Length);
      //output is now 6, because there is a space character at the beginning of the string
      Console.WriteLine(example);//output is " Hello" - there will be a space before "H"

Just remember that an empty string ("") is not the same as (" "). The latter contains a space character. This makes a big difference if you're appending your string and then getting the length. Not that I expect this is done on a regular basis, but the moral of the story is to make sure you know what prior strings contained before appending or you might get a surprise. (Not that this ever happened to me.)

So what if I wanted to get rid of the space character? Truncate.

         StringBuilder x = new StringBuilder(" ");
         Console.WriteLine(x.Length);//output is 1 because of the space character
         x.Length = 0;
         x.Append("Hello");
         Console.WriteLine(x);//output is "Hello"; notice there is no space before "Hello" now
         Console.WriteLine(x.Length);//output is 5;

Here is a screenshot to show the code and output.



Monday, June 9, 2014

C# DateTimePicker and Current Time a.k.a Learning to Load

This is a "helpful hint" post. I was working on a Windows Form and needed the form to update to the current time each time the app was run. I started with the TimeDatePicker in the form, choosing Time for the property Format because I only wanted to display the time, not the date. I didn't have to set Value because that property was automatically set to the current date and time. The code I used was:
private void DateTimePicker_Click(object send, EventArgs e) 
{ DateTime.dateTimePicker1 = DateTime.Now;}
Unfortunately, this combo did not work. Each time I ran the app, it showed the time the app was created and not the current time.

The first lesson here is to not assume that Click is an event for every controller. It's not an event for DateTimePicker. It seemed logical to me, though, so I used that in my code without checking to see if it was an actual event. You click to change the date and/or time, right? Yes, you do. But that was the wrong logic.

The correct logic is to ask: A) What should the controller do? The controller should show the current time. B) When should the controller perform this task? The controller should perform this task when the form loads, which means the data needs to be picked up before the form displays.

Here is one way to write the code correctly:
private void Form1_Load(object sender, EventArgs e)
      {     //Form1 is the name of the class used to create this form
         dateTimePicker1.Value = DateTime.Now;
      }//also see DotNetPerls for another snippet

Since my textbook didn't go into a lot (i.e., any) detail about loading, I had to do a little research. Although I ran across references to Load when I was searching high and low for a way to make the time update, I couldn't find it as an event for DateTimePicker. That's because Load is an event of class Form, which is a class in the Forms namespace. (When you create a form, you will see that the class automatically generated for you is a derived class of class Form.) In the order of events, Load occurs before the form is displayed, which is logical.

The moral of the story is that if you want the current date, i.e. data that must be captured anew each time the app is run, you need the Load event. Just remember that Load is an event of class Form, not the controller DateTimePicker,

I strongly recommend reading these two posts by DotNetPerls: One on Load and one on DateTimePicker to help you understand this better.

Tuesday, June 3, 2014

Getting dates and calculating a time interval in C# - Part II

TimeSpan

You can get the source code on GitHub. (I've updated the code a bit.)

TimeSpan is struct with a method subtract that will calculate the number of days between two dates. This means, though, that we are now dealing with a different type from DateTime. DateTime just gives you dates and, as you know from the previous post, I needed to calculate an interval between dates. So how could I use the  TimeSpan type with the DateTime objects I had created?

My first thought was to convert my TimeSpan object to a DateTime object because I knew how to format DateTime to display only the date. But as someone pointed out on Stack Overflow, it doesn't make sense to do it that way. TimeSpan represents, guess what, a span of time. DateTime represents, yes, you guessed it, a date and a time. The date July 12, 2013 is different from the time span 2 days, 12 hours, 30 minutes and 40 seconds.

So here's how it's done:
TimeSpan daysGoneBy = todayDateOnly.Subtract(boughtDateOnly);
Start with a TimeSpan variable, daysGoneBy. On the other side of the equation is largerDate.methodSubtract(argumentIsSmallerDate).

Now, just display the result:
string output;
output = "The number of days elapsed since the vehicle was bought: " + daysGoneBy.ToString("%d");
As you may recall, "d" is a format specifier. Here, "%d" means only the whole number of days will be displayed. (Remember that % is the symbol for modulo.)

It took some work for me to figure this out on my own, putting all the pieces of the puzzle together, and it was a lot of fun. I hope you find it helpful.

Wednesday, May 21, 2014

Getting dates and calculating a time interval in C# - Part I

I wanted to create a console app in Visual C# which required the app to choose a path based on the number of days elapsed between the current date and a date entered by the user. I assumed I would do a quick search and find a way to do this on MSDN or Stack Overflow. I assumed many people had done this many times and code snippets would be posted all over the web. Wrong. Sure, I found a way to subtract one date from another if I entered the dates as arguments or the app was a form. But I couldn't find a way to do it when 1) the app was a console app, 2) the app provided the current date and 2) the user entered another date which would be subtracted from the current date.

This is a two-part post explaining the program I wrote to resolve the problem. Part I explains how to get the dates. The second part will explain how to subtract the dates to get the time interval. The full source code is on GitHub.

Today is the day
Getting today's date is easy:

     Console.WriteLine("Today's date is {0}.", DateTime.Today);

Microsoft has already provided us with the DateTime struct and its property, Today. By reviewing the source code, you can see that Today is a static property.  Static properties can be called without an object being created, hence, the reason the code snippet above will display the current date and time.

However, for my purposes, there are a couple of problems with this code. First, this format will give you a time of 12:00:00 AM as well as the date. For my app, I didn't need the time. Second, I didn't need to merely display the current date, I needed to store it so that another date could be subtracted from it. As painfully obvious as this is now, I wasn't sure how to do that. If you aren't either, read on.

Construct Today
Starting with the basics, DateTime is structure (a.k.a. struct) in the System namespace. You do not need to use keyword "new" to instantiate a struct object. Create the object like so to display only the date:

     DateTime dateOnly = DateTime.Today;
     Console.WriteLine("Today's date is {0}.", dateOnly.ToString("d");

     (The "d" is a short date format specifier. In other words, this format will give you the date and not the time.)

You may also want to read DotNetPerls which explains why you would choose the Today property over the Now property.

User Input
Since DateTime is a struct, that means it is a type. After I ask the user to input a date, I declare a DateTime variable and convert the line entered by the user to DateTime type. Just as with the code snippet above, though, this will display the date and a time. So the next step is to create a DateTime object and use the short date format specifier in the Console.WriteLine argument.

         Console.WriteLine("Enter the date you bought your vehicle.");
         Console.WriteLine("Use this format, 01/01/2011.");
         DateTime whenBought = Convert.ToDateTime(Console.ReadLine());
         DateTime boughtDateOnly = whenBought.Date;
         Console.WriteLine("Vehicle was bought on {0}.", boughtDateOnly.ToString("d"));

Here is a screen shot of the output.


The next post will go over TimeSpan and its Subtract method.

Sunday, May 11, 2014

Optional Parameters and Named Parameters in C#

I just don't like it when simple things are explained in a complex manner. So let me break it down for other C# noobs, in case you have a textbook like mine that provides an insufficient explanation or if you just don't understand these two types of parameters.

Optional Parameters

You will be surprised to learn that, as the name suggests, this means the parameters* are optional. The client code does NOT have to provide arguments for these parameters. Why? Because a default value is already included for you.

Example: public void optParam (int x, int y =2, int z = 3)
                       {some code};//this method has two optional parameters

In this case, there are two optional parameters, "y" and "z". Parameter "y" has a default value of 2 and parameter "z" has a default value of 3. If no value is provided for "y" or "z", they will retain their default values. You will notice that parameter "x" has no default value provided. This means that the client code MUST provide an argument for this parameter. Also be aware that the required parameter must come before the optional parameters.

Obviously, there is a problem. If you want to provide an argument for "z" and not for "y", how can you make the arguments be evaluated so that the first argument will be applied to "x" and the second argument to "z"? You can't. As MSDN informs us, you would have no choice but to specify the argument for the optional parameter "y" before providing the argument for "z". Needless to say, there would be no point in having an optional parameter "y" in that case. This is where named parameters come to the rescue.

*Per MSDN, optional and named parameters can be used with methods, constructors, indexers and delegates.

Named Parameters

When calling the method, the client code need only name the optional parameters for which it wishes to provide a value, avoiding the problem just described.

Example:  public void optParam (int x, int y =2, int z = 3) {some code};
                optParam (20, z: 30);

This result is x = 20, y =2 and z = 30. You avoid having to rewrite the default value and another benefit is that you can put the named parameters in any order. The same rule about required parameters coming before optional parameters applies here. The arguments supplied for the optional parameters can come in any order as to each other, but they must come after the arguments for the required parameters.

Example:  public void optParam (int x, int y =2, int z = 3, int zz = 5) {some code};
                optParam (20, zz: 30, y: 10);//okay
                optParam (y: 30, zz: 10, 20);//not okay

Here you can see a sample of code I wrote to show how the two types of parameters work together and a screen shot of the results: https://github.com/htravar/Parameters. You may also find this article helpful.

This topic does get more complex, but I hope I've explained the basics in a basic way. Enjoy the parameter shortcut.

Wednesday, April 30, 2014

Math.Min vs. Random.Next in C# - To be (static) or not to be?

As I carefully read through my notes, I had to stop and ask, "Why do I need to create an object for class Random? It bothered me to no end because I had just read about Math.Min being a static method. (Static methods mean you are not required to create an object prior to calling the method.) Yet here I was, perusing an example that created an object of class Random before calling the Next method.

My problem was my assumption. My assumption was that Random.Next was a static method since I had just been reading about static methods in a different section of my lesson/text. It was not explicitly pointed out that I was no longer reading about static methods and I just assumed every method discussed was static.

As a lawyer, I should have been more discerning. Luckily, the light bulb went off and I started a search for "Is Random.Next a static method in C#?" Turns out, I was not the only one who had this question. Stack Overflow turned up first in my search and someone asking the same question received enlightening answers on why Random.Next cannot be static. Although it would have been nice if someone had noted that we were no longer talking about static methods, the fact is that Random.Next was actually discussed in a section on the .NET framework class library in general, not in the section on static methods.

So, for all you noobs who were perplexed as I was, the answer is that Random.Next is not a static method. This is why you must create an object before calling the Next method. Just watch what you're reading and don't assume too much.

Friday, April 18, 2014

Construction Junction in C# - For Beginners

In my Intro to C# class, I felt like I was weaving through a maze when it came to reading the code that brought together the concepts of properties, constructors, methods and objects. It's not really that confusing, once you connect the dots. So let's pretend the world is ending and see how these things work together.

In the post prior to this one, you will see code that includes class Zombie and class ZombieTest. Or get it here: https://github.com/htravar/Zombie. Don't let the fact there are two classes freak you out. Think of it this way - class Zombie contains the general instructions for what the program should do and class ZombieTest gives class Zombie specific data to carry out the program.

Class Zombie
The properties "Relations" and "RelativeName" (lines 9-10) are auto-implemented. This means that instead of writing out the private instance variables and the properties separately, we skip writing out the private instance variables and we skip writing out the get and set accessors. You know when you see auto-implemented properties that private instance variables of the same name have been created for you. (Note: There are times when you will want to add code to your accessors and you will not auto-implement. That is a topic for another day.)

Next we come to the constructor (lines 12-16), which you will recognize because it has a) the same name as the class, b) does not have a return type like method and c) it has parameters. If it did not have parameters, it would be a default constructor. A default constructor is provided by the compiler when you do not provide one yourself. The default values are null or 0. Here, I want to initialize the object with some values other than null or 0, so I have created my own constructor with parameters "name" and "relationship" (line 12), both of type string. For more info on constructors, see http://www.dotnetperls.com/constructor.

Now we connect the first two dots, the properties and the constructor. In the constructor, I use an assignment statement (line 14) to give the property "RelativeName" whatever value is passed to the constructor's parameter "name". Likewise for property "Relations" and the parameter "relationship" (line 15).

We'll come back to how we get the relative's name and relationship actually into the program. For now, we move on to the method (lines 18-22). This method will display a message along with information provided by the user (i.e. the name of the relative and that person's relationship to the user).

Class ZombieTest
This class contains the Main method (lines 27-47), which is the entry point for any program.

First, I get user input. I create a local variable "nameOfRelative" (line 29) which captures the input for relative's name (lines 30-32) and likewise for local variable "relationToRelative" (line 36-38). (You'll see some extra Console.WriteLine() statements. Those are added just to provide some spacing between text to make the output more readable.)

Second, I create a new object (line 42). Since every class in C# is also a type, I just use the name of the class Zombie and call the object "survivor".

Here we do some major connecting  of the dots.

I provide the local variables, nameOfRelative and relationToRelative as the arguments for the object creation expression (line 42). The object creation expression comes after the equals sign when a new object is created, like this: Zombie myZombie = new Zombie (nameOfRelative, relationToRelative). The part in bold is the object creation expression.

Then I call the method, DisplayInfo (line 43), which will display the name and relationship provided by the user. (Remember that you can't call a method in another class without first creating an object of that class, which I did with the Zombie object "survivor".)

That's all well and good, but just how does class Zombie know about these local variables and where they are supposed to be used? I think this part is where it gets really confusing. Let's break it down.

The constructor takes two arguments,"name" and "relationship", both of type string. Remember that these are the names of the constructor's parameters, not the actual values. The object creation expression's arguments are passed to the constructor and this is how the constructor's parameters get actual values. Since the properties are assigned the value of the constructor's parameters, the properties receive the values of the local variables declared in class ZombieTest. Then the method executes.

Recap
When a new object is created, the arguments provided to the the object creation expression are passed to the constructor's parameters. Because the properties are assigned the values in the constructor's parameters, they get those values. Then, the method, which uses the properties, is able to carry out its task.






Code Sample for Construction Junction in C#

1   //created by Heather Travar on 4/1/14
2   //This program asks user who in their family is most likely to survive a zombie
3   //apocalypse and displays the results
4  //also get code here: https://github.com/htravar/Zombie
5   using System;
6
7   class Zombie
8  {
9        public string Relations {get; set;}//auto implemented properties
10      public string RelativeName {get; set;}
11
12      public Zombie(string name, string relationship)
13      {
14         RelativeName = name;
15         Relations = relationship;
16      }
17
18      public void DisplayInfo()
19      {
20         Console.WriteLine("The relative you feel most likely\nto survive a zombie");
21         Console.WriteLine ("apocalypse is {0}, your{1}.", RelativeName, Relations);
22      }    
23  }//end class Zombie
24
25  class ZombieTest
26   {
27      static void Main(string[] args)
28      {
29         string nameOfRelative;
30         Console.WriteLine("Will anyone in your family survive the zombie apocalypse?");
31         Console.WriteLine("Enter the name of the one MOST likely to survive.");
32         nameOfRelative = Console.ReadLine();
33
34         Console.WriteLine();
35
36         string relationtoRelative;
37         Console.WriteLine("Enter this person's relationship to this you.");
38         relationtoRelative = Console.ReadLine();
39
40        Console.WriteLine();
41
42         Zombie survivor = new Zombie(nameOfRelative, relationtoRelative);
43         survivor.DisplayInfo();
44
45         Console.ReadKey();
46
47      }//end Main method
48   }//end class ZombieTest

 

Thursday, April 10, 2014

When did I begin to feel like a programmer?

Answer:  Exercise 5.41, Chapter 5, Control Statements, Part I - Visual C# 2012 (Dietel).

Yes, that was my "a-ha" moment. It doesn't seem so pivotal, chapter 5. Here's why it was a turning point:

The encrypt/decrypt exercise. I wanted some extra practice after I finished my lab assignment, so I picked the last exercise in chapter 5 to do. See code here. (If you can't see the code, let me know. I am in the very beginning phase of learning GitHub.)

In the exercise, the user enters four digits, 0-9. Each digit is first encrypted and then the digits are swapped (first with third, second with fourth). That part was easy. 

The second part of the exercise is the decryption part. At first, I was stuck. I assumed I need to concoct some complex math formula to break down the encryption, but everything I came up with failed to work in all scenarios. I assumed the failure was due to my very weak math background. It is rather anemic.

But then I saw the problem for what it really was - a programming problem. My failure was in addressing it as a mathematical problem. What I finally realized was that a good algorithm, utilizing components of math, yielded the correct results. The emphasis should have been on the algorithm and not some convoluted formula. I couldn't see the forest for the trees.

As you can see from the code, my solution was this:

First, add "1" to each encrypted digit to avoid having a negative number in the fourth step. 
Second, subtract "7". This gave me the decrypted numbers, except that there would be some double digits. Third, swap the numbers back to their original places. 
Fourth, use modulo (dividing by 10) to get rid of the first digit of the double digits (ex. 12 becomes 2) without losing the single digits (ex. 3/10 has a remainder of 3).

When I started law school, I recall the learning curve the first semester being practically vertical. But I worked hard to learn to think like a lawyer and the learning curve flattened out dramatically the second semester. By the time I started my second year, it was all routine.

I realize this encryption exercise is very simplistic, but it taught me an important lesson about troubleshooting. Sometimes, it's a matter of making sure you have the right logical perspective. While  I have a long way to go before I can call myself a programmer with any confidence, chapter 5 helped me climb higher on the learning curve.