Search

Categories

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Send mail to the author(s) E-mail

# Friday, December 18, 2009

image

rb – Radio Button

cbk - Checkbox

cmb – Combobox

dtp – DateTimePicker

Debug helper code

int exp1 = 5;
int exp2 = 0;
try
{
    throw new ArgumentOutOfRangeException();
    int result = exp1 / exp2;
}
catch (DivideByZeroException)
{
    MessageBox.Show("Expression 1 is 0, please reenter");
}
catch (Exception ex)
{
    MessageBox.Show("Bad things are afoot:\r\n" + ex.Message + "\r\n" + ex.StackTrace);
}
finally {
    MessageBox.Show("and finally");
}
Comments [0] | | # 
Chrome and Google

Ctrl Enter to open link in new tab

Up / Down arrow to select different search items

VS2010

Shift Del – deletes line and puts into clipboard

Ctrl Space – intellisense

Ctrl – , Ctrl Shift -    Jumps forwards, back to where you are editing.

Ctrl +

Alt R, Alt R – Refactor, Rename (F2 has stopped working for some reason).. or Shift F10, R R

Control , – Goto something

Control . – import namespace

Ctrl + E, D   Format Document

Shift + F10, U   Run tests.. only does 1 if in that test.

Ctrl R Ctrl T – Run Test (in debug).. to get Test Window to open, run the app (say forms app) and open the window.  it remembers!

Ctrl R, T – Run test

Ctrl R A = Run test in current context

Shift Alt C – Add class

VS2008

Shift Alt Enter – Full Screen

Ctrl + M, O – Collapse all methods

Ctrl + M, P – Expand all methods

Ctrl M, Ctrl M – Collapse / Expand current method

Ctrl + Alt – navigate between methods quickly

Ctrl -     - if you go to a method, this brings you back to where you were

Ctrl space – intellisense

Ctrl . – puts in a using statement (if needed)

Alt V P – View Solution

Alt V V – View Server Explorer (DB)

VS – Web

Alt B H to publish a website

Alt B O to select configuration manager

Ctrl Shift N – hides non visual controls.. clashes with resharper

Resharper

Alt Enter – do stuff

Alt Insert – Resharper generate

Ctrl Shift R – Refactor (ie to extract a method)

Ctrl + Q – Resharper.. documentation

Alt Up / Down – go to next member / tag

Ctrl Shift N – go to a file

Ctrl Shift Alt N – go to a method anywhere

VS – MVC

ctrl M, ctrl C – add a controller

ctrl M, ctrl  V – Add a view

Vimperator

:set guioptions+=mT   - have created an autohotkey script for this

:mkv!  - save settings

 

j and k – up and down

ctrl d and ctr u – page up and down

shift G and GG – bottom and top

/ – search

N – next… shift N previous

:qa and shift zz and   - exit

d – delete tab

Shift H or alt left arrow - back

O to open a URL with current page selected

t – tabopen

f – follow

F – follow in new window

gt flip between tabs

escape up arrow – shows the history in vimperator!

:qmark g http://www.gmail.com   - adds a quickmark

gog   - goes to the quickmark g  (gmail in my case)

Windows

tab tab – on login screen (winxp) this highlights the box

win l – lock

win d – minimize

win e – explorer

explorer type ph quickly to go to the first directory starting with ‘ph’

alt f4 – close

shift alt space n – minimize (with launch installed, otherwise alt space n)

Alt Tab

Alt Esc – cycle through open windows

F4 – Alt D  - display address bar in explorer

Shift F10 – right click

Ctrl Escape – display start menu

Backspace – go up a level in windows explorer

Win M – minimize

Win SHIFT M – restore

Nul Lock + Asterisk – in explorer display all subfolders under this one

Win F – Find (am trying out Windows Search 4.0)

 

Quicktime Player

L – fast forward

K – fast backwards

Outlook

F9 – Send and Reeive All

Programming Winform Element Names

txt – Text Box

lbl – Label

lst – Listbox

rb – Radio Button

cbk - Checkbox

