How to get the parameters from your Stored Procedures in code behind.

Category : ADO / SQL, ASP.Net, C#

THE KEY LINE BELOW IS : SqlCommandBuilder.DeriveParameters(cmd);

SqlConnection c = new SqlConnection(TextboxConnString.Text);
 
//NAME OF STORED PROC
string sql = DropdownStoredProcs.Value.ToString();
 
SqlCommand cmd = new SqlCommand(sql, c);
cmd.CommandType = CommandType.StoredProcedure;
 
c.Open();
SqlCommandBuilder.DeriveParameters(cmd);
foreach (SqlParameter param in cmd.Parameters)
{
     if ((param.Direction == ParameterDirection.Input) || (param.Direction == ParameterDirection.InputOutput))
     {
         //Notice that I can get the Name of the parameter as well as it's DBType...
         string paramDescription = param.ParameterName + " | " + param.SqlDbType.ToString();
         DropdownSPParameters.Items.Add(paramDescription, param.ParameterName);
     }
}
c.Close();

How to get a list of your databases Stored Procedures from code behind.

Category : ADO / SQL, C#

This particular example fills a dropdown list with the list of Stored Procedures and takes it’s connection string from a textbox.

SqlConnection c = new SqlConnection(TextboxConnString.Text);
 
c.Open();
 
string sql = "SELECT name AS spname FROM sysobjects WHERE (xtype = 'p') ORDER BY name";
SqlCommand cmd = new SqlCommand(sql, c);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dtStoredProcs = new DataTable();
adapter.Fill(dtStoredProcs);
 
if (dtStoredProcs.Rows.Count > 0)
  {
       DropdownStoredProcs.Items.Clear();
 
        foreach (DataRow dr in dtStoredProcs.Rows)
                      DropdownStoredProcs.Items.Add(dr["spname"].ToString(), dr["spname"]);
   }
 
c.Close();

Creating a TABLE in the code behind.

Category : ASP.Net, C#

This worked well for me.  I created the TABLE in markup [MAKE SURE ITS AN ASP:TABLE with the runat server tag].

Then you can manipulate it from code-behind like so:

   TableRow tr = new TableRow();
   TableCell tc = new TableCell();
   Label label2 = new Label();
   label2.Text = "LAJLKFJDSLJFLKDF";
   tc.Controls.Add(label2);
   tr.Cells.Add(tc);
   MyTable.Rows.Add(tr);

Hope this helps!

Important difference between for each and for next loops.

Category : C#, VB.Net

For Each loops is a read-only loop! In other words, you cannot mutate the reference you are referring to.

A For Next loop allows mutation, plus I like For Next’s because they allow me to determine if I am on the final loop or not…

Examples,

For x as integer = 0 to myStringArray.Count – 1

myStringArray(x) += “add this to end”

if x = myStringArray.Count – 1 then myStringArray(x) += “, and this is the last element!”
Next

cheers!
t

C# Vs. VB – Arrays….

Category : C#, VB.Net

I would just like to point out two areas where both C# and VB.Net beat the other one in the usage of arrays.

C# PRO:

You can redefine your array simply in C# by simply reinitializing the array:

//Declare array
int[ ] myInts = new int[20];
//Now reinitialize like this
myInts = new int[40];

In VB you have to reinitialize with the ReDim keyword

Dim myInts(20)
ReDim myInts(40)

Not a big deal but I give the better implementation to C# on this one…however.
===========================================

In VB.Net you can actually reinitialize an array AND MAINTAIN the data within the current array!
This is accomplished by using the ‘Preserve’ keyword. (this is not available in C#)

'Declare array
Dim myInts() As Integer = { 1,2,3,4 }
'Resize array and keep the data with the Preserve keyword
ReDim Preserve myInts(20)

VB —> C# Syntax Reference

Category : C#, VB.Net

Created by Dr. Frank McCown, Harding University Computer Science Dept.  http://www.harding.edu/fmccown/vbnet_csharp_comparison.html

Program Structure


VB.NET

C#

Imports System

Namespace Hello
Class HelloWorld
Overloads Shared Sub Main(ByVal args() As String)
Dim name As String = “VB.NET”

‘See if an argument was passed from the command line
If args.Length = 1 Then name = args(0)

Console.WriteLine(“Hello, ” & name & “!”)
End Sub
End Class
End Namespace

using System;

namespace Hello {
public class HelloWorld {
public static void Main(string[] args) {
string name = “C#”;

// See if an argument was passed from the command line
if (args.Length == 1)
name = args[0];

Console.WriteLine(“Hello, ” + name + “!”);
}
}
}

Data Types


VB.NET

C#

Value Types
Boolean
Byte, SByte
Char
Short, UShort, Integer, UInteger, Long, ULong
Single, Double
Decimal
Date

Reference Types
Object
String

Initializing
Dim correct As Boolean = True
Dim b As Byte = &H2A   ‘hex
Dim o As Byte = &O52   ‘octal
Dim person As Object = Nothing
Dim name As String = “Dwight”
Dim grade As Char = “B”c
Dim today As Date = #12/31/2007 12:15:00 PM#
Dim amount As Decimal = 35.99@
Dim gpa As Single = 2.9!
Dim pi As Double = 3.14159265
Dim lTotal As Long = 123456L
Dim sTotal As Short = 123S
Dim usTotal As UShort = 123US
Dim uiTotal As UInteger = 123UI
Dim ulTotal As ULong = 123UL

Type Information
Dim x As Integer
Console.WriteLine(x.GetType())          ‘ Prints System.Int32
Console.WriteLine(GetType(Integer))   ‘ Prints System.Int32
Console.WriteLine(TypeName(x))        ‘ Prints Integer

Type Conversion
Dim d As Single = 3.5
Dim i As Integer = CType(d, Integer)   ‘ set to 4 (Banker’s rounding)
i = CInt(d)  ‘ same result as CType
i = Int(d)    ‘ set to 3 (Int function truncates the decimal)

Value Types
bool
byte, sbyte
char
short, ushort, int, uint, long, ulong
float, double
decimal
DateTime   (not a built-in C# type)

Reference Types
object
string

Initializing
bool correct = true;
byte b = 0×2A;   // hex

object person = null;
string name = “Dwight”;
char grade = ‘B’;
DateTime today = DateTime.Parse(“12/31/2007 12:15:00″);
decimal amount = 35.99m;
float gpa = 2.9f;
double pi = 3.14159265;
long lTotal = 123456L;
short sTotal = 123;
ushort usTotal = 123;
uint uiTotal = 123;
ulong ulTotal = 123;

Type Information
int x;
Console.WriteLine(x.GetType());              // Prints System.Int32
Console.WriteLine(typeof(int));               // Prints System.Int32
Console.WriteLine(x.GetType().Name);   // prints Int32

Type Conversion
float d = 3.5f;
int i = (int)d;   // set to 3  (truncates decimal)

Properties


VB.NET

C#

Private _size As Integer

Public Property Size() As Integer
Get
Return _size
End Get
Set (ByVal Value As Integer)
If Value < 0 Then
_size = 0
Else
_size = Value
End If
End Set
End Property

foo.Size += 1

private int _size;

public int Size {
get {
return _size;
}
set {
if (value < 0)
_size = 0;
else
_size = value;
}
}
foo.Size++;

File I/O


VB.NET

C#

Imports System.IO

‘ Write out to text file
Dim writer As StreamWriter = File.CreateText(“c:\myfile.txt”)
writer.WriteLine(“Out to file.”)
writer.Close()

‘ Read all lines from text file
Dim reader As StreamReader = File.OpenText(“c:\myfile.txt”)
Dim line As String = reader.ReadLine()
While Not line Is Nothing
Console.WriteLine(line)
line = reader.ReadLine()
End While
reader.Close()

‘ Write out to binary file
Dim str As String = “Text data”
Dim num As Integer = 123
Dim binWriter As New BinaryWriter(File.OpenWrite(“c:\myfile.dat”))
binWriter.Write(str)
binWriter.Write(num)
binWriter.Close()

‘ Read from binary file
Dim binReader As New BinaryReader(File.OpenRead(“c:\myfile.dat”))
str = binReader.ReadString()
num = binReader.ReadInt32()
binReader.Close()

using System.IO;

// Write out to text file
StreamWriter writer = File.CreateText(“c:\\myfile.txt”);
writer.WriteLine(“Out to file.”);
writer.Close();

// Read all lines from text file
StreamReader reader = File.OpenText(“c:\\myfile.txt”);
string line = reader.ReadLine();
while (line != null) {
Console.WriteLine(line);
line = reader.ReadLine();
}
reader.Close();

// Write out to binary file
string str = “Text data”;
int num = 123;
BinaryWriter binWriter = new BinaryWriter(File.OpenWrite(“c:\\myfile.dat”));
binWriter.Write(str);
binWriter.Write(num);
binWriter.Close();

// Read from binary file
BinaryReader binReader = new BinaryReader(File.OpenRead(“c:\\myfile.dat”));
str = binReader.ReadString();
num = binReader.ReadInt32();
binReader.Close();

Levels of Access for Classes and Modules

Category : C#, VB.Net

Visual Basic Visual C# Available to
Public public All members in all classes and projects.
Friend internal All members in the current project.
Protected protected All members in the current class and in classes derived from this member’s class. Can be used only in member definitions, not for class or module definitions.
Protected Friend protected internal All members in the current project and all members in classes derived from theis member’s class.
Can be used only in member definitions, not for class or module definitions.
Private private Members of the current class only.

Getting simple text input from player in XNA game (tutorial)

Category : C#, XNA/Game programming

I needed a simple way to take text input from my XNA game for the use of a high score table. From what I could find, there is a class (GUIDE) that has a BeginShowKeyboardInput method….but

I honestly didn’t (and still DON’T) understand the whole IAsyncResult thing from the BeginShowKeyboardInput (I dont know what type that is or what an AsyncCallback function is … and I couldn’t really find an ‘English’ explanation…. so I resigned myself to the fact that I was going to have to think up my own solution (never really a BAD thing, huh)). **Not to mention that a full keyboard input thing (if that is what happens, never got a chance to see it) didn’t really fit the look and feel of my throwback space invaders clone.**

*********BTW – if anyone out there can point me to good a tute on that Keyboard thing, I would be grateful. ***************

So I decided to go with a brute force type of solution. It’s not pretty but it works and I was fairly proud of my newbie self and I thought it might be a good idea to put it out here since so many other people were trying to do the same kind of thing. Here is what I done:

I create a very brutish string array (notice that the FIRST index is a ‘_’ so that when it gets drawn to the screen the player sees ‘_ _ _ _ _’) that holds each character of the alphabet, index counters for each letter holder and a name for each letter position, and finally a variable that tells which of the five letters we are on.

bool hiScore = false; 
 
//Here is our alphabet array that we will use to fill the letter objects. 
string[] alphabet = new string[] { "_", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; 
 
//Index counters for the letters 
int ltrCounter1, ltrCounter2, ltrCounter3, ltrCounter4, ltrCounter5; 
 
//Here are the letters of the players name 
string plyrNamePos1, plyrNamePos2, plyrNamePos3, plyrNamePos4, plyrNamePos5; 
 
//This variable holds the position of what letter the player is changing 
int letterPosition = 1;

Make sure you zero them out at the beginning of your class and when you leave.
ltrCounter1 = 0;
ltrCounter2 = 0;
ltrCounter3 = 0;
ltrCounter4 = 0;
ltrCounter5 = 0;
plyrNamePos1 = alphabet[0];
plyrNamePos2 = alphabet[0];
plyrNamePos3 = alphabet[0];
plyrNamePos4 = alphabet[0];
plyrNamePos5 = alphabet[0];

Then place methods in your update method to grab the arrow keys and with them, change the letters of your holders.

            //UP AND DOWN KEYS FOR HIGH SCORE METHOD 
            if (InputHelper.IsNewKeyPress(Keys.Up)) 
            { 
                hiScoreUp(); 
            } 
            else if (InputHelper.IsNewKeyPress(Keys.Down)) 
            { 
                hiScoreDown();                    
            } 
 
            //Side to side for each letter - not allowing to go higher than 5 letters or less than 1 
            if (InputHelper.IsNewKeyPress(Keys.Right)) 
            { 
                letterPosition++; 
                if (letterPosition > 5) 
                { 
                    letterPosition = 5; 
                }                
            } 
            else if (InputHelper.IsNewKeyPress(Keys.Left)) 
            { 
                letterPosition--; 
                if (letterPosition < 1) 
                { 
                    letterPosition = 1; 
                }               
            } 
 
///////////////////////NOW HERE ARE THE METHODS TO CHANGE YOUR LETTERS 
//Case statement looks at where we are in the 5 letters and changes that one - IT also loops us through the alphabet and starts again on the other side so we do not go out of the array index.     
private void hiScoreUp() 
        { 
            switch (letterPosition) 
            { 
                case 1: 
                    ltrCounter1++; 
                    if (ltrCounter1 > 26) 
                    { 
                        ltrCounter1 = 0; 
                    } 
                    plyrNamePos1 = alphabet[ltrCounter1]; 
                    break; 
                case 2: 
                    ltrCounter2++; 
                    if (ltrCounter2 > 26) 
                    { 
                        ltrCounter2 = 0; 
                    } 
                    plyrNamePos2 = alphabet[ltrCounter2]; 
                    break; 
                case 3: 
                    ltrCounter3++; 
                    if (ltrCounter3 > 26) 
                    { 
                        ltrCounter3 = 0; 
                    } 
                    plyrNamePos3 = alphabet[ltrCounter3]; 
                    break; 
                case 4: 
                    ltrCounter4++; 
                    if (ltrCounter4 > 26) 
                    { 
                        ltrCounter4 = 0; 
                    } 
                    plyrNamePos4 = alphabet[ltrCounter4]; 
                    break; 
                case 5: 
                    ltrCounter5++; 
                    if (ltrCounter5 > 26) 
                    { 
                        ltrCounter5 = 0; 
                    } 
                    plyrNamePos5 = alphabet[ltrCounter5]; 
                    break; 
            } 
        } 
//Same thing only backwards. 
private void hiScoreDown() 
        { 
            switch (letterPosition) 
            { 
                case 1: 
                    ltrCounter1--; 
                    if (ltrCounter1 < 0) 
                    { 
                        ltrCounter1 = 26; 
                    } 
                    plyrNamePos1 = alphabet[ltrCounter1]; 
                    break; 
                case 2: 
                    ltrCounter2--; 
                    if (ltrCounter2 < 0) 
                    { 
                        ltrCounter2 = 26; 
                    } 
                    plyrNamePos2 = alphabet[ltrCounter2]; 
                    break; 
                case 3: 
                    ltrCounter3--; 
                    if (ltrCounter3 < 0) 
                    { 
                        ltrCounter3 = 26; 
                    } 
                    plyrNamePos3 = alphabet[ltrCounter3]; 
                    break; 
                case 4: 
                    ltrCounter4--; 
                    if (ltrCounter4 < 0) 
                    { 
                        ltrCounter4 = 26; 
                    } 
                    plyrNamePos4 = alphabet[ltrCounter4]; 
                    break; 
                case 5: 
                    ltrCounter5--; 
                    if (ltrCounter5 < 0) 
                    { 
                        ltrCounter5 = 26; 
                    } 
                    plyrNamePos5 = alphabet[ltrCounter5]; 
                    break; 
            } 
        }

From here – IN YOUR DRAW METHOD – create a string to hold all your letters:
hiScoreName = plyrNamePos1 + ” ” + plyrNamePos2 + ” ” + plyrNamePos3 + ” ” + plyrNamePos4 + ” ” + plyrNamePos5;

THEN draw that string to the screen:
spriteBatch.DrawString(spriteFont, hiScoreName, hiScoreNamePos, Color.White);

And whalah! You have a string that will eventually hold a players name as they put it in… FOR me, I took that string and sent it to my high score module once a player went back to the main menu….

It’s brutish and maybe a little amateurish but it worked for me. It allowed me to get 5 letters of their name to then save to a high score module…. (It could definitely use some improvement, like a way to visually let the player know which letter holder they are on…but I was really just trying to get the functionality more than anything)

********* I also took that name and from IN GAME allowed them to submit it to a website www.toddvance.com/games/aa where they could then make the high score list (or not.)…. This just has me GEEKED, sorry but this whole XNA thing is just awesome!!!!

Thanks guys! I hope this helps someone!
tv

FIRST XNA GAME IS DONE! Check it!!!

Category : C#, XNA/Game programming

ALIEN AGGRESSORS X

‘Alien Aggressors X’ is a space invaders clone that I created by following Nick Gravelyn’s
fantastic tutorial. (thanks Nick!)

What I have done is add a few extras that I am excited about because this was my first experience with XNA and game programming.

I hope to soon post tutorials on the addon’s that I created because I feel like they are some good introductory concepts to add onto your games.

Visit the game site here

toddvance.com/games/aa

ONE OF THE COOLEST feature that I like is the ability to submit your score in-game to the above website and see if you can make the list…. so the question is, CAN YOU MAKE THE LIST?..

X tras…

Scrolling Background
Scrolling background

Random Special Alien
Scrolling background

High Score Module (with text input not using GUIDE class)
Scrolling background

Submit your score to this web site from within game! (can you make the list?)