String remains null even after putting data - c#

I am new to windows metro apps and totally stuck here. textbox1.text displaying the accurate data inside the function but Aya remains null outside the function. How can i solve this problem ? I think recursion is creating problem but how to solve it ?
public async void Aya_Parse()
{
// Initialize http client.
HttpClient httpClient = new HttpClient();
Stream stream = await httpClient.GetStreamAsync("some link");
// Load html document from stream provided by http client.
HtmlDocument htmlDocument = new HtmlDocument();
htmlDocument.OptionFixNestedTags = true;
htmlDocument.Load(stream);
Aya_ParseHtmlNode(htmlDocument.DocumentNode);
}
int aia = 0;
string Aya = null;
private void Aya_ParseHtmlNode(HtmlNode htmlNode)
{
foreach (HtmlNode childNode in htmlNode.ChildNodes)
{
if (childNode.NodeType == HtmlNodeType.Text && aia == 1)
{
Aya += " " + childNode.InnerText.ToString(); aia = 0;
}
else if (childNode.NodeType == HtmlNodeType.Element)
{
Aya += " "; // removing this causes null exception at textbox1.text
switch (childNode.Name.ToLower())
{
case "span":
Aya += childNode.NextSibling.InnerText.ToString();
Aya_ParseHtmlNode(childNode);
break;
case "td":
aia = 1;
Aya_ParseHtmlNode(childNode);break;
default:
Aya_ParseHtmlNode(childNode); break;
}
}
}
textBox1.Text = Aya;
}

You never assign a starting value to Aya, so even though you try to add text to it in your Aya_ParseHtmlNode(HtmlNode htmlNode) method, you can't add text to a null value. This can be fixed by doing a check for null on the value and setting it to a default. I'm surprised you aren't getting a NullArgumentException inside your method...
public async void Aya_Parse()
{
// Initialize http client.
HttpClient httpClient = new HttpClient();
Stream stream = await httpClient.GetStreamAsync("some link");
// Load html document from stream provided by http client.
HtmlDocument htmlDocument = new HtmlDocument();
htmlDocument.OptionFixNestedTags = true;
htmlDocument.Load(stream);
// greetingOutput.Text = htmlDocument.DocumentNode.InnerText.ToString();
// Parse html node, this is a recursive function which call itself until
// all the childs of html document has been navigated and parsed.
Aya_ParseHtmlNode(htmlDocument.DocumentNode);
}
int aia = 0;
string Aya = null;
private void Aya_ParseHtmlNode(HtmlNode htmlNode)
{
if (Aya == null)
{
Aya = String.empty;
}
foreach (HtmlNode childNode in htmlNode.ChildNodes)
{
if (childNode.NodeType == HtmlNodeType.Text && aia == 1)
{
Aya += " " + childNode.InnerText.ToString(); aia = 0;
}
else if (childNode.NodeType == HtmlNodeType.Element)
{
Aya += " ";
switch (childNode.Name.ToLower())
{
case "span":
Aya += childNode.NextSibling.InnerText.ToString();
Aya_ParseHtmlNode(childNode);
break;
case "td":
aia = 1;
Aya_ParseHtmlNode(childNode);break;
default:
Aya_ParseHtmlNode(childNode); break;
}
}
}
textBox1.Text = Aya;
}
Using a StringBuilder might also be a better idea here since you could recurse and generate a very large string here, so a StringBuilder would be a easier on your memory
public void Aya_Parse()
{
// Initialize http client.
HttpClient httpClient = new HttpClient();
Stream stream = httpClient.GetStreamAsync("some link").Result;
// Load html document from stream provided by http client.
HtmlDocument htmlDocument = new HtmlDocument();
htmlDocument.OptionFixNestedTags = true;
htmlDocument.Load(stream);
// greetingOutput.Text = htmlDocument.DocumentNode.InnerText.ToString();
// Parse html node, this is a recursive function which call itself until
// all the childs of html document has been navigated and parsed.
//you marked the method Async, and
//since Aya is in the class, if multiple threads call this
//method, you could get inconsistent results
//I have changed it to a parameter here so this doesn't happen
StringBuilder Aya = new StringBuilder()
Aya_ParseHtmlNode(htmlDocument.DocumentNode, Aya);
//I would also move your textbox update here, so you aren't calling
//ToString() all the time, wasting all of the memory benefits
textBox1.Text = Aya.ToString();
}
int aia = 0;
private void Aya_ParseHtmlNode(HtmlNode htmlNode, StringBuilder Aya)
{
foreach (HtmlNode childNode in htmlNode.ChildNodes)
{
if (childNode.NodeType == HtmlNodeType.Text && aia == 1)
{
Aya.Append(childNode.InnerText); aia = 0;
}
else if (childNode.NodeType == HtmlNodeType.Element)
{
Aya.Append(" ");
switch (childNode.Name.ToLower())
{
case "span":
Aya.Append(childNode.NextSibling.InnerText);
Aya_ParseHtmlNode(childNode, Aya);
break;
case "td":
aia = 1;
Aya_ParseHtmlNode(childNode, Aya);break;
default:
Aya_ParseHtmlNode(childNode, Aya); break;
}
}
}
}
Edit: Your issue actually probably comes from your use of the async keyword on Aya_Parse() which means that the method calling Aya_Parse() may return immediately before it actually does any processing. So if you are checking the value of Aya after calling Aya_Parse(), it likely has not had enough time to do the computation before you actually check the value elsewhere in your code. I recommend removing the async tag, or changing Aya_Parse() to return the value of Aya when it finishes. Check here for some good info on how to use the async tag with return values.

It could be. It's behaving as if your string variable is passed into the method by value rather than holding the reference.
Keep in mind that by using Async methods you are effectively multi threading, so multiple threads would be contending for the same module level variable. The compiler is likely choosing to make your code threadsafe for you.
If you declare a separate string inside your async method and pass it in by ref is should behave as you expect.
I would also suggest you do the same with your module level int.
OR... you could remove the async from the Aya_Parse and use the Task library (and toss in a Wait call below) to get your stream.

Related

Returning an API response as JSON from C# to angular

I am returning data from API but when I try to parse it as a JSON in Angular ts it says "Argument of type 'Subscription' is not assignable to parameter of type 'string'", what I want to do is to get the json response from API as [{name:"name1"},{name:"name2"}] rather than [{"name":"name1"},{"name":"name2"}] which doesnt write the name on csv file
[HttpGet("getEmployees")]
[ProducesResponseType(200, Type = typeof(IEnumerable<EmployeesView>))]
public async Task<IActionResult> GetEmployeesByCreateDate(DateTime period)
{
try
{
// read model returns users by a logic as enumerable
return Ok(await _readModel.GetEmployees(period));
}
catch (Exception e)
{
// throw exception
}
myService.ts
getAllPosts() {
return this.http.get<IEmployee[]>(this.URL).subscribe((data: any) => {return data;});
}
download(data, filename='data') {
let csvData=this.ConvertToCSV(data, ['name1','name2']);
let blob = new Blob(['\ufeff' + csvData],{type:'text/csv;charset=utf8;'});
let dwldLink = document.createElement("a");
let url = URL.createObjectURL(blob);
dwldLink.setAttribute("href", url);
dwldLink.setAttribute("download", filename + ".csv");
dwldLink.style.visibility = "hidden";
document.body.appendChild(dwldLink);
dwldLink.click();
}
ConvertToCSV(objArray, headerList) {
let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
let str = '';
let row = 'S.No,';
for (let index in headerList) {
row += headerList[index] + ',';
}
row = row.slice(0, -1);
str += row + '\r\n';
for (let i = 0; i < array.length; i++) {
let line = i + 1 + '';
for (let index in headerList) {
let head = headerList[index];
line += ',' + array[i][head];
}
str += line + '\r\n';
}
return str;
}
myComponent.ts
JsonData = JSON.parse( this.URL.getAllPosts());
download2(){ this.URL.download(this.JsonData, 'jsontocsv'); } //here is the problem
I want to return my data as :
[
{
name:"name1",
surname:"surname1"
},
{
name:"name2",
surname:"surname2"
}
]
But instead I get it like this (I need it in format as above becuase I am downloading the data I get as CSV)
[
{
"name":"name1",
"surname":"surname1"
},
{
"name":"name2",
"surname":"surname2"
}
]
The return value from subscribe() is a Subscription, which is used to unsubscribe later. subscribe() does not return your data, it saves your callback function for executing later, once it receives a response. Unsubscribing from a simple http request is not necessary since it will complete after the first response.
You can either do whatever you want to do inside your callback function, or you can use async, await, and firstValueFrom() to get more synchronous looking code.
Also, you don't need to parse it, this is done automatically through the HttpClient service.
async getAllPosts(): Promise<IEmployee[]> {
return await firstValueFrom(this.http.get<IEmployee[]>(this.URL));
}
JsonData = await this.URL.getAllPosts();
OR
getAllPosts(): Observable<IEmployee[]> {
return this.http.get<IEmployee[]>(this.URL);
}
this.URL.getAllPosts().subscribe((data) => JsonData = data);
Following your edits, this solution should work for you:
In your service
async getAllPosts(): Promise<IEmployee[]> {
return await firstValueFrom(this.http.get<IEmployee[]>(this.URL));
}
In your component
async download2() {
this.URL.download(await this.URL.getAllPosts(), 'jsontocsv');
}
I see another issue with your download function, you have:
let csvData = this.ConvertToCSV(data, ['name1','name2'])
When it should be:
let csvData = this.ConvertToCSV(data, ['name', 'surname']);
To implement using callbacks instead of promises:
In your service
getAllPosts(): Observable<IEmployee[]> {
return this.http.get<IEmployee[]>(this.URL);
}
In your component
download2() {
this.URL.getAllPosts().subscribe((data) => this.URL.download(data, 'jsontocsv'));
}

C# Deadlock in Named Pipe

Im stuck. I have joined the project that uses Named Pipes, and have lets say "not ideal architecture". And seems like I accidentally received a deadlock:(
The logic is following. There is Named Pipe. Client and Server model. On server part there is a loop, that always pings named pipe and process what client sends, sometimes sending back responses.
On Client side of my pipe, I have following method, from other developer, that is being used to send request to server and receive and return the response.
private object locker = new Object();
private string ListenOnce(string msg)
{
Debug.WriteLine("Will listen for message " + msg);
string msgFrom = "";
if (run) {
string toReturn = "";
lock (locker) {
sw.WriteLine(msg); //Writing command to the pipes
stream.WaitForPipeDrain(); //Waiting for another process to read the command
msgFrom = sr.ReadLine(); //Reading
toReturn = sr.ReadLine ();
if (toReturn.Contains('¥'))
{
string[] split = toReturn.Split('¥');
if (split.Length > 1)
{
var roomNames = this.connection.application.GameCache.GetRoomNames();
for (int i = 1; i < split.Length; i++)
{
string[] split2 = split[i].Split('¶');
if (split2.Length > 1)
{
string accountName = split2[0];
int offenderActorID = int.Parse(split2[1]);
string offenderRoomName = split2[2];
foreach (var roomName in roomNames)
{
Room room;
if (this.connection.application.GameCache.TryGetRoomWithoutReference(roomName, out room))
{
Game game = room as Game;
if (game != null && game.Name == offenderRoomName)
{
GameClientPeer peer = (GameClientPeer)game.ActorsManager.ActorsGetActorByNumber(offenderActorID).Peer;
if (peer != null)
{
peer.KickPlayer();
}
}
}
}
}
}
}
}
}
if (toReturn.Contains('¥'))
{
return toReturn.Split('¥')[0];
}
else
{
return toReturn;
}
}
return "";
}
The problem is - in some cases I cant receive response from pipe right when requested, and need to start what I called here "poller". This is a task, that loops 5 times, and during those 5 times "polls" the pipe through this ListenOnce method.
private void PollTargets()
{
timer.Dispose();
Debug.WriteLine("Going to start polling");
Task.Factory.StartNew(() => {
int runCount = 0;
while (true)
{
runCount++;
PipeOperation request = new PipeOperation(Consts.Pipes.RequestTargets, uniqueID);
string responseStr = unityConnection.client.SendMessage(JsonConvert.SerializeObject(request));
Debug.WriteLine("Task is running, response is " + responseStr);
if (!string.IsNullOrEmpty(responseStr))
{
try
{
PipeOperation pipeResponse = JsonConvert.DeserializeObject<PipeOperation>(responseStr);
if (!string.IsNullOrEmpty(pipeResponse.Payload))
{
GrenadeExplosionData explosionData = JsonConvert.DeserializeObject<GrenadeExplosionData>(pipeResponse.Payload);
if (explosionData != null)
{
//probably need to invoke that in main thread
DealDamage(explosionData);
//isRunning = false;
Debug.WriteLine("Received nice response, will damage targets");
break;
}
}
}
catch (Exception exc)
{
Debug.WriteLine("Something went wrong while polling...");
Debug.WriteLine(exc.Message);
break;
}
}
if (runCount > 5)
{
Debug.WriteLine("run count exceed " + runCount.ToString());
break;
}
}
RemoveGrenadeFromUnityConnection();
});
}
I am starting poller when the Grenade explodes, from timer like that:
timer = new System.Threading.Timer((obj) =>
{
PollTargets();
},
null, 4000, System.Threading.Timeout.Infinite);
And thats it. After people play 2-3 hrs. Seems like I receive a deadlock. It should be taken into account that there might be many grenades on server who starts that poller, so probably it just goes mad at some point over there.
Pls help, Im stuck with that. Who has ideas?
We should keep in mind, that
sw.WriteLine(msg); //Writing command to the pipes
stream.WaitForPipeDrain();
msgFrom = sr.ReadLine(); //Reading
toReturn = sr.ReadLine ();
should be used only by one thread at a time, as stream might be read only from one source.
There are several calls to ListenOnce from the code, but not a lot. One is being fired every 4 minutes.The rest ones are not constant, but conditional.
Hope somebody would see where is a mistake here...
Found what locks everything...However, it does not help a lot:)
Its
stream.WaitForPipeDrain();
it tries to read another end of pipe, but because of there is no timeouts in message mode, it just hangs for ever..

Regex XML parsing C#

I am trying to build a regex parser for a single XML block.
I know people will say that Regex is not a good plan for xml, but I am working with stream data and I just need to know if a complete xml block has been broadcast and is sitting in the buffer.
I am trying to handle for anything between the Opening and closing blocks of the XML and any data in parameters of the main block header.
My example code is below the broken down Regular Expression, if anyone has any input on how to make this as comprehensive as possible I would greatly appreciate it.
Here is my regular expression formatted for visual aid.
I am balancing the group, as well as the group and validating that they do not exist at the end of the expression segments.
/*
^(?<TAG>[<]
(?![?])
(?<TAGNAME>[^\s/>]*)
)
(?<ParamData>
(
(\"
(?>
\\\"|
[^"]|
\"(?<quote>)|
\"(?<-quote>)
)*
(?(quote)(?!))
\"
)|
[^/>]
)*?
)
(?:
(?<HASCONTENT>[>])|
(?<-TAG>
(?<TAGEND>/[>])
)
)
(?(HASCONTENT)
(
(?<CONTENT>
(
(?<inTAG>[<]\<TAGNAME>)(?<-inTAG>/[>])?|
(?<-inTAG>[<]/\<TAGNAME>[>])|
([^<]+|[<](?![/]?\<TAGNAME>))
)*?
(?(inTAG)(?!))
)
)
(?<TAGEND>(?<-TAG>)[<]/\<TAGNAME>[>])
)
(?(TAG)(?!))
*/
Within my class, I expect that any Null object returned means there was no xml block on the queue.
Here is the class I am using.
(I used a literal string (#"") to limit the escape requirements, All " characters were replaced with "" to format properly.
public class XmlDataParser
{
// xmlObjectExpression defined below to limit code highlight errors
private Regex _xmlRegex;
private Regex xmlRegex
{
get
{
if (_xmlRegex == null)
{
_xmlRegex = new Regex(xmlObjectExpression);
}
return _xmlRegex;
}
}
private string backingStore = "";
public bool HasObject()
{
return (backingStore != null) && xmlRegex.IsMatch(backingStore);
}
public string GetObject()
{
string result = null;
if (HasObject())
{
lock (this)
{
Match obj = xmlRegex.Match(backingStore);
result = obj.Value;
backingStore = backingStore.Substring(result.Length);
}
}
return result;
}
public void AddData(byte[] bytes)
{
lock (this)
{
backingStore += System.Text.Encoding.Default.GetString(bytes);
}
}
private static string xmlObjectExpression = #"^(?<TAG>[<](?![?])(?<TAGNAME>[^\s/>]*))(?<ParamData>((\""(?>\\\""|[^""]|\""(?<quote>)|\""(?<-quote>))*(?(quote)(?!))\"")|[^/>])*?)(?:(?<HASCONTENT>[>])|(?<-TAG>(?<TAGEND>/[>])))(?(HASCONTENT)((?<CONTENT>((?<inTAG>[<]\<TAGNAME>)(?<-inTAG>/[>])?|(?<-inTAG>[<]/\<TAGNAME>[>])|([^<]+|[<](?![/]?\<TAGNAME>)))*?(?(inTAG)(?!))))(?<TAGEND>(?<-TAG>)[<]/\<TAGNAME>[>]))(?(TAG)(?!))";
}
Just use XmlReader and feed it a TextReader. To read streams, you want to change the ConformanceLevel to Fragment.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlReader reader = XmlReader.Create(tr,settings))
{
while (reader.Read())
{
switch (reader.NodeType)
{
// this is from my code. You'll rewrite this part :
case XmlNodeType.Element:
if (t != null)
{
t.SetName(reader.Name);
}
else if (reader.Name == "event")
{
t = new Event1();
t.Name = reader.Name;
}
else if (reader.Name == "data")
{
t = new Data1();
t.Name = reader.Name;
}
else
{
throw new Exception("");
}
break;
case XmlNodeType.Text:
if (t != null)
{
t.SetValue(reader.Value);
}
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
break;
case XmlNodeType.Comment:
break;
case XmlNodeType.EndElement:
if (t != null)
{
if (t.Name == reader.Name)
{
t.Close();
t.Write(output);
t = null;
}
}
break;
case XmlNodeType.Whitespace:
break;
}
}
}

Massive differences in reexecution

I wrote a little C# application that indexes a book and executes a boolean textretrieval algorithm on the index. The class at the end of the post showes the implementation of both, building the index and executing the algorithm on it.
The code is called via a GUI-Button in the following way:
private void Execute_Click(object sender, EventArgs e)
{
Stopwatch s;
String output = "-----------------------\r\n";
String sr = algoChoice.SelectedItem != null ? algoChoice.SelectedItem.ToString() : "";
switch(sr){
case "Naive search":
output += "Naive search\r\n";
algo = NaiveSearch.GetInstance();
break;
case "Boolean retrieval":
output += "boolean retrieval\r\n";
algo = BooleanRetrieval.GetInstance();
break;
default:
outputTextbox.Text = outputTextbox.Text + "Choose retrieval-algorithm!\r\n";
return;
}
output += algo.BuildIndex("../../DocumentCollection/PilzFuehrer.txt") + "\r\n";
postIndexMemory = GC.GetTotalMemory(true);
s = Stopwatch.StartNew();
output += algo.Start("../../DocumentCollection/PilzFuehrer.txt", new String[] { "Pilz", "blau", "giftig", "Pilze" });
s.Stop();
postQueryMemory = GC.GetTotalMemory(true);
output += "\r\nTime elapsed:" + s.ElapsedTicks/(double)Stopwatch.Frequency + "\r\n";
outputTextbox.Text = output + outputTextbox.Text;
}
The first execution of Start(...) runs about 700µs, every rerun only takes <10µs.
The application is compiled with Visual Studio 2010 and the default 'Debug' buildconfiguration.
I experimentad a lot to find the reason for that including profiling and different implementations but the effect always stays the same.
I'd be hyppy if anyone could give me some new ideas what I shall try or even an explanation.
class BooleanRetrieval:RetrievalAlgorithm
{
protected static RetrievalAlgorithm theInstance;
List<String> documentCollection;
Dictionary<String, BitArray> index;
private BooleanRetrieval()
: base("BooleanRetrieval")
{
}
public override String BuildIndex(string filepath)
{
documentCollection = new List<string>();
index = new Dictionary<string, BitArray>();
documentCollection.Add(filepath);
for(int i=0; i<documentCollection.Count; ++i)
{
StreamReader input = new StreamReader(documentCollection[i]);
var text = Regex.Split(input.ReadToEnd(), #"\W+").Distinct().ToArray();
foreach (String wordToIndex in text)
{
if (!index.ContainsKey(wordToIndex))
{
index.Add(wordToIndex, new BitArray(documentCollection.Count, false));
}
index[wordToIndex][i] = true;
}
}
return "Index " + index.Keys.Count + "words.";
}
public override String Start(String filepath, String[] search)
{
BitArray tempDecision = new BitArray(documentCollection.Count, true);
List<String> res = new List<string>();
foreach(String searchWord in search)
{
if (!index.ContainsKey(searchWord))
return "No documents found!";
tempDecision.And(index[searchWord]);
}
for (int i = 0; i < tempDecision.Count; ++i )
{
if (tempDecision[i] == true)
{
res.Add(documentCollection[i]);
}
}
return res.Count>0 ? res[0]: "Empty!";
}
public static RetrievalAlgorithm GetInstance()
{
Contract.Ensures(Contract.Result<RetrievalAlgorithm>() != null, "result is null.");
if (theInstance == null)
theInstance = new BooleanRetrieval();
theInstance.Executions++;
return theInstance;
}
}
Cold/warm start of .Net application is usually impacted by JIT time and disk access time to load assemblies.
For application that does a lot of disk IO very first access to data on disk will be much slower than on re-run for the same data due to caching content (also applies to assembly loading) if data is small enough to fit in memory cache for the disk.
First run of the task will be impacted by disk IO for assemblies and data, plus JIT time.
Second run of the same task without restart of application - just reading data from OS memory cache.
Second run of application - reading assemblies from OS memory cache and JIT again.

Unhandled exception, unable to debug

I'm trying to debug my c# application that check MIPS syntax. But its not allowing be to debug it. No matter where I enter my break point it gets ignored, including the first line of the Main() function. Its also throwing me this error.
'add a b c' works fine if i don't call HasValidParams()
'add a b' throws exception in the same situation
neither works when calling HasValidParams()
program.cs
private static void Main(string[] args)
{
var validator = new MipsValidator();
Console.Write("Please enter a MIPS statement: ");
string input = Console.ReadLine();
List<string> arguments = input.Split(new char[0]).ToList();
Response status = validator.IsSyntaxValid(arguments);
//Check syntax
if (status.Success.Equals(true))
{
Response stat = validator.HasValidParams(arguments);
//Check parameters
if (stat.Success.Equals(true))
{
Console.WriteLine(string.Format("'{0}' is a valid mips instruction ", input));
}
else
{
foreach (var reason in stat.Reasons)
{
Console.WriteLine(reason);
}
}
}
else
{
foreach (string reason in status.Reasons)
{
Console.WriteLine(reason);
}
}
}
mips-validator.cs
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace mips_validator.utils
{
public class MipsValidator : IMipsValidator
{
#region Implementation of IMipsValidator
public Response IsSyntaxValid(List<string> args)
{
var response = new Response {Success = true};
var op = (Operator) Enum.Parse(typeof (Operator), args[0]);
switch (op)
{
case Operator.addi:
case Operator.add:
case Operator.beq:
if (args.Count != 4)
{
response.Reasons.Add(string.Format("4 operands required for {0}, {1} parameters provided.",
op, args.Count));
response.Success = false;
}
break;
case Operator.j:
if (args.Count != 2)
{
response.Reasons.Add(string.Format("1 operands required for {1}, {0} parameters provided.",
args.Count, op));
response.Success = false;
}
break;
default:
response.Reasons.Add(string.Format("{0} is an unknown mips operation", op));
response.Success = false;
break;
}
return response;
}
public Response HasValidParams(List<string> parameters)
{
string op1, op2, op3;
var temporary = new Regex(#"/\$t\d+/");
var store = new Regex(#"/\$s\d+/");
var zero = new Regex(#"/\$zero/");
var osReserved = new Regex(#"/\$k0|1/");
var memory = new Regex(#"");
var constant = new Regex(#"/-?\d*/");
var label = new Regex(#"/.*\:/");
Operator operation;
var response = new Response {Success = true};
string opString = parameters[0];
Enum.TryParse(opString.Replace("$", string.Empty), true, out operation);
switch (operation)
{
case Operator.add:
{
op1 = parameters[1];
op2 = parameters[2];
if (!temporary.IsMatch(op1) && !store.IsMatch(op1) && !zero.IsMatch(op1))
{
response.Reasons.Add(string.Format("{0}: error register expected", op1));
response.Success = false;
}
if (!temporary.IsMatch(op2) && !store.IsMatch(op2) && !zero.IsMatch(op2))
{
response.Reasons.Add(string.Format("{0}: error register expected", op2));
response.Success = false;
}
}
break;
case Operator.addi:
{
op1 = parameters[1];
op2 = parameters[2];
if (!temporary.IsMatch(op1) && !store.IsMatch(op1) && !zero.IsMatch(op1))
{
response.Reasons.Add(string.Format("{0}: error register expected", op1));
response.Success = false;
}
if (!constant.IsMatch(op2) && !zero.IsMatch(op2))
{
response.Reasons.Add(string.Format("{0}: error constant expected", op2));
response.Success = false;
}
}
break;
case Operator.beq:
{
op1 = parameters[1];
op2 = parameters[2];
op3 = parameters[3];
if (!temporary.IsMatch(op1) && !store.IsMatch(op1) && !zero.IsMatch(op1))
{
response.Reasons.Add(string.Format("{0}: error register expected", op1));
response.Success = false;
}
if (!temporary.IsMatch(op2) && !store.IsMatch(op2) && !zero.IsMatch(op2))
{
response.Reasons.Add(string.Format("{0}: error register expected", op2));
response.Success = false;
}
if (!label.IsMatch(op3) && !constant.IsMatch(op3))
{
response.Reasons.Add(string.Format("{0}: error label or constant expected", op3));
response.Success = false;
}
}
break;
}
return response;
}
#endregion
}
}
SOLUTION-------
Response.cs(old)
public class Response
{
public List<string> Reasons;
public bool Success = true;
}
Response.cs(current)
public class Response
{
public Response()
{
Reasons = new List<string>();
Success = true;
}
public List<string> Reasons;
public bool Success = true;
}
I can't tell if you're looking for a way to be able to debug your project or if you'd prefer to be told potential issues in your code.
For the latter:
Make sure Response.Reasons is initialized by the constructor of Response (or a field initializer).
You're not showing the Response class, so make sure Reasons is actually set to a collection you can add to and not left to the default, null.
Edit: The below possible cause for a crash was pointed put by #nodakai not to be one at all; turns out an empty char array is a special case to split on whitespace.
*You calculate arguments by doing
List arguments = input.Split(new char[0]).ToList();
...which as far as I can tell does absolutely nothing except put the original string inside a List. You probably want to split on new char[] {' '} instead to split on spaces.*
Check if your breakpoint looks like this:
If it does, your source code differs from the code the assembly was actually compiled with. Make sure your project is built properly (right click on the solution and select "Rebuild") and check your current configuration:
Hope this helps...

Categories