CrazyIter hace 5 años
padre
commit
7f51860395

+ 65 - 20
TEAMModelOS.SDK/Module/AzureCosmosDB/Implements/AzureCosmosDBRepository.cs

@@ -108,7 +108,27 @@ namespace TEAMModelOS.SDK.Module.AzureCosmosDB.Implements
                     UriFactory.CreateDatabaseUri(Database), collectionDefinition, new RequestOptions { OfferThroughput = CollectionThroughput }
                     );
             }
+            return CosmosCollection;
+        }
 
+        private async Task<DocumentCollection> InitializeCollection(string CollectionName, string PartitionKey)
+        {
+            if (CosmosCollection == null || !CosmosCollection.Id.Equals(CollectionName))
+            {
+                DocumentCollection collectionDefinition = new DocumentCollection { Id = CollectionName };
+                collectionDefinition.IndexingPolicy = new IndexingPolicy(new RangeIndex(DataType.String) { Precision = -1 });
+              
+                // collectionDefinition.PartitionKey = new PartitionKeyDefinition {  Paths = new System.Collections.ObjectModel.Collection<string>() };
+                if (!string.IsNullOrEmpty(PartitionKey))
+                {
+                    collectionDefinition.PartitionKey.Paths.Add("/" + PartitionKey);
+
+                }
+                // CosmosCollection = await this.CosmosClient.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(Database), collectionDefinition);
+                CosmosCollection = await this.CosmosClient.CreateDocumentCollectionIfNotExistsAsync(
+                    UriFactory.CreateDatabaseUri(Database), collectionDefinition, new RequestOptions { OfferThroughput = CollectionThroughput }
+                    );
+            }
             return CosmosCollection;
         }
 
@@ -252,31 +272,31 @@ namespace TEAMModelOS.SDK.Module.AzureCosmosDB.Implements
         public async Task<List<T>> FindSQL<T>(string sql)
         {
             Type t = typeof(T);
-            List<T> objs = new List<T>();
+            //List<T> objs = new List<T>();
             await InitializeCollection<T>();
             var query = CosmosClient.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(Database, t.Name), sql);
-            foreach (var item in query)
-            {
-                objs.Add(item);
-            }
-            return objs;
+            //foreach (var item in query)
+            //{
+            //    objs.Add(item);
+            //}
+            return query.ToList<T>();
 
         }
 
         public async Task<List<T>> FindSQL<T>(string sql, bool IsPk)
         {
             Type t = typeof(T);
-            List<T> objs = new List<T>();
-            Boolean open = IsPk;
+            //List<T> objs = new List<T>();
+           // Boolean open = IsPk;
             await InitializeCollection<T>();
             //查询条数 -1是全部
-            FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = open };
+            FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = IsPk };
             var query = CosmosClient.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(Database, t.Name), sql, queryOptions);
-            foreach (var item in query)
-            {
-                objs.Add(item);
-            }
-            return objs;
+            //foreach (var item in query)
+            //{
+            //    objs.Add(item);
+            //}
+            return query.ToList<T>();
 
         }
 
@@ -566,7 +586,7 @@ namespace TEAMModelOS.SDK.Module.AzureCosmosDB.Implements
         public async Task<List<T>> FindByDict<T>(Dictionary<string, object> dict, bool IsPk)
         {
             Type t = typeof(T);
-            List<T> objs = new List<T>();
+           // List<T> objs = new List<T>();
             await InitializeCollection<T>();
             StringBuilder sql = new StringBuilder("select * from c where 1=1 ");
             if (dict != null)
@@ -579,11 +599,11 @@ namespace TEAMModelOS.SDK.Module.AzureCosmosDB.Implements
             //查询条数 -1是全部
             FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = IsPk };
             var query = CosmosClient.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(Database, t.Name), sql.ToString(), queryOptions);
-            foreach (var item in query)
-            {
-                objs.Add(item);
-            }
-            return objs;
+            //foreach (var item in query)
+            //{
+            //    objs.Add(item);
+            //}
+            return query.ToList<T>();
         }
 
         private static string GenSql(object obj, string key)
@@ -602,5 +622,30 @@ namespace TEAMModelOS.SDK.Module.AzureCosmosDB.Implements
                 _ => null,
             };
         }
+
+        public async Task<IQueryable<dynamic>> FindByDict(string CollectionName, string PartitionKey, Dictionary<string, object> dict) {
+         
+            await InitializeCollection(CollectionName, PartitionKey);
+            StringBuilder sql = new StringBuilder("select * from "+ CollectionName + " c where 1=1 ");
+            if (dict != null)
+            {
+                foreach (string key in dict.Keys)
+                {
+                    sql.Append(GenSql(dict[key], key));
+                }
+            }
+            FeedOptions queryOptions;
+            if (!string.IsNullOrEmpty(PartitionKey))
+            {
+                queryOptions = new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = true };
+            }
+            else {
+                queryOptions = new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = false };
+            }
+            //查询条数 -1是全部
+          
+            var query = CosmosClient.CreateDocumentQuery(UriFactory.CreateDocumentCollectionUri(Database, CollectionName), sql.ToString(), queryOptions);
+            return query;
+        }
     }
 }

+ 1 - 0
TEAMModelOS.SDK/Module/AzureCosmosDB/Interfaces/IAzureCosmosDBRepository.cs

@@ -24,5 +24,6 @@ namespace TEAMModelOS.SDK.Module.AzureCosmosDB.Interfaces
         Task<List<T>> SaveAll<T>(List<T> enyites);
         Task<List<T>> UpdateAll<T>(Dictionary<string, object> dict, Dictionary<string, object> updateFilters, List<string> deleteKeys = null);
         Task<List<T>> DeleteAll<T>(Dictionary<string, object> dict);