cmb – Combobox

dtp – DateTimePicker

mnu – Menu Options (that go in MDI)

Language

rvalue – register value

lvalue – location value

MDI – Multiple Document Interface

RDC – Really Dumb Code

Comments [0] | | # 
# Monday, December 14, 2009

Was trying to figure out why something worked: http://stackoverflow.com/questions/1896871/c-calling-a-method-and-variable-scope

From http://rapidapplicationdevelopment.blogspot.com/2007/01/parameter-passing-in-c.html and Jon Skeets: http://www.yoda.arachsys.com/csharp/parameters.html

 

static void Main(string[] args)
    {
 
        int i = 5; // #1 a value type.. i and j are both 5, but seperate
        int j = i; 
        j = 10;
        Console.WriteLine(i); // prints 5
 
        StringBuilder sb1 = new StringBuilder("2.hello"); // #2 a reference type
        StringBuilder sb2 = sb1;  
        sb2.Append(" world");
        Console.WriteLine(sb1); // prints 2.hello world
 
        string s1 = "3.hello"; // #3 Immutable reference type
        string s2 = s1;  // s1 and s2 actually point to the same memory location now
        s2 += " world"; // seems like they split now.. behave like value types
        Console.WriteLine(s1); // prints 3.hello
 
        int a = 5; // #4 Value type passed by value
        Change(a); // equivalent to instantiating a new variable and assigning it the the first.
        Console.WriteLine(a);  // prints 5.
 
 
        StringBuilder ssb1 = new StringBuilder("5.hello"); // #5 reference types passed by value
        CChange(ssb1); 
        Console.WriteLine(ssb1); // prints hello world
 
        int g = 5; // #6 value type passed by reference
        DChange(ref g); 
        Console.WriteLine(g); // prints 10
 
        StringBuilder sssb1 = new StringBuilder("7.hello"); // #7 reference type passed by reference
        EChange(ref sssb1);
        Console.WriteLine(sssb1.ToString()); // null ref exception
 
        Console.ReadLine();
    }
 
    static void EChange(ref StringBuilder sssb2)
    {
        sssb2.Append(" world");
        sssb2 = null;
    }
 
    static void DChange(ref int g)
    {
        g = 10;
    }
 
    static void CChange(StringBuilder ssb2)
    {
        ssb2.Append(" world");
        ssb2 = null;
    }
 
    static void Change(int b)
    {
        b = 10;
    }
Value types:

int, etc..

Reference types

Arrays eg int[]

List<T>

Class, Interface, Delegate and Array types are all reference types.

Immutable Reference Types:

string

Comments [0] | | # 

 

On overloaded constructors, call the default constructor.  Constructor chaining

public clsDates(int yr) : this()

public clsDates()

Property Methods (getters and setters)

Cohesion – make a method do a single task only

Coupling - (Method coupling) ability to make changes in one method without forcing changes in another… ie make each method so it can operate independently

Deck of Cards

image

I’ve simplified the example given in the book to:

private void btnShuffle_Click(object sender, EventArgs e)
    {
        clsCardDeck myDeck = new clsCardDeck();
        int numberOfIterations = myDeck.ShuffleDeck();
        lblResult.Text = numberOfIterations.ToString();
 
        // display the newly shuffled deck in the multiline textbox.
        int deckSize = myDeck.DeckSize;
        for (int i = 1; i < deckSize+1; i++)
        {
            txtOutputResult.Text += myDeck.getOneCard(i) + " ";
        }
    }
 
then for clsCardDeck
 
public int ShuffleDeck()
{
    int index;
    int val;
    Random rnd = new Random();
    passCount = 0; // count how many times through the while loop
    index = 1;
    Array.Clear(deck, 0, deck.Length); // initialise the deck array to 0's
 
    while (index < deck.Length) // loop probably 52 times.. initialised at the top of this class.
    {
        // add 1 to the offset 0-based array
        val = rnd.Next(DECKSIZE) + 1; // Generates values between 1 - 52
        if (deck[val] == 0) // Is this card place in the deck "unused"?
        {
            deck[val] = index; // yep, so assign it a card place.. ie put the index number into a random spot
            index++; // get ready for the next card
        }
        passCount++;
    }
    return passCount;
}
 
