Converting vb to c# code - c#

Could you help me here, this is my friend's work(actually don't know where did he get this code, it uses vb language) and i'm trying to convert the code to c#. Thought it was easy, even though i lack of c# knowledge, and i'm stacked from here. I found a vb.net to c# converter from the net, and this is the result:
*see the comment below
clsProcess.cs:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
[Serializable()]
public class clsProcess : IComparable<clsProcess>
{
public int Priority
{
get { return _Priority; }
set { _Priority = value; }
}
public Color ProcessColor
{
get { return _ProcessColor; }
set { _ProcessColor = value; }
}
public double ArrTime
{
get { return _ArrTime; }
set { _ArrTime = value; }
}
public double ExeTime
{
get { return _ExeTime; }
set { _ExeTime = value; }
}
public string Label
{
get { return _Label; }
set { _Label = value; }
}
public clsProcess()
{
}
public clsProcess(int prior, double arr, double exe, string lbl, Color clr)
{
_Priority = prior;
_ArrTime = arr;
_ExeTime = exe;
_Label = lbl;
_ProcessColor = clr;
}
private double _ArrTime;
private double _ExeTime;
private string _Label;
private int _Priority;
private Color _ProcessColor;
public int CompareTo(clsProcess other)
{
switch ((modGlobals.SortColumn))
{
//The method SortType from modGlobals.cs is the error.
//Error says: The name 'SortType' does not exist in the current context
//I'm getting error from here:
case SortType.Arr:
return this.ArrTime.CompareTo(other.ArrTime);
case SortType.Exe:
return this.ExeTime.CompareTo(other.ExeTime);
case SortType.Label:
return this.Label.CompareTo(other.Label);
case SortType.Prior:
return this.Priority.CompareTo(other.Priority);
//Until here.
}
}
}
modGlobals.cs:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
static class modGlobals
{
public enum SortType //The error referring to.
{
Arr,
Exe,
Prior,
Label
}
public static SortType SortColumn; //I doubt it has something to do here.
public static List<clsProcess> CreateMemberwiseClone(List<clsProcess> pList)
{
List<clsProcess> tempList = new List<clsProcess>();
int i = 0;
for (i = 0; i <= pList.Count - 1; i++) {
tempList.Add(CloneProcess(pList[i]));
}
return tempList;
}
public static clsProcess CloneProcess(clsProcess process)
{
clsProcess temp = new clsProcess();
temp.ExeTime = process.ExeTime;
temp.ArrTime = process.ArrTime;
temp.Label = process.Label;
temp.Priority = process.Priority;
temp.ProcessColor = process.ProcessColor;
return temp;
}
public static void MergeBlocks(ref List<clsBlock> blocks)
{
if (blocks.Count < 2)
return;
int i = 0;
while (i < blocks.Count - 1) {
if (blocks[i].BlockCaption == blocks[i + 1].BlockCaption) {
blocks[i].BlockLength += blocks[i + 1].BlockLength;
blocks.RemoveAt(i + 1);
i -= 1;
}
i += 1;
}
}
}
Could you give me an alternate solution for here?

try
public int CompareTo(clsProcess other)
{
switch ((modGlobals.SortColumn))
{
case modGlobals.SortType.Arr:
return this.ArrTime.CompareTo(other.ArrTime);
case modGlobals.SortType.Exe:
return this.ExeTime.CompareTo(other.ExeTime);
case modGlobals.SortType.Label:
return this.Label.CompareTo(other.Label);
case modGlobals.SortType.Prior:
return this.Priority.CompareTo(other.Priority);
}
//This next part will happen if the switch statement doesnt find a match
//use this to return some default value or a value that tells you it didnt find something
//I'll use 0 as an example
return 0;
//now all paths return a value, even if it doesnt find a match in the switch statement
}

Your static class modGlobals should only have static members.
The SortType should be static.
public static enum SortType
{
Arr,
Exe,
Prior,
Label
}

Related

How to patch public int "set" method though Harmony Patches

I'm trying to patch public int "set" method taught Harmony Patches. The method I want to patch is a 7D2D function (ProgressionValue.Level). I wrote a little patch, but It doesn't work.
Method I want to patch:
public void set_Level(int value)
{
this.calculatedFrame = -1;
if (this.ProgressionClass == null)
{
this.level = value;
return;
}
if (this.ProgressionClass.IsSkill)
{
this.level = this.ProgressionClass.MaxLevel;
return;
}
this.level = value;
}
Method I wrote:
using HarmonyLib;
using UnityEngine;
namespace Undead_InstantSkillLeveling
{
[HarmonyPatch(typeof(ProgressionValue))]
[HarmonyPatch(nameof(ProgressionValue.Level))]
public class Udead_Harmony_InstantSkill
{
private static void Prefix(ProgressionValue __instance)
{
__instance.Level = __instance.ProgressionClass.MaxLevel;
}
}
}
Harmony used: Harmony

