Thursday, November 14, 2013

Week 4 Day

We're almost half way through the group project. It's going pretty well. We should have most of the functionality up today. That will give us time to add a good deal of polish and one or two new features before it finishes up.

If the functionality is up tomorrow, I want to spend next week working on an API/Widget that will allow a user to embed some of our functionality in their site.

Maybe we can get users added in next week also...maybe. I don't know what it involves but it would be an interesting challenge.


Tuesday, November 5, 2013

The Wheels Are Off



Week 3- Day 2: We've had two solid days of medium-ish sized projects. This week is starting out to be a bruiser. Loooong days.

On top of the projects I'm trying to squeeze in a mini-side project. A single page application written in Html, jQuery and AngularJs.

jQuery has been giving me fits. I'm trying to make it do something it wasn't really designed to do. That's why I brought Angular into the mix.

I hope to have it in beta by the end of the week...we'll see.

Friday, November 1, 2013

Pagination: Millions of Pages, Pages for Me (Part 1)

Here are the basics of setting up pagination in an ASP.net project using Razor. I'll post a video at the end of the series showing the whole process.

In Part 1, we're just going to set up the logic and a fixed pager
  1. You'll need to create a new project, using the MVC web template.
  2. Create a new class in your models folder called People. Give them 2 properties: Id and Name.
  3. Set up your database with entity framework. Seed it with 12 people. Here's my class & seed data.
Class
public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }

    }
Seeder
context.People.AddOrUpdate(
                p => p.Id,
                new Person { Id=1, Name="Alex" },
                new Person { Id=2, Name="Aaron" },
                new Person { Id=3, Name="Amish" },
                new Person { Id=4, Name="David" },
                new Person { Id=5, Name="Miguel" },
                new Person { Id=6, Name="Andrew" },
                new Person { Id=7, Name="Andy" },
                new Person { Id=8, Name="Josh" },
                new Person { Id=9, Name="Grey" },
                new Person { Id=10, Name="Yola" },
                new Person { Id=11, Name="Mark" },
                new Person { Id=12, Name="Max" },
                new Person { Id=13, Name="Ben" }
                );

Before we start building I think it's useful to look at how pagers work.

There are two key variables:
  1. How many results you want on a page: I'll call this variable PageSize. 
  2. What page the viewer is on. I'll call this CurrentPage. 
  3. There is a third variable called Skip that we'll get to in a second.
Lets look at what happens when a visitor uses our pager
 The visitor goes to our page for the first time. Page counting will start at 0.
Our Controller accesses the Database. Does any sorting. Sort first, or you're gonna have a bad time. THEN pulls the number of records we set PageSize. In this case lets assume we set it to three. The controller passes those records to the view, view displays those three records.

The visitor clicks over to page 2.

Same as before. Our Controller accesses the Database. Sorts.Skip requires some kind of sort even if it's just by Id. Does a Skip.  Then pulls the number of records we set in PageSize. To calculate the Skip you multiply the PageSize and CurrentPage.
First page you skip 0 (this is why you start counting pages at 0), Second page you skip 3, etc...

Go ahead and set up an MVC project, using the above classes and seeder, seed your database.

Onto Code...
Go into your home controller and create a new Action Result with a call to the database.

public ActionResult People()
        {
            ApplicationDbContext db = new ApplicationDbContext();             List<Person> people = db.People.ToList();

            return View(people);
        }
 
Create a view to match the new action result and put a loop creating a table in it.
<table class="table table-responsive table-striped">
    @foreach (var item in Model)
    {
        <tr><td>@item.Id</td><td>@item.Name</td></tr>
    }
</table>


You'll also want to add your @model statement to the top of your view if you haven't

@model IEnumerable<RaginPagin.Models.Person>

If you run this you get all of the results on a single page. We only want 3 results first. To get only 3 modify the People Action code as follows.

 public ActionResult People()
        {
            ApplicationDbContext db = new ApplicationDbContext();
           
            int PageSize = 3;

  
            List<Person> people = db.People.Take(PageSize).ToList();

            return View(people);
        }

We get three results on the first page but there's no way to move forward. We'll need something in the view to help us navigate. add the following under the table in your view.

<ul class="pagination">
    <li><a href="~/home/people/0">1</a></li>
    <li><a href="~/home/people/1">2</a></li>
    <li><a href="~/home/people/2">3</a></li>
    <li><a href="~/home/people/3">4</a></li>
    <li><a href="~/home/people/4">5</a></li>

</ul>

Note that the link text is one more than the CurrentPage
<li><a href="~/home/people/0">1</a></li>

If we run this, we'll still get the page, only three but the pages all return the same three results.
We need to go back to our HomeController and tell it what to do with the CurrentPage we're passing it at the end of the URL.

 public ActionResult People(int? id)
        {
            ApplicationDbContext db = new ApplicationDbContext();
          
            int PageSize = 3;
            skip = PageSize * id.Value;
           

            List<Person> people = db.People.OrderBy(p=>p.Id).Skip(skip).Take(PageSize).ToList();

            return View(people);
        }
