view api/Factories/Xml/WarFoundryXmlSaver.cs @ 104:2f3cafb69799

Re #121: Migrate to AGPL license * Update all API files to AGPL license * Include AGPL license and remove GPL/LGPL documents * Fix copyright dates where they're known
author IBBoard <dev@ibboard.co.uk>
date Sat, 15 Aug 2009 10:36:50 +0000
parents 3ea0ab04352b
children f5aec697b8ea
line source
1 // This file (WarFoundryXmlSaver.cs) is a part of the IBBoard.WarFoundry.API project and is copyright 2008, 2009 IBBoard.
2 //
3 // The file and the library/program it is in are licensed and distributed, without warranty, under the GNU Affero GPL license, either version 3 of the License or (at your option) any later version. Please see COPYING for more information and the full license.
5 using System;
6 using System.Collections.Generic;
7 using System.IO;
8 using IBBoard.Lang;
9 using IBBoard.WarFoundry.API.Objects;
11 namespace IBBoard.WarFoundry.API.Factories.Xml
12 {
13 public class WarFoundryXmlSaver
14 {
15 //FIXME: Rework to saving files in Zips
16 private static WarFoundryXmlSaver saver;
17 private static List<Type> saveAsTypes;
18 private Dictionary<WarFoundryObject, string> savePaths = new Dictionary<WarFoundryObject,string>();
20 public static WarFoundryXmlSaver GetSaver()
21 {
22 if (saver == null)
23 {
24 saveAsTypes = new List<Type>();
25 saveAsTypes.Add(typeof(Army));
26 saver = new WarFoundryXmlSaver();
27 }
29 return saver;
30 }
32 public bool SaveAs(WarFoundryObject toSave, string saveAsPath)
33 {
34 if (CanSaveType(toSave))
35 {
36 FileStream fs = null;
37 bool success = false;
39 try
40 {
41 fs = new FileStream(saveAsPath, FileMode.Create, FileAccess.Write);
42 byte[] bytes = StringManipulation.StringToBytes(CreateXmlString(toSave));
43 fs.Write(bytes, 0, bytes.Length);
44 fs.Flush();
45 savePaths.Add(toSave, saveAsPath);
46 success = true;
47 }
48 finally
49 {
50 if (fs!=null && fs.CanWrite)
51 {
52 fs.Close();
53 }
54 }
56 return success;
57 }
58 else
59 {
60 throw new ArgumentException("Cannot directly save objects of type "+toSave.GetType());
61 }
62 }
64 public bool Save(WarFoundryObject toSave)
65 {
66 if (CanSave(toSave))
67 {
68 return SaveAs(toSave, savePaths[toSave]);
69 }
70 else
71 {
72 throw new InvalidOperationException("Cannot save an object that has not previously been saved using SaveAs");
73 }
74 }
76 private string CreateXmlString(WarFoundryObject toSave)
77 {
78 return ""; //TODO: Create XML string as appropriate
79 }
81 public bool CanSaveAs(WarFoundryObject obj)
82 {
83 return CanSaveType(obj);
84 }
86 public bool CanSave(WarFoundryObject obj)
87 {
88 return savePaths.ContainsKey(obj);
89 }
91 public bool CanSaveType(WarFoundryObject obj)
92 {
93 return saveAsTypes.Contains(obj.GetType());
94 }
95 }
96 }