Archive for the ‘Development’ Category.

Learning the Model-View-ViewModel (MVVM) pattern for WPF and C#

So, I recently came across some information on a development style called Model-View-ViewModel or MVVM.

There is a Microsoft article written by Josh Smith about MVVM here:
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

And an MSDN blog here:
http://blogs.msdn.com/johngossman/archive/2005/10/08/478683.aspx

Basically the idea is that you separate the code for three elements:

There is a book by Josh Smith on Advanced MVVM here:

Advanced MVVM

So I have recently become aware of this model and will learning more about this over time.

I am developing an Application at work and I will try to use the MVVM pattern.

How to process command line parameters or arguments in a WPF application?

UPDATE 10/25/2010:
Avoid using Environment.CommandLine. It appears much easier, but isn’t as robust. I learned a while ago that the command line arguments can be accessed using Environment.CommandLine. This is only different than the process below in that it is way easier and the first argument is the full path of the executable. So all this work is not exactly necessary, right? Wrong! I tried Environment.CommandLine for a while and it didn’t last. There are times when this executable is launched by another executable and the Environment.CommandLine is not set even though the other executable launched this executable with parameters. So I had to return to using the steps below anyway.


Ok, so I wanted to handle command line parameters, which is easy in every other language, however, the need for easy was overlooked in WPF. It is not obvious and you are not going to figure it out without being told how to do it.

Microsoft provides a sample here, you can look at.
http://msdn.microsoft.com/en-us/library/aa972153.aspx

I am going to walk you through creating a new WPF Project in Visual Studio 2008. Then I will walk you through handling command line parameters (arguments).

  1. Open Visual Studio 2008.
  2. Go to File | New | Project.
  3. Under Visual C#, choose WPF Application and give the project a name and then hit OK.
  4. Go to Project | ProjectName Properties (where ProjectName is the name of your project).
  5. In the Properties of you project, click on Debug.
  6. Enter three parameters intothe Command line arguments text field: Param1 Param2 Param3
  7. Close the properties window.
  8. Double-click on App.xaml to open it. It looks like this:
    <Application x:Class="ParametersForWPF.App"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        StartupUri="Window1.xaml">
        <Application.Resources>
    
        </Application.Resources>
    </Application>
    
  9. Add a carriage return after StartupUri=”Window1.xaml” and start type inside the bracket the word Startup=. As soon as you see an equals sign you will get a pop up with the words . Double-click on that. The name Application_Startup will automatically be added.
    <Application x:Class="ParametersForWPF.App"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        StartupUri="Window1.xaml"
        Startup="Application_Startup">
        <Application.Resources>
    
        </Application.Resources>
    </Application>
    

    Note: This will also automatcially update the App.xaml.cs file which originally looks as follows:

    using System.Windows;
    
    namespace ParametersForWPF
    {
        /// <summary>
        /// Interaction logic for App.xaml
        /// </summary>
        public partial class App : Application
        {
        }
    }
    

    But after adding the Startup=”Application_Startup” line, a function called Application_Startup is automatically added.

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Windows;
    
    namespace ParametersForWPF
    {
        /// <summary>
        /// Interaction logic for App.xaml
        /// </summary>
        public partial class App : Application
        {
    
            private void Application_Startup(object sender, StartupEventArgs e)
            {
    
            }
        }
    }
    
  10. Now we only want to work with arguments if there are some, so lets add an if statement inside the Application_Startup function as shown:
            private void Application_Startup(object sender, StartupEventArgs e)
            {
                if (e.Args.Length > 0)
                {
    
                }
            }
    
  11. Ok, so the next step is to create a public static string[] member variable to hold the arguments and assign the arguments array to it. I called my member variable mArgs. I use prefix it with m so I know it is a member variable.
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Windows;
    
    namespace ParametersForWPF
    {
        /// <summary>
        /// Interaction logic for App.xaml
        /// </summary>
        public partial class App : Application
        {
            public static String[] mArgs;
    
            private void Application_Startup(object sender, StartupEventArgs e)
            {
    
                if (e.Args.Length > 0)
                {
                    mArgs= e.Args;
                }
            }
        }
    }
    
  12. Now, in order to access the data in Windows1.xaml.cs, just call the App.mArgs array in the constructor as shown.
            public Window1()
            {
                InitializeComponent();
                String[] args = App.mArgs;
    
            }
    
  13. Put a break point on the line and start with debugging and sure enough you will see your arguments properly assigned to the String[] args variable. So you now have your parameters accessible in your WPF application.Hope this helps you.

    Copyright ® Rhyous.com – Linking to this article is allowed without permission and as many as ten lines of this article can be used along with this link. Any other use of this article is allowed only by permission of Rhyous.com.

How read use an ADO.NET DataSet to read XML files designed with nested attributes?

I am working on a project that is XML driven and I am using ADO.NET DataSet functionality to make reading the XML easier. However, I ran into a problem that really just a lack of knowledge on my part.

Problem
So I have DataSet created using an XML. The XML is using Nested attributes. And I just need to know how to loop properly through the DataSet Tables and their columns.

I have the following XML.

<?xml version="1.0" encoding="utf-8" ?>
<Plugin PluginName="TestName" GroupName="Operating System Settings" Type="Single">
  <Title>Plugin 1</Title>
  <StartTime>1:57:47 PM 2/16/2010</StartTime>
  <EndTime>1:58:03 PM 2/16/2010</EndTime>
  <Description>Runs the TestName process to determine something.</Description>
  <Section SectionName="Section1">
    <Field FieldName="Field Name">
      <Value Operand="EQ">Some Correct Setting1</Value>
      <ActionPlugin Name="" Type="Link" URL="">
        <Executable>SomeAction1.exe</Executable>
        <Parameters>Param1 Param2</Parameters>
      </ActionPlugin>
    </Field>
    <Field FieldName="Field2">
      <Value Operand="RG">900</Value>
      <WarningLevel>10%</WarningLevel>
      <ErrorLevel>20%</ErrorLevel>
      <ActionPlugin Name="ActionPlugin1" Type="Link" URL="http://www.somesite.tld/some/path/file.htm" />
    </Field>
  </Section>
  <Section SectionName="Section2">
    <Field FieldName="Field1">
      <Value Operand="EQ">Some Correct Setting2</Value>
      <ActionPlugin Name="" Type="Link" URL="">
        <Executable>SomeAction2.exe</Executable>
        <Parameters>Param1 Param2</Parameters>
      </ActionPlugin>
    </Field>
    <Field FieldName="Field2">
      <Value Operand="RG">900</Value>
      <WarningLevel>10%</WarningLevel>
      <ErrorLevel>20%</ErrorLevel>
      <ActionPlugin Name="ActionPlugin1" Type="Link" URL="http://www.somesite.tld/some/path/file.htm" />
    </Field>
  </Section>
  <Section SectionName="Section3">
    <Field FieldName="Field1">
      <Value Operand="EQ">Some Correct Setting3</Value>
      <ActionPlugin Name="" Type="Link" URL="">
        <Executable>SomeAction3ds.exe</Executable>
        <Parameters>Param1 Param2</Parameters>
      </ActionPlugin>
    </Field>
    <Field FieldName="Field2">
      <Value Operand="RG">900</Value>
      <WarningLevel>10%</WarningLevel>
      <ErrorLevel>20%</ErrorLevel>
      <ActionPlugin Name="ActionPlugin1" Type="Link" URL="http://www.somesite.tld/some/path/file.htm" />
    </Field>
  </Section>
</Plugin>

So the DataSet is created with these tables (this is copied from the debugger):

– List Count = 5 System.Collections.ArrayList
+ [0] {Plugin} object {System.Data.DataTable}
+ [1] {Section} object {System.Data.DataTable}
+ [2] {Field} object {System.Data.DataTable}
+ [3] {Value} object {System.Data.DataTable}
+ [4] {ActionPlugin} object {System.Data.DataTable}

Table [1] {Section} has 3 rows.
Table [2] {Field} has 6 rows.

So the data looks like this:

Sections Table
Row 1
Row 2
Row 3

Fields Table
Row 1
Row 2
Row 3
Row 4
Row 5
Row 6

But I need to read it as follows:

Sections Table
Row 1  
Fields Table
Row 1
Row 2
Row 2  
Fields Table
Row 3
Row 4
Row 3  
Fields Table
Row 5
Row 6

So I had the code below, but for each Section Row it would loop through all six field rows, which is not what I intend.

string mFullPathToXML = "C:\My.xml";
DataSet ds;
ds.ReadXml(mFullPathToXML);

foreach (DataRow SectionRow in ds.Tables["Section"].Rows)
{
    foreach(DataRow FieldRow in ds.Tables["Field"].Rows)
    {
        // Looping through all rows, not just those that pertain to the section.
        // How to get only the two rows that belong to each Section row here?
    }
}

Solution
Well, I set out on a journey to figure this out. In a few search engines I use search phrases like:
DataSet XML Nested
DataSet XML Nested Relation
DataSet DataTable XML Nested Row
DataSet DataTable XML Nested Row

A lot of documentation on Microsoft’s site to XMLs and DataSets showed up, but nothing describing this problem/solution.

I am happy to say that with help from the MSDN Forums, the solution was found. Please read my post here:
http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataset/thread/2d115ba6-49be-4a5c-bf92-054626109f50

So the solutions is to use the Section_Id assigned to each row in the Sections table inside the Field table’s Select() function as shown:

foreach (DataRow sectionRow in ds.Tables["Section"].Rows)
{
	string sectionId = sectionRow["Section_Id"].ToString();
	Console.WriteLine("Section: {0}", sectionRow["SectionName"]);
	foreach (DataRow fieldRow in ds.Tables["Field"].Select("Section_Id = " + sectionId))
	{
		foreach (object item in fieldRow.ItemArray)
		{
			// Do something here
		}
	}
}

This solution works for me.

How to modify the default new class template for C# in Visual Studio 2008 or 2010?

Updated: 5/17/2010 using information aquired from here: How To: Edit Visual Studio Templates

Ok, so I don’t like the way that the default new class template in Visual Studio 2008/2010 looks. I end up typing a lot of things over and over again.

Here is what it a new class looks like:

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

namespace MyNameSpace
{
	class MyClass
	{
	}
}

Here is what I want it to look like:

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

namespace MyNameSpace
{
	public class MyClass
	{
		#region Member Variables
		#endregion

		#region Constructors

		/// <summary>
		/// The default Constructor.
		/// </summary>
		public MyClass()
      		{
		}

		#endregion

		#region Properties
		#endregion

		#region Functions
		#endregion

		#region Enums
		#endregion
	}
}

So making this change is easy to do. All you have to do is edit a text file that is compressed.

Copy the zip file file located here to the desktop:
Visual Studio 2008

  • For 64 bit: C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip
  • For 32 bit: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip

Visual Studio 2010

  • For 64 bit: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip
  • For 32 bit: C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip

Extract the zip file.

Using a text editor, open the Class.cs file.

The file will have the following text:

using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
$endif$using System.Text;

namespace $rootnamespace$
{
	class $safeitemrootname$
	{
	}
}

Change it to have this text:

using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
$endif$using System.Text;

namespace $rootnamespace$
{
	public class $safeitemrootname$
	{
		#region Member Variables
		#endregion

		#region Constructors

		/// <summary>
		/// The default Constructor.
		/// </summary>
		public $safeitemrootname$()
		{
		}