Here is where we implement the Skip Linq call. Skip requires some sort or order on the data before it will run. I did this with another Linq call ordering the data by Id
The parameter of the current page is coming through as the id. It needs to be nullable to handle the default case of no parameter passed.

You then need to handle the possibility of Null for id. I handle it like this.

public ActionResult People(int? id)
        {
            ApplicationDbContext db = new ApplicationDbContext();
           
            int PageSize = 3;
            int skip = 0;
            if (id.HasValue) {
            skip = PageSize * id.Value;
            }

            List<Person> people = db.People.OrderBy(p=>p.Id).Skip(skip).Take(PageSize).ToList();

            return View(people);
        }
Here's the raw video an edited version is planned.


Wednesday, October 30, 2013

Not Following Conventions and Other Bad Ideas






Conventions are there to help you. Sometimes you need to override them most of the time you don't.

Future Troops: Here are some things I've done (and seen) that you shouldn't do if you can avoid them. Feel free to add your own in the comments


  • If you don't follow class, table, and list naming conventions, you're gonna have a bad time.
  • If you change your namespace mid project, you're gonna have a bad time.
  • If you don't learn to read error messages, you're gonna have a bad time.
  • If you use Bootstrap 3 and Layoutit.com together, you're gonna have a bad time.(Use Bootstrap 2.x and you'll be fine)
  • If you don't practice on your own, you're gonna have a bad time.

Tuesday, October 29, 2013

Get & Set!

Success! 

Data comes out! Data goes in! 

The magic words were:

                 db.Clients.Add(Nclient);
       db.SaveChanges();

It's a little more complicated than that but that's what I was missing. While banging my head against the problem I got the following points.

How to Access Information Returned In A Query String
string a = Request.QueryString["SomeField"];
String Interpolation
 string a = string.Format("{0} {1}!","Hello", "World");
You can also use variables:
string h = "Hello";
string w = "World";
string a = string.Format("{} {}!", h, w);