/// <summary>
/// Show a given card in the deck
/// </summary>
/// <param name="index">the index of the position where the card is found</param>
/// <returns>the pip for the card, or empty or error</returns>
public string getOneCard(int index)
{
    if (index > 0 && index <= deck.Length && nextCard <= deck.Length)
        return pips[deck[index]]; // returns the 6H style string of the deck.
    else
        return ""; // error
}

Sideways Refinement:

1. Initialize – build and display the main form (frmDave)

2. Input – none

3. Process – Shuffle the deck (clsCardDeck)

4. Display – Show deck on 4 rows (frmDave) –> which uses Get One Card at a Time (clsCardDeck)

Clear Deck (frmDave)

5. Terminate – Close (frmDave)

this helped in thinking which class had which responsibilites.

InBetweenGame

You deal 2 cards, then bet on the outcome of the hidden 3rd card. Shown below I bet on a card coming up between 9D and QS.  It was a 3H, so I lost.

Debug information is in the textbox to the right hand side.

Source here

image

The architecture uses a middle ‘tier’ of rules, and a CardDeck class as used above.

Sideways Refinement:.. showing the responsibilities of each class.  Very useful.

1. Initialise – build and display the form (frmMain) – get initial wager and balance (clsRules)

- Do initial shuffle (clsCardDeck)

2. Input – get amount of wager (frmMain)

- ask for new cards.. deal.. (frmMain)

- ask for bet (frmMain)

3. Process – deal a hand (rules)

- enough money to bet (frmMain)

- enough cards in deck (clsCardDeck)

- no? shuffle (clsCardDeck)

- Get three cards (clsRules)

- Figure out winner and position to display card (clsRules) **note here it knows the winner after deal button is pressed

- make a bet (frmMain)

4. Display - display if TIE, WIN, LOSE message and adjust balance (frmMain)

- display card in correct position (frmMain)

5. Terminate – Close

This was interesting code:.. see post on this blog on Parameter Passing in C#.

// get three cards, result, and position to display
 // nb cards is a reference type (all arrays are), so don't need a ref.. it will be changed here.
 myRules.DealHand(cards, ref betResult, ref position);
Comments [0] | | # 
# Saturday, December 12, 2009

Continuing in the book series.

Part III, Chapter 9 – Designing Classes

Major benefits from OOP

  • Data encapsulation
  • Code reuse

Write a class that determines the date of Easter, and whether it is a leap year.

5 Programming Steps:

  1. Initialization
  2. Input
  3. Process
  4. Display
  5. Terminate
UML Light and Static

- daysInMonth : static int[]

// regardless of how many instances of this class you create, you get only one array named daysInMonth.

// the – means it is private..

// properties.. generally we want to hide as much as possible.

Use static with any data that can be shared between instances of classes

or any data that must be present the moment the program is ready to start executing

Code is here

image

This is how the author likes to set out his classes..

using System;
 
public class clsDates
{
    // PROPERTIES
    // symbolic constants
    // static members
    static int[] daysInMonth = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
 
    // instance members.. this is the common term for all non-static properties.
    int day;
    int month;
    int year;
    int leapYear;
    DateTime current;
 
    //METHODS
    // constructor
    public clsDates()
    {
        current = new DateTime();
    }
 
    // property methods
    // helper methods
    // general methods
 
    /// <summary>
    /// Purpose:  To determine if the year is a leap year.
    /// </summary>
    /// <param name="year">the year under construction</param>
    /// <returns>1 if a leap year, 0 otherwise</returns>
    public int getLeapYear(int year)
    {
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
            return 1; // it is a leap year
        else
            return 0;
    }
 
