Link to home
Start Free TrialLog in
Avatar of gr8life
gr8life

asked on

Fernado Soto Please HELP!!!

Fernando, I have been trying to convert some C# code because the solution you helped me with before has some bugs.  The bugs are not a result of anything you helped me with, but are a result of the approach being problematic.

Original question:
https://www.experts-exchange.com/questions/22005104/Variable-problem-Fernando-Soto-PLEASE-HELP.html

I need to convert two files and I believe I will have the bugs eliminated.

I tried to convert the code and even posted asking for ways to convert, but I really just think I need your expertise to solve this one.

https://www.experts-exchange.com/questions/22042864/Convert-C-to-VB-Net.html


Thank you VERY much for your time,
Gr8life
Avatar of gr8life
gr8life

ASKER

I tried to upload the data, but it appears the site is having problems.
Gr8life

Avatar of gr8life

ASKER

Has the upload URL changed?
http://www.ee-stuff.com/login.php
Avatar of gr8life

ASKER

Here is the first file:
namespace Extreme.IPCountryLookup
{
      using System;
      using System.Collections;

      /// <summary>
      /// Represents a trie with keys that are binary values of
      /// length up to 32.
      /// </summary>
      public class BinaryTrie
      {
            internal BinaryTrieNode[] _roots;      // Roots of the trie
            private Int32 _indexLength = 0;
            private Int32 _count = 0;      // Number of entries in the trie

            #region Public instance constructors
            /// <summary>
            /// Constructs a <see cref="BinaryTrie"/> with an index length
            /// of 1.
            /// </summary>
            public BinaryTrie()
            {
                  _indexLength = 1;
                  _roots = new BinaryTrieNode[2];
            }
            /// <summary>
            /// Constructs a <see cref="BinaryTrie"/> with a given index length.
            /// </summary>
            /// <param name="indexLength">The index length.</param>
            public BinaryTrie(Int32 indexLength)
            {
                  if ((indexLength < 1) || (indexLength > 18))
                        throw new ArgumentOutOfRangeException("indexLength");
                  _indexLength = indexLength;
                  _roots = new BinaryTrieNode[1 << indexLength];
            }
            #endregion

            #region Protected instance members
            /// <summary>
            /// Gets the collection of root <see cref="BinaryTrieNode"/>
            /// objects in this <see cref="BinaryTrie"/>.
            /// </summary>
            protected BinaryTrieNode[] Roots
            {
                  get { return _roots; }
            }
            /// <summary>
            /// Gets or sets the number of keys in the trie.
            /// </summary>
            protected Int32 CountInternal
            {
                  get { return _count; }
                  set { _count = value; }
            }

            /// <summary>
            /// Adds a key with the given index to the trie.
            /// </summary>
            /// <param name="index">The index of the root <see cref="BinaryTrieNode"/>
            /// for the given key value.</param>
            /// <param name="key">An <see cref="Int32"/> key value.</param>
            /// <param name="keyLength">The length in bits of the significant
            /// portion of the key.</param>
            /// <returns>The <see cref="BinaryTrieNode"/> that was added to the
            /// trie.</returns></returns>
            protected BinaryTrieNode AddInternal(Int32 index, Int32 key, Int32 keyLength)
            {
                  CountInternal++;
                  BinaryTrieNode root = Roots[index];
                  if (null == root)
                        // Create the new root.
                        return _roots[index] = new BinaryTrieNode(key, keyLength);
                  else
                        // Add the record to the trie.
                        return root.AddInternal(key, keyLength);
            }

            protected Object FindBestMatchInternal(Int32 index, Int32 key)
            {
                  BinaryTrieNode root = _roots[index];
                  if (null == root)
                        return null;
                  return root.FindBestMatch(key).UserData;
            }
            protected Object FindExactMatchInternal(Int32 index, Int32 key)
            {
                  BinaryTrieNode root = _roots[index];
                  if (null == root)
                        return null;
                  return root.FindExactMatch(key).UserData;
            }
            #endregion

            #region Public instance properties
            /// <summary>
            /// Gets the index length of this <see cref="BinaryTrie"/>.
            /// </summary>
            /// <remarks>The index length indicates the number of bits
            /// that is to be used to preselect the root nodes.
            /// </remarks>
            public Int32 IndexLength
            {
                  get { return _indexLength; }
            }
            /// <summary>
            /// Gets the number of keys in the trie.
            /// </summary>
            public Int32 Count
            {
                  get { return _count; }
            }
            #endregion