Catching Errors: (Sometimes) Keeping Errors from Crashing Your Program
try{
CoDeThAtCrAsHesYoUrApP();

catch{
}
The code in try runs and is a success or fails, if it fails then we can handle the error in the catch section. I need more work on this but it's an interesting starting point.

 Week 2 Day 2






 

Monday, October 28, 2013

UPDATE progress SET Week1='done',status='banging head against SQL' WHERE coder='Alex'

Week 1 is behind me at this point and so far things are a success. I can now do in 45 minutes in visual studio with Bootstrap what would have taken me an entire day hand coding PHP.

Today we reviewed what we covered last week. Then moved onto SQL statements. Getting data to populate and narrow with SQL calls from C# is fine(SELECT statements and WHERE clauses). I'm making lists( and therefore dropdown menus) dynamically. It looks good, works well.



There's one small problem.

I can't get the thing to update or insert from C#. The code runs properly in SQL Management Studio, just not when wrapped up in C# goodness. No one in my research is doing it the way I'm trying to. It seems there's a reason.

We'll get some tools later this week that will make life easier.

Thursday, October 24, 2013

Thanks

To future troops: Get help from the people who came before you. They're nice people. They will help.

I wanted post a quick thanks to some people in earlier troops that have helped me out with both lessons and encouragement while I'm still in the sucking phase.

Josh 
Ben




Wednesday, October 23, 2013

Schrodinger's Cat: Wanted Dead AND Alive



If you don't know about Schrodinger's Cat you should.

The state of being alive can be represented by a boolean value. True or False. Alive or Not.

Structs have to have a value. So if I create a new bool, Cat.IsAlive, it takes the default bool value of false. Here's the code to prove it.

public class Cat{
     public bool IsAlive{set; get;}
}

Cat SchrodingersCat = new Cat();

Console.WriteLine(SchrodingersCat.IsAlive);

output:
False

Poor kitty...

If you take the default bool he's always dead. The problem is before you open the box, you don't know whether the cat is alive or dead. Sometimes he survives...and is angry. You still want to use a bool. Just make it nullable.

public class Cat{
     public bool? IsAlive{set; get;}
}

Cat SchrodingersCat = new Cat();

Console.WriteLine(SchrodingersCat.IsAlive);

output:

That's better. It looks empty. And it is...kind of. It's null. After you run Box.Open()the value will change to a good'ol true or false.

Before the box is opened the cat isn't alive or dead, it's just null.


Day 2 Recap -- Getting # on OOP

Today we covered some higher level concepts of Object Oriented Programming. The main ones we focused on were inheritance, encapsulation, data hiding and polymorphism.

The most complex of the three was polymorphism. Essentially you put an instance of a child variable inside of a parent variable's instance. Only the parts of the child variable that the parent can understand (like overridden methods, or properties) are accessible.

In the process we saw some C# and got examples of class creation, child class creation, instantiating a class, writing(simple) functions and calling them.

Creating a class
public class Coder{
     public string Name{set;get;}
     public string Language{set; get;}
     public int Age{set; get;}
}
Creating a new instance of a Class
Coder p = new Coder();
using dot notation to set variables for the new instance
p.name="Alex";
p.Language="C#";
p.Age=27;


public void Code(){
Console.WriteLine("Someone is coding");
}
calling the function
Code();

Tuesday, October 22, 2013

Day 1 Recap

It's the morning of Day 2.

Day 1 went pretty well. We've got 5 great guys in our troop. We're smaller than most of the other troops. This is going to be good for cohesion, but will limit the scope of what we can get done on our group project.

We got bogged down by the release Visual Studio 2013, (it went live yesterday morning and they removed 2012). There are some upgrades like built in support for bootstrap and some aesthetic upgrades.

The group project will go well. We used screen shots and paint to put together mock-ups of new features to add to an existing project base. Today we'll get feedback and make sure we're headed in the correct direction.

David is also going to hit us with the basics of OOP in C# today. The intensity is about to get turned up quite a bit, let the games begin!

Monday, September 23, 2013

Rock, Paper, Scissors, Lizard, Spock is live!

I just posted my RPSLS game on my site at www.alexismy.name.

Blogger won't let you run live scripts, so I hosted it myself. It's written in HTML, jQuery and CSS. I'm new to jQuery but so far it's amazingly powerful.

Here some of the things that I learned along the way:

jQuery
$("#foo").text("<span>Text goes here!</span>");
This result in that exact text being entered into the element with ID foo, the html tags won't be read as html, just printed as text. Not good. The .append( ) method didn't seem to help either.

To get HTML tags to render properly you need to use the .html( ) method, like so.
$("#foo").html("<span>Text goes here!</span>");
This got me part of the way there, but i didn't want to replace everything.

One thing to be aware of is the .html( ) method will replace all of the HTML in an element. This is fine if all you want to do is update the element. If you want to add to the existing HTML you'll need to retrieve the existing html, add you new code and then feed it back into the element.

var existingText = $("#foo").html();
$("#foo").html(existingText + "<span>Text goes here!</span>");
This will append your HTML to the existing html.

CSS

When users click a button to select a choice, the border changes to blue. The computer choice is indicated in red.
.choice .selected {
color:grey;
background-color:white;
border:solid 2px blue;
}
.choice .comp {
color:grey;
background-color:white;
border:solid 2px red;
}

But if there's a tie I wanted a different boarder, green in this case. If you want multiple selectors at the same level the following doesn't work.

.choice .comp .selected {
background-color:yellow;
border:solid 2px green;
}
This looks for the "choice" class, moves down one level and looks for the "comp" class, moves down another level and looks for the "selected" class. The problem is the "comp" and "selected" classes are both direct children of the "choice" class. Here's how it's solved.

.choice .comp.selected {
background-color:yellow;
border:solid 2px green;
Remove the space between ".comp" and  ".selected", this tells CSS (and jQuery) that they are on the same DOM level.

A simple game, but jQuery is outstanding. I'll finish up the try.jQuery.com prep-work today. The next step will be to dig into C# and the .Net framework.

T-minus 26 days

Here's the game in case you missed it the first time.

Monday, September 16, 2013

Web Pre-Work

I gave my notice today. Sad to go, but excited to see what's next and take on a new challenge. My nerves are starting to pick up a little bit.

I've finished the HTML and CSS courses on CodeAcademy. I've done some web design so it was a nice review. It filled in some gaps regarding tables. I like that HTML5 has simplified the DOCTYPE declaration.

I'm about half-way through with the JavaScript section. I've never worked in JavaScript before, it's syntax feels a lot like PHP.

I'm excited to get to jQuery. I'd like to write a simple rock, paper, scissors, lizard, Spock game with clickable icons and a score board. I need the DOM manipulation in jQuery to manipulate the HTML to get this going.

Haven't started the C# yet. My books should arrive from Amazon tomorrow. 6 hours on a plane this Friday to get started working through them. Fingers crossed for an in-seat power plug.

T-minus 34 days

-Alex


Friday, September 13, 2013

I'm in! Let the building begin!

It's time to get started. There are things to build, code to write, and bugs to fix.

The transition will be bitter sweet. I'll be leaving many wonderful and inspiring people at my current job. It's time to move forward though.

There are several projects I've been working that are the start of a portfolio. I'll provide updates as I formalize it and I have more completed to show.

Portfolio
The first project is a reminder program for professional licenses.

The program downloads a CSV file from the web and checks it against an internal database. If changes have been made the internal database is updated and an email is sent congratulating them on renewing. If they need to renew but haven't it sends several reminder emails. I think 30, 10, 5 and 2 days are appropriate. Also an expiration notice email will go out.

Learning the tools
I need to transition over to the tools I'll be working with at camp. I've installed Visual Studio but I need to get comfortable with C# and moving around in my dev environment before camp. Let the refactoring begin!

I have a functioning (early) alpha written in Ruby. My internal 'database' is another CSV at this point. I'll eventually transition that over to SQL. Since I'll be working in C# I'm going to refactor the code as is into C#.

T-minus 37 days!