    /// <summary>
    /// To determine the date for Easter given a year
    /// </summary>
    /// <param name="year">int year - the year under construction</param>
    /// <returns>the date in DateTime as MM/DD/YYYY format</returns>
    public string getEaster(int year)
    {
        int offset;
        int leap;
        int day;
        int temp1;
        int temp2;
        int total;
 
        offset = year % 19;
        leap = year % 4;
        day = year % 7;
        temp1 = (19 * offset + 24) % 30;
        temp2 = (2 * leap + 4 * day + 6 * temp1 + 5) % 7;
        total = (22 + temp1 + temp2);
        if (total > 31)
        {
            month = 4; // Easter is in April
            day = total - 31; // on this day
        }
        else
        {
            month = 3; // Easter is in March
            day = total; // on this day
        }
        DateTime myDT = new DateTime(year, month, day);
        return myDT.ToLongDateString();
    }
}

I loved his irreverant style Exercises:

Q: Give a good example of where you would use the public access specifier to define a class property?

A: I couldn’t think of one either :-)

SOC = Show Off Code :-)

Comments [0] | | # 
# Thursday, December 10, 2009

 

Chapter 8 – Arrays

Array cheat code:

string[] names = new string[10]; // this array can only have 10 elements
        names[0] = "Dave";
        names[1] = "Heidi";
        names[2] = "Scotty";
        for (int i = 0; i < 3; i++)
        {
            lstOutput.Items.Add(names[i].ToString());
        }

        int[] coolNumbers = new int[10] {1,2,5,7,11,13,17,19,23,27};  // initializing an array

        int[,] grades = new int[5,4]; // grades and which type eg Freshman, Sophmore, Junior, Senior
        grades[0, 0] = 1;
        grades[1, 0] = 4;

// Declare a single-dimensional array 
int[] array1 = new int[5];
 
// Declare and set array element values
int[] array2 = new int[] { 1, 3, 5, 7, 9 };
 
// Alternative syntax
int[] array3 = { 1, 2, 3, 4, 5, 6 };

Setting up a project template in Visual Studio.  Very useful if you don’t want a standard WinForms project etc.. to start with:

This is the way the book recommends starting a project.  Notice how few references, and we’re not using partial classes and  a seperate Program.cs file.  I like this method as it is keeping things very simple as easy to understand.

screen8

To export this as a template, go to File, Export as template.

Then to start a new project, do File, New then look for My Templates down the bottom..

screen10

Letter Count program

5 Steps

1) Initialisation

2) Input Step

  text is entered by the user

3) Process Step

  examine each letter types in the textbox and count how many times each alpha character occurs

4) Output Step

  Copy the letter counts to a listbox

5) Terminate

 

image

for (int i = 0; i < input.Length; i++) // loop over each letter in the input string
        {
            oneLetter = input[i]; // extract the letter we want to examine
            index = oneLetter - LETTERA; // taking int 65 away from a character
            if (index < 0 || index > MAXCHARS) // making sure range is between 0 and 25
                continue;
            count[index]++; // adding 1 to the count of the appropriate array
        }

The output to the listbox is interesting in the string.Format.

