|
| 1 | +namespace DotNetToolkit.Repository.AzureStorageTable.Internal |
| 2 | +{ |
| 3 | + using Configuration; |
| 4 | + using Configuration.Conventions; |
| 5 | + using Extensions; |
| 6 | + using Extensions.Internal; |
| 7 | + using Microsoft.Azure.CosmosDB.Table; |
| 8 | + using Microsoft.Azure.CosmosDB.Table.Queryable; |
| 9 | + using Microsoft.Azure.Storage; |
| 10 | + using Queries; |
| 11 | + using Queries.Strategies; |
| 12 | + using System; |
| 13 | + using System.Collections.Generic; |
| 14 | + using System.Configuration; |
| 15 | + using System.Linq; |
| 16 | + using System.Reflection; |
| 17 | + using Utility; |
| 18 | + |
| 19 | + /// <summary> |
| 20 | + /// An implementation of <see cref="IAzureStorageTableRepositoryContext" />. |
| 21 | + /// </summary> |
| 22 | + /// <seealso cref="IAzureStorageTableRepositoryContext" /> |
| 23 | + internal class AzureStorageTableRepositoryContext : LinqRepositoryContextBase, IAzureStorageTableRepositoryContext |
| 24 | + { |
| 25 | + #region Properties |
| 26 | + |
| 27 | + /// <summary> |
| 28 | + /// Gest the cloud Table. |
| 29 | + /// </summary> |
| 30 | + public CloudTable Table { get; private set; } |
| 31 | + |
| 32 | + #endregion |
| 33 | + |
| 34 | + #region Constructors |
| 35 | + |
| 36 | + /// <summary> |
| 37 | + /// Initializes a new instance of the <see cref="AzureStorageTableRepositoryContext" /> class. |
| 38 | + /// </summary> |
| 39 | + /// <param name="nameOrConnectionString">Either the database name or a connection string.</param> |
| 40 | + /// <param name="tableName">The name of the table.</param> |
| 41 | + /// <param name="createIfNotExists">Creates the container if it does not exist.</param> |
| 42 | + public AzureStorageTableRepositoryContext(string nameOrConnectionString, string tableName = null, bool createIfNotExists = false) |
| 43 | + { |
| 44 | + Guard.NotEmpty(nameOrConnectionString, nameof(nameOrConnectionString)); |
| 45 | + |
| 46 | + ConfigureConventions(); |
| 47 | + |
| 48 | + var css = GetConnectionStringSettings(nameOrConnectionString); |
| 49 | + |
| 50 | + var connectionString = css != null |
| 51 | + ? css.ConnectionString |
| 52 | + : nameOrConnectionString; |
| 53 | + |
| 54 | + var account = CloudStorageAccount.Parse(connectionString); |
| 55 | + var client = account.CreateCloudTableClient(); |
| 56 | + |
| 57 | + if (string.IsNullOrEmpty(tableName)) |
| 58 | + tableName = GetType().Name; |
| 59 | + |
| 60 | + Table = client.GetTableReference(tableName); |
| 61 | + |
| 62 | + if (createIfNotExists) |
| 63 | + Table.CreateIfNotExists(); |
| 64 | + } |
| 65 | + |
| 66 | + #endregion |
| 67 | + |
| 68 | + #region Private Methods |
| 69 | + |
| 70 | + private void ConfigureConventions() |
| 71 | + { |
| 72 | + Conventions = new RepositoryConventions(GetType()) |
| 73 | + { |
| 74 | + PrimaryKeysCallback = type => AzureStorageTableConventionsHelper.GetPrimaryKeyPropertyInfos(type) |
| 75 | + }; |
| 76 | + } |
| 77 | + |
| 78 | + private IEnumerable<TElement> ExecuteTableQuery<TElement>(TableQuery<TElement> tableQuery) |
| 79 | + { |
| 80 | + var nextQuery = tableQuery; |
| 81 | + var continuationToken = default(TableContinuationToken); |
| 82 | + var results = new List<TElement>(); |
| 83 | + |
| 84 | + do |
| 85 | + { |
| 86 | + var queryResult = nextQuery.ExecuteSegmented(continuationToken); |
| 87 | + |
| 88 | + results.Capacity += queryResult.Results.Count; |
| 89 | + results.AddRange(queryResult.Results); |
| 90 | + |
| 91 | + continuationToken = queryResult.ContinuationToken; |
| 92 | + |
| 93 | + if (continuationToken != null && tableQuery.TakeCount.HasValue) |
| 94 | + { |
| 95 | + var itemsToLoad = tableQuery.TakeCount.Value - results.Count; |
| 96 | + |
| 97 | + nextQuery = itemsToLoad > 0 |
| 98 | + ? tableQuery.Take<TElement>(itemsToLoad).AsTableQuery() |
| 99 | + : null; |
| 100 | + } |
| 101 | + |
| 102 | + } while (continuationToken != null && nextQuery != null); |
| 103 | + |
| 104 | + return results; |
| 105 | + } |
| 106 | + |
| 107 | + private TableQuery<TEntity> InvokeCreateQuery<TEntity>() |
| 108 | + { |
| 109 | + return (TableQuery<TEntity>)typeof(CloudTable) |
| 110 | + .GetRuntimeMethods() |
| 111 | + .Single(x => x.Name == nameof(CloudTable.CreateQuery) && |
| 112 | + x.IsGenericMethodDefinition && |
| 113 | + x.GetGenericArguments().Length == 1 && |
| 114 | + x.GetParameters().Length == 0) |
| 115 | + .MakeGenericMethod(typeof(TEntity)) |
| 116 | + .Invoke(Table, null); |
| 117 | + } |
| 118 | + |
| 119 | + private TableOperation InvokeRetrieve<TEntity>(string partitionKey, string rowKey) |
| 120 | + { |
| 121 | + return (TableOperation)typeof(TableOperation) |
| 122 | + .GetRuntimeMethods() |
| 123 | + .Single(x => x.Name == nameof(TableOperation.Retrieve) && |
| 124 | + x.IsGenericMethodDefinition && |
| 125 | + x.GetGenericArguments().Length == 1 && |
| 126 | + x.GetParameters().Length == 3) |
| 127 | + .MakeGenericMethod(typeof(TEntity)) |
| 128 | + .Invoke(Table, new[] { partitionKey, rowKey, null }); |
| 129 | + } |
| 130 | + |
| 131 | + private static void ThrowsIfNotTableEntity<TEntity>() |
| 132 | + { |
| 133 | + if (!typeof(TEntity).ImplementsInterface(typeof(ITableEntity))) |
| 134 | + throw new InvalidOperationException($"The specified '{typeof(TEntity).FullName}' type must implement '{typeof(ITableEntity).FullName}.'"); |
| 135 | + } |
| 136 | + |
| 137 | + private static ConnectionStringSettings GetConnectionStringSettings(string nameOrConnectionString) |
| 138 | + { |
| 139 | + var css = ConfigurationManager.ConnectionStrings[nameOrConnectionString]; |
| 140 | + |
| 141 | + if (css != null) |
| 142 | + return css; |
| 143 | + |
| 144 | + for (var i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++) |
| 145 | + { |
| 146 | + css = ConfigurationManager.ConnectionStrings[i]; |
| 147 | + |
| 148 | + if (css.ConnectionString.Equals(nameOrConnectionString)) |
| 149 | + return css; |
| 150 | + } |
| 151 | + |
| 152 | + return null; |
| 153 | + } |
| 154 | + |
| 155 | + #endregion |
| 156 | + |
| 157 | + #region Overrides of LinqRepositoryContextBase |
| 158 | + |
| 159 | + /// <summary> |
| 160 | + /// Returns the entity's query. |
| 161 | + /// </summary> |
| 162 | + /// <typeparam name="TEntity">The type of the of the entity.</typeparam> |
| 163 | + /// <returns>The entity's query.</returns> |
| 164 | + protected override IQueryable<TEntity> AsQueryable<TEntity>() |
| 165 | + { |
| 166 | + ThrowsIfNotTableEntity<TEntity>(); |
| 167 | + |
| 168 | + return ExecuteTableQuery<TEntity>( |
| 169 | + InvokeCreateQuery<TEntity>()) |
| 170 | + .AsQueryable(); |
| 171 | + } |
| 172 | + |
| 173 | + /// <summary> |
| 174 | + /// Apply a fetching options to the specified entity's query. |
| 175 | + /// </summary> |
| 176 | + /// <returns>The entity's query with the applied options.</returns> |
| 177 | + protected override IQueryable<TEntity> ApplyFetchingOptions<TEntity>(IQueryable<TEntity> query, IQueryOptions<TEntity> options) |
| 178 | + { |
| 179 | + ThrowsIfNotTableEntity<TEntity>(); |
| 180 | + |
| 181 | + if (options?.FetchStrategy?.PropertyPaths?.Any() == true) |
| 182 | + Logger.Debug("The azure storage table context does not support fetching strategy."); |
| 183 | + |
| 184 | + return query; |
| 185 | + } |
| 186 | + |
| 187 | + /// <summary> |
| 188 | + /// Tracks the specified entity in memory and will be inserted into the database when <see cref="SaveChanges" /> is called. |
| 189 | + /// </summary> |
| 190 | + /// <typeparam name="TEntity">The type of the entity.</typeparam> |
| 191 | + /// <param name="entity">The entity.</param> |
| 192 | + public override void Add<TEntity>(TEntity entity) |
| 193 | + { |
| 194 | + Guard.NotNull(entity, nameof(entity)); |
| 195 | + |
| 196 | + ThrowsIfNotTableEntity<TEntity>(); |
| 197 | + |
| 198 | + var operation = TableOperation.InsertOrReplace((ITableEntity)entity); |
| 199 | + |
| 200 | + Table.Execute(operation); |
| 201 | + } |
| 202 | + |
| 203 | + /// <summary> |
| 204 | + /// Tracks the specified entity in memory and will be updated in the database when <see cref="SaveChanges" /> is called. |
| 205 | + /// </summary> |
| 206 | + /// <typeparam name="TEntity">The type of the entity.</typeparam> |
| 207 | + /// <param name="entity">The entity.</param> |
| 208 | + public override void Update<TEntity>(TEntity entity) |
| 209 | + { |
| 210 | + Guard.NotNull(entity, nameof(entity)); |
| 211 | + |
| 212 | + ThrowsIfNotTableEntity<TEntity>(); |
| 213 | + |
| 214 | + var operation = TableOperation.Replace((ITableEntity)entity); |
| 215 | + |
| 216 | + Table.Execute(operation); |
| 217 | + } |
| 218 | + |
| 219 | + /// <summary> |
| 220 | + /// Tracks the specified entity in memory and will be removed from the database when <see cref="SaveChanges" /> is called. |
| 221 | + /// </summary> |
| 222 | + /// <typeparam name="TEntity">The type of the entity.</typeparam> |
| 223 | + /// <param name="entity">The entity.</param> |
| 224 | + public override void Remove<TEntity>(TEntity entity) |
| 225 | + { |
| 226 | + Guard.NotNull(entity, nameof(entity)); |
| 227 | + |
| 228 | + ThrowsIfNotTableEntity<TEntity>(); |
| 229 | + |
| 230 | + var operation = TableOperation.Delete((ITableEntity)entity); |
| 231 | + |
| 232 | + Table.Execute(operation); |
| 233 | + } |
| 234 | + |
| 235 | + /// <summary> |
| 236 | + /// Saves all changes made in this context to the database. |
| 237 | + /// </summary> |
| 238 | + /// <returns>The number of state entries written to the database.</returns> |
| 239 | + public override int SaveChanges() |
| 240 | + { |
| 241 | + return -1; |
| 242 | + } |
| 243 | + |
| 244 | + /// <summary> |
| 245 | + /// Finds an entity with the given primary key values in the repository. |
| 246 | + /// </summary> |
| 247 | + /// <typeparam name="TEntity">The type of the of the entity.</typeparam> |
| 248 | + /// <param name="fetchStrategy">Defines the child objects that should be retrieved when loading the entity.</param> |
| 249 | + /// <param name="keyValues">The values of the primary key for the entity to be found.</param> |
| 250 | + /// <returns>The entity found in the repository.</returns> |
| 251 | + public override TEntity Find<TEntity>(IFetchQueryStrategy<TEntity> fetchStrategy, params object[] keyValues) |
| 252 | + { |
| 253 | + Guard.NotEmpty(keyValues, nameof(keyValues)); |
| 254 | + |
| 255 | + ThrowsIfNotTableEntity<TEntity>(); |
| 256 | + |
| 257 | + string partitionKey = string.Empty; |
| 258 | + string rowKey; |
| 259 | + |
| 260 | + if (keyValues.Length == 1) |
| 261 | + { |
| 262 | + rowKey = keyValues[0].ToString(); |
| 263 | + } |
| 264 | + else |
| 265 | + { |
| 266 | + partitionKey = keyValues[0].ToString(); |
| 267 | + rowKey = keyValues[1].ToString(); |
| 268 | + } |
| 269 | + |
| 270 | + var opertation = InvokeRetrieve<TEntity>(partitionKey, rowKey); |
| 271 | + var tableResult = Table.Execute(opertation); |
| 272 | + |
| 273 | + return tableResult.Result as TEntity; |
| 274 | + } |
| 275 | + |
| 276 | + #endregion |
| 277 | + } |
| 278 | +} |
0 commit comments