            #region Public instance methods
            public Int32 Minimize()
            {
                  Int32 nodesEliminated = 0;
                  for(Int32 index = 0; index < _roots.Length; index++)
                  {
                        BinaryTrieNode root = _roots[index];
                        if (null != root)
                              nodesEliminated += root.Minimize();
                  }
                  return nodesEliminated;
            }
            /// <summary>
            /// Adds a node to the trie.
            /// </summary>
            /// <param name="key">An <see cref="Int32"/> key value.</param>
            /// <param name="keyLength">The length in bits of the significant
            /// portion of the key.</param>
            /// <returns>The <see cref="BinaryTrieNode"/> that was added to the
            /// trie.</returns></returns>
            public BinaryTrieNode Add(Int32 key, Int32 keyLength)
            {
                  Int32 index = (Int32)(key >> (32 - _indexLength));
                  return AddInternal(index, key, keyLength);
            }

            public Object FindBestMatch(Int32 key)
            {
                  Int32 index = (Int32)(key >> (32 - _indexLength));
                  return FindBestMatchInternal(index, key);
            }
            #endregion

      }

      /// <summary>
      /// Represents an entry in an <see cref="IPCountryLookup"/> table.
      /// </summary>
      public class BinaryTrieNode
      {
            protected static readonly Object EmptyData = new Object();

            private static Int32[] _bit
                  = {0x7FFFFFFF, 0x7FFFFFFF,0x40000000,0x20000000,0x10000000,
                          0x8000000,0x4000000,0x2000000,0x1000000,
                          0x800000,0x400000,0x200000,0x100000,
                          0x80000,0x40000,0x20000,0x10000,
                          0x8000,0x4000,0x2000,0x1000,
                          0x800,0x400,0x200,0x100,
                          0x80,0x40,0x20,0x10,
                          0x8,0x4,0x2,0x1,0};

            private Int32 _key;            // Key value
            private Int32 _keyLength;      // Length of the key
            private BinaryTrieNode _zero = null;      // First child
            private BinaryTrieNode _one = null;      // Second child
            private Object _userData;

            #region Public instance properties
            /// <summary>
            /// Gets or sets the country code for this entry.
            /// </summary>
            public Object UserData
            {
                  get
                  {
                        if (IsKey)
                              return _userData;
                        else
                              return null;
                  }
                  set { _userData = value; }
            }
            /// <summary>
            /// Gets the key associated with this <b>BinaryTrieNode</b>.
            /// </summary>
            public Int32 Key
            {
                  get { return _key; }
            }
            /// <summary>
            /// Gets a value indicating whether the <b>BinaryTrieNode</b>
            /// contains a key (<b>true</b>) or is a helper node that
            /// does not contain a key (<b>false</b>).
            /// </summary>
            public Boolean IsKey
            {
                  get { return (!Object.ReferenceEquals(_userData, EmptyData)); }
            }
            /// <summary>
            /// Gets the child node in the zero position.
            /// </summary>
            public BinaryTrieNode ZeroNode
            {
                  get { return _zero; }
            }
            /// <summary>
            /// Gets the child node in the one position.
            /// </summary>
            public BinaryTrieNode OneNode
            {
                  get { return _one; }
            }
            /// <summary>
            /// Gets the key length.
            /// </summary>
            public Int32 KeyLength
            {
                  get { return _keyLength; }
            }
            #endregion

            #region Internal instance members
            /// <summary>
            /// Constructs an <see cref="BinaryTrieNode"/> object.
            /// </summary>
            /// <param name="key">Key</param>
            /// <param name="keyLength">Length of the key</param>
            internal BinaryTrieNode(Int32 key, Int32 keyLength)
            {
                  _key = key;
                  _keyLength = keyLength;
                  _userData = EmptyData;
            }