Using methods on arrays

I am very new to C#, and trying to make a program that counts an array, and I'm having trouble using methods/properties on the array (Reset, PrintCounters, Increment). the problems occur from the for loops and below. Thanks in advance if anyone is able to help.
using System;
namespace CounterTest
{
public class MainClass
{
private static void PrintCounters(Counter[] counters)
{
foreach (Counter c in counters)
{
string name = "";
int value = 0;
Console.WriteLine("{0} is {1}", name, value);
}
}
public static void Main(string[] args)
{
Counter[] myCounters = new Counter[3];
myCounters[0] = new Counter("Counter 1");
myCounters[1] = new Counter("Counter 2");
myCounters[2] = myCounters[0];
for (int i = 0; i < 4; i++)
{
Counter.Increment(myCounters[0]);
}
for (int i = 0; i < 9; i++)
{
Counter.Increment(myCounters[1]);
}
Counter.PrintCounters(myCounters);
Counter.Reset(myCounters[2]);
Counter.PrintCounters(myCounters);
}
}
}
Counter class:
using System;
using System.Collections.Generic;
using System.Text;
namespace CounterTest
{
public class Counter
{
private int _count;
private string _name;
public Counter(string name)
{
_name = name;
_count = 0;
}
public void Increment()
{
_count++;
}
public void Reset()
{
_count = 0;
}
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public int Value
{
get
{
return _count;
}
set
{
_count = value;
}
}
}
}
The methods you call are not static methods, so they are called like:
for (int i = 0; i < 4; i++)
{
myCounters[0].Increment();
}
for (int i = 0; i < 9; i++)
{
myCounters[1].Increment();
}
MainClass.PrintCounters(myCounters); //this is static
myCounters[2].Reset();
MainClass.PrintCounters(myCounters);
Counter is a type, not an instance, that's why Counter.Increment is an incorrect call (Increment is not a static method).
// Given intance of Counter - myCounters[1] call Increment() method on it
myCounters[1].Increment();
instead of
// Call static method of Counter class - Counter.Increment on instance of Counter
Counter.Increment(myCounters[1]);
etc. It can be something like this:
public static void Main(string[] args)
{
Counter[] myCounters = new Counter[3]
myCounters[0] = new Counter("Counter 1");
myCounters[1] = new Counter("Counter 2");
myCounters[2] = myCounters[0];
for (int i = 0; i < 4; i++)
{
// call Increment on myCounters[0] instance
myCounters[0].Increment();
}
for (int i = 0; i < 9; i++)
{
// call Increment on myCounters[1] instance
myCounters[1].Increment();
}
// PrintCounters method call
PrintCounters(myCounters);
// call Reset on myCounters[2] instance
myCounters[2].Reset();
// PrintCounters method call
PrintCounters(myCounters);
}
You are calling Counter.Increment and then providing a Counter as a parameter. This piece of code assumes Counter is a static class with static methods, which is not the case.
In your for loops, you should be using the code like this:
for (int i = 0; i < 4; i++)
{
myCounters[0].Increment();
}
You use Counter.Increment(myCounters[0]) like Increment was an extention method on Counter.
public static class ExtentionCounter
{
public static void Increment(this Counter cnt)
{
cnt.Value++;
}
}
When with your current definition you should use :
myCounters[0].Increment();
here is the solution for your code. Just compare with yours but see the changes are with ** .
On the PrintCounters since your looping trough the Counters as c you need to call the counter name and the valu with **c.Name and c.Value
using System;
using Test;
namespace teste
{
static class MainClass{
public static void PrintCounters(Counter[] counters)
{
foreach (Counter c in counters)
{
**string name = c.Name;**
**int value = c.Value;**
Console.WriteLine("{0} is {1}", name, value);
}
}
}
class Program
{
static void Main(string[] args)
{
Counter[] myCounters = new Counter[3];
myCounters[0] = new Counter("Counter 1");
myCounters[1] = new Counter("Counter 2");
myCounters[2] = myCounters[0];
for (int i = 0; i < 4; i++) {
**myCounters[0].Increment();**
}
for (int i = 0; i < 9; i++) {
**myCounters[1].Increment();**
}
**MainClass.PrintCounters(myCounters);**
**myCounters[2].Reset();**
**MainClass.PrintCounters(myCounters);**
}
}
}
Also since the myCounters is an instance of Counters you need to call the method of the instance like this:
myCounters[0].Increment()
Same for the other methods as Reset.
To call a static method you dont need to instantiate but in your case you need to do reference to the class to use the method PrintCounters like this:
MainClass.PrintCounters(myCounters);
Also use the keyword this.something to change instance variables.
using System;
using System.Collections.Generic;
using System.Text;
namespace Test
{
public class Counter
{
private int _count;
private string _name;
public Counter(string name)
{
**this._name = name;**
**this._count = 0;**
}
public void Increment()
{
**this._count++;**
}
public void Reset()
{
**this._count = 0;**
}
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public int Value
{
get
{
return _count;
}
set
{
_count = value;
}
}
}
}
i hope it helps

