public string CreateMatch(MatchData data) { string ret = "{"; try { FileStream file = File.Open(_filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); XDocument xDoc = XDocument.Load(file); counter++; string id = counter.ToString(); XElement newMatch = new XElement("Match"); newMatch.SetAttributeValue("id",id); XElement xHome = new XElement("Home", data.Home); XElement xAway = new XElement("Away", data.Away); XElement xScore = new XElement("Score", data.Score); newMatch.Add(new object[] { xHome, xAway, xScore }); xDoc.Root.Attribute("counter").Value = id; xDoc.Root.Add(newMatch); file.SetLength(0); file.Flush(); xDoc.Save(file); file.Flush(); file.Close(); ret += "\"success\":\"match " + id + " created\""; ret += ",\"match_url\":\"" + OperationContext.Current.EndpointDispatcher.EndpointAddress.Uri.AbsoluteUri + "/Match/" + id + "\"}"; } catch (Exception ex) { ret += "\"error\":\""+ex.Message+"\"}"; } return ret; }
public string UpdateMatch(string id, MatchData data) { string ret = "{"; XElement foundMatch = null; foreach (var match in _matchDetails) if (match.Attribute("id").Value.Equals(id)) { foundMatch = match; break; } if (foundMatch!=null) { XElement newMatch = new XElement("Match"); newMatch.SetAttributeValue("id", id); XElement home = new XElement("Home", data.Home); XElement away = new XElement("Away", data.Away); XElement score = new XElement("Score", data.Score); newMatch.Add(new object[] { home, away, score }); try { FileStream file = File.Open(_filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); XDocument xDoc = XDocument.Load(file); var target = from q in xDoc.Descendants("Match") where q.Attribute("id").Value.Equals(id) select q; target.First().ReplaceWith(newMatch); file.SetLength(0); file.Flush(); xDoc.Save(file); file.Flush(); file.Close(); _matchDetails[_matchDetails.IndexOf(foundMatch)] = newMatch; ret += "\"home\":\"" + newMatch.Element("Home").Value + "\""; ret += ",\"away\":\"" + newMatch.Element("Away").Value + "\""; ret += ",\"score\":\"" + newMatch.Element("Score").Value + "\""; ret += ",\"success\":\"match " + id + " updated\"}"; } catch (Exception ex) { ret += "\"error\":\"" + ex.Message + "\"}"; } } else ret += "\"error\":\"match not found\"}"; return ret; }