[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

need help converting vb.net code to c#.net code

Posted on 2006-04-28
6
Medium Priority
?
367 Views
Last Modified: 2010-05-18
hello.
I am willing to shell out 500 points for the person who can convert this VB.NET 1.1 code to C#.NET 2.0 code that will work.

Here is the code:
------------------------------------------------
'***************************************************************
' ConstantsManager
' Description: Manages the constants that live in the
'          applicationConstants.config file.  These get stored
'          in memory and when the file changes, the file is
'          removed from memory and re-read back into memory
'
' NOTE: Constants file must live in the webroot
'  on the web server for the web application to run.
'
' Author: Rachael Schoenbaum
' Create date: 12/4/2002
'***************************************************************
Imports System, System.Web.Caching, System.Xml, Microsoft.VisualBasic

Public Class ConstantsManager
    ' Cache object that will be used to store and retrieve items from
    ' the cache and constants used within this object
    Protected Friend Shared myCache as System.Web.Caching.Cache = _
                    System.Web.HttpRuntime.Cache()
    Private Shared applicationConstantsFile As String = "ApplicationConstantsFile"
    Public Shared applicationConstantsFileName As String = _
               String.Replace(System.AppDomain.CurrentDomain.BaseDirectory, "/", "\") & _
               "applicationConstants.config"
    Private Shared xmlFile As New XmlDocument()
    Private Shared constantIdentifier As String = "constant"
    Private shared constantKey As String = "cacheDependencyKey"
    Private Shared thisVersion As Integer = getConstant("THIS_VERSION")
   

    Public Shared Function getConstant(ByRef key As String) As Object
            Dim tmpObj As Object
        If Not (myCache(constantIdentifier & key) Is Nothing) Then
          tmpObj = CType(myCache(constantIdentifier & key), Object)
        Else
          tmpObj = pullConstantFromFile(key)

          'Create the cache dependencies and insert the object into the cache
          If Not IsNothing(tmpObj) Then
            If myCache(constantKey) Is Nothing Then
              myCache.Insert(constantKey, now)
            End If                  
            myCache.Insert(constantIdentifier & key, tmpObj, _
                                 New CacheDependency(applicationConstantsFileName))
          End If
        End If
      Return tmpObj
    End Function

    Private Shared Function pullConstantFromFile(ByRef key As String) As Object
      Dim obj As Object = 0
      If myCache(applicationConstantsFile) Is Nothing Then
        PopulateCache()
      End If

      'Attempt to find the element given the "key" for that tag
      Dim elementList As XmlNodeList = xmlFile.GetElementsByTagName(key)
     
      'If the key is found, the element list will have a count greater than
      'zero and we retrieve the value of the tag...
      If elementList.Count > 0 Then
        Dim node As XmlNode

        'If there is only 1 element in the list, then the element doesn't
        'have a version number and can be returned as is.
        If elementList.Count = 1 Then
          node = elementList.Item(0)

          'If there is more than 1 element in the list, find the element for
          'the version of the application
        Else
          node = xmlFile.SelectSingleNode("descendant::" & key & _
                      "[@version=" & thisVersion & "]")
        End If

        'Retrieve the value behind the node that matched the key/version
        If Not (node Is Nothing) Then
            obj = node.InnerText()
          End If

        'If the value is a numeric, convert it to a number; otherwise
        'convert it to a string (we don't store values other than strings
        'and numbers).
        If IsNumeric(obj) Then
          obj = CType(obj,Integer)
        Else
          obj = CType(obj, String)
        End If
      End If

      Return obj
    End Function
   
    Private Shared Sub PopulateCache()
      'With a try around the entire event, the object attempts to load the XML
      'file and store it in the cache with a dependency on the XML file itself.
      'This means that any time the XML file changes, it is removed from the
      'cache.  When the "getConstant" method is called again, the XML file won't
      'exist in memory and the PopulateCache will be re-called.
      Try
        xmlFile.Load(applicationConstantsFileName)
        myCache.Insert(applicationConstantsFile, xmlFile, _
                       New CacheDependency(applicationConstantsFileName))
      Catch e As Exception
        System.Diagnostics.Debug.WriteLine("Error: " & e.Message)
      End Try
    End Sub    
End Class

-------------------------------------------------------------------

thanks
0
Comment
Question by:bugnuker
  • 4
  • 2
6 Comments
 
LVL 7

Expert Comment

by:wnross
ID: 16562674
// ***************************************************************
//  ConstantsManager
//  Description: Manages the constants that live in the
//           applicationConstants.config file.  These get stored
//           in memory and when the file changes, the file is
//           removed from memory and re-read back into memory
//
//  NOTE: Constants file must live in the webroot
//   on the web server for the web application to run.
//
//  Author: Rachael Schoenbaum
//  Create date: 12/4/2002
// ***************************************************************
using System;
,System.Web.Caching;
,System.Xml;
,Microsoft.VisualBasic;
public class ConstantsManager {
   
    //  Cache object that will be used to store and retrieve items from
    //  the cache and constants used within this object
    protected internal static System.Web.Caching.Cache myCache = System.Web.HttpRuntime.Cache[];
   
    private static string applicationConstantsFile = "ApplicationConstantsFile";
   
    public static string applicationConstantsFileName = (System.AppDomain.CurrentDomain.BaseDirectory.Replace("/", "\\") + "applicationConstants.config");
   
    private static XmlDocument xmlFile = new XmlDocument();
   
    private static string constantIdentifier = "constant";
   
    private static string constantKey = "cacheDependencyKey";
   
    private static int thisVersion = getConstant("THIS_VERSION");
   
    public static object getConstant(ref string key) {
        object tmpObj;
        if (!(myCache[(constantIdentifier + key)] == null)) {
            tmpObj = myCache[(constantIdentifier + key)];
        }
        else {
            tmpObj = pullConstantFromFile(key);
            // Create the cache dependencies and insert the object into the cache
            if (!(tmpObj == null)) {
                if ((myCache[constantKey] == null)) {
                    myCache.Insert(constantKey, now);
                }
                myCache.Insert((constantIdentifier + key), tmpObj, new CacheDependency(applicationConstantsFileName));
            }
        }
        return tmpObj;
    }
   
    private static object pullConstantFromFile(ref string key) {
        object obj = 0;
        if ((myCache[applicationConstantsFile] == null)) {
            PopulateCache();
        }
        // Attempt to find the element given the "key" for that tag
        XmlNodeList elementList = xmlFile.GetElementsByTagName(key);
        // If the key is found, the element list will have a count greater than
        // zero and we retrieve the value of the tag...
        if ((elementList.Count > 0)) {
            XmlNode node;
            // If there is only 1 element in the list, then the element doesn't
            // have a version number and can be returned as is.
            if ((elementList.Count == 1)) {
                node = elementList.Item[0];
                // If there is more than 1 element in the list, find the element for
                // the version of the application
            }
            else {
                node = xmlFile.SelectSingleNode(("descendant::"
                                + (key + ("[@version="
                                + (thisVersion + "]")))));
            }
            // Retrieve the value behind the node that matched the key/version
            if (!(node == null)) {
                obj = node.InnerText();
            }
            // If the value is a numeric, convert it to a number; otherwise
            // convert it to a string (we don't store values other than strings
            // and numbers).
            if (IsNumeric(obj)) {
                obj = ((int)(obj));
            }
            else {
                obj = ((string)(obj));
            }
        }
        return obj;
    }
   
    private static void PopulateCache() {
        // With a try around the entire event, the object attempts to load the XML
        // file and store it in the cache with a dependency on the XML file itself.
        // This means that any time the XML file changes, it is removed from the
        // cache.  When the "getConstant" method is called again, the XML file won't
        // exist in memory and the PopulateCache will be re-called.
        try {
            xmlFile.Load(applicationConstantsFileName);
            myCache.Insert(applicationConstantsFile, xmlFile, new CacheDependency(applicationConstantsFileName));
        }
        catch (Exception e) {
            System.Diagnostics.Debug.WriteLine(("Error: " + e.Message));
        }
    }
}
0
 

Author Comment

by:bugnuker
ID: 16562826
This is almost working.
I am getting errors on somelines.
i'll paste the errors here maybe you can help
or i can send the .cs file (but if you've done the conversion, you should also have VS and can make the class to see if it will build.)
--------errors-----------------
Error      1      The best overloaded method match for 'ConstantsManager.pullConstantFromFile(ref string)' has some invalid arguments      C:\Documents and Settings\support\My Documents\Visual Studio 2005\WebSites\UconnDemo\App_Code\ContantsManager.cs      42      22      C:\...\UconnDemo\
Error      2      Argument '1' must be passed with the 'ref' keyword      C:\Documents and Settings\support\My Documents\Visual Studio 2005\WebSites\UconnDemo\App_Code\ContantsManager.cs      42      43      C:\...\UconnDemo\
Error      3      The name 'now' does not exist in the current context      C:\Documents and Settings\support\My Documents\Visual Studio 2005\WebSites\UconnDemo\App_Code\ContantsManager.cs      46      49      C:\...\UconnDemo\
Error      4      Cannot apply indexing with [] to an expression of type 'method group'      C:\Documents and Settings\support\My Documents\Visual Studio 2005\WebSites\UconnDemo\App_Code\ContantsManager.cs      68      24      C:\...\UconnDemo\
Error      5      'System.Xml.XmlNode.InnerText' is a 'property' but is used like a 'method'      C:\Documents and Settings\support\My Documents\Visual Studio 2005\WebSites\UconnDemo\App_Code\ContantsManager.cs      79      28      C:\...\UconnDemo\
Error      6      The name 'IsNumeric' does not exist in the current context      C:\Documents and Settings\support\My Documents\Visual Studio 2005\WebSites\UconnDemo\App_Code\ContantsManager.cs      84      17      C:\...\UconnDemo\
Error      7      'System.Web.HttpRuntime.Cache' is a 'property' but is used like a 'method'      C:\Documents and Settings\support\My Documents\Visual Studio 2005\WebSites\UconnDemo\App_Code\ContantsManager.cs      22      89      C:\...\UconnDemo\
Error      8      The best overloaded method match for 'ConstantsManager.getConstant(ref string)' has some invalid arguments      C:\Documents and Settings\support\My Documents\Visual Studio 2005\WebSites\UconnDemo\App_Code\ContantsManager.cs      34      38      C:\...\UconnDemo\
Error      9      Argument '1' must be passed with the 'ref' keyword      C:\Documents and Settings\support\My Documents\Visual Studio 2005\WebSites\UconnDemo\App_Code\ContantsManager.cs      34      50      C:\...\UconnDemo\
Error      10      Syntax error, value expected      C:\Documents and Settings\support\My Documents\Visual Studio 2005\WebSites\UconnDemo\App_Code\ContantsManager.cs      22      95      C:\...\UconnDemo\

-----end errors---------

thanks for the help so far!
-shane


0
 
LVL 7

Accepted Solution

by:
wnross earned 2000 total points
ID: 16564816
Here, try this one:
--------------- CUT HERE ------------------
using System;
using System.Web.Caching;
using System.Xml;
using Microsoft.VisualBasic;
public class ConstantsManager
{
 protected internal static System.Web.Caching.Cache myCache = System.Web.HttpRuntime.Cache;
 private static string applicationConstantsFile = "ApplicationConstantsFile";
 public static string applicationConstantsFileName = System.AppDomain.CurrentDomain.BaseDirectory.Replace( "/", "\\") + "applicationConstants.config";
 private static XmlDocument xmlFile = new XmlDocument();
 private static string constantIdentifier = "constant";
 private static string constantKey = "cacheDependencyKey";
 private static int thisVersion = Convert.ToInt32((string)getConstant("THIS_VERSION"));

 public static object getConstant(string key)
 {
   object tmpObj = null;
   if (!((myCache[constantIdentifier + key] == null))) {
     tmpObj = ((object)(myCache[constantIdentifier + key]));
   } else {
     tmpObj = pullConstantFromFile(key);
     if (!(Information.IsNothing(tmpObj))) {
       if (myCache[constantKey] == null) {
         myCache.Insert(constantKey, new DateTime());
       }
       myCache.Insert(constantIdentifier + key, tmpObj, new CacheDependency(applicationConstantsFileName));
     }
   }
   return tmpObj;
 }

 private static object pullConstantFromFile(string key)
 {
   object obj = 0;
   if (myCache[applicationConstantsFile] == null) {
     PopulateCache();
   }
   XmlNodeList elementList = xmlFile.GetElementsByTagName(key);
   if (elementList.Count > 0) {
     XmlNode node;
     if (elementList.Count == 1) {
       node = elementList.Item(0);
     } else {
       node = xmlFile.SelectSingleNode("descendant::" + key + "[@version=" + thisVersion + "]");
     }
     if (!((node == null))) {
       obj = node.InnerText;
     }
     if (Information.IsNumeric(obj)) {
       obj = ((int)(obj));
     } else {
       obj = ((string)(obj));
     }
   }
   return obj;
 }

 private static void PopulateCache()
 {
   try {
     xmlFile.Load(applicationConstantsFileName);
     myCache.Insert(applicationConstantsFile, xmlFile, new CacheDependency(applicationConstantsFileName));
   } catch (Exception e) {
     System.Diagnostics.Debug.WriteLine("Error: " + e.Message);
   }
 }
}
--------------- CUT HERE ------------------

Cheers,
-Bill
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:bugnuker
ID: 16565764
Bill-
This works in VS2005 expect for Information.IsNothing and Information.IsNumeric
do not work

I am new to C# and I dont know of another way for the Information.IsNumeric.
I am sure for the Information.IsNothing I can do a = null

i'll look on google to try and find the soultion, unless you post first with it.
as soon as i get it working from either googling the answer, or your post, i'll award the 500 pts.

thanks for all your help today.
turly and expert.
i tried conversion tools, i tried re-writing on my own, but i am not that good a c# for that.
-shane
0
 
LVL 7

Expert Comment

by:wnross
ID: 16566078
For the IsNumeric and IsNothing functions to work, add Microsoft.VisualBasic.dll to your references

* In Solution Explorer, expand the project node you want to add a reference to.
* Right-click the References node for the project and select Add Reference from the shortcut menu.
* To add a reference to a component or components, do the following:
   1. In the Add Reference dialog box, select the tab indicating the type of component you want to reference.
   2. In the top pane, select the component you want to reference, and then click the Select button.

The component you referenced appears in the SelectedComponents pane of the dialog box.

Cheers,
-Bill
0
 
LVL 7

Expert Comment

by:wnross
ID: 16601646
That worked for you I gather?  Thanks for the points

Cheers,
-Bill
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this post we will learn different types of Android Layout and some basics of an Android App.
When you discover the power of the R programming language, you are going to wonder how you ever lived without it! Learn why the language merits a place in your programming arsenal.
Simple Linear Regression
Introduction to Processes

868 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question