for (int i = 0; i < MAXLETTERS; i++)
        {
            // letter has 4 spaces and is right justified
            // space has 20
            // count is just displayed
            buff = string.Format("{0, 4} {1,20} {2} ", (char) (i + LETTERA), " ", count[i]);
            lstOutput.Items.Add(buff);

ListView

Displaying formatted lists is very common, so there is special control for doing this:

image

Go to columns.. and also change view to details, so the column headers are displayed on the output.

image

 

Multidimensional Arrays

image

int[,] myData = new int[number, 3];  // create new array with 3 dimensions

// Program and Display
for (int i = 0; i < number; i++)
{
    myData[i, 0] = i;
    myData[i, 1] = i*i;
    myData[i, 2] = i*i*i;
}

Collections

A collection is a set of objects which share the same characteristics eg strings

image

int[] days = new int[] {0,31,28,31,30,31,30,31,31,30,31,31 };        
string[] weekDays = new string[] {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; 

foreach (string str in weekDays) 
{ 
 lstOutput.Items.Add(str); 
} 

 foreach (int val in days) 
 { 
   lstOutput.Items.Add(val); 
 }

Because arrays are objects, you can treat them as a collection and iterate over them with a foreach loop.

ArrayList

You can’t use a static array until it’s dimension has been set eg

string[] names = new string[100]  // this can hold 100 names, and no more!

image

ArrayList names = new ArrayList();

names.Add(txtName.Text);

Static multiarray, using ListView

Ch9IdealWeights

image

 

Random Values and Sorting

image

Uses a list box which is populated by a 1 dimensional array of random numbers

Sorting is done via:

Array.Sort(arrayOfNumbers);

Random Values and Stars

RandomValues VS2008 source

image

I built the stars using a loop.  However a better solution is:

string stars = “**********************************************************************”

stars.Substring(0, howeverManyYouWant)

this was what I had:

  1. // add appropriate number of start to the end of the string.
  2.             int actualNumber = arrayOfNumbers[i];
  3.             string stars = "";
  4.             // build the number of stars
  5.             for (int j = 1; j <= actualNumber; j++)
  6.             {
  7.                 stars += "*";
  8.             }
  9.             
  10.             string output = actualNumber.ToString() + stars;
  11.             lstResults.Items.Add(output);
Comments [0] | | # 

 

beginning

This book looked interesting as it seemed to be written by someone with a lot of experience teaching.  Sometimes it is great to go back to basics, as there is always something new to learn, and I was so right!  Here are my notes, source code, screenshots.

Chapter 1 – Getting Started

setting up the IDE.. VS2008 Express.   And installing the MSDN library.. 2GB download here: http://www.microsoft.com/downloads/details.aspx?FamilyID=7BBE5EDA-5062-4EBB-83C7-D3C5FF92A373&displaylang=en

Also a tool to take msdn into a chm help file: http://www.codeplex.com/packagethis

Chapter 2 - Understanding Objects

Class eg Person.. a template used to describe an object
  properties..that describe the object
  methods.. or actions that we associate with the object

Object eg the Person Object for Jack

naming convention
  cls - class
  txt - textbob
  btn - button

  good for selecting in the ide

making a blank project
putting in references for winform:

System, System.Drawing, System.Windows.Forms

putting in bootstrapper
change output to winform and tell which startup object asdf

using System;
using System.Windows.Forms;

public class frmMain : Form
{
    #region Windows code
    private void InitializeComponent()
    {
    }
    #endregion

    public frmMain()
    {
        InitializeComponent();
    }

    public static void Main()
    {
        frmMain main = new frmMain();
        Application.Run(main);
    }

}

3d on labels cool
making a default enter button (acceptbutton)
ctrl x and ctrl d shortcut keys with the ampersand on Text
True Type vs non fonts.. good to make things line up properly.

**screenshot mailing label program

**source code here too … c:\code\oopbook

screen

 

Part II – Understand C# Syntax

Chapter 3 – Understanding Data Types

Integer Division
.Focus property when coming back from an error
Int.TryParse method to see if it really is an integer
.Visible proerty of a textbox

Floating Point
AcceptButton
StartPosition - CenterScreen

int
float - 32 bit.. F,f
double - 64 bit... this is the usual one.. D,d
Decimal - 128bit (28 digit precision)..  M,m

eg int i = 0.5M

**insert source code  c:\code\oopbook\ch3IntegerDivision\

screen1

Also Fahrehiegh converter:

** put in source code link… c:\code\oopbook\ch3TempConvert

screen2

Interesting here was the use of consts…

how a division takes up more cycles, so better not to do 5/9 but to put in the decimal equivalent.  The out.. focus when  coming back from an error.  And unhiding the results box when it needs to be.

bool flag;
        double operand1;
        double answer;
        const double FIVENINTHS = 0.55555555;
        const double ZEROFAHRENHEIGHT = 32;

        flag = double.TryParse(txtOperand1.Text, out operand1);
        if (flag == false)
        {
            MessageBox.Show("Enter a whole number", "Input Error");
            txtOperand1.Focus();
            return;
        }

        answer = FIVENINTHS *(operand1 - ZEROFAHRENHEIGHT);

        txtResult.Text = operand1.ToString() + " degressF "  + " equals " + answer.ToString() + " degreesC";
        txtResult.Visible = true;

Ch4 – Understanding C# Statements

operand   eg 10
operator eg +, -, *, /, % these are binary operators
  unary
  binary
  ternary

expression
  one or more operands and their associated operator

statements
  one or more expressions terminated by a semicolon.

lvalue - location value.. memory address
rvalue - register value..actual value

eg int i
this is defining a variable to be at address 900,000 ie lvalue
i = 10
this is declaring a variable to have an rvalue of 10

if narly bug, hardcode data into the textboxes to make it easy!
10 / 6

avoid magic numbers
use const

Ch5 - Reference Data Types

If you're not going to manipulate data with Maths, store it as a string.

intellisense (expect in Resharper which is clearer)
  hand is a property
  diamond is a method

Pass by reference vs Pass by Value

Ctrl spacebar to give help on methods/props near current selection.

**insert source…c:\code\oopbook\ch5StringTester

screen3

Escape characters eg string message = “this is a \\ backlash, and this is a quote \””;

String literals eg string message = @”Go the the c:\program files\ directory and”;

DateTime reference Objects

**upload source code** c:\code\oopbook\ch5DateTime

screen4

Interesting code here is:

txtLongDate.Text = myTime.ToString("D");

Starting the app (everything gets populated automatically without having to press Test)

public frmMain()
{
    // 2) place all the label, textbox and button objects in correct positions on the form and set their properties
    InitializeComponent(); 
    UpdateTimeInfo();  // 3) set the properties of the objects just created
}

public static void Main()
{
    // 1) start here then this goes to constructor now everything is in memory ready to go
    frmMain main = new frmMain(); 
    Application.Run(main);  // 4) run the app
    MessageBox.Show("hello"); // 5) this would only be displayed when Close() is called.
}

Ch6 – Making Decisions In Code

20% of a programs time is spent in initial development

80% of a programs time is spent in testing, debugging, and maintenance

flag = int.TryParse(txtOperand1.Text, out operand1);

don’t need to initialise operand1 to any value.. int operand1 is fine.

**upload code ** c:\code\oopbook\ch6OddOrEven

screen5

Interesting here is the .Clear method after the check.

MessageBox.Show("Enter a whole number", "Input Error");
        txtOperand1.Clear();
        txtOperand1.Focus();
        return;

Brackets Style:

K&R (Kernighan and Ritchie… 1978 book on C)

if (x == 2) {

//do something

}

Other style:

if (x == 2)

{

  //do something

}

or

if (x == 2)

  // do something

the danger of the above is it’s easier to make a mistake like:

if (x == 2);  // notice the semicolon!

  //do something

Nested If Statements / Cascading if statements

Switch

statements are better

switch (expression1)

{

case 1:

// do stuff here

break;

case 2:

// do other stuff

break;

default:

// do the default stuff.

break;

}

Ch7 Statement Repetition Using Loops

screen1

for (i = start; i <= end; i++)
{
    // {0, 5} first argument and right-justify it in a field of five characters
    // {1,20} second argument and right-justify in a field of twenty characters
    buff = string.Format("{0, 5}{1, 20}", i, i*i);
    lstOutput.Items.Add(buff);
}

for loops – ideally suited for counting operations

while loops are good for searching for a particular value in a set

screen6

bucket = 1;
        for (int i = num; i > 1; i--)
        {
            bucket *= i;
        }

Don’t need to do the last factorial as it multiplies by 1, so leave i > 1.

Keyboard shortcut – F7 to view designer / view code

 

screen7

Notice the currency here:

buff = string.Format("{0,4}, {1,15:C}", i, assetIsWorth);
lblResults.Items.Add(buff);

http://www.programgood.net/2009/12/14/ParameterPassingInCValueAndReferenceTypes.aspx
Comments [0] | | # 
# Wednesday, November 25, 2009
( Tools )

A very annoying error in VS2008, when trying to open VS2005/VS2005 Express web projects…

From: http://forum.strataframe.net/Topic20774-14-1.aspx

The solution was to right click on the solution file and click open with.  Navigate to "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe" and click to open.  The conversion wizard runs and the project will then open.

Comments [0] | | # 
# Monday, November 09, 2009
( Stuff )

After browsing Scott Hanselmans Tools list

http://www.hanselman.com/blog/ScottHanselmans2009UltimateDeveloperAndPowerUsersToolListForWindows.aspx 

I thought I’d try Windows Live Writer.. it worked first time :-)

Ahh.. for those who have no idea what Windows Live Writer is (like myself 15mins ago).. it means you can post blog articles from a windows app on your desktop.  No more messing around with html interface (and worrying about session expiring!)

Comments [0] | | # 
# Thursday, November 05, 2009
I know I've skipped a few chapters.. but hey.. who is perfect?  Sometimes, it is good to get to some concrete results to give some pespective.

After months of playing with code (why do things always take longer than you think..?), and having a blast, I've now forgotton everything I know about asp.net.  So time to do some spikes.

Here is a super simple reminder of asp.net syntax and simple events:

Default.aspx (\code\tddBook\SimpleAspSpike)

<%@ Page Language="C#" AutoEventWireup="true"  CodeBehind="Default.aspx.cs" Inherits="WebSite2testWebProj._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form2" runat="server">
    <div>
    hello world from html<br />
    <%= "Hello from asp.net" %> <br />
    
    This is a label: <asp:Label ID="label1" runat="server" /> <br />
    The time is: <%= System.DateTime.Now.ToLongTimeString()%> <br />
    This is a textbox: <asp:TextBox runat="server" ID="textbox1" /><br />
    A button: <asp:Button runat="server" ID="button1" Text="press me" onclick="button1_Click" /><br />
   Label2 is here: <asp:Label ID="label2" runat="server" /><br />
   asp.net uses viewstate.. so the button is just a submit button, which then goes back to the server, refreshes the page with the new data in the label2 label. <br />    
    </div>
    Autopostback is set in the following DropDownList (server control)... makes contact with the server each time an item is selected.. which we can use to wire up an event..onselectedindexchanged<br />
    <asp:DropDownList runat="server" ID="GreetList" AutoPostBack="true" 
        onselectedindexchanged="GreetList_SelectedIndexChanged">
        <asp:ListItem Value="no one">No one</asp:ListItem>
        <asp:ListItem Value="world">World</asp:ListItem>
        <asp:ListItem Value="universe">Universe</asp:ListItem>
    </asp:DropDownList><br />
    Label3: <asp:Label ID="label3" runat="server" /> <br />
    </form>
</body>
</html>

And the Default.aspx.cs

using System;
using System.Web.UI;

namespace WebSite2testWebProj
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write("Hello from Page_Load in codebehind");
            label1.Text = "Hello from the codebehind into a label";
            textbox1.Text = "Textbox from codebehind";
        }

        protected void button1_Click(object sender, EventArgs e)
        {
            label2.Text = "button pressed";
        }

        protected void GreetList_SelectedIndexChanged(object sender, EventArgs e)
        {
            label3.Text = "Hello, " + GreetList.SelectedValue;
        }
    }
}