+        Task<IQueryable<dynamic>> FindByDict(string CollectionName, string PartitionKey, Dictionary<string, object> dict); 
     }
 }

+ 1 - 0
TEAMModelOS.SDK/TEAMModelOS.SDK.csproj

@@ -14,6 +14,7 @@
     <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.0.0" />
     <PackageReference Include="Microsoft.AspNetCore.Authorization" Version="3.0.0" />
     <PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
+    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
     <PackageReference Include="Microsoft.Azure.CosmosDB.BulkExecutor" Version="2.4.1-preview" />
     <PackageReference Include="Microsoft.Azure.DocumentDB.Core" Version="2.9.0" />
     <PackageReference Include="Microsoft.Extensions.Configuration" Version="3.0.0" />

+ 14 - 3
TEAMModelOS/Controllers/Core/CommonController.cs

@@ -7,10 +7,12 @@ using System.Linq;
 using System.Text;
 using System.Text.Json;
 using System.Threading.Tasks;
+using TEAMModelOS.Models;
 using TEAMModelOS.SDK.Context.Exception;
 using TEAMModelOS.SDK.Extension.DataResult.JsonRpcRequest;
 using TEAMModelOS.SDK.Extension.DataResult.JsonRpcResponse;
 using TEAMModelOS.SDK.Helper.Common.JsonHelper.JsonPath;
+using TEAMModelOS.SDK.Module.AzureCosmosDB.Interfaces;
 using static System.Text.Json.JsonElement;
 
 namespace TEAMModelOS.Controllers.Syllabus
@@ -20,11 +22,13 @@ namespace TEAMModelOS.Controllers.Syllabus
     // [Authorize]
     public class CommonController : BaseController
     {
-        public readonly IWebHostEnvironment webHostEnvironment;
 
-        public CommonController(IWebHostEnvironment _webHostEnvironment)
+        private readonly IAzureCosmosDBRepository azureCosmosDBRepository;
+        private readonly IWebHostEnvironment webHostEnvironment;
+        public CommonController(IWebHostEnvironment _webHostEnvironment, IAzureCosmosDBRepository _azureCosmosDBRepository)
         {
             webHostEnvironment = _webHostEnvironment;
+            azureCosmosDBRepository = _azureCosmosDBRepository;
 
         }
         /// <summary>
@@ -58,7 +62,6 @@ namespace TEAMModelOS.Controllers.Syllabus
                 return builder.Data(document.RootElement).build();
             }
         } 
-
         public static async Task<JsonDocument> GetJson(string contentRootPath, string name)
         {
             try
@@ -73,5 +76,13 @@ namespace TEAMModelOS.Controllers.Syllabus
             }
             return null;
         }
+
+        [HttpPost("FindCollection")]
+        public async Task<BaseJosnRPCResponse> FindCollection(JosnRPCRequest<CommonQuery> request)
+        {
+            JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
+            IQueryable<dynamic>  data = await azureCosmosDBRepository.FindByDict(request.@params.collectionName, request.@params.partitionKey , request.@params.queryDict);
+            return builder.Data(data).build();
+        }
     }
 }

+ 14 - 0
TEAMModelOS/Models/CommonQuery.cs

@@ -0,0 +1,14 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace TEAMModelOS.Models
+{
+    public class CommonQuery
+    {
+        public string collectionName { get; set; }
+        public string partitionKey { get; set; }
+        public Dictionary<string ,object> queryDict { get; set; }
+    }
+}

+ 8 - 3
TEAMModelOS/Startup.cs

@@ -35,6 +35,8 @@ namespace TEAMModelOS
         // This method gets called by the runtime. Use this method to add services to the container.
         public void ConfigureServices(IServiceCollection services)
         {
+
+           
             // true,默認情況下,聲明映射將以舊格式映射聲明名稱,以適應較早的SAML應用程序,RoleClaimType = 'http://schemas.microsoft.com/ws/2008/06/identity/claims/role'
             // false,RoleClaimType = 'roles' 
             /*
@@ -86,7 +88,7 @@ namespace TEAMModelOS
             //    });
             //});
             services.AddMemoryCache();
-            services.AddControllers();
+            services.AddControllers().AddNewtonsoftJson();
             // Table配置
             services.AddAzureTableStorage().AddConnection(Configuration.GetSection("Azure:Table").Get<AzureTableOptions>());
             //使用Blob配置
@@ -111,13 +113,16 @@ namespace TEAMModelOS
             {
                 app.UseDeveloperExceptionPage();
             }
-            //以下需要按照順序載入中間件
+            app.UseMiddleware<HttpGlobalExceptionInvoke>();
+            //以下需要按照順序載入中間件  如果应用调用 UseStaticFiles,请将 UseStaticFiles 置于 UseRouting之前。
             app.UseStaticFiles();
             //app.UseSpaStaticFiles(); //使用中間件不開
             app.UseRouting();
-            app.UseMiddleware<HttpGlobalExceptionInvoke>();
+           
             //app.UseCors(MyAllowSpecificOrigins); //使用跨域設定
             //app.UseHttpsRedirection(); //開發中暫時關掉
+            //如果应用使用身份验证/授权功能(如 AuthorizePage 或 [Authorize]),请将对 UseAuthentication 和 UseAuthorization的
+            //调用放在之后、UseRouting 和 UseCors,但在 UseEndpoints之前
             app.UseAuthentication();
             app.UseAuthorization();
             app.UseEndpoints(endpoints =>