How to parse data from the firebase database to int - c#

public void saveData()
{
Reference.Child("users").Child(userId).Child("level").SetValueAsync(levelText.text.ToString());
}
public void loadData()
{
FirebaseDatabase.DefaultInstance.GetReference("").ValueChanged += Script_ValueChanged;
}
private void Script_ValueChanged(object sender, ValueChangedEventArgs e)
{
levelText.text = e.Snapshot.Child("users").Child(userId).Child("level").GetValue(true).ToString();
}
In this example I can load my level from the database and save it. My problem right now is I want to load the level from the database and store it in a Int level Variable so I can make a levelup function and update the level in the database. Does someone know how to do that?
private void Script_ValueChanged(object sender, ValueChangedEventArgs e)
{
level = (int)e.Snapshot.Child("users").Child(userId).Child("level").GetValue(true);
levelText.text = level.ToString();
}
my idea was maybe doing it in that way, but inside unity It gives me an error message at that line:
"System.InvalidCastException: Specified cast is not valid."

You need to parse the int from the string, because a string cannot be cast to an int. You can use int.Parse() for that if you know that it contains a valid integer:
private void Script_ValueChanged(object sender, ValueChangedEventArgs e)
{
level = int.Parse(e.Snapshot.Child("users").Child(userId).Child("level").GetValue(true));
levelText.text = level.ToString();
}
Documentation for int.Parse(): https://learn.microsoft.com/en-us/dotnet/api/system.int32.parse?view=net-7.0
Alternatively, you can also use int.TryParse() if you're not 100% certain that the string contains a valid integer:
private void Script_ValueChanged(object sender, ValueChangedEventArgs e)
{
if(int.TryParse(e.Snapshot.Child("users").Child(userId).Child("level").GetValue(true), out int parsedInt))
{
level = parsedInt;
}
levelText.text = level.ToString();
}
Documentation for int.TryParse():
https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-7.0
Another solution would be to use Convert.ToInt32() instead of int.Parse(), but it will do the same thing:
https://learn.microsoft.com/en-us/dotnet/api/system.convert.toint32?view=net-7.0

Related

C# Asynchronous Server Socket pass additional parameters to BeginAccept [duplicate]

