Free cookie consent management tool by TermsFeed Policy Generator

source: branches/WebJobManager/HeuristicLab.Data/3.3/StringArray.cs @ 16667

Last change on this file since 16667 was 13841, checked in by jlodewyc, 9 years ago

#2582 More parameter datatypes, splitting fileopening service, approving users, reopen last file, change name tasks and repetitions

File size: 7.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections;
24using System.Collections.Generic;
25using System.Drawing;
26using System.Linq;
27using System.Text;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32namespace HeuristicLab.Data {
33  [Item("StringArray", "Represents an array of strings.")]
34  [StorableClass]
35  public class StringArray : Item, IEnumerable<string>, IStringConvertibleArray {
36    private const int maximumToStringLength = 100;
37
38    public static new Image StaticItemImage
39    {
40      get { return new Bitmap(25, 25); }
41    }
42
43    [Storable]
44    protected string[] array;
45
46    [Storable]
47    protected List<string> elementNames;
48    public virtual IEnumerable<string> ElementNames
49    {
50      get { return this.elementNames; }
51      set
52      {
53        if (ReadOnly) throw new NotSupportedException("ElementNames cannot be set. ValueTypeArray is read-only.");
54        if (value == null || !value.Any())
55          elementNames = new List<string>();
56        else if (value.Count() > Length)
57          throw new ArgumentException("The number of element names must not exceed the array length.");
58        else
59          elementNames = new List<string>(value);
60        OnElementNamesChanged();
61      }
62    }
63
64    public virtual int Length
65    {
66      get { return array.Length; }
67      protected set
68      {
69        if (ReadOnly) throw new NotSupportedException("Length cannot be set. StringArray is read-only.");
70        if (value != Length) {
71          Array.Resize<string>(ref array, value);
72          while (elementNames.Count > value)
73            elementNames.RemoveAt(elementNames.Count - 1);
74          OnElementNamesChanged();
75          OnReset();
76        }
77      }
78    }
79        public static StringArray Parse(string val)
80        {
81            try
82            {
83                string[] arr = Array.ConvertAll(val.Trim().Split(';'), p => p.Trim());
84                return new StringArray(arr);
85            }
86            catch (FormatException e)
87            {
88                return null;
89            }
90        }
91        public virtual string this[int index]
92    {
93      get { return array[index]; }
94      set
95      {
96        if (ReadOnly) throw new NotSupportedException("Item cannot be set. StringArray is read-only.");
97        if (value != array[index]) {
98          if ((value != null) || (array[index] != string.Empty)) {
99            array[index] = value != null ? value : string.Empty;
100            OnItemChanged(index);
101          }
102        }
103      }
104    }
105
106    [Storable]
107    protected bool readOnly;
108    public virtual bool ReadOnly
109    {
110      get { return readOnly; }
111    }
112
113    [StorableHook(HookType.AfterDeserialization)]
114    private void AfterDeserialization() {
115      if (elementNames == null) { elementNames = new List<string>(); }
116    }
117
118    [StorableConstructor]
119    protected StringArray(bool deserializing) : base(deserializing) { }
120    protected StringArray(StringArray original, Cloner cloner)
121      : base(original, cloner) {
122      this.array = (string[])original.array.Clone();
123      this.readOnly = original.readOnly;
124      this.elementNames = new List<string>(original.elementNames);
125    }
126    public StringArray() {
127      array = new string[0];
128      readOnly = false;
129      elementNames = new List<string>();
130    }
131    public StringArray(int length) {
132      array = new string[length];
133      for (int i = 0; i < array.Length; i++)
134        array[i] = string.Empty;
135      readOnly = false;
136      elementNames = new List<string>();
137    }
138    public StringArray(string[] elements) {
139      if (elements == null) throw new ArgumentNullException();
140      array = new string[elements.Length];
141      for (int i = 0; i < array.Length; i++)
142        array[i] = elements[i] == null ? string.Empty : elements[i];
143      readOnly = false;
144      elementNames = new List<string>();
145    }
146
147    public override IDeepCloneable Clone(Cloner cloner) {
148      return new StringArray(this, cloner);
149    }
150
151    public virtual StringArray AsReadOnly() {
152      StringArray readOnlyStringArray = (StringArray)this.Clone();
153      readOnlyStringArray.readOnly = true;
154      return readOnlyStringArray;
155    }
156
157    public override string ToString() {
158      if (array.Length == 0) return "[]";
159
160      StringBuilder sb = new StringBuilder();
161      sb.Append("[");
162      sb.Append(array[0]);
163      for (int i = 1; i < array.Length; i++) {
164        sb.Append(";").Append(array[i]);
165        if (sb.Length > maximumToStringLength) {
166          sb.Append("...");
167          break;
168        }
169      }
170      sb.Append("]");
171      return sb.ToString();
172    }
173
174    public virtual IEnumerator<string> GetEnumerator() {
175      return array.Cast<string>().GetEnumerator();
176    }
177
178    IEnumerator IEnumerable.GetEnumerator() {
179      return GetEnumerator();
180    }
181
182    protected virtual bool Validate(string value, out string errorMessage) {
183      if (value == null) {
184        errorMessage = "Invalid Value (string must not be null)";
185        return false;
186      } else {
187        errorMessage = string.Empty;
188        return true;
189      }
190    }
191    protected virtual string GetValue(int index) {
192      return this[index];
193    }
194    protected virtual bool SetValue(string value, int index) {
195      if (value != null) {
196        this[index] = value;
197        return true;
198      } else {
199        return false;
200      }
201    }
202
203    public event EventHandler ElementNamesChanged;
204    protected virtual void OnElementNamesChanged() {
205      EventHandler handler = ElementNamesChanged;
206      if (handler != null)
207        handler(this, EventArgs.Empty);
208    }
209
210    public event EventHandler<EventArgs<int>> ItemChanged;
211    protected virtual void OnItemChanged(int index) {
212      if (ItemChanged != null)
213        ItemChanged(this, new EventArgs<int>(index));
214      if (index < maximumToStringLength)
215        OnToStringChanged();
216    }
217    public event EventHandler Reset;
218    protected virtual void OnReset() {
219      if (Reset != null)
220        Reset(this, EventArgs.Empty);
221      OnToStringChanged();
222    }
223
224    #region IStringConvertibleArray Members
225    int IStringConvertibleArray.Length
226    {
227      get { return Length; }
228      set { Length = value; }
229    }
230    bool IStringConvertibleArray.Validate(string value, out string errorMessage) {
231      return Validate(value, out errorMessage);
232    }
233    string IStringConvertibleArray.GetValue(int index) {
234      return GetValue(index);
235    }
236    bool IStringConvertibleArray.SetValue(string value, int index) {
237      return SetValue(value, index);
238    }
239    #endregion
240  }
241}
Note: See TracBrowser for help on using the repository browser.