BGC Tools
Static Public Member Functions | Static Private Member Functions
BGC.IO.FileReader Class Reference

Static Public Member Functions

static bool ReadJsonFile (string path, Action< JsonObject > successCallback, Action failCallback=null, Action fileNotFoundCallback=null, Action< string, Exception > overrideExceptionHandling=null)
 Offers two error callbacks for when a file is not found and for when a file failed to parse correctly, and one for when the file has been succesfully parsed into a json object. With the latter, you can use the parsed object to build out whatever you need. More...
 
static JsonValue ReadJsonStream (TextReader jsonReader, Action< Exception > exceptionHandler=null)
 Tries reading Json from a TextReader and returns the parsed JsonValue. Includes an optional exceptionHandler argument More...
 
static JsonValue SafeReadJsonString (string jsonText, Action< Exception > exceptionHandler=null)
 Tries reading a Json string and returns the parsed JsonValue. Includes an optional exceptionHandler argument. More...
 

Static Private Member Functions

static void HandleException (string path, Exception excp)
 
static void HandleExceptionFiles (string path, string[] errorMessage)
 

Detailed Description

Definition at line 9 of file FileReader.cs.

Member Function Documentation

◆ HandleException()

static void BGC.IO.FileReader.HandleException ( string  path,
Exception  excp 
)
inlinestaticprivate

Definition at line 125 of file FileReader.cs.

126  {
127  string[] errorMessage;
128 
129  if (excp is ParsingException parsingExcp)
130  {
131  errorMessage = new string[]
132  {
133  "Internal parsing error.",
134  "",
135  parsingExcp.Message,
136  "",
137  "Suggested corrective action:",
138  parsingExcp.correctiveAction
139  };
140  }
141  else if (excp is JsonParseException jsonExcp)
142  {
143  errorMessage = new string[]
144  {
145  "JSON parsing error",
146  "",
147  jsonExcp.Message,
148  "",
149  "Error Location:",
150  $"Line {jsonExcp.Position.line + 1}, Column {jsonExcp.Position.column + 1}"
151  };
152  }
153  else
154  {
155  errorMessage = new string[]
156  {
157  "Exception Encountered",
158  "",
159  excp.Message,
160  };
161  }
162 
163  HandleExceptionFiles(path, errorMessage);
164  }
static void HandleExceptionFiles(string path, string[] errorMessage)
Definition: FileReader.cs:166
The exception that is thrown when a JSON message cannot be parsed.

◆ HandleExceptionFiles()

static void BGC.IO.FileReader.HandleExceptionFiles ( string  path,
string []  errorMessage 
)
inlinestaticprivate

Definition at line 166 of file FileReader.cs.

167  {
168  string fileName = Path.GetFileName(path);
169 
170  string directoryPath = Path.GetDirectoryName(path);
171  string directoryName = Path.GetFileName(directoryPath);
172  string errorDirectory = $"Error{directoryName}";
173  string errorDirectoryPath = Path.Combine(Path.GetDirectoryName(directoryPath), errorDirectory);
174  string errorFilePath = Path.Combine(errorDirectoryPath, fileName);
175  string errorLogPath = $"{errorFilePath}_error.txt";
176 
177  if (!Directory.Exists(errorDirectoryPath))
178  {
179  Directory.CreateDirectory(errorDirectoryPath);
180  }
181 
182  if (File.Exists(errorFilePath))
183  {
184  File.Delete(errorFilePath);
185  }
186  File.Move(path, errorFilePath);
187 
188  if (File.Exists(errorLogPath))
189  {
190  File.Delete(errorLogPath);
191  }
192 
193  File.WriteAllLines(errorLogPath, errorMessage);
194  }

◆ ReadJsonFile()

static bool BGC.IO.FileReader.ReadJsonFile ( string  path,
Action< JsonObject successCallback,
Action  failCallback = null,
Action  fileNotFoundCallback = null,
Action< string, Exception overrideExceptionHandling = null 
)
inlinestatic

Offers two error callbacks for when a file is not found and for when a file failed to parse correctly, and one for when the file has been succesfully parsed into a json object. With the latter, you can use the parsed object to build out whatever you need.

There is also an optional override for exception handling.

Parameters
pathFile Path to load
successCallbackExecuted only on successful read
failCallbackNotifies caller of failure
fileNotFoundCallbackNotifies caller of failure to locate file
overrideExceptionHandlingOptionally replaces default exception handling
Returns
Whether the json file was successfully read