Let's say I want to pass some extra data when assigning an event handler. Consider the following code:
private void setup(string someData)
{
Object.assignHandler(evHandler);
}
public void evHandler(Object sender)
{
// need someData here!!!
}
How would I go about getting someData into my evHandler method?
private void setup(string someData)
{
Object.assignHandler((sender) => evHandler(sender,someData));
}
public void evHandler(Object sender, string someData)
{
// need someData here!!!
}
I had a hard time figuring out #spender's example above especially with: Object.assignHandler((sender) => evHandler(sender,someData)); because there's no such thing as Object.assignHandler in the literal sense. So I did a little more Googling and found this example. The answer by Peter Duniho was the one that clicked in my head (this is not my work):
snip
The usual approach is to use an anonymous method with an event handler
that has your modified signature. For example:
void Onbutton_click(object sender, EventArgs e, int i) { ... }
button.Click += delegate(object sender, EventArgs e)
{ Onbutton_click(sender, e, 172); };
Of course, you don't have to pass in 172, or even make the third parameter
an int. :)
/snip
Using that example I was able to pass in two custom ComboBoxItem objects to a Timer.Elapsed event using lambda notation:
simulatorTimer.Elapsed +=
(sender, e) => onTimedEvent(sender, e,
(ComboBoxItem) cbPressureSetting.SelectedItem,
(ComboBoxItem) cbTemperatureSetting.SelectedItem);
and then into it's handler:
static void onTimedEvent(object sender, EventArgs e, ComboBoxItem pressure, ComboBoxItem temperature)
{
Console.WriteLine("Requested pressure: {0} PSIA\nRequested temperature: {1}° C", pressure, temperature);
}
This isn't any new code from the examples above, but it does demonstrate how to interpret them. Hopefully someone like me finds it instructive & useful so they don't spend hours trying to understand the concept like I did.
This code works in my project (except for a non-thread-safe exception with the ComboBoxItem objects that I don't believe changes how the example works). I'm figuring that out now.
Captured variables:
private void setup(string someData)
{
Object.assignHandler((sender,args) => {
evHandler(sender, someData);
});
}
public void evHandler(Object sender, string someData)
{
// use someData here
}
Or (C# 2.0 alternative):
Object.assignHandler((EventHandler)delegate(object sender,EventArgs args) {
evHandler(sender, someData);
});
you can try doing this:
string yourObject;
theClassWithTheEvent.myEvent += (sender, model) =>
{
yourObject = "somthing";
}
My question that was similar was marked a duplicate so thought I'd add an answer here since it won't let me on my question.
class Program
{
delegate void ComponentEventHandler(params dynamic[] args);
event ComponentEventHandler onTest;
static void Main(string[] args)
{
Program prg = new Program();
// can be bound to event and called that way
prg.onTest += prg.Test;
prg.onTest.Invoke("What", 5, 12.0);
Console.ReadKey();
}
public void Test(params dynamic[] values)
{
// assign our params to variables
string name = values[0];
int age = values[1];
double value = values[2];
Console.WriteLine(name);
Console.WriteLine(age);
Console.WriteLine(value);
}
}
Well, the simplest method id to make someData a member variable like so:
public class MyClass
{
private string _eventData;
private void setup(string someData)
{
_eventData = someData;
Object.assignHandler(evHandler);
}
public void evHandler()
{
// do something with _eventData here
}
}
I'm not sure that's the best way to do it, but it really depends on the event type, the object, etc.
You could create a custom object having additional properties based on Object:
class CustomObject : Object
{
public string SomeData;
}
private void setup(string someData)
{
CustomObject customObject = new CustomObject { SomeData = someData };
CustomObject.assignHandler(evHandler);
}
public void evHandler(Object sender)
{
string someData = ((CustomObject)sender).SomeData;
}
If the data should not be changed anymore after initialization, you could also add a custom constructor, for example.
Here is my one-line solution that pass extra parameters to a timer handler.
private void OnFailed(uint errorCode, string message)
{
ThreadPoolTimer.CreateTimer((timer) => {
UI.ErrorMessage = string.Format("Error: 0x{0:X} {1}", errorCode, message);
}, System.TimeSpan.FromMilliseconds(100));
}
This solution offers a way to pass extra parameters to an event handler while still allowing to unsubscibe:
Within the Subscribe() function of my example I create an Action that invokes a lambda function that supplies my event handler with the event args and my extra parameter. I then store this Action in a dictionary. When I want to unsubscribe, I can use the stored Actions to do so.
This works, I read the length of listeners before and after unsubscribing and it did decrease - you can unsubscribe again without problems.
public class Player
{
public Action<JumpInfo> OnJump;
}
public class PlayerJumpListener
{
public List<Player> MyPlayerList;
private Dictionary<Player, Action<JumpInfo>> _jumpActionsByPlayer = new Dictionary<Player, Action<JumpInfo>>();
private void Subscribe()
{
foreach (Player player in MyPlayerList)
{
Action<JumpInfo> playerJumpAction = (jumpInfo) => HandlePlayerJump(jumpInfo, player);
player.OnJump += playerJumpAction;
_jumpActionsByPlayer.Add(player, playerJumpAction);
}
}
private void Unsubscibe()
{
foreach (KeyValuePair<Player, Action<JumpInfo>> kvp in _jumpActionsByPlayer)
{
kvp.Key.OnJump -= kvp.Value;
}
}
private void HandlePlayerJump(JumpInfo jumpInfo, Player player)
{
// player jumped
}
}
I scoured the internet before a coworker kindly helped me, and boy I felt dumb. Brackets is the solution for the EventHandler.
Ex.
event EventHandler<(int, bool)> EventName;
and then pick it up with:
private void Delegate_EventName(object sender, (int, bool) e)
you can then access the info:
var temp = e.Item1;<br>
var temp2 = e.Item2;<br>
or you can add names as you would expect for parameters and call them via e:
private void Delegate_EventName(object sender, (int num, bool val) e)
you can then access the info:
var temp = e.num;
var temp2 = e.val;

Callback with varying number of parameters [duplicate]

Let's say I want to pass some extra data when assigning an event handler. Consider the following code:
private void setup(string someData)
{
Object.assignHandler(evHandler);
}
public void evHandler(Object sender)
{
// need someData here!!!
}
How would I go about getting someData into my evHandler method?
private void setup(string someData)
{
Object.assignHandler((sender) => evHandler(sender,someData));
}
public void evHandler(Object sender, string someData)
{
// need someData here!!!
}
I had a hard time figuring out #spender's example above especially with: Object.assignHandler((sender) => evHandler(sender,someData)); because there's no such thing as Object.assignHandler in the literal sense. So I did a little more Googling and found this example. The answer by Peter Duniho was the one that clicked in my head (this is not my work):
snip
The usual approach is to use an anonymous method with an event handler
that has your modified signature. For example:
void Onbutton_click(object sender, EventArgs e, int i) { ... }
button.Click += delegate(object sender, EventArgs e)
{ Onbutton_click(sender, e, 172); };
Of course, you don't have to pass in 172, or even make the third parameter
an int. :)
/snip
Using that example I was able to pass in two custom ComboBoxItem objects to a Timer.Elapsed event using lambda notation:
simulatorTimer.Elapsed +=
(sender, e) => onTimedEvent(sender, e,
(ComboBoxItem) cbPressureSetting.SelectedItem,
(ComboBoxItem) cbTemperatureSetting.SelectedItem);
and then into it's handler:
static void onTimedEvent(object sender, EventArgs e, ComboBoxItem pressure, ComboBoxItem temperature)
{
Console.WriteLine("Requested pressure: {0} PSIA\nRequested temperature: {1}° C", pressure, temperature);
}
This isn't any new code from the examples above, but it does demonstrate how to interpret them. Hopefully someone like me finds it instructive & useful so they don't spend hours trying to understand the concept like I did.
This code works in my project (except for a non-thread-safe exception with the ComboBoxItem objects that I don't believe changes how the example works). I'm figuring that out now.
Captured variables:
private void setup(string someData)
{
Object.assignHandler((sender,args) => {
evHandler(sender, someData);
});
}
public void evHandler(Object sender, string someData)
{
// use someData here
}
Or (C# 2.0 alternative):
Object.assignHandler((EventHandler)delegate(object sender,EventArgs args) {
evHandler(sender, someData);
});
you can try doing this:
string yourObject;
theClassWithTheEvent.myEvent += (sender, model) =>
{
yourObject = "somthing";
}
My question that was similar was marked a duplicate so thought I'd add an answer here since it won't let me on my question.
class Program
{
delegate void ComponentEventHandler(params dynamic[] args);
event ComponentEventHandler onTest;
static void Main(string[] args)
{
Program prg = new Program();
// can be bound to event and called that way
prg.onTest += prg.Test;
prg.onTest.Invoke("What", 5, 12.0);
Console.ReadKey();
}
public void Test(params dynamic[] values)
{
// assign our params to variables
string name = values[0];
int age = values[1];
double value = values[2];
Console.WriteLine(name);
Console.WriteLine(age);
Console.WriteLine(value);
}
}
Well, the simplest method id to make someData a member variable like so:
public class MyClass
{
private string _eventData;
private void setup(string someData)
{
_eventData = someData;
Object.assignHandler(evHandler);
}
public void evHandler()
{
// do something with _eventData here
}
}
I'm not sure that's the best way to do it, but it really depends on the event type, the object, etc.
You could create a custom object having additional properties based on Object:
class CustomObject : Object
{
public string SomeData;
}
private void setup(string someData)
{
CustomObject customObject = new CustomObject { SomeData = someData };
CustomObject.assignHandler(evHandler);
}
public void evHandler(Object sender)
{
string someData = ((CustomObject)sender).SomeData;
}
If the data should not be changed anymore after initialization, you could also add a custom constructor, for example.
Here is my one-line solution that pass extra parameters to a timer handler.
private void OnFailed(uint errorCode, string message)
{
ThreadPoolTimer.CreateTimer((timer) => {
UI.ErrorMessage = string.Format("Error: 0x{0:X} {1}", errorCode, message);
}, System.TimeSpan.FromMilliseconds(100));
}
This solution offers a way to pass extra parameters to an event handler while still allowing to unsubscibe:
Within the Subscribe() function of my example I create an Action that invokes a lambda function that supplies my event handler with the event args and my extra parameter. I then store this Action in a dictionary. When I want to unsubscribe, I can use the stored Actions to do so.
This works, I read the length of listeners before and after unsubscribing and it did decrease - you can unsubscribe again without problems.
public class Player
{
public Action<JumpInfo> OnJump;
}
public class PlayerJumpListener
{
public List<Player> MyPlayerList;
private Dictionary<Player, Action<JumpInfo>> _jumpActionsByPlayer = new Dictionary<Player, Action<JumpInfo>>();
private void Subscribe()
{
foreach (Player player in MyPlayerList)
{
Action<JumpInfo> playerJumpAction = (jumpInfo) => HandlePlayerJump(jumpInfo, player);
player.OnJump += playerJumpAction;
_jumpActionsByPlayer.Add(player, playerJumpAction);
}
}
private void Unsubscibe()
{
foreach (KeyValuePair<Player, Action<JumpInfo>> kvp in _jumpActionsByPlayer)
{
kvp.Key.OnJump -= kvp.Value;
}
}
private void HandlePlayerJump(JumpInfo jumpInfo, Player player)
{
// player jumped
}
}
I scoured the internet before a coworker kindly helped me, and boy I felt dumb. Brackets is the solution for the EventHandler.
Ex.
event EventHandler<(int, bool)> EventName;
and then pick it up with:
private void Delegate_EventName(object sender, (int, bool) e)
you can then access the info:
var temp = e.Item1;<br>
var temp2 = e.Item2;<br>
or you can add names as you would expect for parameters and call them via e:
private void Delegate_EventName(object sender, (int num, bool val) e)
you can then access the info:
var temp = e.num;
var temp2 = e.val;

C# Copying and pasting an object

So I'm trying to copy and paste an object and having trouble getting it right. I've searched through the topics but I still can't seem to get it to work. Here is the code:
In one solution in Visual studio I have the the class:
namespace test4
{
[Serializable]
public class copypaste
{
public string test = "a";
}
}
and the copy part of the code:
private void btn1_Click(object sender, EventArgs e)
{
var copy_obj = new copypaste();
DataObject d = new DataObject(copy_obj);
Clipboard.SetDataObject(d);
}
And in another solution I have:
namespace test4
{
[Serializable]
public class copypaste
{
public string test = "a";
}
}
and the paste part of the code:
private void btnTest_Click(object sender, EventArgs e)
{
var d = Clipboard.GetDataObject();
if (d.GetDataPresent("test4.copypaste"))
{
var o = d.GetData("test4.copypaste");
Debug.WriteLine( ( (copypaste)o ).test );
}
}
However, I end up with the following error on the final line:
'System.InvalidCastException: 'Unable to cast object of type 'System.IO.MemoryStream' to type 'test4.copypaste'.'
I have gone through other questions which suggest this way of copy/pasting code but none seem to return memory stream when they call the GetData method. I am unsure how to extract the object from the memory stream.
Thanks
With this reference in mind and with your serializable class, this works as expected:
private void copyButton_Click(object sender, EventArgs e)
{
DataFormats.Format myFormat = DataFormats.GetFormat("test4.copypaste");
var copy_obj = new copypaste();
DataObject myDataObject = new DataObject(myFormat.Name, copy_obj);
Clipboard.SetDataObject(myDataObject);
}
private void pasteButton_Click(object sender, EventArgs e)
{
var d = Clipboard.GetDataObject();
if (d.GetDataPresent("test4.copypaste"))
{
var o = d.GetData("test4.copypaste");
Debug.WriteLine(((copypaste)o).test);
}
}

Get textbox.Text from FORM to CLASS

I have tried to get the textbox.text to a class and it doesent work what am I am doing wrong please help!
In my form.cs it looks like this:
public string score1;
public void getPlayerOneScore1Input()
{
score1 = playerOneScore1TextBox.Text;
}
public void playerOneAddScoreButton_Click(object sender, EventArgs e)
{
score1Calculator theCalculator = new score1Calculator(score1);
}
and in my CLASS it looks like this:
class score1Calculator
{
public score1Calculator(string score1)
{
this.score1= score1;
}
public int playerOneDart1Value;
public void calculateDart1()
{
if (score1== "t1" || score1== "T1" || score1== "3")
{
playerOneDart1Value = 3;
}
else
{
MessageBox.Show("Dart 1! This is not a valid input!");
return;
}
}
}
error i get:
'WindowsFormApplication1.score1Calculator' does not contain a definition for 'player' and no extension method 'player' accepting a first argument of type 'WindowsFormApplication1.score1Calculator' could be found (are you missing a using directive or an assembly reference?)
There is no need to do it overly complicated. A Textbox.Text value is just a string. You can directly call the constructor with this reference.
Just write it like this
score1Calculator theCalculator = new dart1Calculator(playerOneScore1TextBox.Text);
No need to store the value on module level.
you dont call getPlayerOneScore1Input() in order the score1 to be assigned, in Form1 try:
public void playerOneAddScoreButton_Click(object sender, EventArgs e)
{
getPlayerOneScore1Input();
score1Calculator theCalculator = new dart1Calculator(score1);
}
On button click you are not calling your function getPlayerOneScore1Input() which actually assign value to score1.
public void playerOneAddScoreButton_Click(object sender, EventArgs e)
{
getPlayerOneScore1Input();
score1Calculator theCalculator = new dart1Calculator(score1);
}
Instead of assigning value to score1 in form class and assign it to your class member field. You may try this.
public void playerOneAddScoreButton_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(playerOneScore1TextBox.Text))
{
score1Calculator theCalculator = new dart1Calculator(playerOneScore1TextBox.Text);
}
}

C# passing string between voids

All i want to do is pass a string from one void to another.
private void getFilename2()
{
if (textBox2.TextLength.Equals("0"))
{
}
else
{
string inputString = textBox2.Text.ToString();
string last = inputString.Substring(inputString.LastIndexOf('\\') + 1);
string[] filename2 = last.Split('.');
}
}
private void button1_Click(object sender, EventArgs e)
{
getFilename1();
getFilename2();
string filez = filename2;
}
I know this doesn't work but I'm very unfamiliar with how to move strings around in voids.
You should replace your getFilename2 function with
Path.GetFileNameWithoutExtension(textBox2.Text)
Your best bet would be to use a class field/property, or a function that returns a value.
string filez = GetFilename2();
private string GetFilename2() {
{
if (textBox2.TextLength.Equals("0")) return "";
string inputString = textBox2.Text.ToString();
string last = inputString.Substring(inputString.LastIndexOf('\\') + 1);
return last.Split('.');
}
You could pass the string by reference as a parameter to your functions
private void button1_Click(object sender, EventArgs e)
{
string fileName;
getFilename1(ref string fileName);
}
private void getFilename1(ref string fileName)
{
// Whatever you do with fileName here will be reflected in the other function
}
Let's start with the name of your method: getFilename2.
The prefix of "get" implies the method should have a return type
A more appropriate name may be SetFileName
I'm assuming there is a getFileName1 method that is retrieving the file name from textBox1 and has the exact same code as getFileName2, but uses textBox1 instead of textBox2. This would be a good place to refactor your code and create a common method that can be reused:
private string GetFileName(string str)
{
if (string.IsNullOrEmpty(str)) return string.Empty;
string last = str.Substring(str.LastIndexOf('\\') + 1);
return last.Split('.');
}
But, we can refactor again and just use a built-in .NET method:
private string GetFileName(string str)
{
return Path.GetFileNameWithoutExtension(str);
}
And now that there is a common method, we can re-use it as needed:
private void button1_Click(object sender, EventArgs e)
{
string filez = GetFileName(textBox2.Text);
}
Now we have a method of GetFileName(); all it is doing is calling a built-in .NET method of GetFileNameWithoutExtension(). So, instead of even having a method, we should just use the built-in .NET method for returning a file name:
private void button1_Click(object sender, EventArgs e)
{
string filez = Path.GetFileNameWithoutExtension(textBox2.Text);
}
Now, let's look at passing a string from one void to another. Typically, you'd want to do this with an internal field or property. Since I'm partial to properties, I'll use them as an example:
private string FileName1 {get; set;}
private string FileName2 {get; set;}
private void SetFileName1()
{
FileName1 = Path.GetFileNameWithoutExtension(textBox1.Text);
}
private void SetFileName2()
{
FileName2 = Path.GetFileNameWithoutExtension(textBox2.Text);
}
private void button1_Click(object sender, EventArgs e)
{
SetFileName1();
SetFileName2();
string filez1 = FileName1;
string filez2 = FileName2;
}
However, if you did not want to use internal fields or properties, you could set the values by ref as answered by Rachel
If you're passing strings around, ideally you should be explicitly passing them around. IE: make your functions take and/or return the values they'll work with, especially if the return values aren't intended to be used by anything but the code that calls getFilename2. If you can't do that, however, you can declare a private string filename1 = null; public string[] filename2 = null inside the class, but outside any of your methods.
If you go that route, make sure to remove any string filename1 or string[] filename2 from your methods, or you'll end up declaring a local variable with the same name (and never setting the instance variables).
You can store it in a class level variable. In that way it can be accessed by any function.

Categories