            /// <summary>
            /// Adds a record to the trie using the internal representation
            /// of an IP address.
            /// </summary>
            internal BinaryTrieNode AddInternal(Int32 key, Int32 keyLength)
            {
                  // Find the common key keyLength
                  Int32 difference = key ^ _key;
                  // We are only interested in matches up to the keyLength...
                  Int32 commonKeyLength = Math.Min(_keyLength, keyLength);
                  // ...so count down from there.
                  while (difference >= _bit[commonKeyLength])
                        commonKeyLength--;

                  // If the new key length is smaller than the common key length,
                  // or equal but smaller than the current key length,
                  // the new key should be the parent of the current node.
                  if ((keyLength < commonKeyLength)
                        || ((keyLength == commonKeyLength) && (keyLength < _keyLength)))
                  {
                        // Make a copy that will be the child node.
                        BinaryTrieNode copy = (BinaryTrieNode)this.MemberwiseClone(); // new BinaryTrieNode(this);
                        // Fill in the child references based on the first
                        // bit after the common key.
                        if ((_key & _bit[keyLength+1]) != 0)
                        {
                              _zero = null;
                              _one = copy;
                        }
                        else
                        {
                              _zero = copy;
                              _one = null;
                        }
                        _key = key;
                        _keyLength = keyLength;
                        UserData = EmptyData;
                        return this;
                  }

                  // Do we have a complete match?
                  if (commonKeyLength == _keyLength)
                  {
                        if (keyLength == _keyLength)
                              return this;

                        // Yes. Add the key as a child.
                        if ((key & _bit[_keyLength+1]) == 0)
                        {
                              // The remainder of the key starts with a zero.
                              // Do we have a child in this position?
                              if (null == _zero)
                                    // No. Create one.
                                    return _zero = new BinaryTrieNode(key, keyLength);
                              else
                                    // Yes. Add this key to the child.
                                    return _zero.AddInternal(key, keyLength);
                        }
                        else
                        {
                              // The remainder of the key starts with a one.
                              // Do we have a child in this position?
                              if (null == _one)
                                    // No. Create one.
                                    return _one = new BinaryTrieNode(key, keyLength);
                              else
                                    // Yes. Add this key to the child.
                                    return _one.AddInternal(key, keyLength);
                        }
                  }
                  else
                  {
                        // No. The match is only partial, so split this node.
                        // Make a copy that will be the first child node.
                        BinaryTrieNode copy = (BinaryTrieNode)this.MemberwiseClone(); // new BinaryTrieNode(this);
                        // And create the other child node.
                        BinaryTrieNode newEntry = new BinaryTrieNode(key, keyLength);
                        // Fill in the child references based on the first
                        // bit after the common key.
                        if ((_key & _bit[commonKeyLength+1]) != 0)
                        {
                              _zero = newEntry;
                              _one = copy;
                        }
                        else
                        {
                              _zero = copy;
                              _one = newEntry;
                        }
                        _keyLength = commonKeyLength;
                        UserData = EmptyData;
                        return newEntry;
                  }
            }
            #endregion

            #region Public instance members
            /// <summary>
            /// Minimizes a <see cref="BinaryTrieNode"/> by removing
            /// redundant child nodes.
            /// </summary>
            /// <returns>The number of nodes that were eliminated.
            /// </returns>
            public Int32 Minimize()
            {
                  return Minimize(_userData);
            }
            /// <summary>
            /// Helper for the public <see cref="Minimize"/> method.
            /// </summary>
            private Int32 Minimize(Object userData)
            {
                  Int32 eliminatedNodes = 0;

                  if (_userData == EmptyData)
                        _userData = userData;

                  if (null != _zero)
                  {
                        eliminatedNodes += _zero.Minimize(_userData);
                        if (_zero._userData == _userData)
                        {
                              eliminatedNodes++;
                              if ((_zero._zero == null) && (_zero._one == null))
                                    _zero = null;
                              else if (_zero._one == null)
                                    _zero = _zero._zero;
                              else if (_zero._zero == null)
                                    _zero = _zero._one;
                              else
                                    eliminatedNodes--;
                        }
                  }
                  if (null != _one)
                  {
                        eliminatedNodes += _one.Minimize(_userData);
                        if (_one._userData == _userData)
                        {
                              eliminatedNodes++;
                              if ((_one._zero == null) && (_one._one == null))
                                    _one = null;
                              else if (_one._one == null)
                                    _one = _one._zero;
                              else if (_one._zero == null)
                                    _one = _one._one;
                              else
                                    eliminatedNodes--;
                        }
                  }
                  return eliminatedNodes;
            }