Definition at line 24 of file FileReader.cs.

References LightJson.Serialization.JsonReader.ParseFile().

Referenced by BGC.Users.ProfileData.Deserialize(), BGC.Audio.Calibration.Initialize(), and BGC.Study.ProtocolManager.LoadProtocolSet().

30  {
31  bool jsonFileRead = false;
32 
33  try
34  {
35  if (!File.Exists(path))
36  {
37  Debug.LogError($"Unable to find Json file at path \"{path}\"");
38  fileNotFoundCallback?.Invoke();
39  }
40  else
41  {
42  successCallback(JsonReader.ParseFile(path));
43  //If the above callback itself throws an exception, it will be caught here and
44  //ultimately the method will return false.
45  jsonFileRead = true;
46  }
47  }
48  catch (Exception excp)
49  {
50  Debug.LogError($"Error parsing file at {path}: {excp.Message}");
51 
52  failCallback?.Invoke();
53 
54  if (overrideExceptionHandling != null)
55  {
56  overrideExceptionHandling.Invoke(path, excp);
57  }
58  else
59  {
60  HandleException(path, excp);
61  }
62  }
63 
64  return jsonFileRead;
65  }
static void HandleException(string path, Exception excp)
Definition: FileReader.cs:125
static JsonValue ParseFile(string path)
Creates a JsonValue by reading the given file.
Definition: JsonReader.cs:386
Represents a reader that can read JsonValues.
Definition: JsonReader.cs:13
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ReadJsonStream()

static JsonValue BGC.IO.FileReader.ReadJsonStream ( TextReader  jsonReader,
Action< Exception exceptionHandler = null 
)
inlinestatic

Tries reading Json from a TextReader and returns the parsed JsonValue. Includes an optional exceptionHandler argument

Parameters
jsonReaderAs reader containing serialized Json
exceptionHandlerAn optional exception handler
Returns
Whether the json was successfully read

Definition at line 74 of file FileReader.cs.

References LightJson.JsonValue.Null, and LightJson.Serialization.JsonReader.Parse().

77  {
78  Debug.Assert(jsonReader != null);
79 
80  JsonValue parsedJson;
81 
82  try
83  {
84  parsedJson = JsonReader.Parse(jsonReader);
85  }
86  catch (Exception excp)
87  {
88  Debug.LogError($"Error parsing Json by text: {excp.Message}");
89  parsedJson = JsonValue.Null;
90  exceptionHandler?.Invoke(excp);
91  }
92 
93  return parsedJson;
94  }
static readonly JsonValue Null
Represents a null JsonValue.
Definition: JsonValue.cs:20
A wrapper object that contains a valid JSON value.
Definition: JsonValue.cs:13
Represents a reader that can read JsonValues.
Definition: JsonReader.cs:13
Here is the call graph for this function:

◆ SafeReadJsonString()

static JsonValue BGC.IO.FileReader.SafeReadJsonString ( string  jsonText,
Action< Exception exceptionHandler = null 
)
inlinestatic

Tries reading a Json string and returns the parsed JsonValue. Includes an optional exceptionHandler argument.

Parameters
jsonTextAs string containing deserialized Json
exceptionHandlerAn optional exception handler
Returns
Whether the json was successfully read

Definition at line 103 of file FileReader.cs.

References LightJson.JsonValue.Null, and LightJson.Serialization.JsonReader.Parse().

106  {
107  Debug.Assert(string.IsNullOrEmpty(jsonText) == false);
108 
109  JsonValue parsedJson;
110 
111  try
112  {
113  parsedJson = JsonReader.Parse(jsonText);
114  }
115  catch (Exception excp)
116  {
117  Debug.LogError($"Error parsing Json by text: {excp.Message}");
118  parsedJson = JsonValue.Null;
119  exceptionHandler?.Invoke(excp);
120  }
121 
122  return parsedJson;
123  }
static readonly JsonValue Null
Represents a null JsonValue.
Definition: JsonValue.cs:20
A wrapper object that contains a valid JSON value.
Definition: JsonValue.cs:13
Represents a reader that can read JsonValues.
Definition: JsonReader.cs:13
Here is the call graph for this function:

The documentation for this class was generated from the following file: