Share This!

Wednesday, November 21, 2007

Creating a new Class

Create a new winforms project, then right-click the project and do this:

Create a new Class object

Add this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClassDemo
{
    class newClass
    {
        public string sharedString = "This can be read and written by anyone.";
        private string myString = "Only visible in newClass.";


    }
}

And then right-click and add a 'ctor' (constructor) snippet as shown.

Tuesday, November 20, 2007

Day 5: Arrays

The website of the day is here.

And here is the example code...


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace Arrays
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            /*
             * Arrays Demo
             */
            richTextBox1.AppendText("FIXED ARRAYS"+Environment.NewLine);
            //a fixed array of 4 strings (0-3), initialized on create.
            String[] myfamily = new String[]
               {"Bryan", "Ruth", "Rebekah", "Rachel"};
            
            //a fixed array initialized later
            String[] myPets = new String[3];
            myPets[0] = "Sasha";
            myPets[1] = "Ross";
            myPets[2] = "Nightstar";
            
            //reading fixed arrays
            foreach (string s in myfamily) 
            {
                richTextBox1.AppendText(s + Environment.NewLine);
            }
            foreach (string s in myPets)
            {
                richTextBox1.AppendText(s + Environment.NewLine);
            }

            Random R = new Random();
            

            int P = (int)R.Next(3);
            int F = (int)R.Next(4);

            string playtime = 
              string.Format("{0} is playing with {1}", myPets[P], myfamily[F]);
            richTextBox1.AppendText(playtime + Environment.NewLine);

            //variable Arrays
            richTextBox1.AppendText(Environment.NewLine + 
              "VARIABLE ARRAYS" + 
              Environment.NewLine);
            //untyped array
            ArrayList RandomStuff = new ArrayList();
            //you can put anything into this array            
            RandomStuff.Add(new Font("Arial",12));
            RandomStuff.Add(7.1);
            RandomStuff.Add("The Castle Anthrax");

            //now... how can we work with this collection of trash?

            foreach (object O in RandomStuff)
            {
                richTextBox1.AppendText("I see a(n) " + 
                  O.GetType()+Environment.NewLine);
                if (O is System.Drawing.Font)
                    richTextBox1.AppendText("   ->" + 
                      (Font).FontFamily+Environment.NewLine);
                if (O is Double)
                    richTextBox1.AppendText("   ->" + O.ToString() +  
                      Environment.NewLine);
                if (O is String)
                    richTextBox1.AppendText("   ->" + O.ToString() + 
                      Environment.NewLine);                    
            }

            //typed vararrays
            richTextBox1.AppendText(Environment.NewLine + 
             "TYPED VARIABLE ARRAYS" + 
             Environment.NewLine);
            List<String> myStrings = new List<String>();
            List<Double> myNumbers = new List<Double>();
            List<Button> myButtons = new List<Button>();


            myStrings.Add("Bread");
            myStrings.Add("Mayo"); 
            myStrings.Add("Turkey");
            myStrings.Add("Cheese.Provolone");
            myStrings.Add("Bread");

            foreach (string ingredient in myStrings)
            {
                richTextBox1.AppendText(ingredient + " ");
            }
            richTextBox1.AppendText(Environment.NewLine);

            /*
             * Since these arrays are stongly typed, you can't put a 
             * string into the button array nor a number into the 
             * string array.  you *can* however put the descendant
             * of a any object into a typed array.
             */
        }
    }
}



Todays Assignment: make a list of your favorite things.

Monday, November 19, 2007

Day 4: launch an outside App

This is a little less formal than previous posts, but here goes. First, create a form with a button, a RichText, and a PictureBox.

Here is the source code I wrote to accomplish this. I am a big believer in examples. They tell the story in a far more eloquent way than my witty expose'.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using System.Diagnostics;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        Process POVRay = new Process();
        

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            StringBuilder povtext = new StringBuilder();
            string camera = "camera{location <0,1,-1>*10 look_at<0,0,0>}";
            string light1 = "light_source{<0,1,0>*1000 color rgb 1}";
            string water = "plane{y,0 texture{pigment{color rgb 0.5}"+
                " finish{reflection .2 }" +
                " normal{ bumps .4 turbulence .7 }}}";
            string sphere = "sphere{<0,1,0>,1 pigment{color rgb<1,0,0>}}";

            povtext.AppendLine(camera);
            povtext.AppendLine(light1);
            povtext.AppendLine(water);
            povtext.AppendLine(sphere);

            richTextBox1.Text = povtext.ToString();

            //save to file

            using (StreamWriter sw = new StreamWriter("C:\\temp\\demo.pov"))
            {
                // Add some text to the file.                
                sw.WriteLine(povtext);
                sw.Flush();
                sw.Close();
            }


            //launch POV-RAY and create a new bitmap;
            Process POVRay = new Process();
            POVRay.StartInfo.FileName = 
                "C:\\Program Files\\POV3.6\\bin\\pvengine.exe";
            POVRay.StartInfo.Arguments = 
                "+IC:\\temp\\demo.pov +OC:\\temp\\demo.bmp +w320 +h200 -P -D /EXIT";
            POVRay.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;           

            POVRay.Start();
            POVRay.WaitForExit();
            this.pictureBox1.Load("file:C:\\temp\\demo.bmp");
           
        }
    }
}


You will need POVRay to run this.

Your assignment: figure out how to launch another application like Word, Firefox, or Notepad.

Enjoy.

Thursday, November 15, 2007

Day 3: WinForms App

Less prose! More examples!

Start C# File - New Project.

Windows Forms Application.

This is what you should see.

Look in the toolbox for a class object called a button and another called a textbox. Do something like this:

Rightclick the textbox. Select properties.

Look now at the properties box.

Ok now a few things to note. Look at the speed buttons just below the word "textbox1". The first 2 icons pick whether you are sorting alphabetically or by groups. The next 2 icons determine whether you are viewing properties or methods.

Now find the multiline property of textbox1 and change it to true.

Note how the handles on the textbox have changed. Grab the lower right handle and stretch it like this.

ok, now double click button1 in the editor.


        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = "Written by CODE";
        }

Add the text in bold. Then hit the F5 key to start with debugging. After clicking the button, you'll see this.

More examples...

        private void button1_Click(object sender, EventArgs e)
        {
            //this is a comment, the compiler ignores it.
            /*
             * this kind of comment can span more
             * than one line
             */

            //putting text in the textbox
            textBox1.Text = "Written by CODE";

            //adding to the text that is already there.
            textBox1.Text += " because we cared.";
            
            //newline example 
            /*(Environment.NewLine ensures that 
             * the correct chars are used based 
             * on the operating environment)*/
            textBox1.Text += Environment.NewLine+"(new line)"; 

            //appendtext
            textBox1.AppendText(Environment.NewLine);
            textBox1.AppendText("appended text");

            //casting non-strings
            textBox1.AppendText(Environment.NewLine);
            double j = 22.0 / 7.0;
            textBox1.AppendText(j.ToString("F04"));

            textBox1.AppendText(Environment.NewLine);
            int i = 1024;
            textBox1.AppendText(i.ToString());

            //results of methods
            textBox1.AppendText(Environment.NewLine);
            textBox1.AppendText(Environment.CommandLine);

            //math results
            textBox1.AppendText(Environment.NewLine);
            textBox1.AppendText(Math.Cos(0.1).ToString("F05"));

            textBox1.AppendText(Environment.NewLine);
            textBox1.AppendText((110.0/73.0).ToString("F05"));

            //dates
            textBox1.AppendText(Environment.NewLine);
            DateTime D = new DateTime(2007, 12, 31, 17, 00, 00);
            textBox1.AppendText(D.ToShortDateString());
            textBox1.AppendText(" "+D.ToShortTimeString());

            DateTime NOW = DateTime.Now;
            TimeSpan diff = D - NOW;
            textBox1.AppendText(Environment.NewLine);
            textBox1.AppendText(diff.Days.ToString()+" days " );
            textBox1.AppendText(diff.Hours.ToString() + " hours");
            textBox1.AppendText(diff.Minutes.ToString() + " minutes");

            //changing object properties
            this.BackColor = Color.AliceBlue;
            this.ForeColor = Color.Blue;

            /*
             * note how we can refer to the current form as "this"
             * 
             */
        }

Tuesday, November 13, 2007

Day 2

housekeeping

Here are the books and websites I use most when the answers are not coming to me.

C# for Programmers (2nd Edition) (Deitel Developer Series)

Pop open Microsoft Visual C# 2008 Express Edition - I suggest you pin it to your start menu.

Notice the area in the center, called the Start Page.

Now look closer at the "Getting Started" section.

There are actually some good resources there for you to use.

ready, set, go.

Today we create our first application.

Sadly it'll be a console app.

Click File - New Project - Console Application. You'll get something that looks like this:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
  class Program
  {
      static void Main(string[] args)
      {
      }
  }
}

The using's are all the .net namespaces or libraries that are included in the project by default.

The ConsoleApplication1 namespace is your own private realm where your code exists. All .net code exists in a namespace.

Variables

As I mentioned, all things in C# are class objects. The difference between a class object and a variable are that class objects can contain methods and they can be extended. An int in Delphi can't have any of its own functions, but in C#, even the simplest data object can and does.

Do this: Add this to the code above.

      static void Main(string[] args)
      {
          int x;
          int y = 2;
          x = 7;
          int z = x + y;          
      }
  }

int x; creates an integer class object but does not assign it a default value. Any attempt to read or manipulate it at this point would cause an exception.

The int y = 2; line shows a shorthand way of creating and initializing the value at the same time.

The x = 7; shows how to add or change data in an existing data object.

The int z = x + y; line shows a variable z being created containing the results of a calculation. Note that subsequent changes to x and y will not cause z to recalculate, it just works the math at the time and stores it in z.

Now do this. Type z. and a popup context helper appears. This shows the methods that can be accessed from an int.

if you mouse-hover over the items you get an explanation like this.

Ok, time to move on to...

EMail Demo

Now clear out all the varibables and type in the word MailMessage as shown.

Note the little rectangle under the "e". Hover your mouse over that and you'll see this:

What the IDE is offering to do is add the namespace System.Net.Mail to your using section or, alternately, add it to the declaration itself. You don't have to add a namespace to your project to access it, you can explicitly pick objects from any namespace by using their fully qualified name. Adding them to the using clause just simplifies the typing.

In this case, choose the first one, add System.Net.Mail to the using section.

Now you'll see the using System.Net.Mail; has been added to the top section of the program and all the objects and methods in that namespace are now native to your program.

The MailMessage class is an object that can be used to send or receive email messages. You can create an empty one and load it later like this...


MailMessage myMailMessage = new MailMessage();
myMailMessage.To = new MailAddress("bryanv@eloan.com", "Bryan Valencia");
myMailMessage.From = new MailAddress("gumby@eloan.com", "Gumby and Pokey");
myMailMessage.Subject = "I am feeling down again.";
myMailMessage.Body = "I am all congested with disclosures.";

Or you can create it and initialize it with variables. Note that we had to create 2 MailAddress objects to set the To and From addresses in myMailMessage.

The following example shows how to create a MailMessage object with all its values pre-initialized.


      static void Main(string[] args)
      {
          MailMessage myMailMessage = new MailMessage(
              "gumby@eloan.com",
              "bryanv@eloan.com",
              "I am feeling down again.",
              "I am all congested with disclosures."
          );
      }


Ok, now let's send this bad-boy. In order to do that (and please feel free to substitute your own address for the To address), you need an object called the SMTPClient. It's in the same namespace as the MailMessage.


      static void Main(string[] args)
      {
          MailMessage myMailMessage = new MailMessage(
              "gumby@eloan.com",
              "bryanv@eloan.com",
              "I am feeling down again.",
              "I am all congested with disclosures."
          );

          SmtpClient mySMPTClient = new SmtpClient("eloan.com");
          mySMPTClient.Send(myMailMessage);

          Console.WriteLine("Message Sent");
      }

Now, hit Control-F5, or from the menu, Debug - Start without debugging. You should get this:

Then in about 10 seconds, whoever you decided to bless with your email should see it in their inbox.

Let me diagram what we just did. When we created the MailMessage object, here's what was happening:

what we typedwhat happened
MailMessageWe told C# that we are about to create an object of the class MailMessage in the System.Net.Mail namespace.
myMailMessagewe told C# that we are going to call it myMailMessage.
= new MailMessage(...)We told C# to go ahead and create it now - that means to allocate memory and initialize it with either default values or the ones we are passing in. The object is now created and resides somewhere in memory, and can be accessed by the name myMailMessage.

Constructors

Every class object has a predefined method called a constructor. It tells C# how to create instances of itself. Constructors can be simple, like the constructor for an int, or more complicated like the one for MailMessage. They can even be overloaded.

Try this:

Note how the context helper pops up a helper for the constructor. There are 4 overloaded constructors for the MailMessage class. Use the down arrow key to see the formats you can choose from. All methods in all objects will pop these helpers while you are editing.

A few little items

Single quotes and double quotes are not interchangeable. Strings use the double quote marks "like this". Chars use the single quote (or tickmark or apostrophe), like this: 'A'.

A class is the organization of an object, an object is an instance of that class. Or, think of classes as cookie cutters (or blueprints) and objects as cookies (or Lear Jets).

Overloading means that there can be many methods with the same name. More on this later.

Monday, November 12, 2007

Getting Started with Visual Studio Part 1

This is intended to be a quick start tutorial so make sure to read them all in order. Use the GettingStarted Label on the web page to find all the articles in this series. This is the result of what happened to us last week. We had been promised a class in C#.NET to accommodate an upgrade project, but instead, most of us got laid off. Since I had been to the pre-training training, I attempt here to share the wealth.

This tutorial will use the Visual Studio 2008 Express (free) editions only, and will cover ASP.NET and C#.NET development ONLY. There will be no VB or J# here. Also, I am not a Microsoft hack, so when something sucks, I'll say so. Ok, on with it.

First topic: Getting the software.

Today the software may be found here.

If this page is not live anymore, then try googling for VS Express 2008 Download. Be sure to download C# and Visual Web Developer.

Accept all the defaults and reboot between and after the installs. Now you will see the IDE's under Start - All Programs.

Let's get started.

Click on the Visual Studio 2008 link to bring up the IDE. It takes the news channel several seconds to load so be patient. Let's talk about some conceptual topics before we start coding.

C# is like C++

Yes, it's kind of like C++ and kind of like Java. Everything is a class object. Even strings and integers are classes. Even though C# makes it easy to instantiate them, they are very much the same.

Managed memory

Because of the way the .NET framework manages memory, you need not worry about memory and resource leaks. When the memory manager notices that nobody is holding a pointer to some object, it places it on a list of items that can be wiped. This means that you as a developer have no control over when objects are destroyed, and no guarantee that they'll be destroyed in any particular order, even if the item is a parent of an object that is not being destroyed. I know, it's not the coder's way. Get over it.

CLR and Languages

The Microsoft Common Language Runtime makes it so you can create objects in one language and use them freely in another. For instance a Zip code lookup object in C# can be used in J#, VB.NET, or other C# projects. The CLR is your friend. Gone are the days of having to rewrite all your Delphi Projects into VB. You're going to like this, I promise.

Tomorrow, our first project. Don't forget to bookmark this. Your assignment for tonight is to download and install C#, ASP.NET, and optionally the GIMP.

Thursday, November 1, 2007

OracleGetClob Woes

Must... type... this... before... head... explodes!

Ok, I have constructed a query and I'm fetching data from the database, including an Oracle Clob column.

The regular columns work great and look like this:

description = reader.GetValue(5).ToString();

bot for some inane reason,

description = reader.GetValue(6).ToString();

...when run against a clob field will not work if your life depends on it.

I have been to a total of 25 web pages now looking of one solitary example of how to read an oracleclob, and there isn't one! Just one f'ing example is all I need, to see what needs to be done to put the data from my clob object into my string object.

There are many sites that contain volumes about the OracleGetClob() method, and some about the Fetchsize property, but not one solid example that starts with a clob and ends up with the text in a string!

How does it all work together? Anyone?

This is so goddamned frustrating. Where is my Delphi CD?

Contact Us

Name

Email *

Message *