"The name 'modToSend' does not exist in the current context" - c#

I have this simple piece of coding in my Homecontroller.cs, but I receive the error message on the last line, saying "The name 'modToSend' does not exist in the current context". How is that possible? Only in the last line is it not known????
public class HomeController : Controller, IDisposable
{
private MvcEShop2.WcfEshop2Service.Eshop2ServiceClient proxy = null;
private String GetDuration(DateTime startdatum, DateTime einddatum)
{
String maand1 = startdatum.Month.ToString("MMMM");
String maand2 = einddatum.Month.ToString("MMMM");
String duration = "";
if (maand1 == maand2)
{
duration = startdatum.Day.ToString()
+ " - " + einddatum.Day.ToString()
+ " " + maand1
+ " " + startdatum.Year.ToString();
}
else
{
duration = startdatum.Day.ToString()
+ startdatum.Month.ToString("MMMM")
+ " - " + einddatum.Day.ToString()
+ " " + einddatum.Month.ToString("MMMM")
+ " " + startdatum.Year.ToString();
}
return duration;
}
public HomeController()
{
proxy = new MvcEShop2.WcfEshop2Service.Eshop2ServiceClient();
}
struct EventStruct
{
public SEvent Event { get; set; }
public String Duration { get; set; }
};
public ActionResult Index()
{
List<SEvent> modFromWcf = proxy.GetAllEventsByPeriod(#System.DateTime.Now.Year, #System.DateTime.Now.Year + 1, "EN").ToList();
List<EventStruct> modTosend = new List<EventStruct>();
foreach (SEvent item in modFromWcf)
{
EventStruct ES;
ES.Event = item;
ES.Duration = GetDuration(item.StartDate ,item.EndDate);
modTosend.Add(ES);
};
return View("Index", modToSend);
}
}

If that's a direct copy & paste from your code, check the case of the 'S' in your parameter to the View being returned.

Related

C# Iterate through nested properties using IEnumerator

I have seen examples (and official ones) for IEnumerator on lists and arrays or dicts, but I have a different problem. I have classes with properties, how may I implement the IEnumerable and IEnumerator in that case?
My properties classes are:
public class standardMessage
{
public messageProperties message { get; set; }
public messageFlag flag { get; set; }
}
public class messageProperties
{
public string messageSubject { get; set; }
public string messageBody { get; set; }
}
public class messageFlag
{
public Boolean flagImportant { get; set; }
public Boolean flagPersonal { get; set; }
}
And this is the Program:
public class Program
{
static void Main(string[] args)
{
standardMessage myMessage = new standardMessage();
myMessage.message = new messageProperties
{
messageSubject = "Greetings",
messageBody = "Happy Weekend"
};
myMessage.flag = new messageFlag
{
flagImportant = false,
flagPersonal = true
};
//how do I iterate through all properties, without knowing how many are there, instead of writing this worm line of code?
Console.WriteLine(myMessage.message.messageSubject.ToString() + "\r\n" + myMessage.message.messageBody.ToString() + "\r\n" + myMessage.flag.flagImportant.ToString() + "\r\n" + myMessage.flag.flagPersonal.ToString());
Console.ReadLine();
}
}
If you want a production-grade way of printing your objects as a formatted string, you need to go and override ToString in all your classes to return whatever format you want.
However, if you just want to print the things on screen for debugging or logging purposes, why not JSON?
public static string ToJson(object #object) =>
System.Text.Json.JsonSerializer.Serialize(#object, new JsonSerializerOptions{WriteIndented = true});
Console.WriteLine(ToJson(myMessage));
Prints
{
"message": {
"messageSubject": "Greetings",
"messageBody": "Happy Weekend"
},
"flag": {
"flagImportant": false,
"flagPersonal": true
}
}
Quick and dirty, but quick and working.
I made a very primitive object to json converter. I wouldn't use this in production and it's about 30% slower than Newtonsoft but it get's the job done.
private static string PrintObject(object obj, int depth = 1)
{
var type = obj.GetType();
if (type.IsPrimitive || type == typeof(Decimal) || type == typeof(String))
return "\"" + obj.ToString() + "\"";
var props = type.GetProperties();
string ret = "";
for (var i = 0; i < props.Length; i++)
{
var val = props[i].GetValue(obj);
ret += new string('\t', depth) + "\"" + props[i].Name + "\":" + PrintObject(val, depth + 1);
if (i != props.Length - 1)
ret += "," + Environment.NewLine;
}
return ("{" + Environment.NewLine + ret + Environment.NewLine + new string('\t', depth - 1) + "}").Replace("\t", " ");
}
Gives the result
{
"message":{
"messageSubject":"Greetings",
"messageBody":"Happy Weekend"
},
"flag":{
"flagImportant":"False",
"flagPersonal":"True"
}
}

Can I send SQlite database data in Xamarin Forms to Wear application

I have a SQlite based Xamarin Forms application on my Android Phone and Wear device. Syncing between my Phone and my Wear watch is performed according to my answer to another Question.
My database has the folowing tables Match and MatchStat:
public class Match
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public DateTime MatchDate { get; set; }
public TimeSpan MatchTime { get; set; }
public string Home { get; set; }
public string Guest { get; set; }
public int HomeScore { get; set; }
public int GuestScore { get; set; }
public bool Active { get; set; }
public bool Done { get; set; }
public string HomeColor { get; set; }
public string GuestColor { get; set; }
public Match()
{ }
}
public class MatchStat
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public int MatchId { get; set; }
public int ActionMin { get; set; }
public int HomeScore { get; set; }
public int GuestScore { get; set; }
public string ActionItem { get; set; }
public string PlayerName { get; set; }
public MatchStat()
{ }
}
If I want to sync my Match and all the MatchStat data from one device to the other I am doing it by mapping the data as strings in my MainActivity:
public async static void SendNewMatch(Match match, string path)
{
if (!client.IsConnected)
client.Connect();
await Task.Delay(200);
try
{
var request = PutDataMapRequest.Create(path);
var map = request.DataMap;
if (match != null)
{
map.PutString("Device", device);
map.PutString("Item", "AddMatch");
map.PutString("Home", match.Home);
map.PutString("Guest", match.Guest);
map.PutString("Active", match.Active.ToString());
map.PutString("Done", match.Done.ToString());
map.PutString("GuestScore", match.GuestScore.ToString());
map.PutString("HomeScore", match.HomeScore.ToString());
map.PutString("Date", match.MatchDate.Date.ToString());
map.PutString("Time", match.MatchTime.ToString());
map.PutLong("UpdatedAt", DateTime.UtcNow.Ticks);
await WearableClass.DataApi.PutDataItem(client, request.AsPutDataRequest());
}
request.UnregisterFromRuntime();
}
catch
{ }
finally
{
client.Disconnect();
}
}
public async static void SendMatchStat(MatchStat matchstat, Match match, int matchstatsize, string path)
{
if (!client.IsConnected)
client.Connect();
await Task.Delay(200);
try
{
var request = PutDataMapRequest.Create(path);
var map = request.DataMap;
MatchHelper mh = new MatchHelper();
if (matchstat != null)
{
map.PutString("Device", device);
map.PutString("Item", "MatchStat");
map.PutString("Home", match.Home);
map.PutString("Date", match.MatchDate.Date.ToString());
map.PutString("Time", match.MatchTime.ToString());
map.PutString("ActionItem", matchstat.ActionItem);
map.PutString("ActionMin", matchstat.ActionMin.ToString());
map.PutString("GuestScore", matchstat.GuestScore.ToString());
map.PutString("HomeScore", matchstat.HomeScore.ToString());
map.PutString("MatchStatSize", matchstatsize.ToString());
//map.PutString("PlayerName", matchstat.PlayerName.ToString());
map.PutLong("UpdatedAt", DateTime.UtcNow.Ticks);
await WearableClass.DataApi.PutDataItem(client, request.AsPutDataRequest());
}
request.UnregisterFromRuntime();
}
catch
{ }
finally
{
client.Disconnect();
}
}
public void ProcessMessage(Intent intent)
{
if (intent.GetStringExtra("Device") != device)
{
switch (intent.GetStringExtra("Item"))
{
case "AddMatch":
{
AddMatch(intent);
break;
}
case "MatchStat":
{
InsertMatchStat(intent);
break;
}
}
}
}
private void AddMatch(Intent intent)
{
MatchHelper mh = new MatchHelper();
if (bool.Parse(intent.GetStringExtra("Active")))
{
ObservableCollection<Match> activeMatches = mh.GetActiveMatches();
foreach (Match activeMatch in activeMatches)
{
mh.InactivateMatch(activeMatch);
}
}
Match newmatch = new Match();
newmatch.Home = intent.GetStringExtra("Home");
newmatch.Guest = intent.GetStringExtra("Guest");
newmatch.HomeColor = intent.GetStringExtra("HomeColor");
newmatch.GuestColor = intent.GetStringExtra("GuestColor");
newmatch.Active = bool.Parse(intent.GetStringExtra("Active"));
newmatch.Done = bool.Parse(intent.GetStringExtra("Done"));
newmatch.HomeScore = int.Parse(intent.GetStringExtra("HomeScore"));
newmatch.GuestScore = int.Parse(intent.GetStringExtra("GuestScore"));
newmatch.Active = bool.Parse(intent.GetStringExtra("Active"));
newmatch.Done = bool.Parse(intent.GetStringExtra("Done"));
newmatch.MatchDate = DateTime.Parse(intent.GetStringExtra("Date"));
newmatch.MatchTime = TimeSpan.Parse(intent.GetStringExtra("Time"));
mh.InsertMatch(newmatch);
}
private void InsertMatchStat(Intent intent)
{
MatchHelper mh = new MatchHelper();
Match match = mh.GetSpecificMatch(intent.GetStringExtra("Home"), DateTime.Parse(intent.GetStringExtra("Date")), TimeSpan.Parse(intent.GetStringExtra("Time")));
if (match != null)
{
MatchStat machstat = new MatchStat();
machstat.MatchId = match.Id;
machstat.ActionItem = intent.GetStringExtra("ActionItem");
machstat.ActionMin = int.Parse(intent.GetStringExtra("ActionMin"));
machstat.GuestScore = int.Parse(intent.GetStringExtra("GuestScore"));
machstat.HomeScore = int.Parse(intent.GetStringExtra("HomeScore"));
machstat.PlayerName = intent.GetStringExtra("PlayerName");
mh.InsertMatchStat(machstat);
}
}
In my WearService I have my OnDataChanged:
public override void OnDataChanged(DataEventBuffer dataEvents)
{
var dataEvent = Enumerable.Range(0, dataEvents.Count)
.Select(i => dataEvents.Get(i).JavaCast<IDataEvent>())
.FirstOrDefault(x => x.Type == DataEvent.TypeChanged && x.DataItem.Uri.Path.Equals(_syncPath));
if (dataEvent == null)
return;
//get data from wearable
var dataMapItem = DataMapItem.FromDataItem(dataEvent.DataItem);
var map = dataMapItem.DataMap;
Intent intent = new Intent();
intent.SetAction(Intent.ActionSend);
intent.PutExtra("Device", map.GetString("Device"));
intent.PutExtra("Item", map.GetString("Item"));
switch (map.GetString("Item"))
{
case "AddMatch":
{
intent.PutExtra("Home", map.GetString("Home"));
intent.PutExtra("Guest", map.GetString("Guest"));
intent.PutExtra("HomeColor", map.GetString("HomeColor"));
intent.PutExtra("GuestColor", map.GetString("GuestColor"));
intent.PutExtra("Active", map.GetString("Active"));
intent.PutExtra("Done", map.GetString("Done"));
intent.PutExtra("HomeScore", map.GetString("HomeScore"));
intent.PutExtra("GuestScore", map.GetString("GuestScore"));
intent.PutExtra("Date", map.GetString("Date"));
intent.PutExtra("Time", map.GetString("Time"));
LocalBroadcastManager.GetInstance(this).SendBroadcast(intent);
break;
}
case "MatchStat":
{
intent.PutExtra("Home", map.GetString("Home"));
intent.PutExtra("Date", map.GetString("Date"));
intent.PutExtra("Time", map.GetString("Time"));
intent.PutExtra("ActionItem", map.GetString("ActionItem"));
intent.PutExtra("ActionMin", map.GetString("ActionMin"));
intent.PutExtra("GuestScore", map.GetString("GuestScore"));
intent.PutExtra("HomeScore", map.GetString("HomeScore"));
intent.PutExtra("PlayerName", map.GetString("PlayerName"));
LocalBroadcastManager.GetInstance(this).SendBroadcast(intent);
break;
}
}
}
Instead of sending the data via separate strings I want to send my Match data as database file (if necessary as .ToString). Is it possible to achieve this and how can I thereafter retrieve the data.
Second of all I have my MatchStats as a list (IEnumerable or ObservableCollection). Is it possible to send this as a list or do I have to send each MatchStat seperately. By sending the Matchstats seperately my other device will not receive them in the desired order and not all MatchStats are received.
Instead of sending database data as database file I now solved this by sending the Matchstats in one file instead of sending all seperate data.
public async static void SendMatchStats(ObservableCollection<MatchStat> matchstats, Match match, int matchstatsize, string path)
{
if (!client.IsConnected)
client.Connect();
await Task.Delay(80);
try
{
var request = PutDataMapRequest.Create(path);
var map = request.DataMap;
MatchHelper mh = new MatchHelper();
int cnt = 1;
if (matchstatsize != 0)
{
map.PutString("Device", device);
map.PutString("Item", "MatchStats");
map.PutString("Home", match.Home);
map.PutString("Date", match.MatchDate.Date.ToString());
map.PutString("Time", match.MatchTime.ToString());
map.PutString("MatchStatSize", matchstatsize.ToString());
map.PutString("Path", path);
foreach (MatchStat matchstat in matchstats)
{
map.PutString("ActionItem" + cnt.ToString(), matchstat.ActionItem);
map.PutString("ActionMin" + cnt.ToString(), matchstat.ActionMin.ToString());
map.PutString("Color" + cnt.ToString(), matchstat.Color);
//map.PutString("ColorSchemeId", matchstat.ColorSchemeId.ToString());
map.PutString("GuestScore" + cnt.ToString(), matchstat.GuestScore.ToString());
map.PutString("HomeScore" + cnt.ToString(), matchstat.HomeScore.ToString());
if (matchstat.PlayerName == null)
map.PutString("PlayerName" + cnt.ToString(), "");
else
map.PutString("PlayerName" + cnt.ToString(), matchstat.PlayerName.ToString());
cnt++;
}
map.PutLong("UpdatedAt", DateTime.UtcNow.Ticks);
await WearableClass.DataApi.PutDataItem(client, request.AsPutDataRequest());
}
request.SetUrgent();
request.UnregisterFromRuntime();
}
catch
{ }
finally
{
client.Disconnect();
}
}
In my WearService I have my OnDataChanged:
case "MatchStats":
{
int size = int.Parse(map.GetString("MatchStatSize"));
intent.PutExtra("Home", map.GetString("Home"));
intent.PutExtra("Date", map.GetString("Date"));
intent.PutExtra("Time", map.GetString("Time"));
intent.PutExtra("MatchStatSize", map.GetString("MatchStatSize"));
intent.PutExtra("Path", map.GetString("Path"));
for (int cnt = 1; cnt <= size; cnt++)
{
intent.PutExtra("ActionItem" + cnt.ToString(), map.GetString("ActionItem" + cnt.ToString()));
intent.PutExtra("ActionMin" + cnt.ToString(), map.GetString("ActionMin" + cnt.ToString()));
intent.PutExtra("Color" + cnt.ToString(), map.GetString("Color" + cnt.ToString()));
intent.PutExtra("GuestScore" + cnt.ToString(), map.GetString("GuestScore" + cnt.ToString()));
intent.PutExtra("HomeScore" + cnt.ToString(), map.GetString("HomeScore" + cnt.ToString()));
intent.PutExtra("PlayerName" + cnt.ToString(), map.GetString("PlayerName" + cnt.ToString()));
Console.WriteLine("PutExtra " + map.GetString("ActionMin" + cnt.ToString()) + " min " + map.GetString("HomeScore" + cnt.ToString()) + "-" + map.GetString("GuestScore" + cnt.ToString()));
Console.WriteLine("GetStringExtra " + intent.GetStringExtra("ActionMin" + cnt.ToString()) + " min " + intent.GetStringExtra("HomeScore" + cnt.ToString()) + "-" + intent.GetStringExtra("GuestScore" + cnt.ToString()));
}
LocalBroadcastManager.GetInstance(this).SendBroadcast(intent);
break;
}
And in MainActivity I am processing the data in a seperate void InsertMatchstats:
private void InsertMatchStats(Intent intent)
{
MatchHelper mh = new MatchHelper();
Match match = mh.GetSpecificMatch(intent.GetStringExtra("Home"), DateTime.Parse(intent.GetStringExtra("Date")), TimeSpan.Parse(intent.GetStringExtra("Time")));
int size = int.Parse(intent.GetStringExtra("MatchStatSize"));
if (match != null)
{
for (int cnt = 1; cnt <= size; cnt++)
{
MatchStat matchstat = new MatchStat
{
MatchId = match.Id,
ActionItem = intent.GetStringExtra("ActionItem" + cnt.ToString()),
ActionMin = int.Parse(intent.GetStringExtra("ActionMin" + cnt.ToString())),
Color = intent.GetStringExtra("Color" + cnt.ToString()),
//ColorSchemeId = int.Parse(intent.GetStringExtra("ColorSchemeId"));
GuestScore = int.Parse(intent.GetStringExtra("GuestScore" + cnt.ToString())),
HomeScore = int.Parse(intent.GetStringExtra("HomeScore" + cnt.ToString())),
PlayerName = intent.GetStringExtra("PlayerName" + cnt.ToString()),
Sync = true
};
if (matchstat.Color == null)
matchstat.Color = "#FFFFFF";
MatchStat checkMatchStat = mh.CheckMatchStat(matchstat.HomeScore, matchstat.GuestScore, matchstat.ActionItem, matchstat.MatchId);
if (checkMatchStat == null)
mh.InsertMatchStat(matchstat);
else
{
checkMatchStat.ActionMin = matchstat.ActionMin;
checkMatchStat.Color = matchstat.Color;
//checkMatchStat.ColorSchemeId = matchstat.ColorSchemeId;
checkMatchStat.PlayerName = matchstat.PlayerName;
mh.UpdateMatchStat(checkMatchStat);
}
Console.WriteLine("PutExtra " + intent.GetStringExtra("ActionMin" + cnt.ToString()) + " min " + intent.GetStringExtra("HomeScore" + cnt.ToString()) + "-" + intent.GetStringExtra("GuestScore" + cnt.ToString()));
}
SendBack(intent.GetStringExtra("Path"));
}
}
Using this method the syncing is much faster and more precise. No data is lost and all data is received and processed in the right order.

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

String.ToString() method on null String Object

I have the following code:
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
//Your code goes here
var obj=(person)Activator.CreateInstance(typeof(person));
Console.WriteLine(obj);
}
}
public class person
{
public int id { get; set; }
public string name { get; set; }
public DateTime dob { get; set; }
public override string ToString()
{
return id.ToString() + " " + name + " " + dob.ToString();
}
}
}
which yields the following output:
0 1/1/0001 12:00:00 AM
However, if change the person.ToString() to the following:
public override string ToString()
{
return id.ToString() + " " + name.ToString() + " " + dob.ToString();
}
I get the following error:
System.NullReferenceException: Object reference not set to an instance of an object.
at Rextester.person.ToString()
Can someone shed some light on it.
Edited
I'm guessing your code samples aren't correct as it stands in your question and you're actually seeing this behavior:
return id.ToString() + " " + name + " " + dob.ToString();
works
return id.ToString() + " " + name.ToString() + " " + dob.ToString();
doesn't work
This is because adding a null value to a string is legal but calling a method on a null instance is not.
See this question:
Why is adding null to a string legal?

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