Why am I getting this StackOverFlowException

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Test
{
private int myFaveNumber; //fields
private const int myLeastFaveNumber = 5;
private string secretPassword = "Pickle";
public int MyFaveNumber
{
get
{
return MyFaveNumber;
}
set
{
if (value > 0)
MyFaveNumber = value;
else
myFaveNumber = 10;
}
}
public int Math()
{
return myFaveNumber - myLeastFaveNumber;
}
public Test()
{
Console.WriteLine("Secret password is " + secretPassword);
}
public Test(string two)
{
Console.WriteLine("The full password is {0}", two);
}
}
class Program
{
static void Main(string[] args)
{
Test quick = new Test();
Console.WriteLine(quick.ToString());
quick.MyFaveNumber = 5;
Console.WriteLine(quick.Math());
Test quicky = new Test("Drill");
Console.ReadKey();
}
}
}
I am messing around as a beginner, and am wondering why I am getting a "Process is terminated due to StackOverflowException". If you could help me figure this out that would be great. Also any tips are always welcome.
It should be myFaveNumber not MyFaveNumber = value;
set
{
if (value > 0)
myFaveNumber = value;
else
myFaveNumber = 10;
}
The problem is in this part:
public int MyFaveNumber
{
get
{
return MyFaveNumber;
}
...
}
You've set the MyFaveNumber property to return itself. Likewise, in the setter:
set
{
if (value > 0)
MyFaveNumber = value;
else
myFaveNumber = 10;
}
You (conditionally) assign MyFaveNumber, causing the setter to call itself. Both of these scenarios will cause the property to recursively call its getter/setter over and over again until the program crashes.
You need to be getting/setting the private backing field myFaveNumber instead:
public int MyFaveNumber
{
get
{
return myFaveNumber;
}
set
{
if (value > 0)
myFaveNumber = value;
else
myFaveNumber = 10;
}
}
Consider property as a function.
When you write this functions
public int GetMyProperty()
{
return GetMyProperty();
}
public void SetMyProperty(int value)
{
if (value > 0)
SetMyProperty(value);
}
You will obviously recognize that there is possibility in infinite recursive call which will "blow up" your stack(default size of the stack for .NET applications is 1 MB). So you increase size of the stack with every recursive call which happened in you program when you execute.
quick.MyFaveNumber = 5;
And you will get same exception in case when you will try to read value of the property
Console.WriteLine(quick.MyFaveNumber);
So correct way of using properties assign values to the underlying private field when needed validation is done.
private int _myProperty;
public int MyProperty
{
}

String building and form component access from class

Background
I am writing a program, which collects different events (key press, mouse position, and others) and sends a single string to a serial port.
There is a small part of the program, where a key is pressed, to control movement (forward - W key; left - A key, Forward-left - WA key).
When an event happens, a method is invoked, which grabs a numeric string and processes in the FinalStringClass Class. On the main form , there is a method, which assigns collected value to a label.
However, I am encountering a problem with code due to lack of experience in programming :(
Main Form:
Serial port;
FinalStringClass fstr;
public Form1()
{
InitializeComponent();
//... Serial port settings
timer.Start();
fstr = new FinalStringClass(UpdateLabel2);
}
public void UpdateLabel2(string x, string y, string speed, string mvm) //
{
label2.Text = "x: " + x + "y: " + y + "speed: " + speed + "mvm: " + mvm;
}
private void timer_Tick(object sender, EventArgs e)
{
var up = KeyboardInfo.GetKeyState(Keys.W);
var down = KeyboardInfo.GetKeyState(Keys.S);
var left = KeyboardInfo.GetKeyState(Keys.A);
var right = KeyboardInfo.GetKeyState(Keys.D);
if (left.IsPressed)
{
if (up.IsPressed == true) // if W and A keys are pressed, ->
{
fstr.mvmMethod("7"); // this method is triggered
return;
}
if (down.IsPressed)
{
fstr.mvmMethod("9");
return;
}
if (right.IsPressed)
{
fstr.mvmMethod("1");
return;
}
fstr.mvmMethod("4"); //if W key is pressed, then this method is triggered
}
//... (other if condition statements)
label2.Text = fstr.FinalStringBuilder();
port.Write(fstr.FinalStringBuilder());
}
External Class:
class FinalStringClass
{
private Action<string, string, string, string> updateLabel2;
Action<String> _x, _y, _speed, _mvm;
string xF, yF, speedF, mvmF;
public FinalStringClass(Action<string, string, string, string> updateLabel2)
{
this.updateLabel2 = updateLabel2;
}
public FinalStringClass(Action<String> x, Action<String> y, Action<String> speed, Action<String> mvm)
{
_x = x;
_y = y;
_speed = speed;
_mvm = mvm;
}
public void xMethod(string x)
{
_x(x);
xF = x;
}
public void yMethod(string y)
{
_y(y);
yF = y;
}
public void speedMethod(string speed)
{
_speed(speed);
speedF = speed;
}
public void mvmMethod(string mvm)
{
_mvm(mvm);
mvmF = mvm;
}
public string FinalStringBuilder()
{
return xF + yF + speedF + mvmF;
}
}
When working with a single parameter, everything works fine. But dealing with multiple parameters causes a problem :(
Example of working with a single parameter (full working code):
Main Form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FFApp
{
public partial class Form1 : Form
{
SerialPort port;
MyClass outside;
public Form1()
{
InitializeComponent();
timer.Start();
outside = new MyClass(UpdateLabel);
}
public void UpdateLabel(string str)
{
label1.Text = str;
}
private void init()
{
port = new SerialPort();
port.PortName = "COM1";
port.BaudRate = 115200;
try
{
port.Open();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
}
public struct KeyStateInfo
{
private Keys key;
private bool isPressed;
private bool isToggled;
public KeyStateInfo(Keys key, bool ispressed, bool istoggled)
{
this.key = key;
isPressed = ispressed;
isToggled = istoggled;
}
public static KeyStateInfo Default
{
get
{
return new KeyStateInfo(Keys.None, false, false);
}
}
public Keys Key
{
get { return key; }
}
public bool IsPressed
{
get { return isPressed; }
}
public bool IsToggled
{
get { return isToggled; }
}
}
private void timer_Tick(object sender, EventArgs e)
{
var up = KeyboardInfo.GetKeyState(Keys.W);
var down = KeyboardInfo.GetKeyState(Keys.S);
var left = KeyboardInfo.GetKeyState(Keys.A);
var right = KeyboardInfo.GetKeyState(Keys.D);
Keyboard kb = new Keyboard();
if (left.IsPressed)
{
if (up.IsPressed == true)
{
outside.MyMethod("7");
return;
}
if (down.IsPressed)
{
outside.MyMethod("9");
return;
}
if (right.IsPressed)
{
outside.MyMethod("1");
return;
}
outside.MyMethod("4");
}
if (right.IsPressed)
{
if (up.IsPressed)
{
outside.MyMethod("6");
return;
}
if (down.IsPressed)
{
outside.MyMethod("8");
return;
}
if (left.IsPressed)
{
outside.MyMethod("1");
return;
}
outside.MyMethod("5");
}
if (up.IsPressed)
{
if (left.IsPressed)
{
outside.MyMethod("7");
return;
}
if (right.IsPressed)
{
outside.MyMethod("6");
return;
}
if (down.IsPressed)
{
outside.MyMethod("1");
return;
}
outside.MyMethod("2");
}
if (down.IsPressed)
{
if (left.IsPressed)
{
outside.MyMethod("9");
return;
}
if (right.IsPressed)
{
outside.MyMethod("8");
return;
}
if (up.IsPressed)
{
outside.MyMethod("9");
return;
}
outside.MyMethod("3");
}
if (!right.IsPressed && !left.IsPressed && !up.IsPressed && !down.IsPressed)
{
outside.MyMethod("1");
}
}
public class KeyboardInfo
{
[DllImport("user32")]
private static extern short GetKeyState(int vKey);
private KeyboardInfo()
{
}
public static KeyStateInfo GetKeyState(Keys key)
{
short keyState = GetKeyState((int)key);
int low = Low(keyState), high = High(keyState);
bool toggled = low == 1;
bool pressed = high == 1;
return new KeyStateInfo(key, pressed, toggled);
}
private static int High(int keyState)
{
return keyState > 0 ? keyState >> 0x10
: (keyState >> 0x10) & 0x1;
}
private static int Low(int keyState)
{
return keyState & 0xffff;
}
}
}
}
Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FFApp
{
class MyClass
{
Action<String> labelSetter;
public MyClass(Action<String> labelSetter)
{
this.labelSetter = labelSetter;
}
public string MyProperty { get; set; }
public void MyMethod(string text)
{
labelSetter(text);
MyProperty = text;
}
}
}
Or is it possible within this code, to get changing values (store in a variable), when pressed W/A/D/S/W+A/W+D etc keys in order to allow building final string? ex: string finalstring = x + y + speed + pressed_key;

Modifying List in ViewState does not persist

I have a ViewState holding a List<T>
public List<AwesomeInt> MyList
{
get { return ((List<int>)ViewState["MyIntList"]).Select(i => new AwesomeInt(i)).ToList(); }
set { ViewState["MyIntList"] = value.GetIntegers(); }
}
Now, when I call MyList.Add(new AwesomeInt(3)) let's say, the list does not persist the change.
I believe this is because the .ToList() in the get is creating a new List object and therefore the set will never be called, thus never saving in ViewState.
I have worked around this problem before by either
not calling .Select/.ToList() by saving/calling directly without a
conversion.
not using the .Add or .Remove functions and instead
re-initializing the List with an equals.
However sometimes 1. is impractical if the class is not serializable and I have no control over that, and 2. is kind of ugly because I have to copy it to a temp first, then add, then re-assign, or play around with Concat to add a single item.
Is there a better way of doing this?
Alright, below is a fully functional console application that should give you the capabilities you need. I leveraged generics so that you could build surrounding collections of whatever type necessary - but yet serialize something more rudimentary. Keep in mind I don't have a real view state to write to in the set but you can fix that up.
Also bear in mind I wrote this in a pretty short time frame (e.g. 20 minutes) so there may be optimizations that exist (e.g. the set on the ViewState property isn't really necessary generally because this solution modifies the underlying rudimentary data source).
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static List<int> _viewState = new List<int>();
static RawCollection<AwesomeInt, int> ViewState
{
get { return new RawCollection<AwesomeInt, int>(_viewState); }
set { _viewState = value.RawData; }
}
static void Main(string[] args)
{
ViewState.Add(new AwesomeInt(1));
ViewState.Add(new AwesomeInt(2));
WriteViewState();
ViewState[0].Val = 5;
WriteViewState();
ViewState.RemoveAt(0);
WriteViewState();
for (int i = 10; i < 15; i++)
{
ViewState.Add(new AwesomeInt(i));
}
WriteViewState();
}
private static void WriteViewState()
{
for (int i = 0; i < ViewState.Count; i++)
{
Console.WriteLine("The value at index {0} is {1}.", i, ViewState[i].Val);
}
Console.WriteLine();
Console.WriteLine();
}
}
public class RawCollection<T, K> : Collection<T>
{
private List<K> _data;
public RawCollection(List<K> data)
{
foreach (var i in data)
{
var o = (T)Activator.CreateInstance(typeof(T), i);
var oI = o as IRawData<K>;
oI.RawValueChanged += (sender) =>
{
_data[this.IndexOf((T)sender)] = sender.Val;
};
this.Add(o);
}
_data = data;
}
public List<K> RawData
{
get
{
return new List<K>(
this.Items.Select(
i => ((IRawData<K>)i).Val));
}
}
protected override void ClearItems()
{
base.ClearItems();
if (_data == null) { return; }
_data.Clear();
}
protected override void InsertItem(int index, T item)
{
base.InsertItem(index, item);
if (_data == null) { return; }
_data.Insert(index, ((IRawData<K>)item).Val);
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
if (_data == null) { return; }
_data.RemoveAt(index);
}
protected override void SetItem(int index, T item)
{
base.SetItem(index, item);
if (_data == null) { return; }
_data[index] = ((IRawData<K>)item).Val;
}
}
public class AwesomeInt : IRawData<int>
{
public AwesomeInt(int i)
{
_val = i;
}
private int _val;
public int Val
{
get { return _val; }
set
{
_val = value;
OnRawValueChanged();
}
}
public event Action<IRawData<int>> RawValueChanged;
protected virtual void OnRawValueChanged()
{
if (RawValueChanged != null)
{
RawValueChanged(this);
}
}
}
public interface IRawData<T> : INotifyRawValueChanged<T>
{
T Val { get; set; }
}
public interface INotifyRawValueChanged<T>
{
event Action<IRawData<T>> RawValueChanged;
}
}

Categories

Resources