Visual C++ CLR Part I

This week I will be doing a five part series on Visual C++/CLR . Today I will discuss the general overview on Visual C++ and beginning to design an application.

Why Visual C++?

  1. Visual C++ is much easier than C++ (Mostly CLR).
  2. Visual C++ works just as well as C++ if the user has the .NET Framework (For CLR at least).
  3. A hell of a lot easier to make a GUI using the Windows Forms Designer (Only CLR).
  4. It is easy to convert C#/VB.NET code to Visual C++ (Only CLR again).
  5. Can be used as a COM DLL (I will show how in another tutorial) for use with other applications (Such as a Messenger Plus Live! Plug-in).
  6. Is more complicated than C# and VB.NET but worth it in the end.
  7. Has plenty of advantages over the other .NET languages.

The Ugly

  • Only works on Windows based Systems.
  • Requires .NET Framework 2.0 (Comes with Vista, separate install for Windows Operating Systems before Vista)

Prerequisites

  • This will be easier if you have had some previous programming experience.
  • A Windows PC (Or a Mac with a Windows Bootcamp partition).
  • Visual C++ 2008 Express Edition (free and can be downloaded from here: http://www.microsoft.com/express/vc/) installed.
  • Common Sense (Yes, you have to be smart for C++. ;) ).

Getting Started

Now that you have everything ready let’s begin. Once you launch Visual C++ you will see the Start Page. Click Create Project (Under Recent Projects).

create_project

You should be greeted with the following (without my call-out):

new_project

Choose Windows Form Application (CLR should be selected under Project Types by default).

Next enter a name for the project (I’m going to use: Visual C++ - Tutorial 1)

Keep the checkbox checked under Create directory for solution. You do not need to change solution name (it will change to your project name, you can change it if you wish.)

Next click OK for the project to be created. Once it’s done creating the project, go to the next step.

Tour de IDE

Once the project is created, you should see this with Form1.h open and in Design Mode (May look a bit different, I’m using Vista).

IDE

To the left we have the Solution Explorer. It’s like a project manager, it helps you manage your project’s files. In the middle we have the code/design view. This is where you will be coding and designing your interface.

On the bottom is the Code Definition Window, this may come in handy for some (I never use it, I also don’t use the Express Edition). It shows definitions of certain parts of code. On the far right (not captured by my screen shot) is the Toolbox and Database Explorer (if you installed SQL Server Express you will see the Database Explorer). The toolbox holds all your interface design controls (We will get to this next).

Your tour is over, please step-up to your next excursion.

Designing an Interface

We have come to the easy yet overlooked part of programming, the interface. This is what the users will see, they won’t see your code (but you still want to keep it clean. ;) ). Interfaces are often overlooked by newer programmers. The interface is an important part of your application. You want your users to feel at home and be awed by your beautiful yet simple interface. You do not want to over-blingify your interface; make it simple, make it safe.

Controls

A control in any operating system is basicly an item that the user interacts with (or a part of your interface).

Examples:

  • A text box
  • A picture
  • A radio-button/checkbox
  • Button
  • Label (not really interactive but the user sees it)

Controls can be dragged from the toolbox onto the form (the little window in design view). You can also double click the control to add it to the selected form.

Review

That’s all the time I have for today. Let’s review what I have gone over today:

  • Why you may want to learn Visual C++.
  • What you need to get started.
  • How to create a project.
  • Overview on the IDE (Integrated Development Environment)
  • Designing a interface. We will go more in-depth in my next tutorial.
  • What controls are.

The Author

The writer of these tutorials is an eighteen year old college student named Brent Friedman. His username is "Brent" on Nystic.com’s forums. In the past he was an Administrator on Nystic, now just a simple moderator in two forum categories. He loves teaching computer information to those who do not yet have the knowledge of what he has to offer. He looks forward to teaching you more about Visual C++ in the coming weeks. Until then, stay tuned to the forum or subscribe to his blog (http://cg.nystic.com).

VB.NET & C# Screen Capture Basics

Some of you have seen my screen capture program Gotcha. Well, here is how some of the source for the basic screen shot taking.

First add a picture box to your form and name it PictureBox1. Next, add a button with any name you want. Now we are ready for the code. VB.NET users, put this under the button’s click event:

Dim bounds As Rectangle Dim screenshot As System.Drawing.Bitmap Dim graph As Graphics bounds = Screen.PrimaryScreen.Bounds screenshot = New System.Drawing.Bitmap(bounds.Width, bounds.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb) graph = Graphics.FromImage(screenshot) graph.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy) PictureBox1.Image = screenshot

C# users put this under the button’s click event:

Rectangle bounds; System.Drawing.Bitmap screenshot; Graphics graph; bounds = Screen.PrimaryScreen.Bounds; screenshot = new System.Drawing.Bitmap(bounds.Width, bounds.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); graph = Graphics.FromImage(screenshot); graph.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy); PictureBox1.Image = screenshot;

For saving your screenshots just add another button to the form. Add this code for VB.NET users:

Dim SaveFileDialog1 As New SaveFileDialog() SaveFileDialog1.Filter = "PNG|*.png|GIF|*.gif" If SaveFileDialog1.ShowDialog() = DialogResult.OK Then If Not PictureBox1.Image Is Nothing Then PictureBox1.Save(SaveFileDialog1.FileName) End If End If

C# users use this instead:

SaveFileDialog SaveFileDialog1 = new SaveFileDialog(); SaveFileDialog1.Filter = "PNG|*.png|GIF|*.gif"; if (SaveFileDialog1.ShowDialog() == DialogResult.OK) { if (PictureBox1.Image != null) { PictureBox1.Save(SaveFileDialog1.FileName); } }

That’s it folks, have fun!

Visual C# 2005 Keyboard Shortcuts Poster

I found this handy poster on the Microsoft site.

Just print it out and hang it on your wall. ;-)

Google AJAX Search API BBCODE - For phpBB 3

I made a bbcode MOD for my forum that you can use to display Google search results in your posts. This is an example of what it looks like. This is a tutorial on how to modify your forum to do the same. It requires phpBB 3.0 Beta 2 and above.

First register to get your API key: http://code.google.com/apis/ajaxsearch/signup.html

You must have ACP access to continue. Now go to the ACP. Click the Styles tab. Click the templates link. Next to prosilver, click edit. Select template file, Overall_Header.html.

Find:
<script type=”text/javascript”>
// <![CDATA[
    var jump_page = ‘{L_JUMP_PAGE}:’;
    var on_page = ‘{ON_PAGE}’;
    var per_page = ‘{PER_PAGE}’;
    var base_url = ‘{BASE_URL}’;
    var style_cookie = ‘phpBBstyle’;
    var onload_functions = new Array();
    var onunload_functions = new Array();

Before that add:

<link href=”http://www.google.com/uds/css/gsearch.css” type=”text/css” rel=”stylesheet”/>
<script src=”http://www.google.com/uds/api?file=uds.js&amp;v=1.0&amp;key=your_key” type=”text/javascript”></script>

Replace your_key with the key you got after registering your site with Google API.

Next find:

    window.onunload = function()
    {
        for (i = 0; i <= onunload_functions.length; i++)
        {
            eval(onunload_functions[i]);
        }
    }

After that add:

function Load() {
      // Create a search control
      var searchControl = new GSearchControl();

      // Add in a full set of searchers
      var localSearch = new GlocalSearch();
      searchControl.addSearcher(localSearch);
      searchControl.addSearcher(new GwebSearch());
      searchControl.addSearcher(new GvideoSearch());
      searchControl.addSearcher(new GblogSearch());

      // Set the Local Search center point
      localSearch.setCenterPoint(”New York, NY”);

      // Tell the searcher to draw itself and tell it where to attach
      searchControl.draw(document.getElementById(”searchcontrols”));
      var x=document.getElementById(”GSearch”)
      // Execute an inital search
      searchControl.execute(x.getAttribute(”value”));
    }
          GSearch.setOnLoadCallback(Load);

Now submit your changes. Now, time to create the bbcode. Click the posting tab. Now click add a bbcode. The bbcode usage is:

[google]{TEXT1}[/google]

The HTML replacement is:

<input type=”hidden” id=”GSearch” value=”{TEXT1}” /><ul id=”searchcontrols” style=”list style:none none;”/>

You can put whatever you want in help line. Check Display on posting page if you want people to be able to use the BBCODE.

Now click submt.  Now people can add Google Searches to their posts. One thing I have noticed, you need to have your comments above the google bbcode in your post or else your comments will be hidden. To use the bbcode. Just do something like this:

[google]search terms[/google]

Where search terms is what to search for.

Have fun!

Beginning ASP.NET

ASP.NET is Microsoft’s extension to HTML. It requires an ASP.NET compatible web server. Such as, Abyss or IIS (Internet Information Services from Microsoft). There are however plug-ins for Apache Web Server also. Before you continue you will need to know VB.NET which is required for the scripting part of the tutorial.

You don’t necessarily need a compiler to build an ASP.NET script. Any text editor will work. Let’s start by building or first aspx file. Create a new text document in your favorite text editor. Call it default.aspx. Now lets jump in, shall we?

 

<%@ Page Language=”VB” AutoEventWireup=”false” CodeFile=”Default.aspx.vb” Inherits=”_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 runat=”server”>
    <title>Untitled Page</title>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
    </div>
    </form>
</body>
</html>

The above is your basic ASP.NET template. Let me explain what each line does.

 

<%@ Page Language=”VB” AutoEventWireup=”false” CodeFile=”Default.aspx.vb” Inherits=”_Default” %>

This this tells the server to parse and attach the VB file we will write later on in the lesson.

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

This is just your normal XHTML Transitional doctype.

<html xmlns=”http://www.w3.org/1999/xhtml”>

The xmls attribute declares a namespace for custom tags in an your document.

<head runat=”server”>

The runat=”server” attribute indicates that the form should be processed on the server. It also indicates that the enclosed controls can be accessed by server scripts.

<title>My First ASP.NET Script</title>

Your average title tags.

</head>

Close the head tag.

<body>

Start the body of the page.

<form id=”form1″ runat=”server”>

This indicates that to start a form  named form1 and that is should be processed on the server.

<div>

Open a div tag.

</div>

Close a div tag.

</form>

Close the form.

</body>

End the body of the page.

</html>

End the HTML section of the page.

 

The body of your document will go between the open and close div tags.

Example:

<%@ Page Language=”VB” AutoEventWireup=”false” CodeFile=”Default.aspx.vb” Inherits=”_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 runat=”server”>
    <title>My First ASP.NET Script</title>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
    <a id=”link1″ runat=”server”>Visit Nystic</a>
    </div>
    </form>
</body>
</html>

Now it’s time to create or VB code file. Create a new text document and call it default.aspx.vb. 

 

Here is your vb template:

Partial Class _Default
    Inherits System.Web.UI.Page

End Class

Pretty basic, huh?  Your custom code will between Inherits System.Web.UI.Page  and End Class.

 

Example:

Partial Class _Default
    Inherits System.Web.UI.Page
Sub Page_Load

    link1.HRef=“http://www.nystic.com
End Sub
End Class

Save both files in the same directory and upload them to your ASP.NET server.

I will go more in depth in my next ASP.NET tutorial. Until then, have fun!

MySQL and C#

Introduction

Many of you might be trying to get MySQL working with Visual Studio 2005 or C# Express Edition. Well, Microsoft clearly made the DB manager for Microsoft SQL Server and Oracle Server. Although, the makers of MySQL Server have released an extension for VS 2005 and C# Express. You will need to download and install it on your development computer to continue. Here is the download link: MySQL Connector/Net 5.1.

References

If you’ve installed it, launch your C# compiler/IDE. Next, open the project you want to add MySQL support to.

Now, go to the Project menu => Add Reference. Under the .NET tab look for MySQL.Data under “Component Name.” Click “OK” and were are ready to start coding.

Import Namespaces

Now we are ready to import the “MySQL.Data” namespace. To do that. Just add this to the very beginning of your VB Code file:

using MySQL.Data;

Connection String

Before we can connect to the MySQL Server, we must create a connection string. Here is the format:

Database=yourdb;Data Source=yourIP/domain;User Id=userID;Password=yourPassword

To make your connection string, just start replacing “yourdb” with the name of the database you want to connect to. Next, replace “yourIP/domain” with the address of your server. It can be a domain or IP address. It can not be “localhost” if you want other people to use your application from the Internet. Replace “userID” with your login name to the server. Lastly, replace “yourPassword” with the password you use to login to the MySQL Server.

Example Connection String:

Database=CGFavs;Data Source=cg.nystic.com;User Id=Brent;Password=Friedman

Declarations

Next, let us declare our variables:

MySqlClient.MySqlCommand cmd = New MySqlClient.MySqlCommand;
Object returnValue;
MySqlClient.MySqlConnection connect = New MySqlClient.MySqlConnection(”Database=CGFavs;Data Source=cg.nystic.com;User Id=Brent;Password=Friedman”);

Replace my example connection string with the one you created in the step before this.

Select Statements That Return One Row

If you need to get the value of a certain column but that query will only return only one row. Here is how to do that.

cmd.CommandText = “SELECT `password` FROM `users` WHERE (username=’foobar’)”;
cmd.Connection = connect;
connect.Open();
returnValue = cmd.ExecuteScalar;
connect.Close();

Now replace “password” with your column’s name. Next replace “users” with the table’s name. and last just change your WHERE clause to how you need it. The syntax for that is “WHERE (column=’rowsColumnValue’)”

Select Statements That Return More Than One Row

MySqlClient.MySqlDataReader read;
cmd3.CommandText = “SELECT * FROM `favs` WHERE (column=’rowsColumnValue’)”;
cmd3.Connection = connect;
read = cmd3.ExecuteReader;
while (read.Read())
{
Messagebox.Show(read.GetString(1));
}
read.Close();
connect.Close();

To get the value of a colum just use the following command: “read.GetString()”
Put the colum number inside the parentheses so it knows which column to return. Like: “read.GetString(1)”
The column numbering starts with ‘0′ not ‘1′.

Insert, Delete, and Update Statements

For a query that do not return a value, here is how to do just that:

cmd.CommandText = “INSERT INTO `favs` VALUES (’1′, ‘foo’, ‘foobar’)”;
cmd.Connection = connect;
connect.Connect();
cmd.ExecuteNonQuery();
connect.Close();

It’s pretty basic. ExecuteNonQuery just executes a query that doesn’t return a value.

Variables Inside a Query

To insert a variable inside a query just do end the string by closing the quotes, add a space then the and symbol (&&) then the variable. Then add another space, another and symbol, then open a new quote. Then continue the string for the query. Example:

cmd.CommandText = “SELECT `password` FROM `cgfavs`.`users` WHERE (username=’” && TextBox1.Text && “‘)”

In Closing

That’s it. Just make sure that the MySQL.Data.dll is saved with the project and sent together. To do that. go to the Project Menu => Show All Files. Then, in the solution exploerer, go to the References folder and click on the MySQL.Data item. Next, go to the properties window, and make sure that “Copy Local” is set to True. Then, make sure you distribute the MySQL.Data.dll with your EXE and in the same folder.

See ya folks!

MySQL and Visual Basic .NET

Introduction

Many of you might be trying to get MySQL working with Visual Studio 2005 or Visual Basic Express Edition. Well, Microsoft clearly made the DB manager for Microsoft SQL Server and Oracle Server. Although, the makers of MySQL Server have released an extension for VS 2005 and VB Express. You will need to download and install it on your development computer to continue. Here is the download link: MySQL Connector/Net 5.1.

References

If you’ve installed it, launch your Visual Basic compiler/IDE. Next, open the project you want to add MySQL support to.

Now, go to the Project menu => Add Reference. Under the .NET tab look for MySQL.Data under “Component Name.” Click “OK” and were are ready to start coding.

Import Namespaces

Now we are ready to import the “MySQL.Data” namespace. To do that. Just add this to the very beginning of your VB Code file:

Imports MySQL.Data

Connection String

Before we can connect to the MySQL Server, we must create a connection string. Here is the format:

Database=yourdb;Data Source=yourIP/domain;User Id=userID;Password=yourPassword

To make your connection string, just start replacing “yourdb” with the name of the database you want to connect to. Next, replace “yourIP/domain” with the address of your server. It can be a domain or IP address. It can not be “localhost” if you want other people to use your application from the Internet. Replace “userID” with your login name to the server. Lastly, replace “yourPassword” with the password you use to login to the MySQL Server.

Example Connection String:

Database=CGFavs;Data Source=cg.nystic.com;User Id=Brent;Password=Friedman

Declarations

Next, let us declare our variables:

Dim cmd As New MySqlClient.MySqlCommand
Dim returnValue As Object
Dim connect As New MySqlClient.MySqlConnection(”Database=CGFavs;Data Source=cg.nystic.com;User Id=Brent;Password=Friedman”)

Replace my example connection string with the one you created in the step before this.

Select Statements That Return One Row

If you need to get the value of a certain column but that query will only return only one row. Here is how to do that.

cmd.CommandText = “SELECT `password` FROM `users` WHERE (username=’foobar’)”
cmd.Connection = connect
connect.Open()
returnValue = cmd.ExecuteScalar
connect.Close()

Now replace “password” with your column’s name. Next replace “users” with the table’s name. and last just change your WHERE clause to how you need it. The syntax for that is “WHERE (column=’rowsColumnValue’)”

Select Statements That Return More Than One Row

Dim read As MySqlClient.MySqlDataReader
cmd3.CommandText = “SELECT * FROM `favs` WHERE (column=’rowsColumnValue’)”
cmd3.Connection = connect
read = cmd3.ExecuteReader
While read.Read()
Messagebox.Show(read.GetString(1))
End While
read.Close()
connect.Close()

To get the value of a colum just use the following command: “read.GetString()”
Put the colum number inside the parentheses so it knows which column to return. Like: “read.GetString(1)”
The column numbering starts with ‘0′ not ‘1′.

Insert, Delete, and Update Statements

For a query that do not return a value, here is how to do just that:

cmd.CommandText = “INSERT INTO `favs` VALUES (’1′, ‘foo’, ‘foobar’)”
cmd.Connection = connect
connect.Connect()
cmd.ExecuteNonQuery()
connect.Close()

It’s pretty basic. ExecuteNonQuery just executes a query that doesn’t return a value.

Variables Inside a Query

To insert a variable inside a query just do end the string by closing the quotes, add a space then the and symbol (&) then the variable. Then add another space, another and symbol, then open a new quote. Then continue the string for the query. Example:

cmd.CommandText = “SELECT `password` FROM `cgfavs`.`users` WHERE (username=’” & TextBox1.Text & “‘)”

In Closing

That’s it. Just make sure that the MySQL.Data.dll is saved with the project and sent together. To do that. go to the Project Menu => Show All Files. Then, in the solution exploerer, go to the References folder and click on the MySQL.Data item. Next, go to the properties window, and make sure that “Copy Local” is set to True. Then, make sure you distribute the MySQL.Data.dll with your EXE and in the same folder.

See ya folks!

Learning VB.NET in 5 minutes

To start programming we need to download a compiler. In this tutorial we will use Microsoft’s Visual VB 2005 Express Edition. It is a free complier that we will be using for this tutorial. You download and install it here. Select the Visual VB option which should be on the left, it looks like this:

 

After installation open it up. Click on the new project icon in the top left.

 

Make sure that Windows Application is selected and then name your project. I am going to name mine “Hello World”.

After your project loads you should see something like this:

 

The window you see is your form. On the left side you should see something that says toolbox. If you don’t use the shortcut ctrl+w then x to bring it up. The list of icons and text on the right make up 90% of all applications. For example, if we used the button control, on our window there would be a little button in the window. Find the button control on the toolbox window. It looks like this:

Double Click on it. It should pop up in your form or window. You can click and drag it around form to a desired location. After you have the button where you want it double click the button. After double clicking the button a code editor should pop up. By default you code should look something like this:

 

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    End Sub
End Class
 

Place your cursor after Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click and press enter. Then type in the following code. MessageBox.Show(”Hello World!”) The code should look like this after you add that code line:

 

 

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        MessageBox.Show(“Hello World!”)
    End Sub
End Class

 

Now hit F5 on your keyboard to compile and run your program. A window should pop up and when you click that button a window should pop up saying “Hello World”.

 

 

Congratulations, you now know some VB!

This is a mirror image tutorial of Learning C# in 5 minutes.

[HTML] Hyperlinks

Now let’s get started:

First, open up your favorite HTML editor. My favorite is Dreamweaver, but most people use WordPad/Notepad. Next, enter in the following code:

<!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>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<title>My New Page!</title>
</head>
<body>
<p><u><font size=”+2″>My Links</font></u></p>
<br />
<p>Search: <a href=”http://www.google.com”>Google</a></p>
<p>Forum: <a href=”http://www.nystic.com/index.php”>Nystic</a><br />
</p>
</body>
</html>

Did you notice the following code?

<a href=”http://www.nystic.com/index.php”>Nystic</a>

This code created the hyperlink.
If you replace http://www.nystic.com/index.php with the url you have a working hyperlink. :D
All you have to do now is change the hyperlink text.
Replace, Nystic with the text you want.

e.g:

<a href=”http://your-url.com”>Your-Text</a>

Will look like this: Your-Text

That’s it!

[PHP] The Echo Command

The PHP Echo Command

This command allows you to output data in a PHP webpage. There are many ways to do this. Sometimes you don’t even need to use this command. You will always use this command if you aren’t going to use an HTML output/design. This section may not make sense to some of you. I am trying my hardest to explain.

Ok, let’s follow up with some examples.
______________________________________________________________________________

Let’s say you want to output the value of a variable. This is how you would do this. Let “$var” equal the variable.

<?php
/* Declare the variable */
$var=”ABC123”

/* Output the variables value */
echo “$var”
?>

That will output:

ABC123

Now you want to output some normal text. Here is how you would do it.

<?php
/* Output the text */
echo “This is text.”
?>

This will show:

This is text.

Now you want to output some HTML code yet, have it show as if it were typed in a HTML document. Here is how..

<?php
/* Declare the variable as the html you want to use. */
$code = “<b><u>This is a test.</u></b>”
/* Output the HTML */
echo “$code”
?>

Or:

<?php
/* Output the HTML */
echo “<b><u>This is a test.</u></b>”
?>

Both will show:

This is a test.