2
0

DynamicDataContainerModelProvider.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.DynamicData;
  7. using System.Web.DynamicData.ModelProviders;
  8. using MonoTests.DataSource;
  9. namespace MonoTests.ModelProviders
  10. {
  11. public class DynamicDataContainerModelProvider : DataModelProvider
  12. {
  13. IDynamicDataContainer container;
  14. Type containerType;
  15. ReadOnlyCollection<TableProvider> tables;
  16. IDynamicDataContainer Container
  17. {
  18. get
  19. {
  20. if (container != null)
  21. return container;
  22. container = Activator.CreateInstance (containerType) as IDynamicDataContainer;
  23. if (container == null)
  24. throw new InvalidOperationException ("Failed to create an instance of container type '" + ContextType + "'.");
  25. return container;
  26. }
  27. }
  28. public override Type ContextType
  29. {
  30. get
  31. {
  32. return Container.ContainedType;
  33. }
  34. protected set
  35. {
  36. throw new InvalidOperationException ("Setting the context type on this provider is not supported.");
  37. }
  38. }
  39. public DynamicDataContainerModelProvider (Type containerType)
  40. {
  41. if (containerType == null)
  42. throw new ArgumentNullException ("contextType");
  43. if (!typeof (IDynamicDataContainer).IsAssignableFrom (containerType))
  44. throw new ArgumentException ("Container type must implement the IDynamicDataContainer interface.", "contextType");
  45. this.containerType = containerType;
  46. }
  47. public DynamicDataContainerModelProvider (IDynamicDataContainer container)
  48. {
  49. if (container == null)
  50. throw new ArgumentNullException ("container");
  51. this.container = container;
  52. }
  53. public override object CreateContext ()
  54. {
  55. return Activator.CreateInstance (ContextType);
  56. }
  57. public override ReadOnlyCollection<TableProvider> Tables
  58. {
  59. get {
  60. if (tables != null)
  61. return tables;
  62. tables = LoadTables ();
  63. return tables;
  64. }
  65. }
  66. ReadOnlyCollection<TableProvider> LoadTables ()
  67. {
  68. List<DynamicDataTable> containerTables = Container.GetTables ();
  69. if (containerTables == null || containerTables.Count == 0)
  70. return new ReadOnlyCollection<TableProvider> (new List <TableProvider> ());
  71. var tables = new List<TableProvider> ();
  72. foreach (var table in containerTables)
  73. tables.Add (new DynamicDataContainerTableProvider (this, table));
  74. return new ReadOnlyCollection<TableProvider> (tables);
  75. }
  76. }
  77. }