MyBB Community Forums

Full Version: Anyone good converting C# to VB.NET?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2 3
Big Grin thanks Toungue

I understand most C# code, but not this one bit Toungue So I cant convert it well, as i cant figure out what it is, and its equivalent in vb Toungue
Why don't you show us the spot that is having trouble? Or is it a very large section?
It just converting the "delegate" phrases:

          ml.Queue(delegate
            {
                bannedIP = PlayerList.Load("banned-ip.txt", null);
                ircControllers = PlayerList.Load("IRC_Controllers.txt", null);

                foreach (Group grp in Group.GroupList)
                    grp.playerList = PlayerList.Load(grp.fileName, grp);
                if (Server.useWhitelist)
                    whiteList = PlayerList.Load("whitelist.txt", null);
            });

            ml.Queue(delegate
            {
                if (File.Exists("text/autoload.txt"))
                {
                    try
                    {
                        string[] lines = File.ReadAllLines("text/autoload.txt");
                        foreach (string line in lines)
                        {
                            //int temp = 0;
                            string _line = line.Trim();
                            try
                            {
                                if (_line == "") { continue; }
                                if (_line[0] == '#') { continue; }
                                int index = _line.IndexOf("=");

                                string key = _line.Split('=')[0].Trim();
                                string value;
                                try
                                {
                                    value = _line.Split('=')[1].Trim();
                                }
                                catch
                                {
                                    value = "0";
                                }

                                if (!key.Equals(mainLevel.name))
                                {
                                    Command.all.Find("load").Use(null, key + " " + value);
                                    Level l = Level.FindExact(key);
                                }
                                else
                                {
                                    try
                                    {
                                        int temp = int.Parse(value);
                                        if (temp >= 0 && temp <= 3)
                                        {
                                            mainLevel.setPhysics(temp);
                                        }
                                    }
                                    catch
                                    {
                                        Server.s.Log("Physics variable invalid");
                                    }
                                }


                            }
                            catch
                            {
                                Server.s.Log(_line + " failed.");
                            }
                        }
                    }
                    catch
                    {
                        Server.s.Log("autoload.txt error");
                    }
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
                else
                {
                    Log("autoload.txt does not exist");
                }
            });

            ml.Queue(delegate
            {
                Log("Creating listening socket on port " + Server.port + "... ");
                if (Setup())
                {
                    s.Log("Done.");
                }
                else
                {
                    s.Log("Could not create socket connection.  Shutting down.");
                    return;
                }
            });

            ml.Queue(delegate
            {
                updateTimer.Elapsed += delegate
                {
                    Player.GlobalUpdate();
                    PlayerBot.GlobalUpdatePosition();
                };

                updateTimer.Start();
            });


            // Heartbeat code here:

            ml.Queue(delegate
            {
                try
                {
                    Heartbeat.Init();
                }
                catch (Exception e)
                {
                    Server.ErrorLog(e);
                }
            });

            // END Heartbeat code

            /*
            Thread processThread = new Thread(new ThreadStart(delegate
            {
                try
                {
                    PCCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
                    ProcessCounter = new PerformanceCounter("Process", "% Processor Time", Process.GetCurrentProcess().ProcessName);
                    PCCounter.BeginInit();
                    ProcessCounter.BeginInit();
                    PCCounter.NextValue();
                    ProcessCounter.NextValue();
                }
                catch { }
            }));
            processThread.Start();
            */

            ml.Queue(delegate
            {
                messageTimer.Elapsed += delegate
                {
                    RandomMessage();
                };
                messageTimer.Start();

                process = System.Diagnostics.Process.GetCurrentProcess();

                if (File.Exists("text/messages.txt"))
                {
                    StreamReader r = File.OpenText("text/messages.txt");
                    while (!r.EndOfStream)
                        messages.Add(r.ReadLine());
                    r.Dispose();
                }
                else File.Create("text/messages.txt").Close();

                if (Server.irc)
                {
                    new IRCBot();
                }
            

                //      string CheckName = "FROSTEDBUTTS";

                //       if (Server.name.IndexOf(CheckName.ToLower())!= -1){ Server.s.Log("FROSTEDBUTTS DETECTED");}
                new AutoSaver(Server.backupInterval);     //2 and a half mins

                blockThread = new Thread(new ThreadStart(delegate
                {
                    while (true)
                    {
                        Thread.Sleep(blockInterval * 1000);
                        foreach (Level l in levels)
                        {
                            l.saveChanges();
                        }
                    }
                }));
                blockThread.Start();

                locationChecker = new Thread(new ThreadStart(delegate
                {
                    while (true)
                    {
                        Thread.Sleep(3);
                        for (int i = 0; i < Player.players.Count; i++)
                        {
                            try
                            {
                                Player p = Player.players[i];

                                if (p.frozen)
                                {
                                    unchecked { p.SendPos((byte)-1, p.pos[0], p.pos[1], p.pos[2], p.rot[0], p.rot[1]); } continue;
                                }
                                else if (p.following != "")
                                {
                                    Player who = Player.Find(p.following);
                                    if (who == null || who.level != p.level) 
                                    { 
                                        p.following = "";
                                        if (!p.canBuild)
                                        {
                                            p.canBuild = true;
                                        }
                                        if (who != null && who.possess == p.name)
                                        {
                                            who.possess = "";
                                        }
                                        continue; 
                                    }
                                    if (p.canBuild)
                                    {
                                        unchecked { p.SendPos((byte)-1, who.pos[0], (ushort)(who.pos[1] - 16), who.pos[2], who.rot[0], who.rot[1]); }
                                    }
                                    else
                                    {
                                        unchecked { p.SendPos((byte)-1, who.pos[0], who.pos[1], who.pos[2], who.rot[0], who.rot[1]); }
                                    }
                                } else if (p.possess != "") {
                                    Player who = Player.Find(p.possess);
                                    if (who == null || who.level != p.level)
                                        p.possess = "";
                                }

                                ushort x = (ushort)(p.pos[0] / 32);
                                ushort y = (ushort)(p.pos[1] / 32);
                                ushort z = (ushort)(p.pos[2] / 32);

                                if (p.level.Death) 
                                    p.RealDeath(x, y, z);
                                p.CheckBlock(x, y, z);

                                p.oldBlock = (ushort)(x + y + z);
                            } catch (Exception e) { Server.ErrorLog(e); }
                        }
                    }
                }));

                locationChecker.Start();

                Log("Finished setting up server");
            });
        }
No idea if it has converted correctly, but it's worth a shot trying.

ml.Queue(Function() Do
	bannedIP = PlayerList.Load("banned-ip.txt", Nothing)
	ircControllers = PlayerList.Load("IRC_Controllers.txt", Nothing)

	For Each grp As Group In Group.GroupList
		grp.playerList = PlayerList.Load(grp.fileName, grp)
	Next
	If Server.useWhitelist Then
		whiteList = PlayerList.Load("whitelist.txt", Nothing)
	End If
End Function)

ml.Queue(Function() Do
	If File.Exists("text/autoload.txt") Then
		Try
			Dim lines As String() = File.ReadAllLines("text/autoload.txt")
			For Each line As String In lines
				'int temp = 0;
				Dim _line As String = line.Trim()
				Try
					If _line = "" Then
						Continue Try
					End If
					If _line(0) = "#"C Then
						Continue Try
					End If
					Dim index As Integer = _line.IndexOf("=")

					Dim key As String = _line.Split("="C)(0).Trim()
					Dim value As String
					Try
						value = _line.Split("="C)(1).Trim()
					Catch
						value = "0"
					End Try

					If Not key.Equals(mainLevel.name) Then
						Command.all.Find("load").Use(Nothing, key & " " & value)
						Dim l As Level = Level.FindExact(key)
					Else
						Try
							Dim temp As Integer = Integer.Parse(value)
							If temp >= 0 AndAlso temp <= 3 Then
								mainLevel.setPhysics(temp)
							End If
						Catch
							Server.s.Log("Physics variable invalid")
						End Try


					End If
				Catch
					Server.s.Log(_line & " failed.")
				End Try
			Next
		Catch
			Server.s.Log("autoload.txt error")
		End Try
		GC.Collect()
		GC.WaitForPendingFinalizers()
	Else
		Log("autoload.txt does not exist")
	End If
End Function)

ml.Queue(Function() Do
	Log("Creating listening socket on port " + Server.port & "... ")
	If Setup() Then
		s.Log("Done.")
	Else
		s.Log("Could not create socket connection.  Shutting down.")
		Return
	End If
End Function)

ml.Queue(Function() Do
	updateTimer.Elapsed += Function() Do
		Player.GlobalUpdate()
		PlayerBot.GlobalUpdatePosition()
	End Function

	updateTimer.Start()
End Function)


' Heartbeat code here:

ml.Queue(Function() Do
	Try
		Heartbeat.Init()
	Catch e As Exception
		Server.ErrorLog(e)
	End Try
End Function)

' END Heartbeat code

'
'            Thread processThread = new Thread(new ThreadStart(delegate
'            {
'                try
'                {
'                    PCCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
'                    ProcessCounter = new PerformanceCounter("Process", "% Processor Time", Process.GetCurrentProcess().ProcessName);
'                    PCCounter.BeginInit();
'                    ProcessCounter.BeginInit();
'                    PCCounter.NextValue();
'                    ProcessCounter.NextValue();
'                }
'                catch { }
'            }));
'            processThread.Start();
'            


ml.Queue(Function() Do
	messageTimer.Elapsed += Function() Do
		RandomMessage()
	End Function
	messageTimer.Start()

	process = System.Diagnostics.Process.GetCurrentProcess()

	If File.Exists("text/messages.txt") Then
		Dim r As StreamReader = File.OpenText("text/messages.txt")
		While Not r.EndOfStream
			messages.Add(r.ReadLine())
		End While
		r.Dispose()
	Else
		File.Create("text/messages.txt").Close()
	End If

	If Server.irc Then
		New IRCBot()
	End If


	'      string CheckName = "FROSTEDBUTTS";

	'       if (Server.name.IndexOf(CheckName.ToLower())!= -1){ Server.s.Log("FROSTEDBUTTS DETECTED");}
	New AutoSaver(Server.backupInterval)
	'2 and a half mins
	blockThread = New Thread(New ThreadStart(Function() Do
		While True
			Thread.Sleep(blockInterval * 1000)
			For Each l As Level In levels
				l.saveChanges()
			Next
		End While
	End Function))
	blockThread.Start()

	locationChecker = New Thread(New ThreadStart(Function() Do
		While True
			Thread.Sleep(3)
			For i As Integer = 0 To Player.players.Count - 1
				Try
					Dim p As Player = Player.players(i)

					If p.frozen Then
												p.SendPos(CByte(-1), p.pos(0), p.pos(1), p.pos(2), p.rot(0), p.rot(1))

						Continue Try
					ElseIf p.following <> "" Then
						Dim who As Player = Player.Find(p.following)
						If who Is Nothing OrElse who.level <> p.level Then
							p.following = ""
							If Not p.canBuild Then
								p.canBuild = True
							End If
							If who IsNot Nothing AndAlso who.possess = p.name Then
								who.possess = ""
							End If
							Continue Try
						End If
						If p.canBuild Then
														p.SendPos(CByte(-1), who.pos(0), CUShort(who.pos(1) - 16), who.pos(2), who.rot(0), who.rot(1))

						Else
														p.SendPos(CByte(-1), who.pos(0), who.pos(1), who.pos(2), who.rot(0), who.rot(1))

						End If
					ElseIf p.possess <> "" Then
						Dim who As Player = Player.Find(p.possess)
						If who Is Nothing OrElse who.level <> p.level Then
							p.possess = ""
						End If
					End If

					Dim x As UShort = CUShort(p.pos(0) / 32)
					Dim y As UShort = CUShort(p.pos(1) / 32)
					Dim z As UShort = CUShort(p.pos(2) / 32)

					If p.level.Death Then
						p.RealDeath(x, y, z)
					End If
					p.CheckBlock(x, y, z)

					p.oldBlock = CUShort(x + y + z)
				Catch e As Exception
					Server.ErrorLog(e)
				End Try
			Next
		End While
	End Function))

	locationChecker.Start()

	Log("Finished setting up server")
End Function)
ok, that seemed to work thanks Smile Now i just have another problem. In the C# code there is:

p.Blockchange += new Player.BlockchangeEventHandler(Blockchange1);

now, player.BlockchangeEventHandles in c# is:
public delegate void BlockchangeEventHandler(Player p, ushort x, ushort y, ushort z, byte type);
        public event BlockchangeEventHandler Blockchange = null;


In VB.NET that has converted to:
p.Blockchange += New Player.BlockchangeEventHandler(AddressOf Blockchange1)

and in the class:
Public Delegate Sub BlockchangeEventHandler(p As Player, x As UShort, y As UShort, z As UShort, type As Byte)
		Public Event Blockchange As BlockchangeEventHandler = Nothing

In C# it works fine, in vb.net it gives:
'Public Event Blockchange(p As Player, x As UShort, y As UShort, z As UShort, type As Byte)' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event.
Try:

p.Blockchange += New Player.BlockchangeEventHandler(Blockchange1)
Inside an event you must have "address of", "sub" or "function" Smile
Oops, posted the code I was trying to convert. Sorry about that. Anyway, the code I should have posted is incorrect also, so I guess it's best that I didn't. Toungue

Check out these links; they may help you.

http://bytes.com/topic/visual-basic-net/...-code-c-vb
http://msdn.microsoft.com/en-us/library/h23z7t2c.aspx

Just out of interest, what type of server is it? Minecraft?
Yup Big Grin a McLawl fork Smile
(2011-04-02, 04:08 PM)Dylan M. Wrote: [ -> ]Well, I wish you the best of luck. I know how annoying it is trying to convert code Wink

+1 for that. I spent 2 days converting C# to Visual C++ (.net) and all that because of Microsoft, some functions had different names, some didn't exist, some data types didn't exist either (so I had to use similar ones), I think Microsoft could have made my life easier.

But converting from C# to VB.NET is way easier because most of the functions, data types, etc, are similar.
Pages: 1 2 3