An unhandled exception of type 'System.StackOverflowException' occurred and few different issues with toString first [duplicate] - c#

This question already has answers here:
Why does Property Set throw StackOverflow exception?
(3 answers)
Closed 3 years ago.
I have been working on this all day and can't figure out why I can't pull this to print of the main class, keeps throwing an error
An unhandled exception of type 'System.StackOverflowException' occurred
I've tried a few things now and nothing. It works to pull my list from on another class, but I can replicate it. Sorry about code been adjusting a lot
using System;
using System.Collections.Generic;
namespace MpaintV2.Customer
{
public class Trade
{
public String TradeName { get; set; }
public String TradeAddress { get; set; }
public String TradePhone { get; set; }
public Double PaintCoverage { get; set; }
public String TradeNames { get; set; }
public string RecCal
{
get { return RecCal; }
set { RecCal = RecCal; }
}
public string DataTrade
{
get
{
List<string> FileData = Utilities.Helper.get_file_data();
for (int counter = 0; counter < FileData.Count; counter++)
{
String[] SplitRecord = FileData[counter].Split(',');
if (SplitRecord[0].Equals("Trade"))
{
TradeName = SplitRecord[1];
TradeAddress = SplitRecord[2];
TradePhone = SplitRecord[3];
PaintCoverage = (double.Parse(SplitRecord[4]) / 10.00);
// Console.WriteLine(" " + TradeName + " " + TradeAddress + " " + TradePhone + " " + PaintCoverage + "Paints");
//List<String> TradeFiles = new List<string>();
//TradeNames = String.Join(TradeName, TradeFiles[500]);
}
}
//TradeFiles = TradeName.Insert.TradeFiles;
RecCal = TradeNames + TradeAddress + TradePhone + PaintCoverage + "otherthings";
return RecCal;
}
}
public override string ToString()
{
return base.ToString();
}
}
}

Set RecCal to just { get; set; } as suggested or add a backing field and change the right hand side of the setter to value (keyword). This will let you modify the value during get/set
private string _recCal;
public string RecCal
{
get { return _recCal; }
set { _recCal = value; }
}

Related

C# parse textual file in a specific format

