Understanding IP subnets and routing


IP networking and routing is not new to me, but each time I come back to it after a gap of a year or two, I find myself blundering through the same concepts. This post is my attempt to remind myself each time that happens.

IP version 4 uses a 32 bit address, represented as four octets in the decimal notation, separated by dots, e.g. 192.168.1.1. This implies that we can provide a unique address to more than four billion computing devices. Assuming for the moment that 4 billion addresses is enough, we cannot connect all those four billion computers in a single network. The bandwidth of the medium would have to be infinite, iterconnections would have to be very long, each computer would have to receive and discard a lot of information not destined for it and lots of other physical limitations.

The quite obvious solution is to break the problem down, which means creating several small networks and somehow iterconnecting them. To do that we bring into existence an entity called the router, which has a physical presence in one or more sub-networks and can selectively take data from one network to another. We also divide an IP address into two parts, the network address and the host address. This division is stated by using a subnet mask.

The immediate advantage of this scheme is that traffic destined to a subnet is seen only by hosts within that subnet, this is good for security and for scaling the network.

Read a file in C++


I have returned to C++ programming. In the past I have read about it and practiced it as a theoretical exercise, but never for anything serious beyond that.

I was recently looking for a way to read a file, and that simple task turned into an arduous affair. Since I am using VC++ my first thought was to lookup documentation on the fstream library, but that is not easy since members are split across basic_istream, basic_ios and basic_fstream. Eventually, I managed to create a basic example presented below.

#include <string>
#include <fstream>
#include <iostream>
using namespace std;

const int gBufSize = 1024;
string filename = "file.bin";

int main( int argc, char *argv[] )
{
    char* buf[1024];
    streamsize n;
    ifstream binfile;

    binfile.open(filename);

    if (!binfile.is_open() || binfile.bad()) return -1;

    binfile.read((char*)buf, gBufSize);
    n = binfile.gcount();
    cout << "Read " << n << " bytes" << endl;

    while (n == gBufSize)
    {
        binfile.read((char*)buf, gBufSize);
        n = binfile.gcount();
        cout << "Read " << n << " bytes" << endl;
    }

    // we're done
    binfile.close();

    return 0;
}

Configuring a device using an external configuration file


This post discusses a very simple scheme that I used to configure a TopCon GPS device by issuing commands from an external configuration file. This has the advantage of not requiring to recompile the app if you need to quickly change something. This pattern can be quite generally applied to configure any device that presents a command line interface.

Here’s the code of a parser that reads the external config file.

    public class TopconConfigParser
    {
        private StreamReader reader;

        public TopconConfigParser(string file)
        {
            reader = new StreamReader(File.Open(file, FileMode.Open));
        }

        /// Read the next command from the config file or null if
        /// no commands left to read
        public string NextCommand()
        {
            return ReadLine();
        }

        private string ReadLine() {
            StringBuilder line = new StringBuilder();
            int c;
            bool stop = false;
            bool inComment = false;
            while (!stop)
            {
                try
                {
                    c = reader.Read();
                }
                catch
                {
                    break;
                }
                switch (c)
                {
                    case '\r':
                    case '\n':
                    case -1:
                        if (line.Length > 0 || reader.EndOfStream)
                        {
                            stop = true;
                        }
                        break;
                    case '\t':
                    case ' ':
                        // ignore
                        break;
                    case '/':
                        if (reader.Peek() == '*')
                        {
                            inComment = true;
                        }
                        else
                        {
                            if (!inComment)
                            {
                                line.Append((char)c);
                            }
                        }
                        break;
                    case '*':
                        if (reader.Peek() == '/')
                        {
                            inComment = false;
                            reader.Read();
                        }
                        else
                        {
                            if (!inComment)
                            {
                                line.Append((char)c);
                            }
                        }
                        break;
                    case '%':
                    case '#':
                        DiscardTillEOL();
                        break;
                    default:
                        if (!inComment)
                        {
                            line.Append((char)c);
                        }
                        break;
                }
            }
            string retVal = line.ToString();
            return retVal == String.Empty ? null : retVal;
        }

        private void DiscardTillEOL() {
            int c = reader.Peek();
            while (c != -1 && c != '\r' && c != '\n')
            {
                reader.Read();
                c = reader.Peek();
            }
        }
    }

Here’s a simple example of a config file. It uses C language syntax for comments. A single line comment beginning with a # char can also be used.

/* reset device configuration */
init,/par/
/* NMEA version */
set,nmea/ver,v2.3
/* schedule periodic reception of data */
em,/dev/ser/a,/msg/nmea/GGA:1.0

Cost of school textbooks in Brazil


My elder daugther has just begun fourth grade. I reproduce below the expenses incurred on textbooks in Brazil. Leave a comment if you would like readers to compare expenses at other places around the world with your own. I have recorded prices based on the following exchange rates:

  • 1 USD = 1.7 BRL (Brazilian Real)
  • 1 USD = 46 INR (Indian Rupee)