		#endregion

		#region Properties
		#endregion

		#region Functions
		#endregion

		#region Enums
		#endregion
	}
}

Save the file.

Rebuild the zip file with the new Class.cs.  Be careful to build the zip file correctly.

Copy the new zip file back here and overwrite the existing one:
Visual Studio 2008

  • For 64 bit: C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip
  • For 32 bit: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip

Visual Studio 2010

  • For 64 bit: C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip
  • For 32 bit: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip

Now, you have to rebuild the template classes.  To do this:

  1. Open a command prompt as Administrator.
  2. Change to the appropriate directory:
    Visual Studio 2008
    64-bit

    cd C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\

    32-bit

    cd C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\

    Visual Studio 2010
    64-bit

    cd C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\

    32-bit

    cd C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\
  3. Run this command:
    devenv.exe /installvstemplates

Now any new class you create will have your new format.


Copyright ® Rhyous.com – Linking to this article is allowed without permission and as many as ten lines of this article can be used along with this link. Any other use of this article is allowed only by permission of Rhyous.com.

How to get the relative path (folder the executable was launched in) as a string in C#?

Well, lets say you launch an application and you want to know the relative path.

In C# you can use the System.Reflection.Assembly.GetExecutingAssembly().Location value. I have searched through many online sites that tell different ways, and some of the more experienced C# developers say that some of the other ways are not always accurate or won’t always work, while this one should always work.

So if you make a class and add two String class variables, you can use this function to populate them: Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)


        private void GetPaths()
        {
            mExecutablePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            mExecutableRootDirectory = System.IO.Path.GetDirectoryName(mExecutablePath);
        }

Ok, so I like to make sure any newbie can pull this off, so the whole file with it working (using a New WPF project):

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TestPath
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        DataSet mDataSet;
        String mExecutablePath;
        String mExecutableRootDirectory;

        public Window1()
        {
            GetPaths();
            InitializeComponent();
        }

        private void GetPaths()
        {
            mExecutablePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            mExecutableRootDirectory = System.IO.Path.GetDirectoryName(mExecutablePath);
        }
    }
}

Book Review: TCP/IP Sockets in C – Practical Guide for Progammers Second Edition (Chapter 2)

Hello everyone,

I have just made my way through chapter 2. It had a few hiccups but was overall well done.

This chapters introduces you to a simple Client and Server communication process. The client program can send text to the server. The server sends the text back.

Client Code

The client code seems to work fine. I am a big fan of showing the absolute minimum the first time and not including anything else that may get in the way. However, they didn’t do the minimal, (though don’t worry, they were very close to the minimal). They also added two files, so to compile the following files are needed:

  • TCPEchoClient4.c
  • Practical.h
  • DieWithMessage.c

Personally, I have a hard time using code that I don’t understand, so this made me deviate from my purpose of learning sockets to see what is in these other files. Of course, the book give brief explanations too. These files were small and easy to understand.

Practical.h just declares a bunch of functions. However the implementation of these functions are if different .c files.

DieWithMessage.c provides the implementation of two of these functions, DieWithUserMessage and DieWithSystemMessage. These functions are little more than wrappers to output error messages to standard error.

To compile the client code on FreeBSD 8, I did this:

  1. Put the following files in the same directory: /home/jared/Devel/Echo/echoclient
    • TCPEchoClient4.c
    • Practical.h
    • DieWithMessage.c
  2. Change to that directory.
    cd /home/jared/Devel/Echo/echoclient

  3. Run gcc as follows:
    gcc TCPEchoClient4.c DieWithMessage.c -o echoclient

The book includes information about a web site where the code from the book can be downloaded. This web site is here:
http://cs.ecs.baylor.edu/~donahoo/practical/CSockets2/textcode.html
When I downloaded the code from there, the compiling of the client code worked first time and the echoclient works.

When I typed the code in myself (which I like to do because I think it helps me learn better to actually have to type all the code), I had some typos that the compiler errored on and I fixed them.

Server Code (IPv4)
My experience with this first example of server code was…well, lets just say it was confidence building.

The server code also had other files. Not only did it have the same extra files the client code had, but it required even more files:

  • TCPEchoServer4.c
  • Practical.h
  • DieWithMessage.c
  • TCPServerUtility.c
  • AddressUtility.c

We already know what Practical.h and DieWithMessage.c do.

TCPServerUtility.c is similar to DieWithMessage.c in that it provides implementation of functions declared in Practical.h, however, it is not the same in that it is not as short of a file with over 100 lines. It is not as complex as it looks because TCPServerUtility.c provides implementation for only three functions: SetupTCPServerSocket, AcceptTCPConnection, and HandleTCPConnection.

AddressUtility.c provides the implementation to functions declared in Practical.h as well. The following two functions are implemented: PrintSocketAddress, SockAddrsEqual.

I put these files in the same directory and tried to compile just like I did with the client code. However, there was a huge problem when I tried to compile. I got a long lists of errors.

[jared@FBSD8 ~/Devel/Echo/echoserver1]$ gcc TCPEchoServer4.c TCPServerUtility.c DieWithMessage.c AddressUtility.c
TCPServerUtility.c: In function ‘SetupTCPServerSocket’:
TCPServerUtility.c:17: error: ‘IPPROTO_TCP’ undeclared (first use in this function)
TCPServerUtility.c:17: error: (Each undeclared identifier is reported only once
TCPServerUtility.c:17: error: for each function it appears in.)
TCPServerUtility.c:25: error: ‘for’ loop initial declaration used outside C99 mode
AddressUtility.c:6: warning: ‘struct sockaddr’ declared inside parameter list
AddressUtility.c:6: warning: its scope is only this definition or declaration, which is probably not what you want
AddressUtility.c: In function ‘PrintSocketAddress’:
AddressUtility.c:16: error: dereferencing pointer to incomplete type
AddressUtility.c:17: error: ‘AF_INET’ undeclared (first use in this function)
AddressUtility.c:17: error: (Each undeclared identifier is reported only once
AddressUtility.c:17: error: for each function it appears in.)
AddressUtility.c:18: error: dereferencing pointer to incomplete type
AddressUtility.c:19: error: dereferencing pointer to incomplete type
AddressUtility.c:21: error: ‘AF_INET6’ undeclared (first use in this function)
AddressUtility.c:22: error: dereferencing pointer to incomplete type
AddressUtility.c:23: error: dereferencing pointer to incomplete type
AddressUtility.c:30: error: dereferencing pointer to incomplete type
AddressUtility.c: At top level:
AddressUtility.c:40: warning: ‘struct sockaddr’ declared inside parameter list
AddressUtility.c: In function ‘SockAddrsEqual’:
AddressUtility.c:43: error: dereferencing pointer to incomplete type
AddressUtility.c:43: error: dereferencing pointer to incomplete type
AddressUtility.c:45: error: dereferencing pointer to incomplete type
AddressUtility.c:45: error: ‘AF_INET’ undeclared (first use in this function)
AddressUtility.c:48: error: dereferencing pointer to incomplete type
AddressUtility.c:48: error: dereferencing pointer to incomplete type
AddressUtility.c:49: error: dereferencing pointer to incomplete type
AddressUtility.c:49: error: dereferencing pointer to incomplete type
AddressUtility.c:50: error: dereferencing pointer to incomplete type
AddressUtility.c:50: error: ‘AF_INET6’ undeclared (first use in this function)
AddressUtility.c:53: error: dereferencing pointer to incomplete type
AddressUtility.c:53: error: dereferencing pointer to incomplete type
AddressUtility.c:54: error: invalid application of ‘sizeof’ to incomplete type ‘struct in6_addr’
AddressUtility.c:54: error: dereferencing pointer to incomplete type
AddressUtility.c:55: error: dereferencing pointer to incomplete type
[jared@FBSD8 ~/Devel/Echo/echoserver1]$

This was not comforting. I really don’t like to debug sample code but here it goes. In the past, I probably would have stared at these errors and maybe I wouldn’t have had the skills to solve them. However, I was undaunted and resolved these. Let me explain how I resolved them.

  1. TCPServerUtility.c:17: error: ‘IPPROTO_TCP’ undeclared (first use in this function)
    This first error is a problem in TCPServerUtility.c with IPPROTO_TCP variable being undeclared. So I had to figure out where IPPROTO_TCP was declared. It is declared in netinet/in.h, which for some reason is not included. Maybe it only needs to be included on FreeBSD or maybe this is a bug in the Author’s code. Later, I will send the author a link to this post and let him comment on it. For now, I will add this line to the top of the TCPServerUtility.c.

    #include <netinet/in.h>
    
  2. TCPServerUtility.c:25: error: ‘for’ loop initial declaration used outside C99 mode
    This second error can easily be resolved by compiling with C99 mode enabled. This can be added to gcc as a paramter -std=c99.

  3. AddressUtility.c:16: error: dereferencing pointer to incomplete type
    This is not super clear to me at first. However, the line isn’t doing much. So why is the type incomplete? Maybe the struct is not declared yet because again, a file that should be included is not. The struct being called is sockaddr_in and it is defined in netinet/in.h but sure enough, netinet/in.h is not included in AddressUtility.c, so lets add it.

    #include <netinet/in.h>
    
  4. AddressUtility.c:17: error: ‘AF_INET’ undeclared (first use in this function)
    This error in AddressUtility.c is similar to the first error in TCPServerUtility.c. There is probably a header file missing. Again, this may be only a FreeBSD issue or it may be a bug in the author’s code. It is hard to know since I don’t see anywhere where the author specified the platform this was tested on. So I researched and found that AF_INET is declared in sys/socket.h however, again it is not included. Se we add this line to the file.

    #include <sys/socket.h>
    

Ok, now try to compile with this command line:

gcc -std=c99 TCPEchoServer4.c DieWithMessage.c TCPServerUtility.c AddressUtility.c -o echoserver4

Everybody cheer…this time it worked.

It tested the client and the server application together and sure enough, communication occurred. Any string I sent from the client, server sent back.

I was able to use the exact same command with the IPv6 version of the server code, only replacing the TCPEchoServer4.c with TCPEchoServer6.c.

gcc -std=c99 TCPEchoServer6.c DieWithMessage.c TCPServerUtility.c AddressUtility.c -o echoserver6

The rest of the chapter
The rest of the chapter is about what you would expect. The author gives a snippet of code and explains it well. Make sure to take time to read it. This is foundational material for understanding the rest of this book, so it may not hurt to read it twice.

Other notes on the C code
You need to be familar with some common C language features such as typedef and struct as they are used heavily.

typedef
Most the types used are just types that have been renamed with typedef. I am not 100% sure why one would declare a function as follows but I know at least one reason that I will mention:

in_port_t port;

To me this is much more confusing than what it is really saying. in_port_t is just an unsigned short. So it would seem that one should declare the function as follows:

unsigned short port;

However, what if your code is very popular and five years or ten years from now the RFC changes the implementation of a port so that an unsigned int is now required. it is really easy to change in_port_t to point be a typedef of an unsigned int and no other work needs to be done. However, if you declared your variable using unsigned short instead of in_port_t, then every where in your code that you did this, you have to find and manually change it or your code will probably fail.

You can even make a typedef of a typedef and in fact that is what in_port_t is. If you have an IDE (I am using Code::Blocks), then you can highlight the type, right click it and choose something similar to Find Declaration of: in_port_t and it will take you to where this value is defined using a typedef. However, in_port_t is a typedef of uinst16_t, which is a typedef itself of __uinst16_t, which is a typedef of unsigned short. So it is multiple typedefs deep. While sometimes confusing, this can be useful as mentioned above.

struct
C does not have objects or classes. Instead it has structs and one might say that they are the predecessor to objects or classes. However, they are not objects or classes and you should understand how they function. If you understand them, this book will be easier to understand. If you don’t, you will probably struggle. If you aren’t clear on structs, then take time to read about them.

Book Review: TCP/IP Sockets in C – Practical Guide for Progammers Second Edition (Chapter 1)

Hello everyone.

I want to learn sockets on FreeBSD so naturally I bought the following book about it.
TCP/IP Sockets in C, Second Edition: Practical Guide for Programmers (The Morgan Kaufmann Practical Guides Series)

Ok, so chapter one says it is an introduction but would be bettered titles as “Basic Computer Networking Concepts” as it really covers in a very, very broad sense the important points of the OSI model (without mentioning the OSI model). If you are excellent at networking, TCP/IP, etc, this chapter will be a quick read. It is so short that even if you are already an expert, just read it. Who knows, you may find that one line that will teach you something. By the way, I spent four years doing tech support for Nortel Networks Routers, Layer 3 switches, Load Balancers, Wireless APs, etc. I lived in the network world and spent a lot of time in Sniffer Pro or Wireshark (then Ethereal). After which I came to LANDesk (my current employer) where I spent a lot of time working with PXE booting over the network, which uses bootp, dhcp, TFTP and furthered my understanding of client/server communication. So you might think that I should have skipped this chapter entirely. No, I read it.

I found section 1.2.2 – Dealing with Two Versions interesting. This section mentions straight up that socket programmers will have to deal with IPv6. The whole chapter doesn’t just talk of IPv4 only, it includes little snippets of both. I believe the big move to IPv6 will not come quite yet. In 1999, a trainer in my MSCE class said that everyone will be using IPv6 within five years (2004) and if you don’t know, it has really been adopted yet in 2010. It is moving slowing and I think it will continue. Windows 7 and Windows 2008 will cause a lot of adoption, but people are still using Windows 98 in many places even today in 2010. Windows 2000 and Windows XP will take quite a long time to fade away. I predict that some companies (though not many) will still be running Windows XP in 2020. I think that a bigger adoption of IPv6 will occur once the next windows OS (the version after Windows 7) is on the majority of computers. So windows 7 will do what Windows Vista couldn’t and replace XP in the corporate world. The corporate world still must move all their domain environments to Server 2008 (or they may stay on Windows Server 2003 until the next server release after Windows Server 2008 ). The home world will take about five years (2015) to have everyone a majority moved to Windows 7. Anybody on Vista will upgrade to get off that poor unstable operating system and anybody running XP will probably have old hardware that will start dying off and will have to purchase new computers that already come with Windows 7. Moving the operating system is not enough. That aone won’t make everyone move to IPv6. Wireless routers are just starting to support IPv6 such as the DIR-655 Xtreme N Gigabit Router. However, there is a big difference between supporting IPv6 and making IPv6 the default. Most Internet Service Providers (ISPs) still give IPv4 addresses. The infrastructure using IPv4 is so huge it could take a few more decades to completely remove it. You can probably guess that the adoption is going to reach a craze when your ISP starts sending you notices that they are moving to IPv6 and you have to comply and you don’t have a choice, kind of like what just happened with the analog TV service this year. Funny, thing, for a lot of people, me included, their Cable TV service is also their ISP.

Ok, enough rambling about IPv6. It is enough to know that you are going to start to have to deal with it now and at some future time IPv4 will be replaced and you will only have to deal with IPv6.

As for the other topics in the chapter, it is actually amazing that they were able to mention as many topics as they did in such short pages. They mention NAT and DNS and URLs and other important topic (each of which have dozens of large books covering just the one topic). The networking world is a whole other field that have engineers who spend their entire lives becoming experts at just using the equipment, let alone developing software for it. Usually a software developer won’t need to reach such an expert level understanding of networking (unless they are developing the OS for a router/switch or a software such as a firewall).

This chapter was necessary and they added it and I would say they did a good job keeping it short and simple. They did a good job of providing the detail needed at just enough level that a freshman/sophmore in college who knows little about networking and programming would be able to understand the concept of networking enough to have a general idea why they need to code with sockets they way the book will describe.

Stay tuned for a review on Chapter 2.

Update: My review on Chapter 2 is here:
Book Review: TCP/IP Sockets in C – Practical Guide for Progammers Second Edition (Chapter 2)

How to compile a wxWidgets application in Visual Studio 2008?

Step 1 – Install Visual Studio 2008

  1. If you don’t have it, get the express edition here: http://www.microsoft.com/Express/VC/
  2. Run through the installer, not much else to do.

Step 2 – Install wxWidgets

  1. Download wxWidgets (select the wxMSW installer file) from here:
    http://www.wxwidgets.org/downloads/
  2. I choose to install to c:\dev\wxwidgets\wxWidgets-2.8.10 but you can choose a different path if you want.

Step 3 – Create an environment variable for the wxWidgets path.

  1. Click the Start icon.
  2. Right click on Computer and choose Properties.
  3. Click Advanced system settings.
  4. Click the Environment variables button.
  5. Under System Variables, click New.
  6. Enter the Variable name: WXWIN
  7. Enter the Variable Value: C:\Dev\wxWidgets-2.8.10
  8. Click OK, click OK, click OK (yes three times).

Step 4 – Compile the wxWidgets Libraries.

  1. Browse to the following folder: C:\Dev\wxWidgets-2.8.10\build\msw
  2. Located the file called wx.dsw and open it with Visual Studio. (I just double-clicked on it.)
  3. Choose “Yes to all” when Visual Studio prompts you to convert the project.
  4. Build the project.
  5. Wait for the build to complete. It took approximately two minutes on my Lenovo T61p (dual core, 4 GB, Windows 7 64 bit). You should a line like this when it finishes successfully.
    ========== Build: 20 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
  6. Close Visual Studio.

Step 5 – Create a new project

  1. In Visual Studio 2008, go to File | New Project.
  2. Select Visual C++ | Empty Project.
  3. Give the project a name and click OK. I named this wxTest.

Step 6 – Create/Copy your source to this project.

  1. Right-click on the Project name and choose Open Folder in Windows Explorer. This will open to the home folder of your project. (Don’t right click the Solution name, make sure to right click the project under the solution name.)
  2. Open a second Windows Explore window.
  3. In the second window, browse to the wxWidgets sample directory and open the Minimal folder: C:\Dev\wxWidgets-2.8.10\samples\Minimal
    Note: You can choose other projects but you may want to start with Minimal and move on from there.
  4. Copy only the minimal.cpp and minimal.rc files to your project directory (the rest are not needed).
  5. Close the second window pointing to the C:\Dev\wxWidgets-2.8.10\samples\Minimal directory, it is not needed anymore.
  6. From the explorer window open to your project directory, use ctrl+click to highlight both the minimal.cpp and minimal.rc files.
  7. Drag both highlighted files into the Visual Studio Window and drop them over the project name.
    The minimal.cpp file should automatically be placed under the Source files section of your project.
    The minimal.rc file should automatically be placed under the Resource files section of your project.

Step 7 – Customize the project properties

  1. Right-click on the wxTest project and select Properties. (Don’t right click the Solution name, make sure to right click the project under the solution name.)
  2. In the top left of the properties window there is a Configuration drop down menu. Select All Configurations.
  3. Click to expand Configuration Properties.
  4. Click to expand C/C++.

    Note: If you don’t see a C/C++ section, then you don’t have any source files.  You need at least one C++ source file for this section to show up.

  5. Click to highlight General.
  6. Enter the following in Additional Include Directories.
    $(WXWIN)\include;$(WXWIN)\lib\vc_lib\mswd
  7. Click to highlight Preprocessor.
  8. Enter the following in Preprocessor Definitions.
    WIN32;__WXMSW__;_WINDOWS;_DEBUG;__WXDEBUG__
  9. Click to expand Linker.
  10. Click to highlight General.
  11. Enter the following in Additional Library Directories.
    $(WXWIN)\lib\vc_lib
  12. Click to highlight Input.
  13. Enter the following in Additional Dependencies.
    wxmsw28d_core.lib wxbase28d.lib wxtiffd.lib wxjpegd.lib wxpngd.lib wxzlibd.lib wxregexd.lib wxexpatd.lib winmm.lib comctl32.lib rpcrt4.lib wsock32.lib odbc32.lib

    Note: Not all of these libraries are required for this project, however, I list all of these because you may use some of them at some point. If you don’t think one is needed, remove it and recompile and if you don’t get errors, you were right, you probably didn’t need it.

  14. Click to expand Resources. (If you don’t see a Resources option, then you don’t have any files under resources so that is normal. Did you skip Step 5 because you probably should have added a resource in Step 5.)
  15. Click to highlight General.
  16. Enter the following in Preprocessor Definitions.
    _DEBUG;__WXMSW__;__WXDEBUG__;_WINDOWS;NOPCH
  17. Enter the following in Additional Include Directories.
    $(WXWIN)\include;$(WXWIN)\lib\vc_lib\mswd

You are now ready to build your wxWidgets application using Visual Studio 2008 on Windows 7.

Build your project and if you get any errors, go through it again, you probably missed a step (or I did, since I have already been caught with one step left out).


Copyright ® Rhyous.com – Linking to this article is allowed without permission and as many as ten lines of this article can be used along with this link. Any other use of this article is allowed only by permission of Rhyous.com.

How to setup Eclipse C/C++ Development Tools on Windows 7?

How to setup Eclipse C/C++ Development Tools on Windows 7?

Ok, so I download Eclipse C/C++ Development Tools and create a Hello World application and it didn’t run. It failed to compile with this error:

(Cannot run program “make”: Launching failed)

So obviously it is not download and extract and it works…so lets figure it out.

  1. First, install the other dependencies as described here:

    http://help.eclipse.org/galileo/index.jsp

  2. Add c:\mingw\bin to the path of your environment variables.
  3. Then download Eclipse from http://www.eclipse.org.

After doing it all right, I still go this error when I tried to compile the simple Hello World program.