I have never done something like this so I'm really curious on how this can be performed. I imagine it can be either done via regex or in c# somehow...
I have a textual file with data in following format:
12.23.45.56:8080:username:password
12.23.45.56:8080:username:password
12.23.45.56:8080:username:password
12.23.45.56:8080:username:password
I have prepared a class which looks like following:
public class ParsedData
(
public string IP { get; set; }
public string Port { get; set; }
public string Username { get; set; }
public string Password { get; set; }
)
The desired output how I would like it to be is that I can parse each line individually and 1 line should have the data stored in a parsed object (list of ParsedData);
How could do this, and to parse the each line of data individually ?
Can someone help me out ?
var completedList = text.Split(':').Select(pr => new ParsedData
{
IP = pr.ElementAt(0).ToString() // this should be the IP But I'm getting the
// Index was outside the bounds of the array. exception in this part
/*My elements here*/
}).ToList();
It looks like at least one row doesn't have any data in it, maybe there is an empty row in the input data?
Try printing out each row of data before selecting the first element of the array - then you can see which input is causing the exception.
You may use Regex (.+?):(.+?):(.+?):(.+), here example:
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
namespace Main {
public struct ParsedData {
public string IP { get; set; }
public string Port { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
class Prog {
static List<ParsedData> pdl = new List<ParsedData>();
static string file = #"12.23.425.56:90:kukur:psiar%4
151.23.255.52:3131:Zandga:Ikurit
52.23.45.56:5125:Ningame:Mirsga!#
112.223.45.56:4000:Bisgo:One0ne";
static void Main() {
var re = new Regex(#"(.+?):(.+?):(.+?):(.+)");
foreach (Match m in re.Matches(file)) {
pdl.Add(new ParsedData() { IP = m.Groups[1].Value, Port = m.Groups[2].Value, Username = m.Groups[3].Value, Password = m.Groups[4].Value });
Console.WriteLine("IP: " + m.Groups[1] + " PORT: " + m.Groups[2] + " USR_NM: " + m.Groups[3] + " PASS: " + m.Groups[4]);
}
}
}
}
Also I added an List which contains the data.
class Program
{
static void Main(string[] args)
{
//I think you know how to read the file so:
string text =
#"12.23.45.56:8080:username:password
12.23.45.56:8080:username:password
12.23.45.56:8080:username:password
12.23.45.56:8080:username:password";
List<ParsedData> ps = new List<ParsedData>();
text.Split(new char[] { '\r','\n' }, StringSplitOptions.RemoveEmptyEntries).ToList().ForEach(c =>
{
var cols = c.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries).ToList();
//you can check too if cols have content here
ps.Add(new ParsedData()
{
IP = cols[0]!=null?cols[0]:"", //and check if inside it's content..
Port = cols[1],
Username = cols[2],
Password = cols[3]
});
});
foreach(ParsedData p in ps)
{
Console.WriteLine(p.IP + "\t" + p.Port + "\t" + p.Username + "\t" + p.Password);
}
}
}
public class ParsedData
{
public string IP { get; set; }
public string Port { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
I think you make misunderstood about the pr, it not array now, it the element in the array.
var text = "12.23.45.56:8080:username:password";
var array = text.Split(':');
var data = new ParsedData()
{
IP = array[0],
Port = array[1],
Username = array[2],
Password = array[3]
};

Overload error when adding objects to list

I have written a web service and constructor that adds objects to my list. I am getting an error that makes no sense to me because I am passing in the 3 parameters I should be passing in.
The error is:
There is no argument given that corresponds to the required formal
parameter 'myArticleID' of
'MainPage.GetTileDetails.GetTileDetails(string, string, int)'
Here is my code:
Web Service:
[OperationContract]
List<ViewDetails> ViewDetails();
[DataContract]
public class ViewDetails
{
[DataMember]
public string TitleView { get; set; }
[DataMember]
public string BodyView { get; set; }
[DataMember]
public int ArticleID { get; set; }
public ViewDetails() { }
public ViewDetails(string myTitleView, string myBodyView, int myArticleID)
{
this.TitleView = myTitleView;
this.BodyView = myBodyView;
this.ArticleID = myArticleID;
}
}
Project where i am using web service
public async void ViewData()
{
ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
List<GetTileDetails> tileList = new List<GetTileDetails>();
var res = await client.ViewDetailsAsync();
for (int i = 0; i < res.Count; i++)
{
tileList.Add(new GetTileDetails(res[i].TitleView, res[i].BodyView.Substring(0, 170) + " ..."), res[i].ArticleID);
}
tileGridView.ItemsSource = tileList;
}
public class GetTileDetails
{
public string TitleView { get; set; }
public string BodyView { get; set; }
public int ArticleID { get; set; }
public GetTileDetails() { }
public GetTileDetails(string myTitleView, string myBodyView, int myArticleID)
{
this.TitleView = myTitleView;
this.BodyView = myBodyView;
this.ArticleID = myArticleID;
}
}
Can anyone tell me why I am getting that error? I am passing in (string, string, int)....
Replace this line:
tileList.Add(new GetTileDetails(res[i].TitleView, res[i].BodyView.Substring(0, 170) + " ..."), res[i].ArticleID);
with this one:
tileList.Add(new GetTileDetails(res[i].TitleView, res[i].BodyView.Substring(0, 170) + " ...", res[i].ArticleID));
Note you have a misplaced ) right after " ...").

Results from C# JSON-Deserialization to String

I used json2csharp to generate functions and classes but I am a bloody newbie. What I want is using the Data from the JSON Array and display it in a Textbox.
Here is the Code:
public class Sent_SMS
{
public string status { get; set; }
public string error { get; set; }
public string smslog_id { get; set; }
public string queue { get; set; }
public string to { get; set; }
}
public class RootObject
{
public List<Sent_SMS> data { get; set; }
public object error_string { get; set; }
public int timestamp { get; set; }
}
public void doSendSMS()
{
/* API URLs */
APIURL_Send = "http://ipadressofgateway/playsms/index.php?app=ws&op=pv&h=" + apikey + "&u=" + username + "&to=" + receiver_number + "&msg=" + message; // Sending Message
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString(APIURL_Send);
var SMS_Log = JsonConvert.DeserializeObject<RootObject>(json);
richTextBox3.Text = "SMS has been sent to:" + SMS_Log.data.to + "Status is:" + SMS_Log.data.status;
}
}
But of course.. this does not work cause "SMS_Log.data.to" and "SMS_Log.data.status" is not correct. How to do this right?
Regards
If you're sure there is always exactly one SMS in the response, then change your code to:
richTextBox3.Text = "SMS has been sent to:" + SMS_Log.data[0].to + "Status is:" + SMS_Log.data[0].status;
Otherwise, I'd go for a solution like this:
var text = "";
foreach (var sms in SMS_Log.data) {
text += "SMS has been sent to:" + sms.to + "Status is:" + sms.status + "\n";
}
richTextBox3.Text = text;
SMS_Log.data is a list of Sent_SMS instances, so you'd have to iterate through that list to get each individual message's data.
for(int i=0;i<SMS_Log.data.Count();i++)
{
richTextBox3.Text = "SMS has been sent to:" + SMS_Log.data[i].to + "Status is:" + SMS_Log.data[i].status;
}
Though this would set only the last element as your TextBlock text. Would recommend you to add these into a new List and set this list as a source of GridView or ListView

Displaying all items in another class

My problem is that I have a List<> variable connected to another class, and I want to get all the items from that List<> and put it into a string.
In the result string, i'd like to see callNum, copyNum, content, author, year, title
Here is where I'm trying to put it into a string
public class CItemControl
{
//declare a list variable
private List<CItem> mItems;
private CItem mNewItem;
//a method that instantiates the list
public CItemControl()
{
mItems = new List<CItem>();
}
//attribute to get all items
public List<CItem> Items
{
get { return mItems; }
}
public CItem NewItem
{
get { return mNewItem; }
}
//method to add item to the CItem list
public void AddItem(int callNum, int copyNum, string content, string author, string year)
{
mNewItem = new CItem(callNum, copyNum, content, author, year);
mItems.Add(mNewItem);
}
//method to return all items to a string
public CItem ListAllItems()
{
string allItems;
}
Here is the class where I'm trying to get the items from. There will be variables added later.
class CItem
{
//declare attributes
private string mTitle;
private string mAuthor;
private string mContent;
private string mYear;
private int mCopyNum;
private int mCallNum;
private bool mHold = false;
private bool mBorrowed = false;
private bool mShelf = false;
//overload a constructor
public CItem(int CallNum, int CopyNum, string Content, string Author, string Year)
{
callNum = CallNum;
copyNum = CopyNum;
content = Content;
author = Author;
year = Year;
}
//create the default constructor
public CItem()
{
callNum = 0;
copyNum = 0;
content = "";
author = "";
year = "";
}
//set attributes
public int callNum
{
get { return mCallNum; }
set { mCallNum = value; }
}
public string content
{
get { return mContent; }
set { mContent = value; }
}
public string author
{
get { return mAuthor; }
set { mAuthor = value; }
}
public string year
{
get { return mYear; }
set { mYear = value; }
}
public string title
{
get { return mTitle; }
set { mTitle = value; }
}
public int copyNum
{
get { return mCopyNum; }
set { mCopyNum = value; }
}
public bool hold
{
get { return mHold; }
}
public bool borrowed
{
get { return mBorrowed; }
}
public bool shelf
{
get { return mShelf; }
}
//display information for users
public string displayInfo()
{
return "Call Number: " + callNum + ". Copy Number: " + copyNum + ". Title: " + title +
". Author: " + author + ". Year Published: " + year + ". Content: " + content;
}
//new method to display status of item
public string displayStatus()
{
if (borrowed == true)
return "Item is currently being borrowed.";
if (shelf == true && hold == false)
return "Item is available for borrowing.";
else
return "Item is on hold";
}
Any help is much appreciated!
Thanks in advance.
ListAllItems shall look something like this
public string ListAllItems()
{
var sb = new StringBuilder(); // var is of type StringBuilder
mItems.ForEach(item => sb.Append(item.displayInfo());
return sb.ToString();
}
return String.Join("; ", allItems.Select(item => item.displayInfo()));
You don't provide a lot of informations on how and what informations you want in your result string.
Can't you achieve this objective with a simple loop ?
using System.Text;
(...)
public string ListAllItems()
{
StringBuilder allItems = new StringBuilder();
foreach(CItem itm in Items){
allItems.AppendLine(itm.displayInfo());
}
return allItems.ToString();
}
Stringbuilder is optional but is faster than string concatenation.
I don't normally like to add formatter methods to property bags like this. If you want the flexibility to change have many formatting implementations, you might want to make a seperate class do the formatting.
public interface IFormatter<in T>
{
string Format(T obj);
}
public class CItemFormatter : IFormatter<CItem>
{
public string Format(CItem item)
{
//formatting logic
}
}

Getters and Setters, getting multiple fields

public class Teams : INotifyPropertyChanged
{
public string CombinedTeams
{
get
{
return Combined;
}
set
{
{
CombinedTeams += value;
NotifiyPropertyChanged("Combined");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifiyPropertyChanged(string p)
{
if (null != p)
{
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
}
private string Combined
{
get
{
return " " + HomeTeam + " " + HomeScore + " - " + AwayScore + " " + AwayTeam;
}
set
{
{
Combined += value;
}
}
}
public string HomeTeam { get; set; }
public string AwayTeam { get; set; }
public string HomeScore { get; set; }
public string AwayScore { get; set; }
}
I got a problem, when trying combine my strings together and having one LONG string that contains all the values from when I parse my XML I only get the First set of values,
basically I get
Team1 Score1 : Score2 Team2
as opposed to
Team1 Score1 : Score2 Team2 Team3 Score3 : Score4 Team4 Team5 Score5 : Score6 Team6
I am binding my Control to CombinedTeams
could you guys help me out? I just want to store the previous string and then combine the new string with the old one, I cant see it being hard but this is confusing me and reading up on it makes me more confused...
Thanks,
John
Your code concatenates the new value to an empty string (last = "").
You probably want to concatenate to the previous value.
I'm not sure what you are expecting, last is always initialized to "", so the += is irrelevant.
Seems like the class called Teams is really a game?
And I don't think setting HomeTeam, AwayTeam, HomeScore, AwayScore over and over again (and then saving this internally somehow) is a good way to keep track of multiple games.
Why don't you look at using a collection of games?
Try something like this:
In a GamesLib library:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace GamesLib
{
public class Game
{
public string HomeTeam { get; private set; }
public string AwayTeam { get; private set; }
public string HomeScore { get; private set; }
public string AwayScore { get; private set; }
public string Combined
{
get
{
return " " + HomeTeam + " " + HomeScore + " - " + AwayScore + " " + AwayTeam;
}
}
public Game(string HomeTeam, string AwayTeam, string HomeScore, string AwayScore)
{
this.HomeTeam = HomeTeam;
this.HomeScore = HomeScore;
this.AwayTeam = AwayTeam;
this.AwayScore = AwayScore;
}
}
public class Games : List<Game>, INotifyPropertyChanged
{
public string CombinedTeams
{
get
{
var str = "";
foreach (Game g in this)
{
str += g.Combined;
}
return str;
}
}
public new void Add(Game g)
{
base.Add(g);
if ( PropertyChanged != null ) {
PropertyChanged(this, new PropertyChangedEventArgs("CombinedTeams"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
In a console program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GamesLib;
namespace TestHarness
{
class Program
{
static void Main(string[] args)
{
var gs = new GamesLib.Games();
gs.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(gs_PropertyChanged);
var g = new Game("hometeam", "awayteam", "1", "0");
gs.Add(g);
g = new Game("lions", "bears", "1", "0");
gs.Add(g);
Console.WriteLine("Final result:" + gs.CombinedTeams);
}
static void gs_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
var gs = sender as Games;
Console.WriteLine("Changed: " + gs.CombinedTeams);
}
}
}
The reason you are getting the incorrect results is because you have one property referring to another property, and the second property always returns a specific value.
This block of code, when called from elsewhere, will return the results of some other variable called "Combined" which you have defined below...
public string CombinedTeams
{
get
{
return Combined;
}
...
}
private string Combined
{
get
{
return " " + HomeTeam + " " + HomeScore + " - " + AwayScore + " " + AwayTeam;
}
...
}
Everything else is academic because you're getter(s) essentially always return " " + HomeTeam + " " + HomeScore + " - " + AwayScore + " " + AwayTeam.
I suspect you will want to restructure your code to be something more like this
public class Teams : INotifyPropertyChanged
{
private string Combined; // Backing for CombinedTeams
public string CombinedTeams
{
get
{
return Combined;
}
set
{
// This only concatinates values; Combined will get longer each time.
Combined += value;
// ViewModels should always notify after the vale has changed
NotifyOfPropertyChange("CombinedTeams");
}
}
// Adds a new team, assuming HomeTeam, HomeScore, AwayScore, and AwayTeam have been initialized
public void AddTeam()
{
CombinedTeams = " " + HomeTeam + " " + HomeScore + " - " + AwayScore + " " + AwayTeam;
}
}
Certainly there are better ways to do that, but that should get you a start, I hope.
General rule (broken all the time by the code-ninjas, which is fine) is that a Property shouldn't do any calculations of it's own, it's really there to allow public access to private data in the class.
It might be worthwhile to run through a couple of articles on C# Properties. Here are some suggestions to get you started: http://msdn.microsoft.com/en-us/library/x9fsa0sw(v=vs.80).aspx and http://msdn.microsoft.com/en-us/library/aa288470(v=vs.71).aspx and of course, some Good Search Results

Categories