This is how much each text book cost me. You can usually wring a ten percent discount if you pay in cash or using a debit card. I paid using a credit card.

  • Math – USD 49
  • Science – USD 47
  • History – USD 32
  • Geography – USD 44
  • Portuguese – USD 47
  • English – USD 44

The schools usually ask the parents to buy story books that can cost an additional USD 120. Notebooks and other supporting material can cost another USD 150. That takes the total cost of books per year for a fourth grader to USD 530. For the sake of comparison that is about INR 24,380 or about BRL 900.

How much have you spent on school textbooks this year?

Consuming WCF services using JQuery JSON


In this post we’ll use the WebHttpBinding for communication between a browser application and a service.

Test App

We’ll use the following assemblies and the corresponding namespaces from the .NET Framework version 3.5.

System.ServiceModel
System.ServiceModel.Web

The console application listed below hosts and exposes a test service. All the service methods are annotated using the WebGetAttribute class, which means they will be accessed using the HTTP GET method. Other HTTP methods such as POST, PUT or DELETE can be specified using the WebInvokeAttribute class.

    [ServiceContract]
    interface IMyService
    {
        [OperationContract]
        [WebGet]
        void SetSomething(string something);

        [OperationContract]
        [WebGet]
        string GetSomething();
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    class MyService : IMyService
    {
        string _something = String.Empty;

        #region IMyService Members

        public void SetSomething(string something)
        {
            _something = something;
        }

        public string GetSomething()
        {
            return _something;
        }

        #endregion
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(wcf.MyService)))
            {
                host.Open(); // end point specified in app config

                Console.WriteLine("Hit Enter to quit.");
                Console.ReadLine();
            }
        }
    }

App.Config

We specify the service endpoint and behavior configuration in the application configuration file, it can also be done in code. If you intend to run your service under IIS, you can copy the system.serviceModel element to your Web.config.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name="webBinding"/>
      </webHttpBinding>
    </bindings>
    <behaviors>
      <endpointBehaviors>
        <behavior name="jsonBehavior">
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="wcf.MyService">
        <endpoint address="http://localhost:8003/myservice"
          binding="webHttpBinding"
          bindingConfiguration="webBinding"
          contract="wcf.IMyService"
          behaviorConfiguration="jsonBehavior"/>
      </service>
    </services>
  </system.serviceModel>
</configuration>

Netsh

You must allow a user without admin privileges to register a URL. If you don’t do this, you’ll get the following exception when you run the app:

Unhandled Exception: System.ServiceModel.AddressAccessDeniedException: HTTP could
not register URL http://+:8003/myservice/. Your process does not have access rights to this
namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details).
---> System.Net.HttpListenerException: Access is denied

Run the netsh command as follows to grant your user permission to access the URL:

netsh http add urlacl url=http://+:8003/myservice user=DOMAIN\user

Test the service

Launch a browser go to the following URL. It calls the SetSomething method.

http://localhost:8003/myservice/SetSomething?something=hello%20world

Then, go to the following URL. It retrieves the value set using the previous call.

http://localhost:8003/myservice/GetSomething

The following output should appear in the browser window.

hello world

JQuery JSON app

The following application built using JQuery repeats the previous test. Most modern browsers will not allow cross-origin requests unless authorized by the server. It is fairly easy to enable cross-origin requests in Chrome.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
  <head>
    <title></title>
    <script type="text/javascript"
      src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js">
    </script>
    <script type="text/javascript">
      var url = 'http://localhost:8003/myservice/';
      $(document).ready(function() {
        $("#set").click(function() {
          var urlSet = url + 'SetSomething?something='
              + $("#text").val();
          $.getJSON(urlSet, function(data) {
              // nothing to do
          });
        });

        $("#get").click(function() {
          var urlGet = url + 'GetSomething';
          $.getJSON(urlGet, function(data) {
              $('#text').val(data.d);
          });
        });
      });
    </script>
  </head>
  <body>
    <p>Test MyService</p>
    <form action="">
      <input id="text" type="text" value="Hello" />
      <input id="set" type="button" value="Set"/>
      <input id="get" type="button" value="Get" />
    </form>
  </body>
</html>

That’s all for now. Leave your comments or suggestions below.

Insert a handwritten signature in Microsoft Word 2007


I have a Wacom tablet that I use on rare occasions to insert signatures into documents. I just figured out how to do that in Microsoft Word 2007 and thought I’d share it. In the ribbon toolbar go to the Review tab and click the Start Inking button. More details can be found at this support page from Microsoft.

Log all CLR exceptions using WinDbg


This is a short post to complement my earlier post regarding post-mortem debugging. Sometimes, an application or service crashes without giving us an opportunity to save a detailed memory dump. In such a scenario, it may be useful to run WinDbg, attach to the process of the application or service, and log all exceptions that occur. To log an exception (handled or not) and continue process execution use the following command:

sxe -c "!pe;!clrstack;gc" clr

All credits go to this post here.