2122c0c1e6491cf8b254c96b80294efbefe0325a
[mono.git] / mcs / class / referencesource / System.Activities.Presentation / Microsoft.Tools.Common / Microsoft / Activities / Presentation / Xaml / ViewStateIdManager.cs
1 // <copyright>
2 //   Copyright (c) Microsoft Corporation.  All rights reserved.
3 // </copyright>
4
5 namespace Microsoft.Activities.Presentation.Xaml
6 {
7     using System.Collections.Generic;
8
9     class ViewStateIdManager
10     {
11         readonly char separatorChar = '_';
12         Dictionary<string, int> prefixToIntMap = new Dictionary<string, int>();
13
14         public void UpdateMap(string id)
15         {
16             int separatorLocation = id.LastIndexOf('_');
17
18             // If the separator is not found or if the separator is the first or last character
19             // in the id then use id value itself as the prefix.
20             if (separatorLocation == -1 || separatorLocation == 0 || separatorLocation == id.Length - 1)
21             {
22                 this.prefixToIntMap[id] = 0;
23             }
24             else
25             {
26                 string[] idParts = new string[2];
27                 idParts[0] = id.Substring(0, separatorLocation);
28                 idParts[1] = id.Substring(separatorLocation + 1, id.Length - (separatorLocation + 1));
29
30                 int suffix;
31                 if (int.TryParse(idParts[1], out suffix))
32                 {
33                     int oldValue;
34                     if (this.prefixToIntMap.TryGetValue(idParts[0], out oldValue))
35                     {
36                         if (suffix > oldValue)
37                         {
38                             this.prefixToIntMap[idParts[0]] = suffix;
39                         }
40                     }
41                     else
42                     {
43                         this.prefixToIntMap[idParts[0]] = suffix;
44                     }
45                 }
46                 else
47                 {
48                     this.prefixToIntMap[id] = 0;
49                 }
50             }
51         }
52
53         public string GetNewId(string prefix)
54         {
55             int suffix = 0;
56             this.prefixToIntMap.TryGetValue(prefix, out suffix);
57             
58             while (suffix == int.MaxValue)
59             {
60                 prefix = prefix + this.separatorChar + suffix;
61                 this.prefixToIntMap.TryGetValue(prefix, out suffix);
62             }
63
64             this.prefixToIntMap[prefix] = ++suffix;
65             return prefix + this.separatorChar + suffix;
66         }
67     };
68 }