            /// <summary>
            /// Finds an exact match to a key.
            /// </summary>
            /// <param name="key">The key to look up.</param>
            /// <returns>The <see cref="BinaryTrieNode"/> that
            /// matches the specified <paramref name="key"/>,
            /// or <b>null</b> (<b>Nothing</b> in Visual Basic)
            /// if the key can't be found.</returns>
            public BinaryTrieNode FindExactMatch(Int32 key)
            {
                  if ((key ^ _key) == 0)
                        return this;
                  
                  // Pick the child to investigate.
                  if ((key & _bit[_keyLength+1]) == 0)
                  {
                        // If the key matches the child's key, pass on the request.
                        if (null != _zero)
                        {
                              if ((key ^ _zero._key) < _bit[_zero._keyLength])
                                    return _zero.FindExactMatch(key);
                        }
                  }
                  else
                  {
                        // If the key matches the child's key, pass on the request.
                        if (null != _one)
                        {
                              if ((key ^ _one._key) < _bit[_one._keyLength])
                                    return _one.FindExactMatch(key);
                        }
                  }
                  // If we got here, neither child was a match, so the current
                  // node is the best match.
                  return null;
            }

            /// <summary>
            /// Looks up a key value in the trie.
            /// </summary>
            /// <param name="key">The key to look up.</param>
            /// <returns>The best matching <see cref="BinaryTrieNode"/>
            /// in the trie.</returns>
            public BinaryTrieNode FindBestMatch(Int32 key)
            {
                  BinaryTrieNode best = this;
                  BinaryTrieNode current = this;

                  // We always exit this loop:
                  while (true)
                  {
                        // Pick the child to investigate.
                        if ((key & _bit[current._keyLength+1]) == 0)
                        {
                              // If the key matches the child's key, pass on the request.
                              current = current._zero;
                              if (null == current)
                                    return best;
                              else if ((key ^ current._key) >= _bit[current._keyLength])
                                    return best;
                              else
                                    best = current;
                        }
                        else
                        {
                              // If the key matches the child's key, pass on the request.
                              current = current._one;
                              if (null == current)
                                    return best;
                              else if ((key ^ current._key) >= _bit[current._keyLength])
                                    return best;
                              else
                                    best = current;
                        }
                  }
            }
            #endregion
      }

      /// <summary>
      /// Iterates over the nodes of a <see cref="BinaryTrie"/>
      /// </summary>
      public class BinaryTrieEnumerator : IEnumerator
      {
            private BinaryTrieNode[] _stack = new BinaryTrieNode[32];
            private Int32 _stackPtr;
            private BinaryTrieNode _root;
            private BinaryTrieNode _currentNode;
            
            /// <summary>
            /// Constructs a new <b>BinaryTrieEnumerator</b>.
            /// </summary>
            /// <param name="root">The root node of the trie.</param>
            public BinaryTrieEnumerator(BinaryTrieNode root)
            {
                  _root = root;
            }

            /// <summary>
            /// Implements the <b>Reset</b> method of
            /// <see cref="IEnumerator"/>.
            /// </summary>
            public void Reset()
            {
                  _stackPtr = 0;
                  _stack[0] = _currentNode = _root;
            }

            /// <summary>
            /// Implements the <b>Current</b> property of
            /// <see cref="IEnumerator"/>.
            /// </summary>
            /// <value>The <see cref="BinaryTrieNode"/> at
            /// the current position in the iteration.</value>
            public Object Current
            {
                  get
                  {
                        return _stack[_stackPtr];
                  }
            }

            /// <summary>
            /// Implements the <b>MoveNext</b> method of
            /// <see cref="IEnumerator"/>.
            /// </summary>
            /// <returns><b>false</b> if the end of the iteration
            /// has been reached, <b>true</b> otherwise.</returns>
            public Boolean MoveNext()
            {
                  if (null != _currentNode.ZeroNode)
                  {
                        _stack[++_stackPtr] = _currentNode = _currentNode.ZeroNode;
                        return true;
                  }
                  if (null != _currentNode.OneNode)
                  {
                        _stack[++_stackPtr] = _currentNode = _currentNode.OneNode;
                        return true;
                  }

                  while (_stackPtr > 0)
                  {
                        _stackPtr--;
                        BinaryTrieNode newNode = _stack[_stackPtr];

                        if (newNode.ZeroNode == _currentNode)
                              if (null != newNode.OneNode)
                              {
                                    _stack[++_stackPtr] = _currentNode = newNode.OneNode;
                                    return true;
                              }
                        _currentNode = newNode;
                  }
                  return false;
            }
      }
}
Avatar of gr8life

ASKER

Here is the second file:
using System;
using System.Collections;
using System.IO;
using System.Net;
using Extreme;

namespace Extreme.IPCountryLookup
{
      /// <summary>
      /// Represents a trie that can be used to look up the country
      /// corresponding to an IP address.
      /// </summary>
      public class IPCountryTable : BinaryTrie
      {
            private Int32 _extraNodes = 0;