Ok, looking good so far.

Difference between CodeBehind and CodeFile

WebSite or Web Application Project?
http://www.dotnetspider.com/resources/1520-Difference-between-web-site-web-application.aspx

WebSite is really simple, with no project file.  Web Application Project has a project file.

Found that remembering how to access databases isn't too easy:

looking at old project:
http://treasuresprint.blogspot.com

Realised I didn't put up the sourcecode at the time, and have managed to find it on my laptop:


Connecting to and displaying data from a DB very easily:

Deafult.aspx (\code\tddBook\DBConnectySpike)
<form id="form1" runat="server">
    <div>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TreasureConnectionString %>"
            SelectCommand="SELECT [StuffId], [Description] FROM [Stuff]"></asp:SqlDataSource>
        <br />
        <br />
        this is a gridview&nbsp;<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataKeyNames="StuffId" DataSourceID="SqlDataSource1">
            <Columns>
                <asp:BoundField DataField="StuffId" HeaderText="StuffId" InsertVisible="False" ReadOnly="True"
                    SortExpression="StuffId" />
                <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
            </Columns>
        </asp:GridView>
        <br />
        this is a datalist<br />
        <br />
        <asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1" >
            <ItemTemplate>
                <asp:Literal ID="Literal2" runat="server" Text="Description:"></asp:Literal>
                <asp:Literal ID="Literal1" runat="server" Text='<%# Eval("Description") %>'></asp:Literal>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:Literal ID="Literal2" runat="server" Text="Description:"></asp:Literal>
                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("Description") %>' Width="208px"></asp:TextBox>
            </EditItemTemplate>
        </asp:DataList><br />
        <br />
        this is a details view</div>
        <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" CellPadding="4"
            DataKeyNames="StuffId" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None"
            Height="50px" Width="341px">
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <CommandRowStyle BackColor="#D1DDF1" Font-Bold="True" />
            <EditRowStyle BackColor="#2461BF" />
            <RowStyle BackColor="#EFF3FB" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <Fields>
                <asp:BoundField DataField="StuffId" HeaderText="StuffId" InsertVisible="False" ReadOnly="True"
                    SortExpression="StuffId" />
                <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
            </Fields>
            <FieldHeaderStyle BackColor="#DEE8F5" Font-Bold="True" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" />
        </asp:DetailsView>
        <br />
        <br />
    </form>
