FastNameCreator.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Collections;
  5. namespace FastReport.Utils
  6. {
  7. /// <summary>
  8. /// The helper class used to create unique component names using the fastest method.
  9. /// </summary>
  10. /// <remarks>
  11. /// <para>Note: you can create unique component's name using its <b>CreateUniqueName</b> method.
  12. /// However, it is very slow and can't be used in some situations (when you create a report
  13. /// layout in a code and have a lot of objects on a page).</para>
  14. /// </remarks>
  15. /// <example>This example demonstrates how to use this class.
  16. /// <code>
  17. /// FastNameCreator nameCreator = new FastNameCreator(Report.AllObjects);
  18. /// foreach (Base c in Report.AllObjects)
  19. /// {
  20. /// if (c.Name == "")
  21. /// nameCreator.CreateUniqueName(c);
  22. /// }
  23. /// </code>
  24. /// </example>
  25. public class FastNameCreator
  26. {
  27. private readonly Hashtable baseNames;
  28. /// <summary>
  29. /// Creates the unique name for the given object.
  30. /// </summary>
  31. /// <param name="obj">The object to create name for.</param>
  32. public void CreateUniqueName(Base obj)
  33. {
  34. string baseName = obj.BaseName;
  35. int num = 1;
  36. if (baseNames.ContainsKey(baseName))
  37. num = (int)baseNames[baseName] + 1;
  38. obj.SetName(baseName + num.ToString());
  39. baseNames[baseName] = num;
  40. }
  41. /// <summary>
  42. /// Initializes a new instance of the <b>FastNameCreator</b> class with collection of
  43. /// existing report objects.
  44. /// </summary>
  45. /// <param name="objects">The collection of existing report objects.</param>
  46. public FastNameCreator(ObjectCollection objects)
  47. {
  48. baseNames = new Hashtable();
  49. foreach (Base obj in objects)
  50. {
  51. string objName = obj.Name;
  52. if (!String.IsNullOrEmpty(objName))
  53. {
  54. // find numeric part
  55. int i = objName.Length - 1;
  56. while (i > 0 && objName[i] >= '0' && objName[i] <= '9')
  57. {
  58. i--;
  59. }
  60. if (i >= 0 && i < objName.Length - 1)
  61. {
  62. // get number
  63. string baseName = objName.Substring(0, i + 1);
  64. int num;
  65. int.TryParse(objName.Substring(i + 1), out num);
  66. if (baseNames.ContainsKey(baseName))
  67. {
  68. int maxNum = (int)baseNames[baseName];
  69. if (num < maxNum)
  70. num = maxNum;
  71. }
  72. baseNames[baseName] = num;
  73. }
  74. else if (!baseNames.ContainsKey(objName))
  75. {
  76. baseNames[objName] = 0;
  77. }
  78. }
  79. }
  80. }
  81. }
  82. }