            static protected Int32 GetKeyLength(Int32 length)
            {
                  if (length < 0)
                        return 1;
                  Int32 keyLength = 33;
                  while (length != 0)
                  {
                        length >>= 1;
                        keyLength--;
                  }
                  return keyLength;
            }

            private Int32 _indexOffset; // Number of bits after index part.
            private Int32 _indexLength;

            /// <summary>
            /// Constructs an <see cref="IPCountryTable3"/> object.
            /// </summary>
            public IPCountryTable(Int32 indexLength) : base(indexLength)
            {
                  _indexOffset = 32 - indexLength;
                  _indexLength = 1 << _indexOffset;
            }

            /// <summary>
            /// Loads an IP-country database file into the trie.
            /// </summary>
            /// <param name="filename">The path and filename of the file
            /// that holds the database.</param>
            /// <param name="calculateKeyLength">A boolean value that
            /// indicates whether the <em>size</em> field in the database
            /// contains the total length (<strong>true</strong>) or the
            /// exponent of the length (<strong>false</strong> of the
            /// allocated segment.</param>
            public void LoadStatisticsFile(String filename, Boolean calculateKeyLength)
            {
                  StreamReader reader = new StreamReader(filename);
                  try
                  {
                        String record;
                        while (null != (record = reader.ReadLine()))
                        {
                              String[] fields = record.Split('|');

                              // Skip if not the right number of fields
                              if (fields.Length != 7)
                                    continue;
                              // Skip if not an IPv4 record
                              if (fields[2] != "ipv4")
                                    continue;
                              // Skip if header or info line
                              if (fields[1] == "*")
                                    continue;

                              String ip = fields[3];

                              // Interning the country strings saves us
                              // quite a bit of memory.
                              String countryCode = String.Intern(fields[1]);

                              Int32 length = Int32.Parse(fields[4]);

                              // Find the length of the range of IP's.
                              if (!calculateKeyLength)      
                                    length = 1 << length;


                              // The first IndexLength bits of the IP address get
                              // to be the index into our table of roots.
                              String [] parts = ip.Split('.');
                              Int32 indexBase = ((Int32.Parse(parts[0]) << 8)
                                    + Int32.Parse(parts[1]));
                              Int32 keyBase = (indexBase << 16)
                                    + (Int32.Parse(parts[2]) << 8)
                                    + Int32.Parse(parts[3]);
                              indexBase >>= (_indexOffset - 16);

                              // With the latest changes to the file format,
                              // records can begin and end in arbitrary
                              // positions spanning multiple root nodes.
                              // This means we have to add trie nodes
                              // in up to three stages:

                              Int32 currentLength;
                              Int32 keyLength;      

                              // 1. Do as much as possible with the initial
                              //    root node.
                              Int32 lengthToFill = keyBase & (_indexLength-1);
                              if (lengthToFill != 0)
                              {
                                    lengthToFill = Math.Min(length, _indexLength - lengthToFill);
                                    length -= lengthToFill;
                              }

                              currentLength = _indexLength;
                              keyLength = 32 - _indexOffset;
                              while (lengthToFill > 0)
                              {
                                    currentLength >>= 1;
                                    keyLength++;
                                    if ((lengthToFill & currentLength) != 0)
                                    {
                                          base.AddInternal(indexBase, keyBase, keyLength).UserData = countryCode;
                                          _extraNodes++;
                                          keyBase += currentLength;
                                          lengthToFill -= currentLength;
                                          if (lengthToFill == 0)
                                          {
                                                indexBase++;
                                                break;
                                          }
                                    }
                              }

                              // 2. Add root nodes until the remaining length
                              //    is less than the range spanned by a root
                              //    node.
                              while (length >= _indexLength)
                              {
                                    base.AddInternal(indexBase, keyBase, _indexOffset).UserData = countryCode;
                                    _extraNodes++;
                                    indexBase++;
                                    keyBase += _indexLength;
                                    length -= _indexLength;
                              }

                              // 3. Count down the remaining length.
                              currentLength = _indexLength;
                              keyLength = 32 - _indexOffset;
                              while (length > 0)
                              {
                                    currentLength >>= 1;
                                    keyLength++;
                                    if ((length & currentLength) != 0)
                                    {
                                          base.AddInternal(indexBase, keyBase, keyLength).UserData = countryCode;
                                          _extraNodes++;
                                          keyBase += currentLength;
                                          length -= currentLength;
                                    }
                              }
                              _extraNodes--;
                        }
                  }
                  finally
                  {
                        reader.Close();
                  }
            }