And in the web.config:
<connectionStrings>
    <add name="TreasureConnectionString" connectionString="Data Source=localhost;Initial Catalog=Treasure;Persist Security Info=True;User ID=dave;Password=letmein" providerName="System.Data.SqlClient"/>
    </connectionStrings>
So it should come out like this:


Thoughts
ASP.NET offers some controls to make life 'easier' such as databinding, edit, deleting, sorting on the gridview:  All pretty powerful for RAD, however for testable apps.. am not sure this is the way.  Or perhaps other Grid controls like Telerik are better.  Maybe best to Keep it Simple.

Ideally we want testable code, with a thin layer of UI code on top.
A gridview with update
        <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:TreasureConnectionString %>" 
        SelectCommand="SELECT [StuffId], [Description] FROM [Stuff]"
        UpdateCommand="UPDATE Stuff SET Description=@Description WHERE StuffID=@StuffID">
        </asp:SqlDataSource>
         <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="StuffId" AutoGenerateEditButton="true" DataSourceID="SqlDataSource2">
           <Columns>
                <asp:BoundField DataField="StuffId" HeaderText="StuffId"/>
                <asp:BoundField DataField="Description" HeaderText="Description"/>
            </Columns>
         </asp:GridView>


And DropDownList / TextBox common usage:




This is all in the DB spike source code here:
DBConnectSpike.zip (15.17 KB)

Data Control Summary
http://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/data/default.aspx

Gridview - the classic Grid..edit, delete, sort, page.  Takes advantage of DataSource controls
DataList - items in a repeating list
DetailsView - typically used.. if a gridview item is selected, the detailsView is displayed to edit.
FormView - same as above but with no built in template.
Repeater - has no built in layout or styles.  No column layout. No Edit/Del

Going through the SearchPage.aspx.. trying to get any of this application to compile.  Have got source from book.. however..  good practise to chop code and and try and work through.  Hmm - sometimes better to revert back to compiling code in source control.

This project is in need of refactoring... too complex currently.  Would like to 'defactor' for simplicity, then put some patterns back in.  Webservice would be first to go, and use POCOs.  XSD definition for DTOs would go as well, with simple objects as definitions.  DAL I'd like to take out Datasets and use a manual DAL.

Most important thing is to get it working.  Good thing about this project so far, is that it is testable at every level.
Comments [0] | | #