Convert C# Class to VB

Simply put, I need the following C# class converted to VB so I can complie it with the rest of my VB project.  I'm not to experienced with c# so this is causing me some problems.  I'm aware that there are conversion tools available which I have used, but the tools are not converting the entire code correctly and I don't know enough about C# to finish it.  This C# class file was obtained at http://msdn.microsoft.com/msdnmag/issues/06/02/WickedCode/.  The best conversion tool I have used so far is at http://authors.aspalliance.com/aldotnet/examples/translate.aspx which converts 99% of the code the other 1% is what I'm having a problem with.  I have included the original C# code along with what I have converted so far to VB.  ToDo: comments are added to the VB code that wasn't converted correctly.  Thanks in advance for all of your help and let me know if you need anymore details.


ORIGINAL C# CLASS BELOW
___________________________________________________________________________________________________

using System;
using System.Web;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Configuration;
using System.Web.Configuration;
using System.Collections.Generic;
using System.Configuration.Provider;
using System.Security.Permissions;
using System.Data.Common;
using System.Data;
using System.Web.Caching;

/// <summary>
/// Summary description for SqlSiteMapProvider
/// </summary>
[SqlClientPermission (SecurityAction.Demand, Unrestricted=true)]
public class SqlSiteMapProvider : StaticSiteMapProvider
{
      private const string _errmsg1 = "Missing node ID";
    private const string _errmsg2 = "Duplicate node ID";
    private const string _errmsg3 = "Missing parent ID";
    private const string _errmsg4 = "Invalid parent ID";
    private const string _errmsg5 = "Empty or missing connectionStringName";
    private const string _errmsg6 = "Missing connection string";
    private const string _errmsg7 = "Empty connection string";
    private const string _errmsg8 = "Invalid sqlCacheDependency";
    private const string _cacheDependencyName = "__SiteMapCacheDependency";

    private string _connect;              // Database connection string
    private string _database, _table;     // Database info for SQL Server 7/2000 cache dependency
    private bool _2005dependency = false; // Database info for SQL Server 2005 cache dependency
    private int _indexID, _indexTitle, _indexUrl, _indexDesc, _indexRoles, _indexParent;
    private Dictionary<int, SiteMapNode> _nodes = new Dictionary<int, SiteMapNode>(16);
    private readonly object _lock = new object();
    private SiteMapNode _root;

      public override void Initialize (string name, NameValueCollection config)
      {
        // Verify that config isn't null
        if (config == null)
            throw new ArgumentNullException("config");

        // Assign the provider a default name if it doesn't have one
        if (String.IsNullOrEmpty(name))
            name = "SqlSiteMapProvider";

        // Add a default "description" attribute to config if the
        // attribute doesn’t exist or is empty
        if (string.IsNullOrEmpty(config["description"]))
        {
            config.Remove("description");
            config.Add("description", "SQL site map provider");
        }

        // Call the base class's Initialize method
        base.Initialize(name, config);

        // Initialize _connect
        string connect = config["connectionStringName"];

        if (String.IsNullOrEmpty(connect))
            throw new ProviderException(_errmsg5);

        config.Remove("connectionStringName");

        if (WebConfigurationManager.ConnectionStrings[connect] == null)
            throw new ProviderException(_errmsg6);

        _connect = WebConfigurationManager.ConnectionStrings[connect].ConnectionString;

        if (String.IsNullOrEmpty(_connect))
            throw new ProviderException(_errmsg7);
       
        // Initialize SQL cache dependency info
        string dependency = config["sqlCacheDependency"];

        if (!String.IsNullOrEmpty(dependency))
        {
            if (String.Equals(dependency, "CommandNotification", StringComparison.InvariantCultureIgnoreCase))
            {
                SqlDependency.Start(_connect);
                _2005dependency = true;
            }
            else
            {
                // If not "CommandNotification", then extract database and table names
                string[] info = dependency.Split(new char[] { ':' });
                if (info.Length != 2)
                    throw new ProviderException(_errmsg8);

                _database = info[0];
                _table = info[1];
            }

            config.Remove("sqlCacheDependency");
        }
       
        // SiteMapProvider processes the securityTrimmingEnabled
        // attribute but fails to remove it. Remove it now so we can
        // check for unrecognized configuration attributes.

        if (config["securityTrimmingEnabled"] != null)
            config.Remove("securityTrimmingEnabled");
       
        // Throw an exception if unrecognized attributes remain
        if (config.Count > 0)
        {
            string attr = config.GetKey(0);
            if (!String.IsNullOrEmpty(attr))
                throw new ProviderException("Unrecognized attribute: " + attr);
        }
    }

      public override SiteMapNode BuildSiteMap()
      {
        lock (_lock)
        {
            // Return immediately if this method has been called before
            if (_root != null)
                return _root;

            // Query the database for site map nodes
            SqlConnection connection = new SqlConnection(_connect);

            try
            {
                SqlCommand command = new SqlCommand("proc_GetSiteMap", connection);
                command.CommandType = CommandType.StoredProcedure;

                // Create a SQL cache dependency if requested
                SqlCacheDependency dependency = null;

                if (_2005dependency)
                    dependency = new SqlCacheDependency(command);
                else if (!String.IsNullOrEmpty(_database) && !string.IsNullOrEmpty(_table))
                    dependency = new SqlCacheDependency(_database, _table);

                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                _indexID = reader.GetOrdinal("ID");
                _indexUrl = reader.GetOrdinal("Url");
                _indexTitle = reader.GetOrdinal("Title");
                _indexDesc = reader.GetOrdinal("Description");
                _indexRoles = reader.GetOrdinal("Roles");
                _indexParent = reader.GetOrdinal("Parent");

                if (reader.Read())
                {
                    // Create the root SiteMapNode and add it to the site map
                    _root = CreateSiteMapNodeFromDataReader(reader);
                    AddNode(_root, null);

                    // Build a tree of SiteMapNodes underneath the root node
                    while (reader.Read())
                    {
                        // Create another site map node and add it to the site map
                        SiteMapNode node = CreateSiteMapNodeFromDataReader(reader);
                        AddNode(node, GetParentNodeFromDataReader(reader));
                    }

                    // Use the SQL cache dependency
                    if (dependency != null)
                    {
                        HttpRuntime.Cache.Insert(_cacheDependencyName, new object(), dependency,
                            Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable,
                            new CacheItemRemovedCallback(OnSiteMapChanged));
                    }
                }
            }
            finally
            {
                connection.Close();
            }

            // Return the root SiteMapNode
            return _root;
        }
    }

      protected override SiteMapNode GetRootNodeCore ()
      {
        lock (_lock)
        {
            BuildSiteMap();
            return _root;
        }
      }

    // Helper methods
    private SiteMapNode CreateSiteMapNodeFromDataReader (DbDataReader reader)
    {
        // Make sure the node ID is present
        if (reader.IsDBNull (_indexID))
            throw new ProviderException (_errmsg1);

        // Get the node ID from the DataReader
        int id = reader.GetInt32 (_indexID);

        // Make sure the node ID is unique
        if (_nodes.ContainsKey(id))
            throw new ProviderException(_errmsg2);

        // Get title, URL, description, and roles from the DataReader
        string title = reader.IsDBNull (_indexTitle) ? null : reader.GetString (_indexTitle).Trim ();
        string url = reader.IsDBNull (_indexUrl) ? null : reader.GetString (_indexUrl).Trim ();
        string description = reader.IsDBNull (_indexDesc) ? null : reader.GetString (_indexDesc).Trim ();
        string roles = reader.IsDBNull(_indexRoles) ? null : reader.GetString(_indexRoles).Trim();

        // If roles were specified, turn the list into a string array
        string[] rolelist = null;
        if (!String.IsNullOrEmpty(roles))
            rolelist = roles.Split(new char[] { ',', ';' }, 512);

        // Create a SiteMapNode
        SiteMapNode node = new SiteMapNode(this, id.ToString(), url, title, description, rolelist, null, null, null);

        // Record the node in the _nodes dictionary
        _nodes.Add(id, node);
       
        // Return the node        
        return node;        
    }

    private SiteMapNode GetParentNodeFromDataReader(DbDataReader reader)
    {
        // Make sure the parent ID is present
        if (reader.IsDBNull (_indexParent))
            throw new ProviderException (_errmsg3);

        // Get the parent ID from the DataReader
        int pid = reader.GetInt32(_indexParent);

        // Make sure the parent ID is valid
        if (!_nodes.ContainsKey(pid))
            throw new ProviderException(_errmsg4);

        // Return the parent SiteMapNode
        return _nodes[pid];
    }

    void OnSiteMapChanged(string key, object item, CacheItemRemovedReason reason)
    {
        lock (_lock)
        {
            if (key == _cacheDependencyName && reason == CacheItemRemovedReason.DependencyChanged)
            {
                // Refresh the site map
                Clear ();
                _nodes.Clear();
                _root = null;
            }
        }
    }
}

___________________________________________________________________________________________________


CONVERTED VB CLASS BELOW
___________________________________________________________________________________________________

Imports System
Imports System.Web
Imports System.Data.SqlClient
Imports System.Collections.Specialized
Imports System.Configuration
Imports System.Web.Configuration
Imports System.Collections.Generic
Imports System.Configuration.Provider
Imports System.Security.Permissions
Imports System.Data.Common
Imports System.Data
Imports System.Web.Caching

<SqlClientPermission(SecurityAction.Demand, Unrestricted := True)>  _

'/ <summary>
'/ Summary description for SqlSiteMapProvider
'/ </summary>
Public Class SqlSiteMapProvider
   Inherits StaticSiteMapProvider
   Private _errmsg1 As String = "Missing node ID"
   Private _errmsg2 As String = "Duplicate node ID"
   Private _errmsg3 As String = "Missing parent ID"
   Private _errmsg4 As String = "Invalid parent ID"
   Private _errmsg5 As String = "Empty or missing connectionStringName"
   Private _errmsg6 As String = "Missing connection string"
   Private _errmsg7 As String = "Empty connection string"
   Private _errmsg8 As String = "Invalid sqlCacheDependency"
   Private _cacheDependencyName As String = "__SiteMapCacheDependency"
   
   Private _connect As String ' Database connection string
   Private _database, _table As String ' Database info for SQL Server 7/2000 cache dependency
   Private _2005dependency As Boolean = False ' Database info for SQL Server 2005 cache dependency
   Private _indexID, _indexTitle, _indexUrl, _indexDesc, _indexRoles, _indexParent As Integer
   Private __unknown As Dictionary
   Private __unknown As __unknown
   Private __unknown, SiteMapNode As Integer
   Private __unknown As __unknown
   Private __unknown = New Dictionary(__unknown < Integer, SiteMapNode > 16) '
   'ToDo: Error processing original source shown below
   '
   '
   '-----------------------^--- Syntax error: 'identifier' expected
   '
   'ToDo: Error processing original source shown below
   '
   '
   '---------------------------^--- Syntax error: 'identifier' expected
   '
   'ToDo: Error processing original source shown below
   '
   '
   '----------------------------------------^--- Syntax error: ';' expected
   '
   'ToDo: Error processing original source shown below
   '
   '
   '-------------------------------------------------^--- Syntax error: 'identifier' expected
   '
   'ToDo: Error processing original source shown below
   '
   '
   '-----------------------------------------------------------------^--- Syntax error: '(' expected
   '
   'ToDo: Error processing original source shown below
   '
   '
   '---------------------------------------------------------------------^--- Syntax error: '.' expected
   '
   'ToDo: Error processing original source shown below
   '
   '
   '---------------------------------------------------------------------------------------^--- Syntax error: ')' expected
   Private _lock As New Object()
   Private _root As SiteMapNode
   
   
   Public Overrides Sub Initialize(name As String, config As NameValueCollection)
      ' Verify that config isn't null
      If config Is Nothing Then
         Throw New ArgumentNullException("config")
      End If
      ' Assign the provider a default name if it doesn't have one
      If [String].IsNullOrEmpty(name) Then
         name = "SqlSiteMapProvider"
      End If
      ' Add a default "description" attribute to config if the
      ' attribute doesn’t exist or is empty
      If String.IsNullOrEmpty(config("description")) Then
         config.Remove("description")
         config.Add("description", "SQL site map provider")
      End If
     
      ' Call the base class's Initialize method
      MyBase.Initialize(name, config)
     
      ' Initialize _connect
      Dim connect As String = config("connectionStringName")
     
      If [String].IsNullOrEmpty(connect) Then
         Throw New ProviderException(_errmsg5)
      End If
      config.Remove("connectionStringName")
     
      If WebConfigurationManager.ConnectionStrings(connect) Is Nothing Then
         Throw New ProviderException(_errmsg6)
      End If
      _connect = WebConfigurationManager.ConnectionStrings(connect).ConnectionString
     
      If [String].IsNullOrEmpty(_connect) Then
         Throw New ProviderException(_errmsg7)
      End If
      ' Initialize SQL cache dependency info
      Dim dependency As String = config("sqlCacheDependency")
     
      If Not [String].IsNullOrEmpty(dependency) Then
         If [String].Equals(dependency, "CommandNotification", StringComparison.InvariantCultureIgnoreCase) Then
            SqlDependency.Start(_connect)
            _2005dependency = True
         Else
            ' If not "CommandNotification", then extract database and table names
            Dim info As String() = dependency.Split(New Char() {":"c})
            If info.Length <> 2 Then
               Throw New ProviderException(_errmsg8)
            End If
            _database = info(0)
            _table = info(1)
         End If
         
         config.Remove("sqlCacheDependency")
      End If
     
      ' SiteMapProvider processes the securityTrimmingEnabled
      ' attribute but fails to remove it. Remove it now so we can
      ' check for unrecognized configuration attributes.
      If Not (config("securityTrimmingEnabled") Is Nothing) Then
         config.Remove("securityTrimmingEnabled")
      End If
      ' Throw an exception if unrecognized attributes remain
      If config.Count > 0 Then
         Dim attr As String = config.GetKey(0)
         If Not [String].IsNullOrEmpty(attr) Then
            Throw New ProviderException("Unrecognized attribute: " + attr)
         End If
      End If
   End Sub 'Initialize
   
   Public Overrides Function BuildSiteMap() As SiteMapNode
      SyncLock _lock
         ' Return immediately if this method has been called before
         If Not (_root Is Nothing) Then
            Return _root
         End If
         ' Query the database for site map nodes
         Dim connection As New SqlConnection(_connect)
         
         Try
            Dim command As New SqlCommand("proc_GetSiteMap", connection)
            command.CommandType = CommandType.StoredProcedure
           
            ' Create a SQL cache dependency if requested
            Dim dependency As SqlCacheDependency = Nothing
           
            If _2005dependency Then
               dependency = New SqlCacheDependency(command)
            Else
               If Not [String].IsNullOrEmpty(_database) And Not String.IsNullOrEmpty(_table) Then
                  dependency = New SqlCacheDependency(_database, _table)
               End If
            End If
            connection.Open()
            Dim reader As SqlDataReader = command.ExecuteReader()
            _indexID = reader.GetOrdinal("ID")
            _indexUrl = reader.GetOrdinal("Url")
            _indexTitle = reader.GetOrdinal("Title")
            _indexDesc = reader.GetOrdinal("Description")
            _indexRoles = reader.GetOrdinal("Roles")
            _indexParent = reader.GetOrdinal("Parent")
           
            If reader.Read() Then
               ' Create the root SiteMapNode and add it to the site map
               _root = CreateSiteMapNodeFromDataReader(reader)
               AddNode(_root, Nothing)
               
               ' Build a tree of SiteMapNodes underneath the root node
               While reader.Read()
                  ' Create another site map node and add it to the site map
                  Dim node As SiteMapNode = CreateSiteMapNodeFromDataReader(reader)
                  AddNode(node, GetParentNodeFromDataReader(reader))
               End While
               
               ' Use the SQL cache dependency
               If Not (dependency Is Nothing) Then
                  HttpRuntime.Cache.Insert(_cacheDependencyName, New Object(), dependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, New CacheItemRemovedCallback(OnSiteMapChanged))
               End If
            End If
         Finally
            connection.Close()
         End Try
         
         ' Return the root SiteMapNode
         Return _root
      End SyncLock
   End Function 'BuildSiteMap
   
   
   Protected Overrides Function GetRootNodeCore() As SiteMapNode
      SyncLock _lock
         BuildSiteMap()
         Return _root
      End SyncLock
   End Function 'GetRootNodeCore
   
   
   ' Helper methods
   Private Function CreateSiteMapNodeFromDataReader(reader As DbDataReader) As SiteMapNode
      ' Make sure the node ID is present
      If reader.IsDBNull(_indexID) Then
         Throw New ProviderException(_errmsg1)
      End If
      ' Get the node ID from the DataReader
      Dim id As Integer = reader.GetInt32(_indexID)
     
      ' Make sure the node ID is unique
      If _nodes.ContainsKey(id) Then
         Throw New ProviderException(_errmsg2)
      End If
      ' Get title, URL, description, and roles from the DataReader
      Dim title As String = (If reader.IsDBNull(_indexTitle) Then Nothing Else reader.GetString(_indexTitle).Trim()) 'ToDo: Unsupported feature: conditional (?) operator.
      Dim url As String = (If reader.IsDBNull(_indexUrl) Then Nothing Else reader.GetString(_indexUrl).Trim()) 'ToDo: Unsupported feature: conditional (?) operator.
      Dim description As String = (If reader.IsDBNull(_indexDesc) Then Nothing Else reader.GetString(_indexDesc).Trim()) 'ToDo: Unsupported feature: conditional (?) operator.
      Dim roles As String = (If reader.IsDBNull(_indexRoles) Then Nothing Else reader.GetString(_indexRoles).Trim()) 'ToDo: Unsupported feature: conditional (?) operator.
     
      ' If roles were specified, turn the list into a string array
      Dim rolelist As String() = Nothing
      If Not [String].IsNullOrEmpty(roles) Then
         rolelist = roles.Split(New Char() {","c, ";"c}, 512)
      End If
      ' Create a SiteMapNode
      Dim node As New SiteMapNode(Me, id.ToString(), url, title, description, rolelist, Nothing, Nothing, Nothing)
     
      ' Record the node in the _nodes dictionary
      _nodes.Add(id, node)
     
      ' Return the node        
      Return node
   End Function 'CreateSiteMapNodeFromDataReader
   
   
   Private Function GetParentNodeFromDataReader(reader As DbDataReader) As SiteMapNode
      ' Make sure the parent ID is present
      If reader.IsDBNull(_indexParent) Then
         Throw New ProviderException(_errmsg3)
      End If
      ' Get the parent ID from the DataReader
      Dim pid As Integer = reader.GetInt32(_indexParent)
     
      ' Make sure the parent ID is valid
      If Not _nodes.ContainsKey(pid) Then
         Throw New ProviderException(_errmsg4)
      End If
      ' Return the parent SiteMapNode
      Return _nodes(pid)
   End Function 'GetParentNodeFromDataReader
   
   
   Sub OnSiteMapChanged(key As String, item As Object, reason As CacheItemRemovedReason)
      SyncLock _lock
         If key = _cacheDependencyName And reason = CacheItemRemovedReason.DependencyChanged Then
            ' Refresh the site map
            Clear()
            _nodes.Clear()
            _root = Nothing
         End If
      End SyncLock
   End Sub 'OnSiteMapChanged
End Class 'SqlSiteMapProvider

___________________________________________________________________________________________________


williamwatkinsAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

wlfsCommented:
If I didn't miss something, there is only one problem, namely
   private Dictionary<int, SiteMapNode> _nodes = new Dictionary<int, SiteMapNode>(16);
which gets translated to
   Private __unknown As Dictionary
   Private __unknown As __unknown
   Private __unknown, SiteMapNode As Integer
   Private __unknown As __unknown
   Private __unknown = New Dictionary(__unknown < Integer, SiteMapNode > 16) '

The C# construct Dictionary<int, SiteMapNode> is a generic template and allows for a strongly typed hash table. The C# class Dictionary does more or less the same as the VB class Hashtable. But in this case, the type of the key is restricted to int, and the type of the value is restricted to SiteMapNode.

I am not too familiar with VB - after all, this is the C# section :) - so I don't know if there is a strongly typed VB equivalent. However, I guess there isn't, so you should just take a non-typed hash table and do a type cast for the return values of the hash:

The C# line
   private Dictionary<int, SiteMapNode> _nodes = new Dictionary<int, SiteMapNode>(16);
should be translated to
  private _nodes as Hashtable = New Hashtable(16)
instead of all the lines with "__unknown".

Now, the only thing left is the type cast. Replace the VB line
      Return _nodes(pid)
with
      Return CType(_nodes(pid), SiteMapNode)

That should be all there is to it. Let me know, whether it worked out.
woolf
0
Mikal613Commented:
0
Arthur_WoodCommented:
why don't you simply compile the C# class into a DLL, then you can use that DLL, in your VB.NET project (simply add A reference to the new DLL) - calling the methods, and using the properties EXACTLY as if the class had been written in VB.NET - that is one of the great things about .NET.

AW
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

williamwatkinsAuthor Commented:
Great suggestions!  I ran out of time today but I will look at each solution tomorrow and see where I stand!  Thanks for the quick responses!
0
Bob LearnedCommented:
If you have .NET 2005, you can mix C# and VB.NET in the same application.

Bob
0
williamwatkinsAuthor Commented:
Bob-

How must my project be structured to do so?  I'm using Visual Studio 2005 and I thought this could be done.  I have both VB and C# classes in my "App_Code' folder, and my project is a Website if you couldn't tell from the class.  When I build my project I get the following error...

System.Web.HttpException: The files 'myclass.cs' and 'myclass.vb' use a different language, which is not allowed since they need to be compiled together

Am I missing something?  I realize compiling and referencing the class as AW suggested will work, but it would be handy not to, so I could make changes from within the project.  Sorry if this is simple, I typically don't mix code like this.
0
Bob LearnedCommented:
Oh, yeah, that only applies to Window Forms application, and not ASP.NET.

Bob
0
williamwatkinsAuthor Commented:
Thanks for all of your help.  Woolf, you answered my question and it worked, and AW I actually implemented your solution.  In fact I'm a little embarrassed I didn't think of compiling and referencing the class.  I guess I just had a mind set of converting the code.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.