?
Solved

How do I convert old vb code to C# ?

Posted on 2009-07-07
11
Medium Priority
?
401 Views
Last Modified: 2012-05-07
I've recently started a job where they use a simple VB encryption algorithm and I program in C# (something they wish to eventually switch everything to).  I'm having some trouble converting the VB code into useable c# code and was hoping you could help.  Thanks!
// The original code I'm trying to translate
  Public Function SimpleCrypt( _
           ByVal Text As String) As String
        ' Encrypts/decrypts the passed string using 
        ' a simple ASCII value-swapping algorithm
        Dim strTempChar As String, i As Integer
        For i = 1 To Len(Text)
            If Asc(Mid$(Text, i, 1)) < 128 Then
                strTempChar = _
          CType(Asc(Mid$(Text, i, 1)) + 128, String)
            ElseIf Asc(Mid$(Text, i, 1)) > 128 Then
                strTempChar = _
          CType(Asc(Mid$(Text, i, 1)) - 128, String)
            End If
            Mid$(Text, i, 1) = _
                Chr(CType(strTempChar, Integer))
        Next i
        Return Text
    End Function
 
//My failed attempt at translation
  public string SimpleCrypt(string Text)
  {
		// Encrypts/decrypts the passed string using 
		// a simple ASCII value-swapping algorithm
		string strTempChar = null;
		int i;
		for (i = 1; i <= Text.Length; i++)
		{
 
            if (Convert.ToInt16(Encoding.ASCII.GetBytes(Text.Substring(i,1))) < 128);
            if (Convert.ToInt16(Text.Substring(i - 1, 1)) < 128)
			{
                strTempChar = Convert.ToString(Convert.ToInt16(Text.Substring(i - 1, 1)) + 128);
			}
            else if (Convert.ToInt16(Text.Substring(i - 1, 1)) > 128)
			{
                strTempChar = Convert.ToString(Convert.ToInt16(Text.Substring(i - 1, 1)) - 128);
			}
			Text = Text.Remove(i - 1, 1).Insert(i - 1, ((char)(Convert.ToInt16(strTempChar))).ToString());
		}
		return Text;
	}

Open in new window

0
Comment
Question by:megatherian
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
11 Comments
 
LVL 21

Expert Comment

by:Tapan Pattanaik
ID: 24794596
hi megatherian,

                       Check these links, which able to solve your problem.

Convert VB.NET to C#:
(Simply paste in your VB.NET code below, and this free utility will automatically convert it to its equivalent in C#)

http://www.developerfusion.com/tools/convert/vb-to-csharp/

Code Translation for .NET (C#<->VB.NET):

http://www.carlosag.net/Tools/CodeTranslator/

http://vbconversions.net/
0
 

Author Comment

by:megatherian
ID: 24794664
I've tried those converters and that's partially how I came up with my non-working version.  None of them seem to be converting it correctly which is why I need a little more help.  Thanks though.
0
 
LVL 20

Expert Comment

by:alainbryden
ID: 24795010
The translation attempt looks pretty decent. Can you note where it's producing errors, or is it simply not giving the same results as the other algorithm?

--
Alain
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:megatherian
ID: 24795324
ok, the original VB both encrypts and decrypts text.  Using the following code I've gotten it to convert read:

test as ôåóô

but when I put in:
ôåóô it reads it as }}}}


in fact anything I put in that's not regular characters it reads them as }


So I'm halfway there.

    public string SimpleCrypt(string Text)
    {
        // Encrypts/decrypts the passed string using 
        // a simple ASCII value-swapping algorithm
        string strTempChar = null;
        int i = 0;
        for (i = 1; i <= Text.Length; i++)
        {
            if (Convert.ToInt32(Text[i - 1]) < 128)
            {
                strTempChar = Convert.ToString(Convert.ToInt32(Text[i - 1]) + 128);
            }
            else if (Convert.ToInt32(Text[i - 1]) > 128)
            {
                strTempChar = Convert.ToString(Convert.ToInt32(Text[i - 1]) - 128);
            }
            Text = Text.Remove(i - 1, 1).Insert(i - 1, ((char)(Convert.ToInt32(strTempChar))).ToString());
        }
        return Text;
    }

Open in new window

0
 
LVL 20

Expert Comment

by:alainbryden
ID: 24796471
So far as your code adjustments, 16 bit integers should suffice, but that's not an issue here.

Step through your code when decrypting and find out what the value of
Text[i - 1]
Convert.ToInt32(Text[i - 1])
and
Convert.ToString(Convert.ToInt32(Text[i - 1]) + 128)
are for each iteration. One of these functions may have a problem interpreting ascii values outside the normal range?

--
Alain
0
 
LVL 20

Expert Comment

by:alainbryden
ID: 24796674
strangely enough, the encryption isn't occurring as I expected it to given the code provided:

t      e      s      t
116 101 115 116

+128 =

244 229 243 244
      Ã       d      


The encryption you gave is
ô     å     ó     ô
147 134 162 147

Why do you think that is. It it not just adding 128 to the ascii value of the character or removing 128 if it is already over 128?

Note that this code completely fails with ascii characters greater than or equal to 256. If it's 256, it will be encrypted to 128, and then will never be decrypted (because there's no case dealing with 128 exactly, only greater or less than 128). If the character is greater than 256, it will get encrypted a second time instead of decrypted, because the encrypted value is still greater than 128.

Either way, here is the code, as is, properly translated for C#, but you should fix it to be more correct. You should probably have one "Encrypt" and one "Decrypt" function that do the ascii shift consistently.

 I would try using the following code:

--
Alain
    public string SimpleCrypt(string Text)
    {
        // Encrypts/decrypts the passed string using 
        // a simple ASCII value-swapping algorithm
        char newChar;
        int currCharAsc;
        for (i = 0; i < Text.Length; i++)
        {
            newChar = null
            currCharAsc = Convert.ToInt16(Text[i])
            if (currCharAsc < 128)
            {
                newChar = Convert.ToChar(currCharAsc + 128);
            }
            else if (currCharAsc > 128)
            {
                newChar = Convert.ToChar(currCharAsc - 128);
            }
            else
            Text[i] = newChar;
        }
        return Text;
    }

Open in new window

0
 

Author Comment

by:megatherian
ID: 24797618
Thanks Alain,
Unfortunately I wasn't able to get your code to work for either encryption or decryption.  The code I'm using now works in 1 direction, encryption.  That is, if I tell it to the word:

test

it returns:

ôåóô

but if I give it:

ôåóô

it doesn't understand those characters and returns:

ýýýý

which it then decrypts incorrectly (obviously)

I didn't write the original VB code but the best I could figure is that it should be a simple ad or subtract 128 from the character values.

I believe that the problem has something to do with ASCII and Unicode - though I'm a bit shaky on that stuff so maybe that's just silly talk.  The VB code I think assumes ASCII and .NET assumes Unicode.  So when I'm using the 26 letters the code works fine (because they are the same in ASCII and Unicode).  When I go the other direction things don't seem to match up as well.  So, I guess what I need to know now is how to make the encoding all mesh up.

Thanks again for your help!
0
 
LVL 20

Accepted Solution

by:
alainbryden earned 2000 total points
ID: 24797828
Sorry, I had a bunch of syntax errors in my code and I didn't realize you couldn't assign to an indexed string. Please do try the following, I guarantee that it works:

--
Alain
static void Main(string[] args)
        {
            string text = "test";
            Console.WriteLine(text);
            text = SimpleCrypt(text);
            Console.WriteLine(text);
            text = SimpleCrypt(text);
            Console.WriteLine(text);
            Console.ReadKey();
        }
 
        public static string SimpleCrypt(string Text)
        {
            // Encrypts/decrypts the passed string using 
            // a simple ASCII value-swapping algorithm
            string result = "";
            char newChar;
            int currCharAsc;
            for (int i = 0; i < Text.Length; i++)
            {
                newChar = (char)0;
                currCharAsc = Convert.ToInt16(Text[i]);
                if (currCharAsc < 128)
                {
                    newChar = Convert.ToChar(currCharAsc + 128);
                }
                else if (currCharAsc > 128)
                {
                    newChar = Convert.ToChar(currCharAsc - 128);
                }
                result += newChar;
            }
            return result;
        }

Open in new window

0
 
LVL 20

Expert Comment

by:alainbryden
ID: 24797847
Here is the result, just to be sure, it is what you want.

--
Alain
result.JPG
0
 

Author Closing Comment

by:megatherian
ID: 31600598
Thanks, that works great!
0
 
LVL 20

Expert Comment

by:alainbryden
ID: 24798088
You're welcome, and thank you for the points making me a Master in Visual Basic Programming :)

--
Alain
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

Article by: Martin
Here are a few simple, working, games that you can use as-is or as the basis for your own games. Tic-Tac-Toe This is one of the simplest of all games.   The game allows for a choice of who goes first and keeps track of the number of wins for…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
Suggested Courses
Course of the Month10 days, 8 hours left to enroll

765 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