How do I call this list from another class in C#? - arrays

I am still new to the whole C# thing but I found this code posted from grovesNL about 5 years ago which I believe will work.
namespace DataAccessClass
{
public class FileReader
{
static void Main(string[] args)
{
List<DailyValues> values = File.ReadAllLines("C:\\Users\\Josh\\Sample.csv")
.Skip(1)
.Select(v => DailyValues.FromCsv(v))
.ToList();
}
}
public class DailyValues
{
DateTime Date;
decimal Open;
decimal High;
decimal Low;
decimal Close;
decimal Volume;
decimal AdjClose;
public static DailyValues FromCsv(string csvLine)
{
string[] values = csvLine.Split(',');
DailyValues dailyValues = new DailyValues();
dailyValues.Date = Convert.ToDateTime(values[0]);
dailyValues.Open = Convert.ToDecimal(values[1]);
dailyValues.High = Convert.ToDecimal(values[2]);
dailyValues.Low = Convert.ToDecimal(values[3]);
dailyValues.Close = Convert.ToDecimal(values[4]);
dailyValues.Volume = Convert.ToDecimal(values[5]);
dailyValues.AdjClose = Convert.ToDecimal(values[6]);
return dailyValues;
}
}
}
I am trying to read a csv file skipping the header and get it into a list that is accessible from another class. So my Architecture is DataAccessClass that has a class called FileReader and a class called Values. My task is to read this csv file into class FileReader and then to create an object list to hold it in the class Values. When I go to the Values class to call it I can't figure it out. This is how I am trying to call it. It is saying DailyValues.FromCsv(string) is a method that is not valid.
public List<string> GetList()
{
return DataAccessClass.DailyValues.FromCsv.dailyValues;
}
I want to be able to access this list further up the stack.

Your expression DataAccessClass.DailyValues.FromCsv.dailyValues is the culprit.
DataAccessClass.DailyValues.FromCsv is valid, and references the static method named FromCsv in the class DataAccessClass.DailyValues. But then going on by adding .dailyValues is incorrect. It is a method, nothing to peek into and extract stuff using ..
You could (if that was the intention) call the function, and directly work with the result:
DataAccessClass.DailyValues.FromCsv(some_csv_string) is an expression of type DailyValues. There you could then access - as an example - 'High' with:
DailyValues dv;
dv = DataAccessClass.DailyValues.FromCsv(some_csv_string);
dosomething(dv.High);
But for that to work, High would have to have the visibility of public.

Related

How to store an array to Firebase via Unity SDK

I am trying to store an Int32[] Array and bool[] Array to Firebase but it isn't working for me. I have searched on various places, but couldn't find a solution. Can anyone tell me, how one can store an array to Firebase Real-time DB from Unity.
I am using System.Reflection to get all the public static fields of the class UserPrefs.
Here is the code, I am trying to do this job...
System.Type type = typeof(UserPrefs);
FieldInfo[] fields = type.GetFields();
foreach (var field in fields) {
if (user != null)
dbReference.Child("users").Child(user.UserId).Child(field.Name).SetValueAsync(field.GetValue(null));
else
Debug.LogError("There is no user LoggedIn to write...");
}
Above code saves all values other than arrays. Error given on arrays is following:
InvalidCastException: Cannot cast from source type to destination
type.
Firebase.Database.Internal.Utilities.Validation.ValidateWritableObject
(System.Object object)
Any help will be much appreciated...
You need a class like this.
public class MyClass
{
public int[] intArray = new int[10];
}
Then you can write that object to the Firebase like this.
public void WriteArrays()
{
MyClass temp = new MyClass();
for (int i = 0; i < temp.intArray.Length; i++)
{
temp.intArray[i] = i;
}
databaseReference.Child("MyArrayNode").SetRawJsonValueAsync(JsonUtility.ToJson(temp));
}
databaseReference is a reference to your root.
Same way you can do this for your bool[] also.
For a more general solution you can copy the JsonHelper class which was suggested here.
Example usage:
string jsonArray = JsonHelper.ToJsonArray(mySerializeableList);
var nodeToUpdate = this.dbReference.Child("wantedNode");
nodeToUpdate.SetRawJsonValueAsync(jsonArray);

(Unity) Why is my list of a class not getting saved in JSON

I want to save a list of dialogue items. I made a script called dialogue item which is just one message, I made an array of that so it can be a conversation, and I made a list of that conversation so that I can have multiple conversations.
[SerializeField] public List<DialogueList> dialogue = new List<DialogueList();
So I made this variable of a class named DialogueList, that contains the dialogueitems.
[System.Serializable]
public class DialogueList
{
[SerializeField] public string convoName;
[SerializeField] public int dialogueID;
[SerializeField] public DialogueItem[] dialogues;
}
I want to save these conversations so that I can load them in specific languages in later stages. But for some reason my JSON file is empty when I try to save my variable named dialogue.
string jsonData = JsonUtility.ToJson(dialogue, true);
string _fullPath = "/caroline-dialogue" + ".json";
File.WriteAllText(Application.persistentDataPath + _fullPath, jsonData);
I tried using a different method, that actually works, but it can get really messy.
for (int i = 0; i < dialogue.Count; i++)
{
string jsonData = JsonUtility.ToJson(dialogue[i], true);
string _fullPath = "/caroline-dialogue-" + i + ".json";
File.WriteAllText(Application.persistentDataPath + _fullPath, jsonData);
}
My question is: What am I doing wrong? Am I forgetting something? My guess it that something is wrong with the variable named dialogue, since saving all the dialogueitems with a for loop works.
I hope I explained my problem well enough.
Serialization/deserialization of the arrays or lists is not supported using the JsonUtility. You would need to wrap the list in a serializable class:
[Serializable]
private class DialogueListWrapper
{
public List<DialogueList> objects;
}

Unity3D - how to use arrays with custom inspector code?

I seem to be stuck in a catch 22 situation with the OnInspectorGUI method of Unity's UnityEditor class. I want to name array elements in the inspector for easy editing, currently I'm using, as per the documentation:
public override void OnInspectorGUI()
{
J_Character charScript = (J_Character)target;
charScript.aBaseStats[0] = EditorGUILayout.FloatField("Base Health", charScript.aBaseStats[0]);
}
In my J_Character script I initialise the aBaseStats array like so:
public float[] aBaseStats = new float[35];
The problem is that whenever I try to do anything in the editor (and thus OnInspectorGUI is called) I get an index out of range error pointing to the line
charScript.aBaseStats[0] = EditorGUILayout.FloatField("Base Health", charScript.aBaseStats[0]);
I'm guessing this is because my array is initialized on game start while the editor code is running all the time while developing.
How can I get round this situation?
Many thanks.
You have to initialize aBaseStats in an function that runs only once.
The code below is BAD:
public float[] aBaseStats = new float[35];
void Start(){
}
The code below is GOOD:
public float[] aBaseStats;
void Start(){
aBaseStats = new float[35];
}
Initialize it in an Editor callback function that runs once.
EDIT:
I don't know a Start callback function that will run before the OnInspectorGUI function(). The hack below should work.
public float[] aBaseStats;
bool initialized = false;
public override void OnInspectorGUI()
{
if (!initialized)
{
initialized = true;
aBaseStats = new float[35];
}
J_Character charScript = (J_Character)target;
charScript.aBaseStats[0] = EditorGUILayout.FloatField("Base Health",aBaseStats[0]);
}
As an addition to the answer by Programmer I would like to point you to the following:
http://docs.unity3d.com/ScriptReference/ExecuteInEditMode.html
This seems to be exactly what you are looking for in terms of functionality. (it runs the method even when playmode is not active)
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class ExampleClass : MonoBehaviour {
public Transform target;
void Update() {
if (target)
transform.LookAt(target);
}
}

Autofixture, expected behavior?

Having a test similar to this:
public class myClass
{
public int speed100index = 0;
private List<int> values = new List<int> { 200 };
public int Speed100
{
get
{
return values[speed100index];
}
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var fixture = new Fixture();
var sut = fixture.Create<myClass>();
Assert.AreEqual(sut.Speed100, 200);
}
}
Would have expected this to work, but I can see why it's not. But how do I argue, that this is not a problem with AutoFixture, but a problem with the code?
AutoFixture is giving you feedback about the design of your class. The feedback is, you should follow a more object-oriented design for this class.
Protect your private state, to prevent your class from entering an inconsistent state.
You need to make the speed100index field, private, to ensure it remains consistent with the values List.
Here is what I see if I run debugger on your test:
Autofixture assigns a random number to speed100index field because it is public, and in your array there is nothing at point 53 (from my screenshot)
If you set speed100index to be private, Autofixture will not re-assign the number and your test will pass.

How to deserialize several nested Json arrays (more than 2) using DataContractJsonSerializer (Windows Phone 7)

I need to deserialize the next Json string that has several nested Json arrays:
{"d1":[["11791452",[["980",""]]],["11791453",[["1060",""],["1140",""],["1220",""],["1300",""]]],["11791454",[["1070",""]]]]}
I try to do it in several steps, so far I'm able to deserialize three levels of nested arrays. As follow:
{"aOaOa":[[["1060",""],["1140",""],["1220",""],["1300",""]]]}
public class ThreeSimpleNestedArrays
{
public List<List<string[]>> aOaOa; //array of arrays of arrays
public ThreeSimpleNestedArrays()
{
aOaOa = new List<List<string[]>>();
}
}
But the problem arise when I add the extra string in the array structure:
{"TEST": [["11791453",[["1060",""],["1140",""],["1220",""],["1300",""]]],["123456",[["0","1"],["2","3"]]]]}
public class ComplexNestedArray
{
public List<Dictionary<string,List<string[]> >> TEST;
public ComplexNestedArray()
{
TEST = new List<Dictionary<string, List<string[]>>>();
}
}
I'm getting the next error message:
"Unable to cast object of type 'System.String' to type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]'."
What am I missing?
Can anybody suggest a way to deserialize an object like this nested within Json arrays using DataContractJsonSerializer?
The code I use to deserialize is the next:
//Works
DataContractJsonSerializer dcJsonSer = new DataContractJsonSerializer(typeof(ThreeSimpleNestedArrays));
ThreeSimpleNestedArrays root = (ThreeSimpleNestedArrays)dcJsonSer.ReadObject(str);
//Don't work
DataContractJsonSerializer dcJsonSer = new DataContractJsonSerializer(typeof(ComplexNestedArray));
ComplexNestedArray root = (ComplexNestedArray)dcJsonSer.ReadObject(str);
Btw, I'm able to deserilize the object when it is serilized as a Json Object as follow:
{"TEST": [{"s": "11791453","aOa": [["1060",""],["1140",""],["1220",""],["1300",""]]},{"s": "123456","aOa":[["0","1"],["2","3"]]}]}
using a class with two members (a string "s" and a List of string[] "aOa"), but without the names, when the object is serialized as an array, I'm unable to do it.
Any suggestion?
Ok, it looks like the DataContractJsonSerializer is smarter than I though .
It turns out that the way to deserialize that kid of nested objects array is with a class like this:
public class ComplexNestedArray
{
//{"TEST": [["11791453",[["1060",""],["1140",""],["1220",""],["1300",""]]],["123456",[["0","1"],["2","3"]]]]}
public List<List<object>> TEST { get; set; }
}
After that, it is only a mater to do a couple of for cycles and casts to the appropriate class structure.
Btw, This is a MUST in your toolbox in case you have to deal with Json:
json2csharp
Here is my solution. However I'll try to add later a way for your full json:
class Program {
static void Main(string[] args) {
new Program();
}
public Program() {
string full = "{\"d1\":[[\"11791452\",[[\"980\",\"\"]]],[\"11791453\",[[\"1060\",\"\"],[\"1140\",\"\"],[\"1220\",\"\"],[\"1300\",\"\"]]],[\"11791454\",[[\"1070\",\"\"]]]]}";
string simple1 = "{\"aOa\":[[\"1060\",\"\"],[\"1140\",\"\"],[\"1220\",\"\"],[\"1300\",\"\"]]}";
string simple2 = "{\"aOaOa\":[[[\"1060\",\"\"],[\"1140\",\"\"],[\"1220\",\"\"],[\"1300\",\"\"]]]}";
DataContractJsonSerializer d1 = new DataContractJsonSerializer(typeof(S1));
S1 r1 = (S1)d1.ReadObject(new MemoryStream(Encoding.Default.GetBytes(simple1)));
DataContractJsonSerializer d2 = new DataContractJsonSerializer(typeof(S2));
S2 r2 = (S2)d2.ReadObject(new MemoryStream(Encoding.Default.GetBytes(simple2)));
Console.WriteLine("done");
Console.ReadKey();
}
[DataContract]
class S1 {
[DataMember]
List<List<String>> aOa;
}
[DataContract]
class S2 {
[DataMember]
List<List<List<string>>> aOaOa;
}
}

Resources