            /// <summary>
            /// Gets the total number of entries in the trie.
            /// </summary>
            public Int32 NetworkCodeCount
            {
                  get { return base.Count - _extraNodes; }
            }
            /// <summary>
            /// Attempts to find the country code corresponding to
            /// a given IP address.
            /// </summary>
            /// <param name="address">A <see cref="String"/> value
            /// representing the </param>
            /// <returns>The two letter country code corresponding to
            /// the IP address, or <strong>"??"</strong> if it was not
            /// found.</returns>
            public String GetCountry(String address)
            {
                  String [] parts = address.Split('.');

                  // The first IndexLength bits form the key into the
                  // array of root nodes.
                  Int32 indexBase = ((Int32.Parse(parts[0]) << 8)
                        + Int32.Parse(parts[1]));
                  Int32 index = indexBase >> (_indexOffset - 16);

                  BinaryTrieNode root = base.Roots[index];
                  // If we don't have a root, we don't have a value.
                  if (null == root)
                        return null;

                  // Calculate the full key...
                  Int32 key = (indexBase << 16)
                        + (Int32.Parse(parts[2]) << 8)
                        + Int32.Parse(parts[3]);
                  // ...and look it up.
                  return (String)root.FindBestMatch(key).UserData;
            }
      }
}
Avatar of gr8life

ASKER

Thank you very much for taking the time to read this post,
Gr8life
Avatar of Fernando Soto
Hi gr8life;

Is this not the same code I converted to VB .Net for you that you found at this web site?

http://www.codeproject.com/csharp/iplookupoptimise.asp

Fernando
Avatar of gr8life

ASKER

The code you converted originally was posted on that web site; however the original code had problems with its approach.  Therefore I am trying to convert the code posted in this question to fix the problem.  It is not from that same website but deals with the same application.

Thank you,
Gr8life
I will look at it tomorrow. Where on the web did you find this code just in case I need some info?

Fernando
Hi gr8life;

Do you have a copy of the original code I translated for you when I first worked on this for you?

I have Translated the code from the link you gave above but I am having a problem trying to debug the code. In the code they calculate a key of type Int32 and store it. The problem is that when they calculate it in C# the value if it is larger then an Int32 can hold it gives a negative value which looks like they depend on that but in Visual Basic I get a numeric overflow. So I want to see what they did before that was different.

Thanks;

Fernando
Is anyone home?

Anyway here is the converted code for the IP lookup code. You can download the VB project from this link.

        https://filedb.experts-exchange.com/incoming/ee-stuff/1302-IPLookupVB.zip

Fernando
Hi gr8life;

Have your tried the code?

Fernando
Avatar of gr8life

ASKER

I am sorry I did not reply sooner.  I had an unexpected death in the family and I took it very badly. My father died suddenly of a stroke and before this my family all thought he would outlive us all.  Anyway I got back last night and tried the new code.  When I first altered my existing code I had several errors, but I believe I was able to resolve all of them.  They appeared to be all related to my fat fingers. However when I tried to compile the code I got some build errors, (9 total), which I listed below.  I am using the 2003 Visual Studio version and wondered if the reason I got the errors was because the code you provided may be in a newer version and 2003 doesn’t play well with it.

Thank you much for all of your valuable time, and once again I am truly sorry I didn’t reply sooner.

Gr8life  

Below is the section where I am experiencing the build errors.  I numbered the lines to attempt to make it easier to reference the problems.

Public Sub LoadStatisticsFile(ByVal filename As String, ByVal calculateKeyLength As Boolean)
            enterCount += 1
            Dim reader As StreamReader = New StreamReader(filename)
            Try
                Dim record As String = String.Empty
                While Not reader.Peek = -1
                    record = reader.ReadLine()
                    Dim fields() As String = record.Split("|"c)

                    ' Skip if not the right number of fields
                    If Not (fields.Length = 7) Then
                        Continue While ‘line 54
                    End If
                    ' Skip if not an IPv4 record
                    If Not (fields(2) = "ipv4") Then
                        Continue While ‘line 58
                    End If
                    ' Skip if header or info line
                    If (fields(1) = "*") Then
                        Continue While ‘line 62
                    End If

(54): Expression expected.
(54): Name 'Continue' is not declared.
(54): Method arguments must be enclosed in parentheses.
(58): Expression expected.
(58): Method arguments must be enclosed in parentheses.
(58): Name 'Continue' is not declared.
(62): Name 'Continue' is not declared.
(62): Method arguments must be enclosed in parentheses.
(62): Expression expected.