undefined reference to `WinMain@16′

Yeah, I fixed this error by saving my C++ file, as found at this site: http://www.peetm.com/blog/?p=278

How to return an string array from an enum in C++?

How to return an string array from an enum in C++?

Well, you can’t. You can’t just create an enumerator and then get the string. You have to create the string array for it to work.

So if you can’t do it, then what do you need to do?

I would recommend an array of strings, or a vector of strings, etc…

#include <iostream>
enum items
{
	item1 = 1, item2, item3, item4, item5
}

char * item[] = {"item1", 'item2', 'item3', 'item4', 'item5'};

int main()
{
	return 0;
}

I found this way to do this and it doesn’t seem very straight forward. It looks confusing, but hey, it works.

#define OPTIONS_LIST X(Add),\
			         X(Edit),\
					 X(New),\
					 X(Sell),\
					 X(Stock)

#define X(x) x
enum options
{
	OPTIONS_LIST
};
#undef X

#define X(x) #x
const char *szOPTIONS_LIST[] =
{
	OPTIONS_LIST
};
#undef X

There are other ways and they all seem doable but confusing to other developers. Here are some references for other confusing ways….

http://www.cplusplus.com/forum/general/2949/
Note: I liked the comment by Zaita

http://www.codeproject.com/KB/cpp/C___enums_to_strings.aspx

http://www.gamedev.net/community/forums/topic.asp?topic_id=437852

How to get the size in bytes of a file in C++?

How to get the size in bytes of a file in C++?

Using the C++ Standard Library’s fstream object makes this rather easy. I tested this method on Windows 7 and FreeBSD 7.2.

Lets say I have a file called MyFile. How do I get the size of it?

#include
#include

using namespace std;

int main()
{
char * fileName = “MyFile”;
fstream file(fileName, ios::in);
file.seekg(0, ios::end);
int sizeInBytes = file.tellg();

cout << fileName << " is " << sizeInBytes << " bytes long." << endl; } [/sourcecode] That is great. It is simple and it works. Now you can actually make a usable application out. Let's change this to take a parameter, the parameter should be a file, and output the size of the file. [sourcecode language="cpp"] #include
#include

using namespace std;

int main(int argc, char **argv)
{
char * fileName = argv[1];
fstream file(fileName, ios::in);
file.seekg(0, ios::end);
int sizeInBytes = file.tellg();

cout << fileName << " is " << sizeInBytes << " bytes long." << endl; } [/sourcecode] Now if you build this into an executable called filesize, you can run filesize MyFile.

Ok, so their is an idea in the unix world (which I agree with usually) that output should not be chatty, so lets change the output line to only output the size in bytes of the file. This will make it easier for you to use shell scripts to and parse the output.

cout << sizeInBytes << endl; [/sourcecode] Now lets make it a little more rebust and error proof. [sourcecode language="cpp"] #include
#include
#include
#include

using namespace std;

void syntax(char * thisFile);
const char * stripPath(char * inPath);

int main(int argc, char **argv)
{
// Take only one paramter.
// Since there is a default parameter you have to check for 2 not 1
if (argc == 2)
{
char * fileName = argv[1];
fstream file(fileName, ios::in);
if (file)
{
file.seekg(0, ios::end);
int sizeInBytes = file.tellg();
cout << sizeInBytes << endl; } else { cout << "File error. The file you entered could not be sized." << endl; } } else { syntax(argv[0]); exit(1); } return 0; } void syntax(char * thisFile) { cout << "Syntax: " << endl; cout << " " << stripPath(thisFile) << " Filename" << endl; cout << endl; cout << " Filename\t" << "Any file path value such as, MyFile, c:\\myfile, /root/myfile." << endl; cout << endl; } const char * stripPath(char * inPath) { string path = inPath; string fileName = path.substr(path.rfind("\\") + 1); char * retVal = new char[fileName.size() + 1]; strcpy(retVal, fileName.c_str()); return retVal; } [/sourcecode] No there shouldn't be any program crashes when you input an incorrect filename, or a file that you don't have access to. Sources: http://www.cplusplus.com/reference/iostream/istream/read/

What is the syntax for the switch and case statement in C++?

The switch statement is often a good alternate for multiple if..else if...else statements.

switch (expression)
{
  case someConstantValue1 :
    // Your code goes here...
    break;
 case  someConstantValue2:
    // Your code goes here...
    break;
}

So lets look at this using an integer variable intValue and we will show you some other syntax capabilities.

switch (intValue) {

  case 1 :
    // Your code goes here...
    break;

  case 2 :
    // Your code goes here...
    break;

  case 3 :
  case 4 :
    // Both options 3 and 4 will run the same code
    // Your code goes here...
    break;

  case 10 :
  case 5 :
    // The options don't have to be in order but you may want to keep them order because you can.
    // Your code goes here...
    break;

  default :
    // Anything that doesn't match will run this code.
    // Your code goes here...
    break;
}

Keywords: C++ switch case break syntax

A new style guide or a new way to format your code in C++ or C# or any language: "Code like you speak"

Code Like You Speak

Ok, so I wrote a post about why I use long variable names, where I discussed how it is very easy to use long filenames with today’s IDEs. As I code more and more I realize how I want to write like I speak.

As I try to read other people’s code, I have to wonder if they could even understand it themselves if they went six months without touching it.

For example, lets say I am working with a database that has phone numbers and for each phone number I want to do check if it is valid:

Example 1

PhoneNumber p = new PhoneNumber("555-555-5555");
if (p.isValid())
{
    // do something
} else
{
    // Do something different
}

There is nothing wrong with the above code. It even makes sense, mostly because the first line where p is created is right next to the if statement. But of course that is not always the case.

Maybe I have dozens of objects for different database attributes including multiple ojects that start with ‘p’: PhoneNumber, PartList, PersonID, and they all have an isValid() method and those objects are created elsewhere in the code, who knows where. Also, your isValid() function in PhoneNumber checks if the PhoneNumber is formatted correctly, but the isValid() function in PartList checks if it is a valid part in the database and the isValid() function in PersonID does something different, now the above code would be more confusing, especially to some one else reading it (or to yourself six months after writing it).

if (p.isValid())
{
    // do something
} else
{
    // Do something different
}

So if we don’t have the declaration right next to the code, it is hard to understand…

You might say, “Load it in a debugger and just look…why is it so hard?”

My response is this. “What about your Team Leads for you Tech Support team? What about your documentation team? They may have that has access to read the code but they don’t have the tools or know how to compile it. But they may need to see your code to get their job done. And I don’t want to offend your project managers, but there sure are a lot of Project Managers that either never had the ability or have lost the skill to compile code.”

So someone else reading your code is lost. What does p represent? PhoneNumber, PartList, PersonId? What is the object? What does isValid() check for on this object?

So lets code like we speak. First you should say what we really want to do in your language. The sentence below is a valid English sentence and anybody who speaks English can understand it.

If the current phone number is formatted correctly, do something, else do something different.

Well, what if the code were written like this:

// This could be anywhere in code
PhoneNumber theCurrentPhoneNumber = new PhoneNumber("555-555-5555");

// A code like you speak if statement
if (theCurrentPhoneNumber.isFormattedCorrectly())
{
    // do something
} else
{
    // do something different
}

See how it is in “code like you speak” format?

So you may here different theories about writing code and whether to document with comments or not document and have clear code. I am for the theory that when you write your code you should assume that the person reading your code:
1. Doesn’t understand code.
2. Has no technical skills
3. Has an average IQ (in the 90s).
4. Is the worst technical ever who has to document your code…
etc, etc, etc…

So that is why “Code like you speak” is a great way to code. If your technical writer reads the first example, he is confused, but if he read the second, he fully understands the idea what it going one.

Now, it is important that you don’t over do it. You don’t need to have perfect English. Broken English is fine. As you practice you will get better at it. As you get better at it, your code becomes more readable and others can work on it easier. This is especially usefully when working in teams, or one a community-developed open source application.

Don’t go overboard! I mean, there is not reason to define the word “othewise” to replace “else”. If you did that, you may actually confuse veteran developers.

// In a header somewhere...
#define otherwise else

// This could be anywhere in code
PhoneNumber theCurrentPhoneNumber = new PhoneNumber("555-555-5555");

// A code like you speak if statement
if (theCurrentPhoneNumber.isFormattedCorrectly())
{
    // do something
}
otherwise
{
    // do something different
}

However, if the “Code like you speak” development style takes off, the above may not be so overboard, and may become a standard practice to define many English synonyms to help one code in a more clear and understandable method.

One might argue that because not every one speaks english, a language barrier would be more likely, and I would have to disagree. If you code like you speak, someone who doesn’t speak your language could still figure it out a lot faster using something like a language translation tool (such as google’s or babblefish’s) than they could by trying to figure out what a random object is.

As for other style guide information, there are lots of style guides. If you need one and don’t have one, start with this one:
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml

How to create a directory in C++ in Windows?

How to create a directory in C++?

Ok, so this is another task that should be simple but isn’t. Come on C++ Standards people. C++ has been out for decades and you haven’t figured out how to get all Operating Systems to conform to a single piece of code to make a directory? Write an standard and release it.

This document is for Windows, I will talk about FreeBSD some time later.

If wxWidgets can do it with the filefn.h, why can’t the standard C++ Library?

Supposedly Boost can do it also but the standards people are taking their sweet time getting Boost in.

So here is how it can be done. The headers names are the project types I chose in Visual Studio 2008.

Windows Empty Project

Create a main.cpp and put the following in it.

#include <iostream>
#include <string>
#include <direct.h>
#include <sys/stat.h>

using namespace std;

int main ()
{
	string directoryName = "c:\\programdata\\MyApp";

	struct stat st;
	if (stat(directoryName.c_str(), &st) == 0)
	{
		cout << "The directory exists." << endl;
	}
	else
	{
		int mkdirResult = _mkdir(directoryName.c_str());
		if (mkdirResult == 0)
		{
			cout << "The directory is created." << endl;
		}
		else
		{
			cout << "The directory creation failed with error: " + mkdirResult << endl;
		}
	}
}
&#91;/sourcecode&#93;

<strong>Windows CLR Console Application</strong>

[sourcecode language="cpp"]
#include "stdafx.h"

using namespace System;
using namespace System::IO;
int main()
{

   String^ directoryName = "C:\\ProgramData\\MyApp";
   if ( Directory::Exists( directoryName ) )
   {
	   Console::WriteLine( "The directory exists.");
       return 0;
   }
   else
   {
	   try
	   {
		  DirectoryInfo^ directoryInfo = Directory::CreateDirectory(directoryName);
	   }
	   catch ( Exception^ e )
	   {
		   Console::WriteLine(e->ToString());
	   }
   }
}

How to add an enum or enumeration to a class in C++?

How to add an enum or enumeration to a class in C++?

Obviously this is simple, but I keep forgetting one element or other of the syntax (usually the terminating semi-colon) so I thought if I made a post about it, I would never forget again, and if I did, I could look at my post and remember.

There are certain parts to an enum configuration:

  1. The enum keyword.
  2. The name of the enumerator. I name this one Items just as an example but it can be named anything you want almost (of course you can’t use C++ keywords).
  3. The open bracket: {
  4. The names of the items separated by comas:
    item1, item2, item3
    Each item has an integer value starting at 0 and incrementing by one. Optionally, you can change a value, and again, ever value thereafter will be +1. So if you want to start at 1 instead of at 0, you would put this:
    item1 = 1, item2, item3
    If you wanted to count from 1,2,3 and then 7,8,9 you could do this:
    item1 = 1, item2, item3, item7 = 7, item8, item9
    Also you can change every item by having every item by assigning every item.

  5. The closing bracket: }
  6. A statement closing semicolon: ;

    So the code for your Items enumerator look like this:

    enum Items
    {
        item1 = 1, item2, item3
    };
    

    A basic class is shown here:

    class NewObject
    {
    public:
        // Public members and functions
        NewObject();
        ~NewObject();
    protected:
        // Protected members and functions
    private:
        // Private members and functions
    };
    

    So to add an enum to you need to decide, is it a public, protected, or private enum? I think it is most common to have public enumerations so that is what my example shows.

    class NewObject
    {
    public:
        // Public members and functions
        NewObject();
        ~NewObject();
    
        enum Items
        {
            item1 = 1, item2, item3
        };
    
    protected:
        // Protected members and functions
    private:
        // Private members and functions
    };
    

    Now you can use the enum on any instantiated class.