Hi Gr8life;

Very sorry to hear of the lost of your father, please accept my sincerest sympathy.

Yes I did convert the code in VB 2005. The only changes you will need to make in order to make it work in VB 2003 are posted below.

        Public Sub LoadStatisticsFile(ByVal filename As String, _
            ByVal calculateKeyLength As Boolean)

            enterCount += 1
            Dim reader As StreamReader = New StreamReader(filename)
            Try
                Dim record As String = String.Empty
                While Not reader.Peek = -1
                    record = reader.ReadLine()
                    Dim fields() As String = record.Split("|"c)

                    ' Skip if not the right number of fields
                    If Not (fields.Length = 7) Then
                        GoTo Continue            ' Change on this line
                    End If
                    ' Skip if not an IPv4 record
                    If Not (fields(2) = "ipv4") Then
                        GoTo Continue            ' Change on this line
                    End If
                    ' Skip if header or info line
                    If (fields(1) = "*") Then
                        GoTo Continue            ' Change on this line
                    End If

                   ...
                   ...

                            End Try
                            lengthToFill -= currentLength
                            If (lengthToFill = 0) Then
                                indexBase += 1
                                Exit While
                            End If
                        End If
Continue:                                           ' Add this line
                    End While

                    ' 2. Add root nodes until the remaining length


The Continue statement is not supported in VB .2003 and so the need for the GoTo.

Fernando
Avatar of gr8life

ASKER

I changed the continue statements and the application compiled, however shortly there after I receive an error.

An Unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in IPLookupProject.ex

Addtional information: Specified argument was out of the range of valid values.

I am not sure what is causing it but I wanted to post a response to let you know I tried the code.  I am going to try to isolate the issue and resolve it tonight.

Thank you very much for your kindness.

Gr8life
The debug environment should point out the line it error out on. Let me know and I will take a look at it.

Fernando
Avatar of gr8life

ASKER

I ran the application in the debug mode and the Argument error was being thrown from this section of the Binarytrie.vb code.  Other than finding the problem I am really confused about what is causing the error.  I tried examining the code to see I could find the reason for several hours late last night but I really can't find what is causing the problem.  I really don't think the code below is the problem, but here is where the application is halting on the End If statement.  If it would help I can zip up the application and post all source code so maybe you can spot it. As well include the old source code if you think that may be of some help.  Please advice. Also I really would appreciate it if you are able to locate the problem that if is not too much trouble you post a small after the fact of how you found the real cause.  This way I can better understand problems like this and hopefully in the near future have the ability to fix code situations like this on my own. :)

BinaryTrie.vb      

  ‘ Constructs a BinaryTrie with a given index length.
        ‘ Param name = indexLength. Is the index length.
        Public Sub New(ByVal indexLength As Integer)
            If ((indexLength < 1) OrElse (indexLength > 18)) Then
                Throw New ArgumentOutOfRangeException(“indexLength”)
            End If ‘&#61663; here is where the applications halts
            _indexLength = indexLength
            ReDim _roots(1 << indexLength)
        End Sub

Thank you so much for all of your valuable expertise,
Gr8life
Hi Gr8life;

It would help if you post the source code in zip format to the http://www.ee-stuff.com web site so that I can download it. Also include the set of sets you took to recreate the problem so that I can follow the same steps.

Thanks;
Fernando
Hi Gr8life;

These are the steps I took to find the problem with the program throwing the Index Out Of Range exception.

1.      Started the program in debug mode and click on the command button.

2.      When then program throw the error and displayed the message box I clicked on the Break button.

3.      Because the debugger stopped on the End If statement and the only statement in that block was the  Throw New ArgumentOutOfRangeException("indexLength")  I looked at the value of indexLength. The value to which it was set to was 0. The condition of the If statement was ((indexLength < 1) OrElse (indexLength > 18)), so the value was outside the acceptable range and throw the error. By placing the mouse cursor on the variable name indexLength the IDE will display its value.

4.      The value of indexLength was passed in as a parameter into the subroutine. So I opened the Call Stack window.

5.      The first entry in this window is the current location of where the program halted the next line down is the sub that called the current one. I double clicked on the second line and the IDE took me to the calling sub.

6.      In this case the sub was the New subroutine of the IPCountryTable class. The variable indexLength was passed in to the New sub as well. So I the double clicked on the next line of the Call Stack window to find the sub that called it. This took me to this line, table = New IPLookup.IPCountryTable(indexLength) of the Button1 click event handler of Form1 class.

7.      Because this was the first line of code in the event handler and the variable was not assigned a value here I then right clicked on the variable indexLength and selected the Go To Definition menu item. This took me to a class level variable, Private indexLength As Integer. Just below that I noticed where indexLength was getting assigned a value and that was in the Form Load event.

8.      But then I noticed the local variable declaration Dim indexLength As Integer which hides the class level declaration with the same name.

9.      I commented out the local variable name and tried it out. This solved the problem and I was able to get to the OpenFileDialog box. I did not test any further because I did not know the format of the file to create one but I think you should be able to take it from here.


    Private Sub Form1_Load(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load

        'Dim indexLength As Integer     <<====== Commented out this line of code.
        If (Environment.GetCommandLineArgs.Length < 2) Then
            indexLength = 16
        Else
            indexLength = Int32.Parse(Environment.GetCommandLineArgs(1))
        End If

    End Sub

Fernando
Avatar of gr8life

ASKER

Thank you for the extremely well documented explanation of your process. I followed the steps and made the change in the code.  I am going to test the application for any additional problems this evening.

Thank you so much for your time,
Gr8life
Not a problem, always glad to help. ;=)
Avatar of gr8life

ASKER

I started testing the code and there seems to be a problem with the code.  I am going to test further to make sure my fat fingers are not the problem.

Thank you very much,
Gr8life
Avatar of gr8life

ASKER

Good morning. I spent several hours last night testing the application.  The result of the research is the code doesn’t appear to working correctly.  I am really just plain frustrated.  I know that you have done above and beyond the scope of any of my numerous postings and I truly am grateful for that.  I don’t want you to misunderstand my frustration as being directed at you. I just don’t know at this point how I can make this application work. I know it is a long shot, but is it possible that because the code was translated and not created in VB.Net that “something is lost in translation”.  I mean is it possible that a part of the code doesn’t work correctly because in doesn’t function the same in VB.Net as it did in C#?  Also I thought maybe there is more 2005 code that my 2003 version doesn’t interpret correctly. Anyway it would be an understatement to say I really need your help. I am open to almost any possibility to make this application a working tool including opening multiple questions which address each specific problem you might think are causing my erroneous results. Please advice.  

Thank you for your time,
Gr8life
Avatar of gr8life

ASKER

I just read the other post I have that combines vb.net and C# and I will test that solution later today.  If EE allowed experts to give out their home addresses you want defiantly be on my Christmas card list for ever!

Thanks,
Gr8life
Hi gr8life;

To your question, is it possible that because the code was translated and not created in VB.Net that “something is lost in translation”, This is always a possibility when translating code from one language to another. There were a couple of points in the code that had no direct translation and needed a work around but I made all attempts to make sure that the end results were the same. I also tested the programs results to the authors results and they were the same.

To your question, "Also I thought maybe there is more 2005 code that my 2003 version doesn’t interpret correctly.", The original code was translated in VS 2005 and then I recompiled it under 2003 making all the needed changes which was only 1 statement which was not supported in 2003. If the 2003 compiler compiles the code without any problems then there are no code that in that source code that is not supported in 2003.

If the new version that I posted in the other thread does not work correctly let me know. At that point let me know which version you want to pursue. In order to track down the problem you will need to post a sample data file that will show the errors you are having so that I can reproduce the same results here and help to track down the source of the problem.


Fernando
Avatar of gr8life

ASKER

I am going to test the new code and retest the old code to see if there is any difference in the results and if I am able to locate the possible problem.
Thank you very much,
Gr8life
Avatar of gr8life

ASKER

I tested the code with the translated version from this post and the mixed project code that you posted on another thread and I still have problems.  I am not sure at this point what to do, please advice...

Thank you very much for your time,
Gr8life
Hi Gr8life;

In order to track down the problem you will need to post a sample data file that will show the errors you are having or what is happening that should or should not be happening so that I can reproduce the same results here and help to track down the source of the problem. If you post a sample of the data please also let me know what you are looking for and the steps you take to reproduce it.

Fernando
Avatar of gr8life

ASKER

I opened a new question because I think you have exceeded expectation for this one.  I will upload the data and link it to the new question.

Thank you very much for all your help,

Gr8life

Here is the link to the new question.

https://www.experts-exchange.com/questions/22067436/Tree-Assistance.html
Avatar of gr8life

ASKER

Upload completed
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial